<commit_before>"use strict"

/* initialize all canvases */
function initSpectrograms() {
    /* get WebGL context and load required extensions */
    for (var i in IDS) {
        var id = IDS[i];
        SPECTROGRAMS[id] = new Spectrogram(id);
    }
}

function reloadSpectrograms() {
    var patientIdentifier = getElementById("patientIdentifierByMRN").value;
    var fftLen = parseFloat(getElementById("fftLen").value);
    var startTime = parseFloat(getElementById("specStartTime").value);
    var endTime = parseFloat(getElementById("specEndTime").value);
    // first we try to load a file
    if (patientIdentifier) {
        console.log("Requesting spectrogram for: " + patientIdentifier);
        for (var ch = 0; ch < IDS.length; ch++) {
          requestSpectrogram(patientIdentifier, fftLen, startTime, endTime,
            OVERLAP, ch);
        }
    }
    if (!patientIdentifier) {
        console.log("Could not load spectrogram: No file selected");
        return;
    }
}

function setTime(timeId, timeValue) {
    getElementById(timeId).value = parseFloat(timeValue.toFixed(3));
}

function increaseInterval() {
    var interval = parseFloat(getElementById("specInterval").value);
    var specStartTime = parseFloat(getElementById("specStartTime").value);
    var specEndTime = parseFloat(getElementById("specEndTime").value);
    if (specEndTime - specStartTime === interval) {
      setTime("specStartTime", specStartTime + interval);
      setTime("specEndTime", specEndTime + interval);
    } else {
      setTime("specEndTime", specStartTime + interval);
    }
    reloadSpectrograms();
}

function decreaseInterval() {
    var interval = parseFloat(getElementById("specInterval").value);
    var specStartTime = parseFloat(getElementById("specStartTime").value);
    var specEndTime = parseFloat(getElementById("specEndTime").value);
    if (specEndTime - specStartTime === interval) {
      setTime("specStartTime", Math.max(0, specStartTime - interval));
      setTime("specEndTime", Math.max(interval, specEndTime - interval));
    } else {
      setTime("specStartTime", Math.max(0, specStartTime - interval));
    }
    reloadSpectrograms();
}

function testPanning() {
    var mrn = "005";
    var startTime = 0;
    var endTime = 1;
    var interval = 0.5;
    getElementById("patientIdentifierByName").value = mrn;
    var id;

    function pan() {
        getElementById("specStartTime").value = startTime;
        getElementById("specEndTime").value = endTime;
        console.log("startTime: " + startTime + " endTime: " + endTime);
        startTime += interval;
        endTime += interval;
        reloadSpectrograms();
        if (endTime > 70) {
            clearInterval(id);
        }
    }
    id = setInterval(pan, 15 * 1000);
}

/* Test the keyup event for a submission and then reload the spectrogram.
 */
function submitSpectrogram(e) {
    var which = e.which || e.keyCode;
    if (which === 13) {
        reloadSpectrograms();
    }
}

$(document).ready(function() {
    $("body").ready(initSpectrograms);
    $("#patientIdentifierByMRN").keyup(submitSpectrogram);
    $("#specStartTime").keyup(submitSpectrogram);
    $("#specEndTime").keyup(submitSpectrogram);
    $("#fftLen").change(reloadSpectrograms);
    $("#specMode").change(redrawSpectrograms);
    $("#specInterpolation").change(redrawSpectrograms);
    $("#specLogarithmic").change(redrawSpectrograms);
    $("#patientIdentifierMRNSubmit").click(reloadSpectrograms);
    $("#increaseInterval").click(increaseInterval);
    $("#decreaseInterval").click(decreaseInterval);
    // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
    $('.modal-trigger').leanModal();
});
<commit_msg>add close modal on enter when changing interval<commit_after>"use strict"

/* initialize all canvases */
function initSpectrograms() {
    /* get WebGL context and load required extensions */
    for (var i in IDS) {
        var id = IDS[i];
        SPECTROGRAMS[id] = new Spectrogram(id);
    }
}

function reloadSpectrograms() {
    var patientIdentifier = getElementById("patientIdentifierByMRN").value;
    var fftLen = parseFloat(getElementById("fftLen").value);
    var startTime = parseFloat(getElementById("specStartTime").value);
    var endTime = parseFloat(getElementById("specEndTime").value);
    // first we try to load a file
    if (patientIdentifier) {
        console.log("Requesting spectrogram for: " + patientIdentifier);
        for (var ch = 0; ch < IDS.length; ch++) {
          requestSpectrogram(patientIdentifier, fftLen, startTime, endTime,
            OVERLAP, ch);
        }
    }
    if (!patientIdentifier) {
        console.log("Could not load spectrogram: No file selected");
        return;
    }
}

function setTime(timeId, timeValue) {
    getElementById(timeId).value = parseFloat(timeValue.toFixed(3));
}

function increaseInterval() {
    var interval = parseFloat(getElementById("specInterval").value);
    var specStartTime = parseFloat(getElementById("specStartTime").value);
    var specEndTime = parseFloat(getElementById("specEndTime").value);
    if (specEndTime - specStartTime === interval) {
      setTime("specStartTime", specStartTime + interval);
      setTime("specEndTime", specEndTime + interval);
    } else {
      setTime("specEndTime", specStartTime + interval);
    }
    reloadSpectrograms();
}

function decreaseInterval() {
    var interval = parseFloat(getElementById("specInterval").value);
    var specStartTime = parseFloat(getElementById("specStartTime").value);
    var specEndTime = parseFloat(getElementById("specEndTime").value);
    if (specEndTime - specStartTime === interval) {
      setTime("specStartTime", Math.max(0, specStartTime - interval));
      setTime("specEndTime", Math.max(interval, specEndTime - interval));
    } else {
      setTime("specStartTime", Math.max(0, specStartTime - interval));
    }
    reloadSpectrograms();
}

function testPanning() {
    var mrn = "005";
    var startTime = 0;
    var endTime = 1;
    var interval = 0.5;
    getElementById("patientIdentifierByName").value = mrn;
    var id;

    function pan() {
        getElementById("specStartTime").value = startTime;
        getElementById("specEndTime").value = endTime;
        console.log("startTime: " + startTime + " endTime: " + endTime);
        startTime += interval;
        endTime += interval;
        reloadSpectrograms();
        if (endTime > 70) {
            clearInterval(id);
        }
    }
    id = setInterval(pan, 15 * 1000);
}

/* Test the keyup event for a submission and then reload the spectrogram.
 */
function submitSpectrogram(e) {
    var which = e.which || e.keyCode;
    if (which === 13) {
        reloadSpectrograms();
    }
}

$(document).ready(function() {
    $("body").ready(initSpectrograms);
    $("#patientIdentifierByMRN").keyup(submitSpectrogram);
    $("#specStartTime").keyup(submitSpectrogram);
    $("#specEndTime").keyup(submitSpectrogram);
    $("#fftLen").change(reloadSpectrograms);
    $("#specMode").change(redrawSpectrograms);
    $("#specInterpolation").change(redrawSpectrograms);
    $("#specLogarithmic").change(redrawSpectrograms);
    $("#patientIdentifierMRNSubmit").click(reloadSpectrograms);
    $("#increaseInterval").click(increaseInterval);
    $("#decreaseInterval").click(decreaseInterval);
    // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
    $(".modal-trigger").leanModal();
    $("#specInterval").keyup(function(e) {
      var which = e.which || e.keyCode;
      if (which === 13) {
          $("#settingsModal").closeModal();
      }
    });
});
<|endoftext|>


<commit_before>
import Ember from 'ember';
import Production from 'web/models/production';
import ListResult from 'web/models/listResult';

export default Ember.Service.extend({
  client: Ember.inject.service('client'),
  search:function(){
    const client = this.get('client');
    let results = ListResult.create({childType:Family});

    let searchUrl = '/auditioner/productions';

    client.getResource(searchUrl,results);

    return results;
  },
  loadById:function(productionId)
  {
    const client = this.get('client');
    const url = '/auditioner/productions/' + productionId;

    const production = Production.create();

    production.set('client',client);
    production.set('path',url);

    client.getResource(url,production);

    return production;
  },
  reload:function(production)
  {
    const client = this.get('client');

    client.getResource(production.get('location'),production);

    return production;
  },
  deleteFamily:function(production)
  {
    const client = this.get('client');

    return client.deleteResource(production);
  },
  createProduction:function()
  {
    const client = this.get('client');
    const production = Production.create();
    production.set('client',client);
    return production;
  }

});
<commit_msg>Fix typo<commit_after>
import Ember from 'ember';
import Production from 'web/models/production';
import ListResult from 'web/models/listResult';

export default Ember.Service.extend({
  client: Ember.inject.service('client'),
  search:function(){
    const client = this.get('client');
    let results = ListResult.create({childType:Family});

    let searchUrl = '/auditioner/productions';

    client.getResource(searchUrl,results);

    return results;
  },
  loadById:function(productionId)
  {
    const client = this.get('client');
    const url = '/auditioner/productions/' + productionId;

    const production = Production.create();

    production.set('client',client);
    production.set('path',url);

    client.getResource(url,production);

    return production;
  },
  reload:function(production)
  {
    const client = this.get('client');

    client.getResource(production.get('location'),production);

    return production;
  },
  deleteProduction:function(production)
  {
    const client = this.get('client');

    return client.deleteResource(production);
  },
  createProduction:function()
  {
    const client = this.get('client');
    const production = Production.create();
    production.set('client',client);
    return production;
  }

});
<|endoftext|>


<commit_before>var MongoClient = require('mongodb').MongoClient
// var configDB = require('./../config/database.js')
module.exports = function(app) {
	//require('./module')(app)
}
<commit_msg>Added API route for inserting game data<commit_after>var MongoClient = require('mongodb').MongoClient
var url = "mongodb://localhost:27017/TheOrangeAlliance";
// var configDB = require('./../config/database.js')
module.exports = function(app) {
	app.get('/api', function(req, res) {
		res.send('api home')
	})

	app.post('/api/insert-gamedata', function(req, res) {
		MongoClient.connect(url, function(err, db) {
			if (err) {
				res.status(500).send(err)
			} else {
				db.collection("gameData").insertOne(req.body, function(err, result) {
					if (err) {
						res.status(500).send(err)
					} else {
						console.log("Game Data Inserted");
						db.close();
					}
				});
			}
		});
	})
}<|endoftext|>


<commit_before>/* global Image,document,window,setTimeout,console,XMLHttpRequest,common */

/* jshint loopfunc: true */

var draw = function(canvas, level, objects, xOffset, yOffset) {

    var tileset = level.tilesets[0];

    var tilewidth = tileset.tilewidth;
    var tileheight = tileset.tileheight;
    var imagewidth = tileset.imagewidth;
    var imageheight = tileset.imageheight;

    var tilesPerRow = imagewidth / tilewidth;

    var plaatje = common.resources.tilesets.get(tileset.name);

    var numberOfTilesForHeight = Math.ceil(canvas.height/tileheight) * 2;
    var numberOfTilesForWidth = Math.ceil(canvas.width/tilewidth) * 2 + 2;

    var layer = level.layers[0];
    for (var k = 0 ; k < numberOfTilesForHeight ; k++) {
        for (var j = k-1 ; j < numberOfTilesForWidth + 5 ; j++) {
            var i = k*level.width + j - 5;
            if (i < 0) {
                continue;
            }
            var tileIndex = layer.data[i] - 1;
            var sx = tileIndex % tilesPerRow;
            var sy = (tileIndex - sx) / tilesPerRow;
            var cx = i % layer.width;
            var cy = (i - cx) / layer.width;
            canvas.context.drawImage(plaatje,
                                   sx * tilewidth,
                                   sy * tileheight,
                                   tilewidth,
                                   tileheight,
                                   0.5*(cx-cy+5)*tilewidth,
                                   0.5*(cx+cy)*tileheight,
                                   tilewidth,
                                   tileheight
                                );
        }
    }
};<commit_msg>draw with offsets<commit_after>/* global Image,document,window,setTimeout,console,XMLHttpRequest,common */

/* jshint loopfunc: true */

var draw = function(canvas, level, objects) {
    canvas.context.clearRect(0, 0, canvas.width, canvas.height);

    var tileset = level.tilesets[0];

    var tilewidth = tileset.tilewidth;
    var tileheight = tileset.tileheight;
    var imagewidth = tileset.imagewidth;
    var imageheight = tileset.imageheight;

    var tilesPerRow = imagewidth / tilewidth;

    var plaatje = common.resources.tilesets.get(tileset.name);

    var tileXOffset = Math.floor(canvas.xOffset/32);
    var tileYOffset = Math.floor(canvas.yOffset/32);

    var numberOfTilesForHeight = Math.ceil(canvas.height/tileheight);
    var numberOfTilesForWidth = Math.ceil(canvas.width/tilewidth) * 2;

    var layer = level.layers[0];
    for (var k = tileYOffset - Math.floor(tileXOffset/2) - numberOfTilesForHeight ; k < tileYOffset - Math.floor(tileXOffset/2) + numberOfTilesForHeight  ; k++) {
        for (var j = k-1+tileXOffset ; j < numberOfTilesForWidth + k + tileXOffset + 1 ; j++) {
    //for (var k = 0; k < 200  ; k++) {
    //    for (var j = 0 ; j < 200 ; j++) {
            var i = k*level.width + j;
            if (i < 0) {
                continue;
            }
            var tileIndex = layer.data[i] - 1;
            var sx = tileIndex % tilesPerRow;
            var sy = (tileIndex - sx) / tilesPerRow;
            var cx = i % layer.width;
            var cy = (i - cx) / layer.height;
            canvas.context.drawImage(plaatje,
                                   sx * tilewidth,
                                   sy * tileheight,
                                   tilewidth,
                                   tileheight,
                                   0.5*(cx-cy)*tilewidth-0.5*(canvas.xOffset/32)*tilewidth,
                                   0.5*(cx+cy)*tileheight-(canvas.yOffset/32)*tileheight,
                                   tilewidth,
                                   tileheight
                                );
        }
    }
};<|endoftext|>


<commit_before>const qs = require('qs');
const hlpr = require('../lib/helpers');

const Activities = require('./activities');
const User = require('../models/user');

const logObj = {
  file: 'controllers/webhooks',
  logType: 'controller',
  level: 10,
};

/**
* will receive GET query string
*
* ?hub.mode=subscribe
* &hub.challenge=15f7d1a91c1f40f8a748fd134752feb3
* &hub.verify_token=STRAVA
*/
exports.stravaGetReceiver = (req, res) => {
  const q = qs.parse(req.query);
  if (process.env.STRAVA_VERIFY_TOKEN !== '' && q['hub.verify_token'] === process.env.STRAVA_VERIFY_TOKEN) {
    hlpr.logOutArgs(`${logObj.file}.stravaGetReceiver`, logObj.logType, 'success', 1, null, null, `stravaGetReceiver subscribing success local verify_token: ${process.env.STRAVA_VERIFY_TOKEN}, recieved verify_token: ${q['hub.verify_token']}`);
    return res.send({ 'hub.challenge': q['hub.challenge'] });
  }
  hlpr.logOutArgs(`${logObj.file}.stravaGetReceiver 403`, logObj.logType, 'failure', 1, null, null, `stravaGetReceiver subscribing failure ${JSON.stringify(q)}`);
  return res.status(403).send({ error: 'Faild to verify token' });
};

/**
* will receive POST body
*
req.body = {
  "aspect_type": "update", // Always "create," "update," or "delete."
  "event_time": 1516126040,
  "object_id": 1360128428,
  "object_type": "activity",
  "owner_id": 134815,
  "subscription_id": 120475,
  "updates": { // Empty for delete and create events.
    "title": "Messy",
    "type": "",
    "private": false, // Always true or false
  }
}
*/

const postProcessor = (input, done) => {
  if (input.object_type === 'activity') {
    User.findOne({ stravaId: input.owner_id * 1 }, (err, user) => {
      if (err || !user) {
        hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'error', 4, null, null, 'No User');
        return done;
      }
      if (user.stravaId && user.clubMember) {
        const options = {
          id: user.stravaId,
          activityId: input.object_id,
          access_token: user.access_token,
          user,
        };
        const activity = { activityId: input.object_id };
        const toDelete = {
          activityId: input.object_id,
          'athlete.id': user.stravaId,
        };
        switch (input.aspect_type) {
          case 'create':
            return Activities.getActivityDetails(activity, options, (cDone) => {
              hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'success', 8, null, null, `Starting Activities.getActivityDetails ${input}`);
              return cDone;
            });
          case 'update':
            return Activities.getActivityUpdate(activity, options, (cDone) => {
              hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'success', 8, null, null, `Starting Activities.getActivityDetails ${input}`);
              return cDone;
            });
          case 'delete':
            return Activities.removeActivity(toDelete, rDone => rDone);
          default:
            hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'error', 4, null, null, 'Missed Cases');
        }
      } else {
        hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'error', 8, null, null, `Not a user or not clubMember ${user.stravaId}`);
      }
    });
    hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'error', 6, null, null, `Not an activity for user ${input.owner_id}`);
  }
  return done;
};

exports.stravaPostReceiver = (req, res) => {
  postProcessor(req.body, logThis => logThis);
  res.sendStatus(200);
};
<commit_msg>fine tuning error messages for strava webhooks<commit_after>const qs = require('qs');
const hlpr = require('../lib/helpers');

const Activities = require('./activities');
const User = require('../models/user');

const logObj = {
  file: 'controllers/webhooks',
  logType: 'controller',
  level: 10,
};

/**
* will receive GET query string
*
* ?hub.mode=subscribe
* &hub.challenge=15f7d1a91c1f40f8a748fd134752feb3
* &hub.verify_token=STRAVA
*/
exports.stravaGetReceiver = (req, res) => {
  const q = qs.parse(req.query);
  const mssg = `stravaGetReceiver subscribing - local verify_token: ${process.env.STRAVA_VERIFY_TOKEN}, recieved verify_token: ${q['hub.verify_token']}`;
  if (process.env.STRAVA_VERIFY_TOKEN !== '' && q['hub.verify_token'] === process.env.STRAVA_VERIFY_TOKEN) {
    hlpr.logOutArgs(`${logObj.file}.stravaGetReceiver`, logObj.logType, 'success', 1, null, null, mssg);
    return res.send({ 'hub.challenge': q['hub.challenge'] });
  }
  hlpr.logOutArgs(`${logObj.file}.stravaGetReceiver 403`, logObj.logType, 'failure', 1, null, null, mssg);
  return res.status(403).send({ error: 'Faild to verify token' });
};

/**
* will receive POST body
*
req.body = {
  "aspect_type": "update", // Always "create," "update," or "delete."
  "event_time": 1516126040,
  "object_id": 1360128428,
  "object_type": "activity",
  "owner_id": 134815,
  "subscription_id": 120475,
  "updates": { // Empty for delete and create events.
    "title": "Messy",
    "type": "",
    "private": false, // Always true or false
  }
}
*/

const postProcessor = (input, done) => {
  if (input.object_type === 'activity') {
    User.findOne({ stravaId: input.owner_id * 1 }, (err, user) => {
      if (err || !user) {
        hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'error', 4, null, null, 'No User');
        return done;
      }
      if (user.stravaId && user.clubMember) {
        const options = {
          id: user.stravaId,
          activityId: input.object_id,
          access_token: user.access_token,
          user,
        };
        const activity = { activityId: input.object_id };
        const toDelete = {
          activityId: input.object_id,
          'athlete.id': user.stravaId,
        };
        switch (input.aspect_type) {
          case 'create':
            return Activities.getActivityDetails(activity, options, (cDone) => {
              hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'success', 8, null, null, `Starting Activities.getActivityDetails ${input}`);
              return cDone;
            });
          case 'update':
            return Activities.getActivityUpdate(activity, options, (cDone) => {
              hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'success', 8, null, null, `Starting Activities.getActivityDetails ${input}`);
              return cDone;
            });
          case 'delete':
            return Activities.removeActivity(toDelete, rDone => rDone);
          default:
            hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'error', 4, null, null, 'Missed Cases');
        }
      } else {
        hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'error', 8, null, null, `Not a user or not clubMember ${user.stravaId}`);
      }
    });
    hlpr.logOutArgs(`${logObj.file}.stravaPostReceiver`, logObj.logType, 'error', 6, null, null, `Not an activity for user ${input.owner_id}`);
  }
  return done;
};

exports.stravaPostReceiver = (req, res) => {
  postProcessor(req.body, logThis => logThis);
  res.sendStatus(200);
};
<|endoftext|>


<commit_before>// This is the runtime configuration file.  It complements the Gruntfile.js by
// supplementing shared properties.
Packages = undefined;

require.config({
  paths: {
    "vendor": "../vendor",
    "almond": "../vendor/bower/almond/almond",
    "underscore": "../vendor/bower/lodash/dist/lodash.underscore",
    "jquery": "../vendor/bower/jquery/dist/jquery",
    "backbone": "../vendor/bower/backbone/backbone",
	"bootstrap": "../vendor/bower/bootstrap/dist/js/bootstrap",
	"templates": "templates",
	"text" : "../vendor/bower/requirejs-text/text",
	"flexslider":"lib/woothemes-FlexSlider-7ecc526/jquery.flexslider-min"
  }
});
<commit_msg>shim config<commit_after>// This is the runtime configuration file.  It complements the Gruntfile.js by
// supplementing shared properties.
Packages = undefined;

require.config({
  paths: {
    "vendor": "../vendor",
    "almond": "../vendor/bower/almond/almond",
    "underscore": "../vendor/bower/lodash/dist/lodash.underscore",
    "jquery": "../vendor/bower/jquery/dist/jquery",
    "backbone": "../vendor/bower/backbone/backbone",
	"bootstrap": "../vendor/bower/bootstrap/dist/js/bootstrap",
	"templates": "templates",
	"text" : "../vendor/bower/requirejs-text/text",
	"flexslider":"lib/woothemes-FlexSlider-7ecc526/jquery.flexslider-min"
  },
  shim:{
    'flexslider':{
      deps:['jquery']
    },
    'jquery':{
      exports:'jQuery'
    }
  }
});
<|endoftext|>


<commit_before>var path = require('path');
var config = require('../config');
//static page
//about
exports.about = function (req, res, next) {
    res.render('static/about', {
        title: '关于'
    });
};

//FAQ
exports.faq = function (req, res, next) {
    res.render('static/faq', {
        title: 'FAQ'
    });
};

exports.robots = function (req, res, next) {
    res.type('text/plain');
    res.send('User-Agent: * \r\n Disallow: /');
};

exports.favicon = function (req, res, next) {
    res.sendFile(path.join(__dirname, "..", "public", "favicon.ico"));
};

exports.jdRoot = function (req, res, next) {
    res.send(confog.jdRoot);
};<commit_msg>fix text error<commit_after>var path = require('path');
var config = require('../config');
//static page
//about
exports.about = function (req, res, next) {
    res.render('static/about', {
        title: '关于'
    });
};

//FAQ
exports.faq = function (req, res, next) {
    res.render('static/faq', {
        title: 'FAQ'
    });
};

exports.robots = function (req, res, next) {
    res.type('text/plain');
    res.send('User-Agent: * \r\n Disallow: /');
};

exports.favicon = function (req, res, next) {
    res.sendFile(path.join(__dirname, "..", "public", "favicon.ico"));
};

exports.jdRoot = function (req, res, next) {
    res.send(config.jdRoot);
};<|endoftext|>


<commit_before>import axios from "../../utils/APIHelper";
import { combineReducers } from "redux";
import { createAction } from "redux-actions";

import normalize from "../../utils/normalize";

export const FETCH_ENTRIES      = "FETCH_ENTRIES";
export const FETCH_MORE_ENTRIES = "FETCH_MORE_ENTRIES";
export const REFRESH_ENTRIES    = "REFRESH_ENTRIES";
export const UPDATE_ENTRY       = "UPDATE_ENTRY";
export const MARK_ALL_ENTRIES_AS_READ = "MARK_ALL_ENTRIES_AS_READ";

export const fetchEntries     = createAction(FETCH_ENTRIES);
export const fetchMoreEntries = createAction(FETCH_MORE_ENTRIES);
export const refreshEntries   = createAction(REFRESH_ENTRIES);
export const updateEntry      = createAction(UPDATE_ENTRY);
export const markAllEntriesAsRead = createAction(MARK_ALL_ENTRIES_AS_READ);

export function requestMarkEntryAsRead(entry) {
  return dispatch => {
    return axios.put(`/api/entries/${entry.id}/mark_as_read`)
    .then(() => {
      dispatch(updateEntry({ id: entry.id, unread: false}));
    })
    .catch((response) => {
      dispatch(updateEntry(new Error(response.data.error)));
    });
  };
}

export function requestMarkAllEntriesAsRead(params) {
  return dispatch => {
    return axios.put("/api/entries/mark_all_as_read", params)
    .then(() => {
      dispatch(markAllEntriesAsRead(params));
    })
    .catch((response) => {
      dispatch(markAllEntriesAsRead(new Error(response.data.error)));
    });
  };
}

export function requestFetchEntries(options = {}) {
  return dispatch => {
    const params = Object.assign({}, options, { limit: 20 });
    dispatch(fetchEntries());

    return axios.get("/api/entries", { params: params })
    .then(response => {
      dispatch(fetchEntries({
        ...normalize(response.data.entries),
        hasMoreEntries: response.data.entries.length === params.limit
      }));
    })
    .catch((response) => {
      dispatch(fetchEntries(new Error(response.data.error)));
    });
  };
}

export function requestFetchMoreEntries(options = {}) {
  return dispatch => {
    const params = Object.assign({}, options, { limit: 20 });
    dispatch(fetchMoreEntries());

    return axios.get("/api/entries", { params: params })
    .then(response => {
      dispatch(fetchMoreEntries({
        ...normalize(response.data.entries),
        hasMoreEntries: response.data.entries.length === params.limit
      }));
      return Promise.resolve();
    })
    .catch((response) => {
      dispatch(fetchMoreEntries(new Error(response.data.error)));
      return Promise.reject();
    });
  };
}

export function requestLoadMore(requestParams) {
  return (dispatch, getState) => {
    const entries = getState().entries;

    if (entries.hasMoreEntries && !entries.isLoading) {
      const entryId = entries.listedIds[entries.listedIds.length-1];
      let oldestPublishedEntry = entries.byId[entryId].published;
      let params = { ...requestParams, last_published: oldestPublishedEntry };

      return dispatch(requestFetchMoreEntries(params));
    }

    return Promise.resolve();
  };
}

export function requestRefreshEntries(options = {}) {
  return dispatch => {
    const params = Object.assign(options, {});
    dispatch(refreshEntries());

    return axios.put("/api/entries/refresh", params)
    .then(() => {
      dispatch(refreshEntries({}));
      dispatch(requestFetchEntries(options));
    })
    .catch((response) => {
      dispatch(refreshEntries(new Error(response.data.error)));
    });
  };
}

const initialById = {};
const initialListedIds  = [];
const initialIsLoading = false;
const initialError = null;
const initialHasMoreEntries = false;

function hasMoreEntries(state = initialHasMoreEntries, action) {
  if (!action.payload) return state;

  switch (action.type) {
  case FETCH_ENTRIES:
  case FETCH_MORE_ENTRIES:
    return action.payload.hasMoreEntries ? true : false;
  default:
    return state;
  }
}

function isLoading(state = initialIsLoading, action) {
  switch (action.type) {
  case FETCH_ENTRIES:
  case FETCH_MORE_ENTRIES:
  case REFRESH_ENTRIES:
    return !action.payload ? true : false;
  default:
    return state;
  }
}

function error(state = initialError, action) {
  switch (action.type) {
  case UPDATE_ENTRY:
  case FETCH_ENTRIES:
  case FETCH_MORE_ENTRIES:
    return action.error ? action.payload : state;
  default:
    return state;
  }
}

function entryReducer(state, action) {
  if (!action.payload) return state;
  if (action.error) return state;

  switch (action.type) {
  case UPDATE_ENTRY:
    return { ...state, ...action.payload };
  default:
    return state;
  }
}

function listedIds(state = initialListedIds, action) {
  if (!action.payload) return state;
  if (action.error) return state;

  switch (action.type) {
  case FETCH_ENTRIES:
    return action.payload.ids;
  case FETCH_MORE_ENTRIES:
    return [...state, ...action.payload.ids];
  case REFRESH_ENTRIES:
    return state;
  default:
    return state;
  }
}

function byId(state = initialById, action) {
  if (!action.payload) return state;
  if (action.error) return state;

  switch (action.type) {
  case UPDATE_ENTRY:
    return {
      ...state,
      [action.payload.id]: entryReducer(state[action.payload.id], action)
    };
  case REFRESH_ENTRIES:
    return state;
  case FETCH_ENTRIES:
    return action.payload.entities;
  case FETCH_MORE_ENTRIES:
    return {...state, ...action.payload.entities};
  case MARK_ALL_ENTRIES_AS_READ:
    if (action.payload.feed_id === "all") {
      return Object.keys(state).reduce((nextState, id) => {
        nextState[id] = { ...state[id], unread: false };
        return nextState;
      }, {});
    } else if (action.payload.feed_id === "today") {
      const startOfToday = new Date();
      startOfToday.setHours(0, 0, 0, 0);
      const endOfToday = new Date();
      endOfToday.setDate(endOfToday.getDate()+1);
      endOfToday.setHours(0, 0, 0, 0);

      return Object.keys(state).reduce((nextState, id) => {
        const publishedDate = state[id].published instanceof Date
          ? state[id].published
          : new Date(state[id].published);
        publishedDate.setHours(0, 0, 0, 0);

        if (publishedDate >= startOfToday && publishedDate < endOfToday) {
          nextState[id] = { ...state[id], unread: false };
        } else {
          nextState[id] = state[id];
        }
        return nextState;
      }, {});
    } else if (action.payload.feed_id) {
      return Object.keys(state).reduce((nextState, id) => {
        if (state[id].feed.id === action.payload.feed_id) {
          nextState[id] = { ...state[id], unread: false };
        } else {
          nextState[id] = state[id];
        }
        return nextState;
      }, {});
    } else if (action.payload.category_id) {
      return Object.keys(state).reduce((nextState, id) => {
        if (state[id].feed.category_id === action.payload.category_id) {
          nextState[id] = { ...state[id], unread: false };
        } else {
          nextState[id] = state[id];
        }
        return nextState;
      }, {});
    }
    return state;
  default:
    return state;
  }
}

export default combineReducers({ byId, listedIds, isLoading, error, hasMoreEntries });
<commit_msg>refactor entries request functions<commit_after>import axios from "../../utils/APIHelper";
import { combineReducers } from "redux";
import { createAction } from "redux-actions";

import normalize from "../../utils/normalize";

export const FETCH_ENTRIES      = "FETCH_ENTRIES";
export const FETCH_MORE_ENTRIES = "FETCH_MORE_ENTRIES";
export const REFRESH_ENTRIES    = "REFRESH_ENTRIES";
export const UPDATE_ENTRY       = "UPDATE_ENTRY";
export const MARK_ALL_ENTRIES_AS_READ = "MARK_ALL_ENTRIES_AS_READ";

export const fetchEntries     = createAction(FETCH_ENTRIES);
export const fetchMoreEntries = createAction(FETCH_MORE_ENTRIES);
export const refreshEntries   = createAction(REFRESH_ENTRIES);
export const updateEntry      = createAction(UPDATE_ENTRY);
export const markAllEntriesAsRead = createAction(MARK_ALL_ENTRIES_AS_READ);

export function requestMarkEntryAsRead(entry) {
  return dispatch => {
    dispatch(updateEntry());
    return axios.put(`/api/entries/${entry.id}/mark_as_read`)
      .then(() => dispatch(updateEntry({ id: entry.id, unread: false })))
      .catch(e => dispatch(updateEntry(e)));
  };
}

export function requestMarkAllEntriesAsRead(params) {
  return dispatch => {
    dispatch(markAllEntriesAsRead());
    return axios.put("/api/entries/mark_all_as_read", params)
      .then(() => dispatch(markAllEntriesAsRead(params)))
      .catch(e => dispatch(markAllEntriesAsRead(e)));
  };
}

export function requestFetchEntries(options = {}) {
  return dispatch => {
    const params = { ...options, limit: 20 };
    dispatch(fetchEntries());

    return axios.get("/api/entries", { params: params })
      .then(response => {
        dispatch(fetchEntries({
          ...normalize(response.data.entries),
          hasMoreEntries: response.data.entries.length === params.limit
        }));
      })
      .catch(e => dispatch(fetchEntries(e)));
  };
}

export function requestFetchMoreEntries(options = {}) {
  return dispatch => {
    const params = { ...options, limit: 20 };
    dispatch(fetchMoreEntries());

    return axios.get("/api/entries", { params: params })
      .then(response =>
          dispatch(fetchMoreEntries({
            ...normalize(response.data.entries),
            hasMoreEntries: response.data.entries.length === params.limit
          }))
      )
      .catch(e => dispatch(fetchMoreEntries(e)));
  };
}

export function requestLoadMore(requestParams) {
  return (dispatch, getState) => {
    const entries = getState().entries;

    if (entries.hasMoreEntries && !entries.isLoading) {
      const entryId = entries.listedIds[entries.listedIds.length-1];
      let oldestPublishedEntry = entries.byId[entryId].published;
      let params = { ...requestParams, last_published: oldestPublishedEntry };

      return dispatch(requestFetchMoreEntries(params));
    }

    return Promise.resolve();
  };
}

export function requestRefreshEntries(options = {}) {
  return dispatch => {
    const params = Object.assign(options, {});
    dispatch(refreshEntries());

    return axios.put("/api/entries/refresh", params)
    .then(() => {
      dispatch(refreshEntries({}));
    })
    .catch((response) => {
      dispatch(refreshEntries(new Error(response.data.error)));
    });
  };
}

const initialById = {};
const initialListedIds  = [];
const initialIsLoading = false;
const initialError = null;
const initialHasMoreEntries = false;

function hasMoreEntries(state = initialHasMoreEntries, action) {
  if (!action.payload) return state;

  switch (action.type) {
  case FETCH_ENTRIES:
  case FETCH_MORE_ENTRIES:
    return action.payload.hasMoreEntries ? true : false;
  default:
    return state;
  }
}

function isLoading(state = initialIsLoading, action) {
  switch (action.type) {
  case FETCH_ENTRIES:
  case FETCH_MORE_ENTRIES:
  case REFRESH_ENTRIES:
    return !action.payload ? true : false;
  default:
    return state;
  }
}

function error(state = initialError, action) {
  switch (action.type) {
  case UPDATE_ENTRY:
  case FETCH_ENTRIES:
  case FETCH_MORE_ENTRIES:
    return action.error ? action.payload : state;
  default:
    return state;
  }
}

function entryReducer(state, action) {
  if (!action.payload) return state;
  if (action.error) return state;

  switch (action.type) {
  case UPDATE_ENTRY:
    return { ...state, ...action.payload };
  default:
    return state;
  }
}

function listedIds(state = initialListedIds, action) {
  if (!action.payload) return state;
  if (action.error) return state;

  switch (action.type) {
  case FETCH_ENTRIES:
    return action.payload.ids;
  case FETCH_MORE_ENTRIES:
    return [...state, ...action.payload.ids];
  case REFRESH_ENTRIES:
    return state;
  default:
    return state;
  }
}

function byId(state = initialById, action) {
  if (!action.payload) return state;
  if (action.error) return state;

  switch (action.type) {
  case UPDATE_ENTRY:
    return {
      ...state,
      [action.payload.id]: entryReducer(state[action.payload.id], action)
    };
  case REFRESH_ENTRIES:
    return state;
  case FETCH_ENTRIES:
    return action.payload.entities;
  case FETCH_MORE_ENTRIES:
    return {...state, ...action.payload.entities};
  case MARK_ALL_ENTRIES_AS_READ:
    if (action.payload.feed_id === "all") {
      return Object.keys(state).reduce((nextState, id) => {
        nextState[id] = { ...state[id], unread: false };
        return nextState;
      }, {});
    } else if (action.payload.feed_id === "today") {
      const startOfToday = new Date();
      startOfToday.setHours(0, 0, 0, 0);
      const endOfToday = new Date();
      endOfToday.setDate(endOfToday.getDate()+1);
      endOfToday.setHours(0, 0, 0, 0);

      return Object.keys(state).reduce((nextState, id) => {
        const publishedDate = state[id].published instanceof Date
          ? state[id].published
          : new Date(state[id].published);
        publishedDate.setHours(0, 0, 0, 0);

        if (publishedDate >= startOfToday && publishedDate < endOfToday) {
          nextState[id] = { ...state[id], unread: false };
        } else {
          nextState[id] = state[id];
        }
        return nextState;
      }, {});
    } else if (action.payload.feed_id) {
      return Object.keys(state).reduce((nextState, id) => {
        if (state[id].feed.id === action.payload.feed_id) {
          nextState[id] = { ...state[id], unread: false };
        } else {
          nextState[id] = state[id];
        }
        return nextState;
      }, {});
    } else if (action.payload.category_id) {
      return Object.keys(state).reduce((nextState, id) => {
        if (state[id].feed.category_id === action.payload.category_id) {
          nextState[id] = { ...state[id], unread: false };
        } else {
          nextState[id] = state[id];
        }
        return nextState;
      }, {});
    }
    return state;
  default:
    return state;
  }
}

export default combineReducers({ byId, listedIds, isLoading, error, hasMoreEntries });
<|endoftext|>


<commit_before>Vps.Auto.FormPanel = Ext.extend(Vps.Auto.AbstractPanel, {
    autoload: true,
    autoScroll: true, //um scrollbars zu bekommen
    border: false,
    formConfig: {},
    maskDisabled: true,
    layout: 'fit',

    initComponent: function()
    {
        if (!this.actions) this.actions = {};
        if (!this.baseParams) this.baseParams = {};

        this.addEvents(
            'loadform',
            'deleteaction',
            'addaction',
            'renderform'
        );

        Vps.Auto.FormPanel.superclass.initComponent.call(this);

        if (!this.formConfig) this.formConfig = {};
        Ext.applyIf(this.formConfig, {
            baseParams       : {},
            trackResetOnLoad : true,
            maskDisabled     : false,
            autoScroll       : true
        });

        if (!this.controllerUrl) {
            throw new Error('No controllerUrl specified for AutoForm.');
        }
        this.formConfig.url = this.controllerUrl + '/jsonSave';

        if (this.autoload) {
            this.load();
        }
    },

    onMetaChange : function(meta)
    {
        Ext.applyIf(meta.form, this.formConfig);

        if (this.baseCls) meta.form.baseCls = this.baseCls; //use the same

        for (var i in this.actions) {
            if (!meta.permissions[i]) {
                this.getAction(i).hide();
            }
        }

        if (meta.buttons && typeof meta.form.tbar == 'undefined') {
            for (var b in meta.buttons) {
                if (!meta.form.tbar) meta.form.tbar = [];
                meta.form.tbar.push(this.getAction(b));
            }
        }
        if (this.formPanel != undefined) {
            this.remove(this.formPanel, true);
        }

        this.formPanel = new Ext.FormPanel(meta.form);
        this.formPanel.on('render', function() {
            this.fireEvent('renderform', this.getForm());
        }, this);
        this.add(this.formPanel);
        this.doLayout();
        this.getForm().baseParams = this.baseParams;
    },

    isDirty : function() {
        return this.getForm().isDirty();
    },

    getAction : function(type)
    {
        if (this.actions[type]) return this.actions[type];

        if (type == 'save') {
            this.actions[type] = new Ext.Action({
                text    : 'Save',
                icon    : '/assets/silkicons/table_save.png',
                cls     : 'x-btn-text-icon',
                handler : function() {
                    this.onSave();
                },
                scope   : this
            });
        } else if (type == 'delete') {
            this.actions[type] = new Ext.Action({
                text    : 'Delete',
                icon    : '/assets/silkicons/table_delete.png',
                cls     : 'x-btn-text-icon',
                handler : this.onDelete,
                scope   : this
            });
        } else if (type == 'add') {
            this.actions[type] = new Ext.Action({
                text    : 'New Entry',
                icon    : '/assets/silkicons/table_add.png',
                cls     : 'x-btn-text-icon',
                handler : this.onAdd,
                scope   : this
            });
        } else {
            throw 'unknown action-type: ' + type;
        }
        return this.actions[type];
    },

    load : function(params) {
        if (this.el) this.el.mask('Loading...');

        if (!params) params = {};

        //es kann auch direkt die id übergeben werden
        if (typeof params != 'object') params = { id: params };

        if (!this.getForm()) {
            params.meta = true; //wenn noch keine form vorhanden metaDaten anfordern
        }
        Ext.applyIf(params, this.baseParams);

        if (this.getForm()) {
            this.getForm().clearValues();
            this.getForm().clearInvalid();
        }

        Ext.Ajax.request({
            mask: !this.el, //globale mask wenn kein el vorhanden
            url: this.controllerUrl+'/jsonLoad',
            params: params,
            success: function(response, options, result) {
                if (result.meta) {
                    this.onMetaChange(result.meta);
                }
                if (result.data && this.getForm()) {
                    if (this.actions['delete']) this.actions['delete'].enable();
                    this.fireEvent('loadform', this.getForm(), result.data);
//                     if (this.getForm()) {
                        this.getForm().setValues(result.data);
//todo: werte zwischenspeichern und setzen wenn form gerendered wurde?
//erstmal auskommentiert, da das eher nach hack aussschaut und womöglich eh gar nicht gebraucht wird...
//                     } else {
//                         this.on('renderform', function(form) {
//                             form.setValues(this.data);
//                             form.resetDirty();
//                         }, result);
//                     }
                }
                if (this.getForm()) {
                    this.getForm().clearInvalid();
                    this.getForm().resetDirty();
                }
            },
            callback: function() {
                if (this.el) this.el.unmask();
            },
            scope: this
        });
    },

    //für AbstractPanel
    reset : function() {
        this.getForm().reset();
    },

    //deprecated
    onSubmit : function(options, successCallback) {
        if (!options) options = {};
        options.success = successCallback.callback;
        this.submit(options, successCallback);
    },

    //private
    onSave : function() {
        this.submit();
    },

    //für AbstractPanel
    submit: function(options)
    {
        this.getAction('save').disable();
        if (!options) options = {};

        var cb = {
            success: options.success,
            failure: options.failure,
            callback: options.callback,
            scope: options.scope || this
        };

        this.getForm().waitMsgTarget = this.el;
        this.getForm().submit(Ext.apply(options, {
            url: this.controllerUrl+'/jsonSave',
            waitMsg: 'saving...',
            success: function() {
                this.onSubmitSuccess.apply(this, arguments);
                if (cb.success) {
                    cb.success.apply(cb.scope, arguments)
                }
            },
            failure: function() {
                this.onSubmitFailure.apply(this, arguments);
                if (cb.failure) {
                    cb.failure.apply(cb.scope, arguments)
                }
            },
            callback: function() {
                if (cb.callback) {
                    cb.callback.apply(cb.scope, arguments)
                }
            },
            scope: this
        }));
    },
    onSubmitFailure: function(form, action) {
        if(action.failureType == Ext.form.Action.CLIENT_INVALID) {
            Ext.Msg.alert('Speichern', 'Es konnte nicht gespeichert werden, bitte alle Felder korrekt ausfüllen.');
        }
        this.getAction('save').enable();
    },

    onSubmitSuccess: function(form, action) {
        this.getForm().resetDirty();
        this.fireEvent('datachange', action.result);

        var reEnableSubmitButton = function() {
            this.getAction('save').enable();
        };
        reEnableSubmitButton.defer(1000, this);

        if(action.result && action.result.data && action.result.data.addedId) {
            this.getForm().baseParams.id = action.result.data.addedId;
            this.getAction('delete').enable();
            this.getAction('save').enable();
        }
        if (this.getForm().loadAfterSave) {
            //bei file-upload neu laden
            this.reload();
        }
    },
    onDelete : function() {
        Ext.Msg.show({
        title:'löschen?',
        msg: 'Möchten Sie diesen Eintrag wirklich löschen?',
        buttons: Ext.Msg.YESNO,
        scope: this,
        fn: function(button) {
            if (button == 'yes') {

                Ext.Ajax.request({
                        url: this.controllerUrl+'/jsonDelete',
                        params: {id: this.getForm().baseParams.id},
                        success: function(response, options, r) {
                            this.fireEvent('datachange', r);
                            this.getForm().clearValues();
                            this.getForm().clearInvalid();
                            this.disable();
                            this.fireEvent('deleteaction', this);
                        },
                        scope: this
                    });
            }
        }
        });
    },
    onAdd : function() {
        if (!this.getForm()) this.load(); //meta-daten wurden noch nicht geladen

        this.mabySave({
            callback: function() {
                this.enable();
                if (this.deleteButton) this.deleteButton.disable();
                this.getAction('delete').disable();
                this.applyBaseParams({id: 0});
                if (this.getForm()) {
                    this.getForm().setDefaultValues();
                    this.getForm().clearInvalid();
                }
                this.fireEvent('addaction', this);
            },
            scope: this
        });
    },
    findField: function(id) {
        return this.getForm().findField(id);
    },
    getForm : function() {
        if (!this.getFormPanel()) return null;
        return this.getFormPanel().getForm();
    },
    getFormPanel : function() {
        return this.formPanel;
    },
    setBaseParams : function(baseParams) {
        this.baseParams = baseParams;
        if (this.getForm()) {
            this.getForm().baseParams = baseParams;
        }
    },
    applyBaseParams : function(baseParams) {
        Ext.apply(this.baseParams, baseParams);
        if (this.getForm()) {
            Ext.apply(this.getForm().baseParams, baseParams);
        }
    },
    getBaseParams : function() {
        return this.baseParams;
    }
});

Ext.reg('autoform', Vps.Auto.FormPanel);
<commit_msg>Bugfix - id fehlte beim speichern in autoform<commit_after>Vps.Auto.FormPanel = Ext.extend(Vps.Auto.AbstractPanel, {
    autoload: true,
    autoScroll: true, //um scrollbars zu bekommen
    border: false,
    formConfig: {},
    maskDisabled: true,
    layout: 'fit',

    initComponent: function()
    {
        if (!this.actions) this.actions = {};
        if (!this.baseParams) this.baseParams = {};

        this.addEvents(
            'loadform',
            'deleteaction',
            'addaction',
            'renderform'
        );

        Vps.Auto.FormPanel.superclass.initComponent.call(this);

        if (!this.formConfig) this.formConfig = {};
        Ext.applyIf(this.formConfig, {
            baseParams       : {},
            trackResetOnLoad : true,
            maskDisabled     : false,
            autoScroll       : true
        });

        if (!this.controllerUrl) {
            throw new Error('No controllerUrl specified for AutoForm.');
        }
        this.formConfig.url = this.controllerUrl + '/jsonSave';

        if (this.autoload) {
            this.load();
        }
    },

    onMetaChange : function(meta)
    {
        Ext.applyIf(meta.form, this.formConfig);

        if (this.baseCls) meta.form.baseCls = this.baseCls; //use the same

        for (var i in this.actions) {
            if (!meta.permissions[i]) {
                this.getAction(i).hide();
            }
        }

        if (meta.buttons && typeof meta.form.tbar == 'undefined') {
            for (var b in meta.buttons) {
                if (!meta.form.tbar) meta.form.tbar = [];
                meta.form.tbar.push(this.getAction(b));
            }
        }
        if (this.formPanel != undefined) {
            this.remove(this.formPanel, true);
        }

        this.formPanel = new Ext.FormPanel(meta.form);
        this.formPanel.on('render', function() {
            this.fireEvent('renderform', this.getForm());
        }, this);
        this.add(this.formPanel);
        this.doLayout();
        this.getForm().baseParams = this.baseParams;
    },

    isDirty : function() {
        return this.getForm().isDirty();
    },

    getAction : function(type)
    {
        if (this.actions[type]) return this.actions[type];

        if (type == 'save') {
            this.actions[type] = new Ext.Action({
                text    : 'Save',
                icon    : '/assets/silkicons/table_save.png',
                cls     : 'x-btn-text-icon',
                handler : function() {
                    this.onSave();
                },
                scope   : this
            });
        } else if (type == 'delete') {
            this.actions[type] = new Ext.Action({
                text    : 'Delete',
                icon    : '/assets/silkicons/table_delete.png',
                cls     : 'x-btn-text-icon',
                handler : this.onDelete,
                scope   : this
            });
        } else if (type == 'add') {
            this.actions[type] = new Ext.Action({
                text    : 'New Entry',
                icon    : '/assets/silkicons/table_add.png',
                cls     : 'x-btn-text-icon',
                handler : this.onAdd,
                scope   : this
            });
        } else {
            throw 'unknown action-type: ' + type;
        }
        return this.actions[type];
    },

    load : function(params) {
        if (this.el) this.el.mask('Loading...');

        if (!params) params = {};

        //es kann auch direkt die id übergeben werden
        if (typeof params != 'object') params = { id: params };

        this.applyBaseParams(params);

        if (!this.getForm()) {
            params.meta = true; //wenn noch keine form vorhanden metaDaten anfordern
        }
        Ext.applyIf(params, this.baseParams);

        if (this.getForm()) {
            this.getForm().clearValues();
            this.getForm().clearInvalid();
        }

        Ext.Ajax.request({
            mask: !this.el, //globale mask wenn kein el vorhanden
            url: this.controllerUrl+'/jsonLoad',
            params: params,
            success: function(response, options, result) {
                if (result.meta) {
                    this.onMetaChange(result.meta);
                }
                if (result.data && this.getForm()) {
                    if (this.actions['delete']) this.actions['delete'].enable();
                    this.fireEvent('loadform', this.getForm(), result.data);
//                     if (this.getForm()) {
                        this.getForm().setValues(result.data);
//todo: werte zwischenspeichern und setzen wenn form gerendered wurde?
//erstmal auskommentiert, da das eher nach hack aussschaut und womöglich eh gar nicht gebraucht wird...
//                     } else {
//                         this.on('renderform', function(form) {
//                             form.setValues(this.data);
//                             form.resetDirty();
//                         }, result);
//                     }
                }
                if (this.getForm()) {
                    this.getForm().clearInvalid();
                    this.getForm().resetDirty();
                }
            },
            callback: function() {
                if (this.el) this.el.unmask();
            },
            scope: this
        });
    },

    //für AbstractPanel
    reset : function() {
        this.getForm().reset();
    },

    //deprecated
    onSubmit : function(options, successCallback) {
        if (!options) options = {};
        options.success = successCallback.callback;
        this.submit(options, successCallback);
    },

    //private
    onSave : function() {
        this.submit();
    },

    //für AbstractPanel
    submit: function(options)
    {
        this.getAction('save').disable();
        if (!options) options = {};

        var cb = {
            success: options.success,
            failure: options.failure,
            callback: options.callback,
            scope: options.scope || this
        };

        this.getForm().waitMsgTarget = this.el;
        this.getForm().submit(Ext.apply(options, {
            url: this.controllerUrl+'/jsonSave',
            waitMsg: 'saving...',
            success: function() {
                this.onSubmitSuccess.apply(this, arguments);
                if (cb.success) {
                    cb.success.apply(cb.scope, arguments)
                }
            },
            failure: function() {
                this.onSubmitFailure.apply(this, arguments);
                if (cb.failure) {
                    cb.failure.apply(cb.scope, arguments)
                }
            },
            callback: function() {
                if (cb.callback) {
                    cb.callback.apply(cb.scope, arguments)
                }
            },
            scope: this
        }));
    },
    onSubmitFailure: function(form, action) {
        if(action.failureType == Ext.form.Action.CLIENT_INVALID) {
            Ext.Msg.alert('Speichern', 'Es konnte nicht gespeichert werden, bitte alle Felder korrekt ausfüllen.');
        }
        this.getAction('save').enable();
    },

    onSubmitSuccess: function(form, action) {
        this.getForm().resetDirty();
        this.fireEvent('datachange', action.result);

        var reEnableSubmitButton = function() {
            this.getAction('save').enable();
        };
        reEnableSubmitButton.defer(1000, this);

        if(action.result && action.result.data && action.result.data.addedId) {
            this.getForm().baseParams.id = action.result.data.addedId;
            this.getAction('delete').enable();
            this.getAction('save').enable();
        }
        if (this.getForm().loadAfterSave) {
            //bei file-upload neu laden
            this.reload();
        }
    },
    onDelete : function() {
        Ext.Msg.show({
        title:'löschen?',
        msg: 'Möchten Sie diesen Eintrag wirklich löschen?',
        buttons: Ext.Msg.YESNO,
        scope: this,
        fn: function(button) {
            if (button == 'yes') {

                Ext.Ajax.request({
                        url: this.controllerUrl+'/jsonDelete',
                        params: {id: this.getForm().baseParams.id},
                        success: function(response, options, r) {
                            this.fireEvent('datachange', r);
                            this.getForm().clearValues();
                            this.getForm().clearInvalid();
                            this.disable();
                            this.fireEvent('deleteaction', this);
                        },
                        scope: this
                    });
            }
        }
        });
    },
    onAdd : function() {
        if (!this.getForm()) this.load(); //meta-daten wurden noch nicht geladen

        this.mabySave({
            callback: function() {
                this.enable();
                if (this.deleteButton) this.deleteButton.disable();
                this.getAction('delete').disable();
                this.applyBaseParams({id: 0});
                if (this.getForm()) {
                    this.getForm().setDefaultValues();
                    this.getForm().clearInvalid();
                }
                this.fireEvent('addaction', this);
            },
            scope: this
        });
    },
    findField: function(id) {
        return this.getForm().findField(id);
    },
    getForm : function() {
        if (!this.getFormPanel()) return null;
        return this.getFormPanel().getForm();
    },
    getFormPanel : function() {
        return this.formPanel;
    },
    setBaseParams : function(baseParams) {
        this.baseParams = baseParams;
        if (this.getForm()) {
            this.getForm().baseParams = baseParams;
        }
    },
    applyBaseParams : function(baseParams) {
        Ext.apply(this.baseParams, baseParams);
        if (this.getForm()) {
            Ext.apply(this.getForm().baseParams, baseParams);
        }
    },
    getBaseParams : function() {
        return this.baseParams;
    }
});

Ext.reg('autoform', Vps.Auto.FormPanel);
<|endoftext|>


<commit_before>/*global self:true*/
"use strict";

var self = require("sdk/self");
var pageMod = require("sdk/page-mod");
var childProcess = require("sdk/system/child_process");
var { emit } = require("sdk/event/core");
var system = require("sdk/system");
var url = require("sdk/url");

function execBin(args, stdin, event, callbackid, worker) {
  console.info("EB1", args, event);
  var exe = system.platform + "_" + system.architecture + "-" + system.compiler + "/u2f" +
    (system.platform == "winnt" ? ".exe" : "");
  var path = url.toFilename(self.data.url("../bin/" + exe));
  console.info("EB2", path);
  var cmd = childProcess.spawn(path, args, {});
  console.info("EB3", cmd);
  var response = {value: ""};
  cmd.stdout.on("data", function(data) {
    console.info("EBD", data);
    response.value += data;
  });
  cmd.on("close", function(code) {
    console.info("EBC", code, response.value.length);
    if (code == 0 && response.value.length) {
      worker.port.emit(event, callbackid, JSON.parse(response.value));
    } else {
      worker.port.emit(event, callbackid, {errorCode: 1});
    }
  });
  emit(cmd.stdin, "data", stdin);
  emit(cmd.stdin, "end");
}

pageMod.PageMod({ // eslint-disable-line new-cap
  include: "*",
  contentScriptWhen: "start",
  attachTo: ["existing", "top", "frame"],
  contentScriptFile: "./content-script.js",
  onAttach: function(worker) {

    worker.port.on("register", function(requests, callbackid, domain) {
      var req = Array.isArray(requests) ? requests[0] : requests;
      execBin(["r", domain], JSON.stringify(req),
       "registerResponse", callbackid, worker);
    });
    worker.port.on("sign", function(signRequests, callbackid, domain) {
      var req = Array.isArray(signRequests) ? signRequests[0] : signRequests;
      execBin(["s", domain], JSON.stringify(req),
       "signResponse", callbackid, worker);
    });
  }
});
<commit_msg>Don't include existing in PageMod attachTo<commit_after>/*global self:true*/
"use strict";

var self = require("sdk/self");
var pageMod = require("sdk/page-mod");
var childProcess = require("sdk/system/child_process");
var { emit } = require("sdk/event/core");
var system = require("sdk/system");
var url = require("sdk/url");

function execBin(args, stdin, event, callbackid, worker) {
  console.info("EB1", args, event);
  var exe = system.platform + "_" + system.architecture + "-" + system.compiler + "/u2f" +
    (system.platform == "winnt" ? ".exe" : "");
  var path = url.toFilename(self.data.url("../bin/" + exe));
  console.info("EB2", path);
  var cmd = childProcess.spawn(path, args, {});
  console.info("EB3", cmd);
  var response = {value: ""};
  cmd.stdout.on("data", function(data) {
    console.info("EBD", data);
    response.value += data;
  });
  cmd.on("close", function(code) {
    console.info("EBC", code, response.value.length);
    if (code == 0 && response.value.length) {
      worker.port.emit(event, callbackid, JSON.parse(response.value));
    } else {
      worker.port.emit(event, callbackid, {errorCode: 1});
    }
  });
  emit(cmd.stdin, "data", stdin);
  emit(cmd.stdin, "end");
}

pageMod.PageMod({ // eslint-disable-line new-cap
  include: "*",
  contentScriptWhen: "start",
  attachTo: ["top", "frame"],
  contentScriptFile: "./content-script.js",
  onAttach: function(worker) {

    worker.port.on("register", function(requests, callbackid, domain) {
      var req = Array.isArray(requests) ? requests[0] : requests;
      execBin(["r", domain], JSON.stringify(req),
       "registerResponse", callbackid, worker);
    });
    worker.port.on("sign", function(signRequests, callbackid, domain) {
      var req = Array.isArray(signRequests) ? signRequests[0] : signRequests;
      execBin(["s", domain], JSON.stringify(req),
       "signResponse", callbackid, worker);
    });
  }
});
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2013-2014 CNRS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

exports.currentUserIsAdmin = function(req, res, next) {
	if (req.session.user.role == "admin") return next();
}

// retrieve all users
exports.listUsers = function (req, res) {
	var connectedUser = req.session.user;
	if (connectedUser.role == "admin") {
		User.find({}, 'username role affiliation', function (error, users) {
        	if (error) res.status(400).json({error:"error", message:error});
        	if (users) res.status(200).json(users);
			else return res.status(200).json([]);
    	});
	}
    else {
    	User.findOne({username: connectedUser.username}, 'username role affiliation', function (error, users) {
        	if (error) res.status(400).json({error:"error", message:error});
        	if (users) res.status(200).json(users);
        	else return res.status(200).json([]);
    	});
    }
}

// check if user is login
exports.requiredValidUser = function(req, res, next) {
	if (req.session.user) next();
	else res.status(403).json({error:"access denied"});
}

//check if a user exists
exports.userNameFree = function(req, res, next) {
    User.count({username: req.body.username}, function (error, count) {
        if (count === 0)  next();
        else res.status(400).json( {error:"this user name already exists", message:error});
    });
}

// create a user
exports.signup = function (req, res) {
	if (req.body.password == undefined || req.body.username == undefined) res.status(400).json( {error:"the username and/or password fields have not been filled up with data"});
	else {
		var roleuser = req.body.role;
		if (GLOBAL.list_user_role.indexOf(roleuser)==-1)  roleuser = "user";
		hash(req.body.password, function (error, salt, hash) {
			if (error) res.status(400).json({error:"error", message:error});
			var user = new User({
				username: req.body.username,
				affiliation: req.body.affiliation,
				role: roleuser,//req.body.role,
				salt: salt,
				hash: hash,
			}).save(function (error2, newUser) {
				if (error2) res.status(400).json({error:"error", message:error2});
				if (newUser)res.status(200).json( newUser);
			});
		});
	}
}

// check if the given user name or group name exists
exports.requiredRightUGname = function(role) {
	return function(req, res, next) {
    	if (req.session.user) {
    		if (req.session.user.role == "admin") next();
			else if (commonFuncs.isAllowedUser(req.session.user.role, role) < 0) res.status(403).json({error:"access denied"});
			else {
				var userLogin = req.body.username;
				var groupLogin = req.body.groupname;
				if (userLogin == undefined) userLogin = "root";
				User.findOne({username : {$regex : new RegExp('^'+ userLogin + '$', "i")}}, function(error, data){
					if (error) res.status(403).json( {error:"access denied", message:error});
					else {
						if (data == null) res.status(400).json( {error:"this user does not exist"});
						else {
							if (groupLogin == undefined) next();
							else {
								Group.findOne({groupname : {$regex : new RegExp('^'+ groupLogin + '$', "i")}}, function(error2, data){
									if (error2) res.status(403).json( {error:"access denied", message:error2});
									else {
										if (data == null)res.status(400).json( {error:"this group does not exist"});
										else next();
									}
								});
							}
						}
					}
				});
			}
		}
		else res.status(403).json( {error:"access denied"});
	}
}

//retrieve a particular user (with id)
exports.listWithId = function(req, res){
	if (req.params.id == undefined) return res.status(400).json({error:"the given ID is not correct"});
	var connectedUser = req.session.user;
	User.findById(req.params.id, 'username affiliation role', function(error, data){
		if (error) res.status(400).json({error:"error", message:error});
		else if (data == null) res.status(400).json({error:"no such user"});
		else
			if (connectedUser.role == "admin")  res.status(200).json(data);
			else {
				if (data.username == connectedUser.username)	res.status(200).json(data);
				else res.status(403).json({error:"You dont have enough right to access this resource"});
			}
	});
}

//retrieve a particular user (with id)
exports.listGroupsOfUserId = function(req, res){
	if (req.params.id == undefined) return res.status(400).json({error:"the given ID is not correct"});
	var connectedUser = req.session.user;
	User.findById(req.params.id, 'username affiliation role', function(error, data){
		if (error) res.status(400).json({error:"error", message:error});
		else if (data == null) res.status(200).json(400, '{"error":"no such user"}')
		else {
			Group.find({'usersList' : {$regex : new RegExp('^'+ data.username + '$', "i")}}, function(error2, dataGroup) {
				if (error2) res.status(400).json({error:"error", message:error2});
				else {
					if (connectedUser.role == "admin")  res.status(200).json(dataGroup);
					else {
						if (data.username == connectedUser.username)	res.status(200).json(dataGroup);
						else res.status(403).json({error:"You dont have enough right to access this resource"});
					}
				}
			});
		}
	});
}

exports.update = function(req, res){
	if (req.params.id == undefined) return res.status(400).json({error:"one or more data fields are not filled out properly"});
	var connectedUser = req.session.user;

	User.findById(req.params.id, 'username affiliation role', function(error0, data0){
		if (error0) res.status(400).json({error:"error", message:error0});
		else if (data0 == null) res.status(400).json({error:"no such user"});
		else {
			var update = {};
			if (connectedUser.role == "admin" && GLOBAL.list_user_role.indexOf(req.body.role)!=-1 && connectedUser.username != "root") update.role = req.body.role;
			if (req.body.affiliation) update.affiliation = req.body.affiliation;
			if (req.body.password == undefined) {
				User.findByIdAndUpdate(req.params.id, update, function (error, data) {
					if (error) res.status(400).json({error:"error", message:error});
					else res.status(200).json(data);
				});
			}
			else {
				pass.hash(req.body.password, function (error, salt, hash) {
					if (error) res.status(400).json({error:"error", message:error});
					else {
						update.salt = salt;
						update.hash = hash;
						User.findByIdAndUpdate(req.params.id, update, function (error2, data) {
							if (error2) res.status(400).json({error:"error", message:error2});
							else res.status(200).json(data);
						});
					}
				});
			}
		}
	});
}

// remove a user
exports.remove  = function(req, res){
	if (req.params.id == undefined) return res.status(400).json({error:"one or more data fields are not filled out properly"});
	User.remove({_id : req.params.id}, function (error, data) {
		if (error) res.status(400).json({error:"error", message:error});
		else if (data == 1){
			ACLAPI.removeAUserFromALC(data.username);
			res.status(200).json({message:"The user as been delete"});
		}
		else  res.status(200).json({message:"The user do not exist"});
	});
}
<commit_msg>ajout fonction get all<commit_after>/*
The MIT License (MIT)

Copyright (c) 2013-2014 CNRS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

exports.currentUserIsAdmin = function(req, res, next) {
	if (req.session.user.role == "admin") return next();
}

// retrieve all users
exports.getAll = function (req, res) {
	User.find({}, 'username role affiliation', function (error, users) {
    	if (error) res.status(400).json({error:"error", message:error});
    	if (users) res.status(200).json(users);
		else res.status(200).json([]);
	});
}

// check if user is login
exports.requiredValidUser = function(req, res, next) {
	if (req.session.user) next();
	else res.status(403).json({error:"access denied"});
}

//check if a user exists
exports.userNameFree = function(req, res, next) {
    User.count({username: req.body.username}, function (error, count) {
        if (count === 0)  next();
        else res.status(400).json( {error:"this user name already exists", message:error});
    });
}

// create a user
exports.signup = function (req, res) {
	if (req.body.password == undefined || req.body.username == undefined) res.status(400).json( {error:"the username and/or password fields have not been filled up with data"});
	else {
		var roleuser = req.body.role;
		if (GLOBAL.list_user_role.indexOf(roleuser)==-1)  roleuser = "user";
		hash(req.body.password, function (error, salt, hash) {
			if (error) res.status(400).json({error:"error", message:error});
			var user = new User({
				username: req.body.username,
				affiliation: req.body.affiliation,
				role: roleuser,//req.body.role,
				salt: salt,
				hash: hash,
			}).save(function (error2, newUser) {
				if (error2) res.status(400).json({error:"error", message:error2});
				if (newUser)res.status(200).json( newUser);
			});
		});
	}
}

// check if the given user name or group name exists
exports.requiredRightUGname = function(role) {
	return function(req, res, next) {
    	if (req.session.user) {
    		if (req.session.user.role == "admin") next();
			else if (commonFuncs.isAllowedUser(req.session.user.role, role) < 0) res.status(403).json({error:"access denied"});
			else {
				var userLogin = req.body.username;
				var groupLogin = req.body.groupname;
				if (userLogin == undefined) userLogin = "root";
				User.findOne({username : {$regex : new RegExp('^'+ userLogin + '$', "i")}}, function(error, data){
					if (error) res.status(403).json( {error:"access denied", message:error});
					else {
						if (data == null) res.status(400).json( {error:"this user does not exist"});
						else {
							if (groupLogin == undefined) next();
							else {
								Group.findOne({groupname : {$regex : new RegExp('^'+ groupLogin + '$', "i")}}, function(error2, data){
									if (error2) res.status(403).json( {error:"access denied", message:error2});
									else {
										if (data == null)res.status(400).json( {error:"this group does not exist"});
										else next();
									}
								});
							}
						}
					}
				});
			}
		}
		else res.status(403).json( {error:"access denied"});
	}
}

//retrieve a particular user (with id)
exports.listWithId = function(req, res){
	if (req.params.id == undefined) return res.status(400).json({error:"the given ID is not correct"});
	var connectedUser = req.session.user;
	User.findById(req.params.id, 'username affiliation role', function(error, data){
		if (error) res.status(400).json({error:"error", message:error});
		else if (data == null) res.status(400).json({error:"no such user"});
		else
			if (connectedUser.role == "admin")  res.status(200).json(data);
			else {
				if (data.username == connectedUser.username)	res.status(200).json(data);
				else res.status(403).json({error:"You dont have enough right to access this resource"});
			}
	});
}

//retrieve a particular user (with id)
exports.listGroupsOfUserId = function(req, res){
	if (req.params.id == undefined) return res.status(400).json({error:"the given ID is not correct"});
	var connectedUser = req.session.user;
	User.findById(req.params.id, 'username affiliation role', function(error, data){
		if (error) res.status(400).json({error:"error", message:error});
		else if (data == null) res.status(200).json(400, '{"error":"no such user"}')
		else {
			Group.find({'usersList' : {$regex : new RegExp('^'+ data.username + '$', "i")}}, function(error2, dataGroup) {
				if (error2) res.status(400).json({error:"error", message:error2});
				else {
					if (connectedUser.role == "admin")  res.status(200).json(dataGroup);
					else {
						if (data.username == connectedUser.username)	res.status(200).json(dataGroup);
						else res.status(403).json({error:"You dont have enough right to access this resource"});
					}
				}
			});
		}
	});
}

exports.update = function(req, res){
	if (req.params.id == undefined) return res.status(400).json({error:"one or more data fields are not filled out properly"});
	var connectedUser = req.session.user;

	User.findById(req.params.id, 'username affiliation role', function(error0, data0){
		if (error0) res.status(400).json({error:"error", message:error0});
		else if (data0 == null) res.status(400).json({error:"no such user"});
		else {
			var update = {};
			if (connectedUser.role == "admin" && GLOBAL.list_user_role.indexOf(req.body.role)!=-1 && connectedUser.username != "root") update.role = req.body.role;
			if (req.body.affiliation) update.affiliation = req.body.affiliation;
			if (req.body.password == undefined) {
				User.findByIdAndUpdate(req.params.id, update, function (error, data) {
					if (error) res.status(400).json({error:"error", message:error});
					else res.status(200).json(data);
				});
			}
			else {
				pass.hash(req.body.password, function (error, salt, hash) {
					if (error) res.status(400).json({error:"error", message:error});
					else {
						update.salt = salt;
						update.hash = hash;
						User.findByIdAndUpdate(req.params.id, update, function (error2, data) {
							if (error2) res.status(400).json({error:"error", message:error2});
							else res.status(200).json(data);
						});
					}
				});
			}
		}
	});
}

// remove a user
exports.remove  = function(req, res){
	if (req.params.id == undefined) return res.status(400).json({error:"one or more data fields are not filled out properly"});
	User.remove({_id : req.params.id}, function (error, data) {
		if (error) res.status(400).json({error:"error", message:error});
		else if (data == 1){
			ACLAPI.removeAUserFromALC(data.username);
			res.status(200).json({message:"The user as been delete"});
		}
		else  res.status(200).json({message:"The user do not exist"});
	});
}
<|endoftext|>


<commit_before>/* file: form.js
 * authors: H. Bouakaz, S. de Vliet, S. de Jong & E. Werkema
 * date: 19/3/2016
 * version 1.1
 *
 * Description:
 */

define(['app/config', 'app/database', 'jquery', 'bootstrap', 'parsley', 'app/selectLanguage', 'app/selectSubject', 'app/date'], function (config, db, $, bootstrap, parsley, language, subject, date) {
	var numberOfFormItems = 0;
	var formItemId = 0;

	// Function for removing elements from the form
	function remove_element(element) {
		if (numberOfFormItems > 1) {
			element.parents("tr").remove();
			numberOfFormItems--;
		}
	}

  // Auxiliary replace functions
  function giveId(string, formItemId) {
    return string.replace(/{i}/g, formItemId);
  }
  function giveRequired(string) {
    return string.replace(/{required}/g, 'required=""');
  }

	// Function for adding elements to the form
	function add_element() {
		var newElement = $('#item-layout').clone(true).appendTo("#items table").removeAttr("id");
		newElement.html(giveId(newElement.html(), formItemId));
    newElement.html(giveRequired(newElement.html()));
		newElement.on("click", ".remove", function() {
			remove_element($(this));
		});
		numberOfFormItems++;
		formItemId++;
	}

	// Add the first element
	add_element();

	$(".add").click(function(add) {
		add_element();
		return false;
	});

	$('#items input[type="text"]:last').on('keydown', function(e) {
	  if (e.keyCode == config.key("TAB")) {
	      add_element();
	  }
	});

	// Check in the database if the name of the dataset already exists
	window.Parsley.addValidator('datasetName', {
		validateString: function(value, requirement) {
			var result = db.getQuery("getDatasetByName", [value]);
			return result.length == 0;
		},
		messages: {
			en: 'This name is already used for another dataset.'
		}
	});

	// Script for evaluating the input of the upload form
	$(function () {
		$('#createForm').parsley().on('field:validated', function() {
			// Initiate form error and success handling
			var ok = $('.parsley-error').length === 0;
			$('.bs-callout-info').toggleClass('hidden', !ok);
			$('.bs-callout-warning').toggleClass('hidden', ok);
		})
		.on('form:submit', function() {
			return false; // Don't submit form
		})
		.on('form:success', function() {
			// Save data into the database
			var name = $('#createForm').find('input[name="name"]').val();
			var language = $('#createForm').find('select[name="language"]').val();
			var subject = $('#createForm').find('select[name="subject"]').val();
			var currentdate = new Date();

			db.executeQuery("addDataset", [0, name, language, subject, 0, 0, date.formatDate(currentdate), date.formatDate(currentdate)]);
			var id = db.lastInsertRowId("tbldatasets", "dataset_id");
			// Save all items in the dataset
			for (i = 0; i<=formItemId; i++) {
				var question = $("#items input[name='question"+i+"']").val();
				var answer = $("#items input[name='answer"+i+"']").val();
				var hint = $("#items input[name='hint"+i+"']").val();
				hint = (hint==="undefined") ? "" : hint;

				db.executeQuery('addDatasetItem' , [id, question, answer, hint]);
			}
			db.close();
			window.location = 'index.html';
		});
	});
});
<commit_msg>Put form value reading in own function<commit_after>/* file: form.js
 * authors: H. Bouakaz, S. de Vliet, S. de Jong & E. Werkema
 * date: 19/3/2016
 * version 1.1
 *
 * Description:
 */

define(['app/config', 'app/database', 'jquery', 'bootstrap', 'parsley', 'app/selectLanguage', 'app/selectSubject', 'app/date'], function (config, db, $, bootstrap, parsley, language, subject, date) {
	var numberOfFormItems = 0;
	var formItemId = 0;

	// Function for removing elements from the form
	function remove_element(element) {
		if (numberOfFormItems > 1) {
			element.parents("tr").remove();
			numberOfFormItems--;
		}
	}

	// Function for adding elements to the form
	function add_element() {
		var newElement = $('#item-layout').clone(true).appendTo("#items table").removeAttr("id");
		newElement.html(giveId(newElement.html(), formItemId));
    newElement.html(giveRequired(newElement.html()));
		newElement.on("click", ".remove", function() {
			remove_element($(this));
		});
		numberOfFormItems++;
		formItemId++;
	}

  // Auxiliary replace functions
  function giveId(string, formItemId) {
    return string.replace(/{i}/g, formItemId);
  }
  function giveRequired(string) {
    return string.replace(/{required}/g, 'required=""');
  }

  // Auxiliary form function
  function getFormVal(formType, formName) {
    return $('#createForm').find(formType + '[name="' + formName + '"]').val();
  }

	// Add the first element
	add_element();

	$(".add").click(function(add) {
		add_element();
		return false;
	});

	$('#items input[type="text"]:last').on('keydown', function(e) {
	  if (e.keyCode == config.key("TAB")) {
	      add_element();
	  }
	});

	// Check in the database if the name of the dataset already exists
	window.Parsley.addValidator('datasetName', {
		validateString: function(value, requirement) {
			var result = db.getQuery("getDatasetByName", [value]);
			return result.length == 0;
		},
		messages: {
			en: 'This name is already used for another dataset.'
		}
	});

	// Script for evaluating the input of the upload form
	$(function () {
		$('#createForm').parsley().on('field:validated', function() {
			// Initiate form error and success handling
			var ok = $('.parsley-error').length === 0;
			$('.bs-callout-info').toggleClass('hidden', !ok);
			$('.bs-callout-warning').toggleClass('hidden', ok);
		})
		.on('form:submit', function() {
			return false; // Don't submit form
		})
		.on('form:success', function() {
			// Save data into the database
			var name = getFormVal("input", "name");
			var language = getFormVal("select", "language");
			var subject = getFormVal("select", "subject");
			var currentdate = new Date();

			db.executeQuery("addDataset", [0, name, language, subject, 0, 0, date.formatDate(currentdate), date.formatDate(currentdate)]);
			var id = db.lastInsertRowId("tbldatasets", "dataset_id");
			// Save all items in the dataset
			for (i = 0; i<=formItemId; i++) {
				var question = $("#items input[name='question"+i+"']").val();
				var answer = $("#items input[name='answer"+i+"']").val();
				var hint = $("#items input[name='hint"+i+"']").val();
				hint = (hint==="undefined") ? "" : hint;

				db.executeQuery('addDatasetItem' , [id, question, answer, hint]);
			}
			db.close();
			window.location = 'index.html';
		});
	});
});
<|endoftext|>


<commit_before>(function(window) {
	var orgRequire = window.require;
	var queue = [];
	var counter = 0;

	window.require = function(dependencies, callback, errBack) {
		if (!Array.isArray(dependencies)) {
			return orgRequire.apply(window, arguments);
		}

		var i = counter++;
		queue.push(i);

		if (errBack) {
			orgRequire(dependencies, function() {
				var args = arguments;

				queue[queue.indexOf(i)] = function() { callback.apply(window, args); };

				executeCallbacks();
			}, function() {
				var args = arguments;

				queue[queue.indexOf(i)] = function() { errBack.apply(window, args); };

				executeCallbacks();
			});
		}
		else {
			orgRequire(dependencies, function() {
				var args = arguments;

				queue[queue.indexOf(i)] = function() { callback.apply(window, args); };

				executeCallbacks();
			});
		}
	};
	window.require.config = orgRequire.config;

	function executeCallbacks() {
		while (queue.length) {
			if (typeof queue[0] !== 'function') {
				break;
			}

			queue.shift()();
		}
	}
})(window);
<commit_msg>Return Promise in require()<commit_after>(function(window) {
	var orgRequire = window.require;
	var queue = [];
	var counter = 0;

	window.require = function(dependencies, callback, errBack) {
		if (!Array.isArray(dependencies)) {
			return orgRequire.apply(window, arguments);
		}

		var promise = new Promise(function (resolve, reject) {
			var i = counter++;
			queue.push(i);

			orgRequire(dependencies, function () {
				var args = arguments;

				queue[queue.indexOf(i)] = function() { resolve(args); };

				executeCallbacks();
			}, function (err) {
				queue[queue.indexOf(i)] = function() { reject(err); };

				executeCallbacks();
			});
		});

		if (callback) {
			promise.then(function (objects) {
				callback.apply(window, objects);
			});
		}
		if (errBack) {
			promise.catch(errBack);
		}

		return promise;
	};
	window.require.config = orgRequire.config;

	function executeCallbacks() {
		while (queue.length) {
			if (typeof queue[0] !== 'function') {
				break;
			}

			queue.shift()();
		}
	}
})(window);
<|endoftext|>


<commit_before>import {GraphQLNonNull, GraphQLID, GraphQLString, GraphQLInt} from 'graphql'
import {GraphQLURL, GraphQLDateTime} from 'graphql-custom-types'
import {GraphQLObjectType, GraphQLList} from 'graphql/type'

import {Chapter, chapterResolver} from '../Chapter/schema'

import {getProjectById} from '../../../../server/db/project'

const projectFields = {
  id: {type: new GraphQLNonNull(GraphQLID), description: "The project's UUID"},
  name: {type: new GraphQLNonNull(GraphQLString), description: 'The project name'},
  chapter: {
    type: Chapter,
    description: 'The chapter',
    resolve: chapterResolver,
  },
  artifactURL: {type: GraphQLURL, description: 'The URL pointing to the output of this project'},
  // Punting on cycleHistory for now
  createdAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was created'},
  updatedAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was last updated'},
}

export const Project = new GraphQLObjectType({
  name: 'Project',
  description: 'A project engaged in by learners to complete some goal',
  fields: () => projectFields,
})

const ProjectReviewResponse = new GraphQLObjectType({
  name: 'ProjectReviewResponse',
  description: 'A named question and response value',
  fields: () => ({
    name: {type: new GraphQLNonNull(GraphQLString), description: 'The question name'},
    value: {type: GraphQLString, description: 'The response to the question'},
  })
})

export const ProjectWithReviewResponses = new GraphQLObjectType({
  name: 'ProjectWithReviewResponses',
  description: 'A project which includes any project review survey responses for the current user',
  fields: () => Object.assign({}, projectFields, {
    projectReviewResponses: {
      type: new GraphQLList(ProjectReviewResponse),
      description: 'The responses to the named questions on the project review survey',
    },
  }),
})

export const ProjectsSummary = new GraphQLObjectType({
  name: 'ProjectsSummary',
  description: 'A summary of project-related information for the player and chapter',
  fields: () => ({
    numActiveProjectsForCycle: {type: new GraphQLNonNull(GraphQLInt), description: 'The number of active projects in the current cycle'},
    numTotalProjectsForPlayer: {type: new GraphQLNonNull(GraphQLInt), description: 'The number of total projects in which the player participated'},
  }),
})

export async function projectResolver(parent /* , args, ast */) {
  if (parent.project) {
    return parent.project
  }

  if (parent.projectId) {
    return await getProjectById(parent.projectId)
  }
}
<commit_msg>integrate review feedback: use `...` rather than Object.assign<commit_after>import {GraphQLNonNull, GraphQLID, GraphQLString, GraphQLInt} from 'graphql'
import {GraphQLURL, GraphQLDateTime} from 'graphql-custom-types'
import {GraphQLObjectType, GraphQLList} from 'graphql/type'

import {Chapter, chapterResolver} from '../Chapter/schema'

import {getProjectById} from '../../../../server/db/project'

const projectFields = {
  id: {type: new GraphQLNonNull(GraphQLID), description: "The project's UUID"},
  name: {type: new GraphQLNonNull(GraphQLString), description: 'The project name'},
  chapter: {
    type: Chapter,
    description: 'The chapter',
    resolve: chapterResolver,
  },
  artifactURL: {type: GraphQLURL, description: 'The URL pointing to the output of this project'},
  // Punting on cycleHistory for now
  createdAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was created'},
  updatedAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was last updated'},
}

export const Project = new GraphQLObjectType({
  name: 'Project',
  description: 'A project engaged in by learners to complete some goal',
  fields: () => projectFields,
})

const ProjectReviewResponse = new GraphQLObjectType({
  name: 'ProjectReviewResponse',
  description: 'A named question and response value',
  fields: () => ({
    name: {type: new GraphQLNonNull(GraphQLString), description: 'The question name'},
    value: {type: GraphQLString, description: 'The response to the question'},
  })
})

export const ProjectWithReviewResponses = new GraphQLObjectType({
  name: 'ProjectWithReviewResponses',
  description: 'A project which includes any project review survey responses for the current user',
  fields: () => ({...projectFields,
    projectReviewResponses: {
      type: new GraphQLList(ProjectReviewResponse),
      description: 'The responses to the named questions on the project review survey',
    },
  }),
})

export const ProjectsSummary = new GraphQLObjectType({
  name: 'ProjectsSummary',
  description: 'A summary of project-related information for the player and chapter',
  fields: () => ({
    numActiveProjectsForCycle: {type: new GraphQLNonNull(GraphQLInt), description: 'The number of active projects in the current cycle'},
    numTotalProjectsForPlayer: {type: new GraphQLNonNull(GraphQLInt), description: 'The number of total projects in which the player participated'},
  }),
})

export async function projectResolver(parent /* , args, ast */) {
  if (parent.project) {
    return parent.project
  }

  if (parent.projectId) {
    return await getProjectById(parent.projectId)
  }
}
<|endoftext|>