code
stringlengths 2
1.05M
|
---|
var db = require("../database");
var valid = require("../utilities").isValidChannelName;
var fs = require("fs");
var path = require("path");
var Logger = require("../logger");
var tables = require("./tables");
var Flags = require("../flags");
var util = require("../utilities");
var blackHole = function () { };
function dropTable(name, callback) {
db.query("DROP TABLE `" + name + "`", callback);
}
function initTables(name, owner, callback) {
if (!valid(name)) {
callback("Invalid channel name", null);
return;
}
}
module.exports = {
init: function () {
},
/**
* Checks if the given channel name is registered
*/
isChannelTaken: function (name, callback) {
if (typeof callback !== "function") {
return;
}
if (!valid(name)) {
callback("Invalid channel name", null);
return;
}
db.query("SELECT name FROM `channels` WHERE name=?",
[name],
function (err, rows) {
if (err) {
callback(err, true);
return;
}
callback(null, rows.length > 0);
});
},
/**
* Looks up a channel
*/
lookup: function (name, callback) {
if (typeof callback !== "function") {
return;
}
if (!valid(name)) {
callback("Invalid channel name", null);
return;
}
db.query("SELECT * FROM `channels` WHERE name=?",
[name],
function (err, rows) {
if (err) {
callback(err, null);
return;
}
if (rows.length === 0) {
callback("No such channel", null);
} else {
callback(null, rows[0]);
}
});
},
/**
* Searches for a channel
*/
search: function (name, callback) {
if (typeof callback !== "function") {
return;
}
db.query("SELECT * FROM `channels` WHERE name LIKE ?",
["%" + name + "%"],
function (err, rows) {
if (err) {
callback(err, null);
return;
}
callback(null, rows);
});
},
/**
* Searches for a channel by owner
*/
searchOwner: function (name, callback) {
if (typeof callback !== "function") {
return;
}
db.query("SELECT * FROM `channels` WHERE owner LIKE ?",
["%" + name + "%"],
function (err, rows) {
if (err) {
callback(err, null);
return;
}
callback(null, rows);
});
},
/**
* Validates and registers a new channel
*/
register: function (name, owner, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (typeof name !== "string" || typeof owner !== "string") {
callback("Name and owner are required for channel registration", null);
return;
}
if (!valid(name)) {
callback("Invalid channel name. Channel names may consist of 1-30 " +
"characters a-z, A-Z, 0-9, -, and _", null);
return;
}
module.exports.isChannelTaken(name, function (err, taken) {
if (err) {
callback(err, null);
return;
}
if (taken) {
callback("Channel name " + name + " is already taken", null);
return;
}
db.query("INSERT INTO `channels` " +
"(`name`, `owner`, `time`) VALUES (?, ?, ?)",
[name, owner, Date.now()],
function (err, res) {
if (err) {
callback(err, null);
return;
}
db.users.getGlobalRank(owner, function (err, rank) {
if (err) {
callback(err, null);
return;
}
rank = Math.max(rank, 5);
module.exports.setRank(name, owner, rank, function (err) {
if (err) {
callback(err, null);
return;
}
callback(null, { name: name });
});
});
});
});
},
/**
* Unregisters a channel
*/
drop: function (name, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (!valid(name)) {
callback("Invalid channel name", null);
return;
}
db.query("DELETE FROM `channels` WHERE name=?", [name], function (err) {
module.exports.deleteBans(name, function (err) {
if (err) {
Logger.errlog.log("Failed to delete bans for " + name + ": " + err);
}
});
module.exports.deleteLibrary(name, function (err) {
if (err) {
Logger.errlog.log("Failed to delete library for " + name + ": " + err);
}
});
module.exports.deleteAllRanks(name, function (err) {
if (err) {
Logger.errlog.log("Failed to delete ranks for " + name + ": " + err);
}
});
fs.unlink(path.join(__dirname, "..", "..", "chandump", name),
function (err) {
if (err && err.code !== "ENOENT") {
Logger.errlog.log("Deleting chandump failed:");
Logger.errlog.log(err);
}
});
callback(err, !Boolean(err));
});
},
/**
* Looks up channels registered by a given user
*/
listUserChannels: function (owner, callback) {
if (typeof callback !== "function") {
return;
}
db.query("SELECT * FROM `channels` WHERE owner=?", [owner],
function (err, res) {
if (err) {
callback(err, []);
return;
}
callback(err, res);
});
},
/**
* Loads the channel from the database
*/
load: function (chan, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (!valid(chan.name)) {
callback("Invalid channel name", null);
return;
}
db.query("SELECT * FROM `channels` WHERE name=?", chan.name, function (err, res) {
if (err) {
callback(err, null);
return;
}
if (res.length === 0) {
callback("Channel is not registered", null);
return;
}
if (chan.dead) {
callback("Channel is dead", null);
return;
}
// Note that before this line, chan.name might have a different capitalization
// than the database has stored. Update accordingly.
chan.name = res[0].name;
chan.uniqueName = chan.name.toLowerCase();
chan.id = res[0].id;
chan.setFlag(Flags.C_REGISTERED);
chan.logger.log("[init] Loaded channel from database");
callback(null, true);
});
},
/**
* Looks up a user's rank
*/
getRank: function (chan, name, callback) {
if (typeof callback !== "function") {
return;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("SELECT * FROM `channel_ranks` WHERE name=? AND channel=?",
[name, chan],
function (err, rows) {
if (err) {
callback(err, -1);
return;
}
if (rows.length === 0) {
callback(null, 1);
return;
}
callback(null, rows[0].rank);
});
},
/**
* Looks up multiple users' ranks at once
*/
getRanks: function (chan, names, callback) {
if (typeof callback !== "function") {
return;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
var replace = "(" + names.map(function () { return "?"; }).join(",") + ")";
/* Last substitution is the channel to select ranks for */
names.push(chan);
db.query("SELECT * FROM `channel_ranks` WHERE name IN " +
replace + " AND channel=?", names,
function (err, rows) {
if (err) {
callback(err, []);
return;
}
callback(null, rows.map(function (r) { return r.rank; }));
});
},
/**
* Query all user ranks at once
*/
allRanks: function (chan, callback) {
if (typeof callback !== "function") {
return;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("SELECT * FROM `channel_ranks` WHERE channel=?", [chan], callback);
},
/**
* Updates a user's rank
*/
setRank: function (chan, name, rank, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (rank < 2) {
module.exports.deleteRank(chan, name, callback);
return;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("INSERT INTO `channel_ranks` VALUES (?, ?, ?) " +
"ON DUPLICATE KEY UPDATE rank=?",
[name, rank, chan, rank, chan], callback);
},
/**
* Removes a user's rank entry
*/
deleteRank: function (chan, name, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("DELETE FROM `channel_ranks` WHERE name=? AND channel=?", [name, chan],
callback);
},
/**
* Removes all ranks for a channel
*/
deleteAllRanks: function (chan, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("DELETE FROM `channel_ranks` WHERE channel=?", [chan], callback);
},
/**
* Adds a media item to the library
*/
addToLibrary: function (chan, media, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
var meta = JSON.stringify({
bitrate: media.meta.bitrate,
codec: media.meta.codec,
scuri: media.meta.scuri,
embed: media.meta.embed
});
db.query("INSERT INTO `channel_libraries` " +
"(id, title, seconds, type, meta, channel) " +
"VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE id=id",
[media.id, media.title, media.seconds, media.type, meta, chan], callback);
},
/**
* Retrieves a media item from the library by id
*/
getLibraryItem: function (chan, id, callback) {
if (typeof callback !== "function") {
return;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("SELECT * FROM `channel_libraries` WHERE id=? AND channel=?", [id, chan],
function (err, rows) {
if (err) {
callback(err, null);
return;
}
if (rows.length === 0) {
callback("Item not in library", null);
} else {
callback(null, rows[0]);
}
});
},
/**
* Search the library by title
*/
searchLibrary: function (chan, search, callback) {
if (typeof callback !== "function") {
return;
}
db.query("SELECT * FROM `channel_libraries` WHERE title LIKE ? AND channel=?",
["%" + search + "%", chan], callback);
},
/**
* Deletes a media item from the library
*/
deleteFromLibrary: function (chan, id, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("DELETE FROM `channel_libraries` WHERE id=? AND channel=?",
[id, chan], callback);
},
/**
* Deletes all library entries for a channel
*/
deleteLibrary: function (chan, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("DELETE FROM `channel_libraries` WHERE channel=?", [chan], callback);
},
/**
* Add a ban to the banlist
*/
ban: function (chan, ip, name, note, bannedby, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("INSERT INTO `channel_bans` (ip, name, reason, bannedby, channel) " +
"VALUES (?, ?, ?, ?, ?)",
[ip, name, note, bannedby, chan], callback);
},
/**
* Check if an IP address or range is banned
*/
isIPBanned: function (chan, ip, callback) {
if (typeof callback !== "function") {
return;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
var range = util.getIPRange(ip);
var wrange = util.getWideIPRange(ip);
db.query("SELECT * FROM `channel_bans` WHERE ip IN (?, ?, ?) AND channel=?",
[ip, range, wrange, chan],
function (err, rows) {
callback(err, err ? false : rows.length > 0);
});
},
/**
* Check if a username is banned
*/
isNameBanned: function (chan, name, callback) {
if (typeof callback !== "function") {
return;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("SELECT * FROM `channel_bans` WHERE name=? AND channel=?", [name, chan],
function (err, rows) {
callback(err, err ? false : rows.length > 0);
});
},
/**
* Lists all bans
*/
listBans: function (chan, callback) {
if (typeof callback !== "function") {
return;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("SELECT * FROM `channel_bans` WHERE channel=?", [chan], callback);
},
/**
* Removes a ban from the banlist
*/
unbanId: function (chan, id, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("DELETE FROM `channel_bans` WHERE id=? AND channel=?",
[id, chan], callback);
},
/**
* Removes all bans from a channel
*/
deleteBans: function (chan, id, callback) {
if (typeof callback !== "function") {
callback = blackHole;
}
if (!valid(chan)) {
callback("Invalid channel name", null);
return;
}
db.query("DELETE FROM `channel_bans` WHERE channel=?", [chan], callback);
}
};
|
var searchData=
[
['begin',['begin',['../classTNT_1_1i__refvec.html#a254ea4b6909abc147991b0f3d58d77a7',1,'TNT::i_refvec::begin()'],['../classTNT_1_1i__refvec.html#ad804687b0ece34c37104629467cae2db',1,'TNT::i_refvec::begin() const'],['../classTNT_1_1Vector.html#a8be20c12f428f0762ff546d7146141a1',1,'TNT::Vector::begin()'],['../classTNT_1_1Vector.html#a2a3e40f24376f1578eeb67a39813e580',1,'TNT::Vector::begin() const']]],
['boundary',['boundary',['../classBoundaryCondition.html#ae8f57743167e1fec9b32f8febccf833a',1,'BoundaryCondition']]]
];
|
import { objectToHistory, objectFromHistory } from './'
describe('objectToHistory', () => {
it('returns context with only context and text at the context levels', () => {
const res = objectToHistory({
F: {
context: undefined,
text: 'M',
equation: 'blah'
}
})
expect(res).toEqual({ F: { t: 'M', c: undefined } })
})
})
describe('objectFromHistory', () => {
it('returns context and text from c/t', () => {
const res = objectFromHistory({
F: {
c: {
M: {
t: '1'
}
},
t: 'M'
}
})
expect(res).toEqual({ F: { text: 'M', context: { M: { context: undefined, text: '1' } } } })
})
})
|
const isProduction = process.env.NODE_ENV === 'production';
const path = require('path');
const webpack = require('webpack');
const packageConfig = require('./package.json');
const modulesDirectory = path.resolve(__dirname, 'node_modules');
const sourceDirectory = path.resolve(__dirname, 'src');
const targetDirectory = __dirname;
module.exports = {
entry: [
'babel-polyfill',
path.resolve(sourceDirectory, 'index.js')
],
output: {
path: targetDirectory,
filename: 'index.js'
},
plugins: [
isProduction && new webpack.optimize.UglifyJsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
].filter(Boolean),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{ loader: 'babel-loader', options: { cacheDirectory: true } },
{ loader: 'eslint-loader' }
]
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader', options: { modules: true } }
]
},
{
test: /\.css$/,
include: /node_modules/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' }
]
}
]
},
resolve: {
alias: { _: sourceDirectory },
modules: [modulesDirectory]
}
};
|
Ext.define('Journal.controller.modules.Schedule', {
extend: 'Journal.controller.Module',
shortcutId: 'schedule',
shortcutName: 'Stundu saraksts',
shortcutIconCls: 'schedule-icon',
viewClass: 'schedule', //galvenais skats
views: [ 'modules.ScheduleView', 'modules.AddScheduleView' ],
models: [ 'ScheduleModel', 'ClassRegisterClassModel' ],
stores: [ 'ScheduleStore', 'ClassRegisterClassStore' ],
requires: [
'Journal.Notification'
],
// Pašreizejais mēnesis un gads
curMonth: null,
curYear: null,
idParent: 0,
idStore: 0,
scheduleEditView: null,
startSched: 0,
endSched: 0,
coursesNames: [
[0, 'Informātika'],
[1, 'Latviešu valoda un literatūra'],
[2, 'Matemātika'],
[3, 'Vēsture'],
[4, 'Pirmā svešvaloda (angļu valoda)'],
[5, 'Otrā svešvaloda (vācu vai krievu valoda)'],
[6, 'Sports'],
[7, 'Informātika'],
[8, 'Biznesa ekonomiskie pamati'],
[9, 'Ģeogrāfija'],
[10, 'Fizika'],
[11, 'Ķīmija'],
[12, 'Bioloģija'],
[13, 'Veselības mācība'],
[14, 'Mūzika'],
[15, 'Kultūras vēsture'],
[16, 'Programmēšanas pamati'],
[17, 'Psiholoģija'],
[18, 'Politika un tiesības'],
[19, 'Tehniskā grafika'],
[20, 'Angļu valoda'],
[21, 'Latviešu literatūra'],
[22, 'Krievu valoda'],
[23, 'Fizika'],
[24, 'Ķīmija'],
[25, 'Matemātika'],
[26, 'Latviešu valoda'],
[27, 'Amatu mācība/Mājturība'],
[28, 'Sports'],
[29, 'Franču valoda'],
[30, 'Geogrāfija'],
[31, 'Bioloģija'],
[32, 'Krievu literatūra'],
[33, 'Vizuāla māksla'],
[34, 'Mūzika'],
[35, 'Vēsture'],
[36, 'Informātika']
],
init: function() {
var me = this,
tDate = new Date();
me.callParent();
me.curYear = tDate.getFullYear();
me.curMonth = tDate.getMonth();
me.setStartEndDate();
},
afterMainView: function (mView) {
var me = this;
var crcombo = mView.down('#sv-class-combo');
if(crcombo) crcombo.select(crcombo.store.getAt(0));
},
getLessonTime: function() {
var tDate = new Date(),
shortBreak = 10,
longBreak = 20,
lesson = 45,
time = [];
tDate.setHours(8);
tDate.setMinutes(0);
for (var d = 0; d < 8; d++) {
var hour = tDate.getHours(),
minutes = tDate.getMinutes();
tDate.setMinutes(minutes+lesson);
var endHours = tDate.getHours(),
endMinutes = tDate.getMinutes();
hour = (hour < 10 ? '0':'')+hour;
minutes = (minutes < 10 ? '0':'')+minutes;
timeStr = hour+':'+minutes+' - '+(endHours < 10 ? '0'+endHours:endHours)+':'+(endMinutes < 10 ? '0'+endMinutes:endMinutes);
time[d] = [hour+':'+minutes, timeStr];
tDate.setMinutes(tDate.getMinutes()+(d%4 == 0 ? longBreak:shortBreak));
}
return time;
},
setShceduleInterval: function() {
var me = this,
month = me.curMonth+1,
interval = me.getMView().down('#sv-month-interval');
if(interval){
intText = (month<10? '0':'')+month+'.'+me.curYear;
interval.setText(intText);
}
},
getScheduleData: function () {
var me = this,
cList = me.coursesNames,
scheduleGrid = [],
tDate = new Date(me.curYear, me.curMonth, 1),
fWDay = tDate.getDay(),
shortBreak = 10,
longBreak = 20,
lesson = 45,
dStart = 1,
dEnd = 6;
fWDay = fWDay == 0 ? 7:fWDay;
if(fWDay > 1 && fWDay < 6) me.app.changeDate(tDate, 1-fWDay);
else if(fWDay == 6) me.app.changeDate(tDate, 2);
else if(fWDay == 7) me.app.changeDate(tDate, 1);
// for testing purpose
//me.app.changeDate(tDate, -7);
do {
for(var i = dStart; i < dEnd ;i++) {
var date = tDate.getDate(),
month = tDate.getMonth()+1;
if(month < 10) { month = '0'+month; }
if(date < 10) { date = '0'+date; }
num = Math.floor(4+(8-4)*Math.random());
tDate.setHours(8);
tDate.setMinutes(0);
for (var d = 0; d < num; d++) {
var hour = tDate.getHours(),
minutes = tDate.getMinutes();
tDate.setMinutes(minutes+lesson);
var endHours = tDate.getHours(),
endMinutes = tDate.getMinutes();
hour = (hour < 10 ? '0':'')+hour;
minutes = (minutes < 10 ? '0':'')+minutes;
var c = scheduleGrid.length;
scheduleGrid[c] = [];
scheduleGrid[c][0] = c;
scheduleGrid[c][1] = '';
scheduleGrid[c][2] = date+'.'+month+'.'+tDate.getFullYear();
scheduleGrid[c][3] = tDate.getDay();
scheduleGrid[c][4] = hour+':'+minutes;
scheduleGrid[c][5] = (endHours < 10 ? '0'+endHours:endHours)+':'+(endMinutes < 10 ? '0'+endMinutes:endMinutes);
scheduleGrid[c][6] = '';
scheduleGrid[c][7] = cList[Math.floor(Math.random()*cList.length)][0];
scheduleGrid[c][8] = '';
scheduleGrid[c][9] = '';
scheduleGrid[c][10] = '';
scheduleGrid[c][11] = false;
scheduleGrid[c][12] = '';//2;
scheduleGrid[c][13] = '';//'Diena';
scheduleGrid[c][14] = '';//'01.04.2012';
scheduleGrid[c][15] = '';// 5;
tDate.setMinutes(tDate.getMinutes()+(d%4 == 0 ? longBreak:shortBreak));
}
var c = scheduleGrid.length;
scheduleGrid[c] = [];
scheduleGrid[c][0] = c;
scheduleGrid[c][1] = '';
scheduleGrid[c][2] = date+'.'+month+'.'+tDate.getFullYear();
scheduleGrid[c][3] = tDate.getDay();
scheduleGrid[c][4] = '99:99';
scheduleGrid[c][5] = '';
scheduleGrid[c][6] = '';
scheduleGrid[c][7] = '';
scheduleGrid[c][8] = '';
scheduleGrid[c][9] = '';
scheduleGrid[c][10] = '';
scheduleGrid[c][11] = '';
scheduleGrid[c][12] = '';
scheduleGrid[c][13] = '';
scheduleGrid[c][14] = '';
scheduleGrid[c][15] = '';
me.app.changeDate(tDate, scheduleGrid[c][3] == 5 ?3:1);
}
} while (tDate.getMonth() <= me.curMonth);
return scheduleGrid;
},
onScheduleEventClick: function (dataView, rec, item, index, e, eOpts) {
var me = this;
data = rec.data,
me.scheduleEditView = Ext.widget('addschedule', { app: me.app, controller: me });
if(data.sc_from != '99:99') {
me.scheduleEditView.items.getAt(0).loadRecord(rec);
} else {
me.scheduleEditView.items.getAt(0).loadRecord(new Journal.model.ScheduleModel({
sc_date: data['sc_date']
}));
}
me.getMView().add(me.scheduleEditView);
me.scheduleEditView.show();
me.getMView().setDisabled(true);
},
onCheckHide: function(chb, state) {
var me = this,
shl = me.scheduleEditView,
fVals = shl.items.getAt(0).getValues(),
tDate = shl.down('#fields-to-hide3').safeParse(fVals.sc_date, 'd.m.Y');
me.app.changeDate(tDate, 1);
//shl.down('#fields-to-hide1').clearInvalid();
//shl.down('#fields-to-hide2').clearInvalid();
//shl.down('#fields-to-hide3').clearInvalid();
shl.down('#fields-to-hide1').setDisabled(!state);
shl.down('#fields-to-hide2').setDisabled(!state);
shl.down('#fields-to-hide3').setDisabled(!state);
shl.down('#fields-to-hide1').setVisible(state);
shl.down('#fields-to-hide2').setVisible(state);
shl.down('#fields-to-hide3').setVisible(state);
me.scheduleEditView.items.getAt(0).loadRecord(new Journal.model.ScheduleModel({
sc_cr_id: fVals.sc_cr_id,
sc_date: fVals.sc_date,
sc_from: fVals.sc_from,
sc_selected: state,
freq_count: !fVals.freq_count ? 1:fVals.freq_count,
freq_period: !fVals.freq_period ? 2:fVals.freq_period,
sc_till: !fVals.sc_till && !state ? tDate:(fVals.sc_till || '')
//sc_till: !fVals.sc_till && !state ? tDate:''
}));
},
onSheduleSaveEdit: function() {
var me = this,
dForm = me.scheduleEditView.items.getAt(0), // Form
fVals = dForm.getValues(),
vModel = new Journal.model.ScheduleModel(fVals),
errors = vModel.validate(),
store = this.getMView().items.getAt(0).store;
me.idStore = this.getMView().items.getAt(0).store.count();
if(fVals.sc_selected) {
var curDate = fVals.sc_date.split("."),
tillD = fVals.sc_till.split("."),
tDate = new Date(parseInt(tillD[2],10), parseInt(tillD[1],10)-1, parseInt(tillD[0],10)),
fDate = new Date(parseInt(curDate[2],10), parseInt(curDate[1],10)-1, parseInt(curDate[0],10)),
fqCount = parseInt(fVals.freq_count,10),
fqPeriod = parseInt(fVals.freq_period,10);
}
if(!errors.isValid()) {
dForm.markInvalid(errors);
return false;
}
if(fVals.sc_id) {//edit
var model = this.getMView().items.getAt(0).store.findRecord('sc_id', fVals.sc_id); //selected item in model
if(model && model.data.sc_selected) { // editing repeats in model
me.scheduleEditView.setDisabled(true);
if (fVals.sc_selected) { // editing repeats in model and is selected to repeat in form
Ext.Msg.show({
title:'Saglabāt izmaiņas?',
msg: ' Vai uzdot izmaiņas iepriekš uzdotām periodam?',
modal:true,
buttons: Ext.Msg.YESNO,
icon: Ext.Msg.QUESTION,
fn: function (buttonId, text, opt) {
me.scheduleEditView.setDisabled(false);
switch (buttonId) {
case 'yes':
var month = model.data.sc_till.getMonth()+1,
text = (model.data.sc_till.getDate()<10 ? '0':'')+model.data.sc_till.getDate()+'.'+(month<10 ? '0':'')+month+'.'+model.data.sc_till.getFullYear();
if( model.data.freq_period != fVals.freq_period || model.data.sc_till != fVals.sc_till || model.data.freq_count != fVals.freq_count) {
me.getMView().items.getAt(0).store.each(function(record){
if(record.data.sc_parent === model.data.sc_parent) { //find all repeated items
fVals.sc_date = record.data.sc_date;
fVals.sc_id = record.data.sc_id;
record.set(fVals);
}
}, this );
store.sort();
me.scheduleEditView.close();
} else {//reload data
me.scheduleEditView.setDisabled(true);
me.showError('Iepriekš uzdotām periodam nedrīkst mainīt atkārtojuma biežumu vai datumu līdz kuram atkārtot!');
me.scheduleEditView.setDisabled(false);
me.scheduleEditView.items.getAt(0).loadRecord(new Journal.model.ScheduleModel({
sc_cr_id: model.data.sc_cr_id,
sc_from: model.data.sc_from,
sc_selected: model.data.sc_selected,
sc_date: model.data.sc_date,
freq_period: model.data.freq_period,
sc_till: model.data.sc_till,
freq_count: model.data.freq_count
}));
}
break;
case 'no':
me.notSelectedInForm(fVals);
break;
}
}
});
} else { // repeats in model but do not selected in form
me.notSelectedInForm(fVals);
}
}else if(model && fVals.sc_selected) { // editing don't repeats in model still but is selected to repeat in form
if(tDate < fDate) {
me.showError('Datums līdz kuram atkārtot ir mazāks par izvēlēto!');
} else {
if(fVals.sc_freq_count == '' || fVals.freq_period == '' || fVals.sc_till == '') {
me.showError('Perioda lauki nav aizpildīti!');
} else {
fVals.sc_parent = me.idParent;
me.idParent=me.idParent-1;
model.set(fVals);
store.sort();
fDate.setDate(fDate.getDate()+(fqPeriod==1 ? fqCount:fqCount*7) );
me.lessonAddingPer(fDate,tDate,fVals, store);
me.scheduleEditView.close();
me.app.baloon('Priekšmets veiksmīgi pievienots!');
}
}
} else if(model){ // editing don't repeats in model still and not selected to repeat in form
model.set(fVals);
store.sort();
me.scheduleEditView.close();
me.app.baloon('Priekšmets veiksmīgi saglabāts!');
}
} else {//new
if(fVals.sc_selected) { //repeats
if(tDate < fDate) {
me.showError('Datums līdz kuram atkārtot ir mazāks par izvēlēto!');
} else {
me.lessonAddingPer(fDate,tDate,fVals, store);
me.scheduleEditView.close();
me.app.baloon('Priekšmets veiksmīgi pievienots!');
}
}else{ //new lesson
fVals.sc_id = me.idStore;
me.idStore = me.idStore + 1;
store.add(fVals);
me.scheduleEditView.close();
me.app.baloon('Priekšmets veiksmīgi pievienots!');
}
}
},
notSelectedInForm: function(fVals){
var me = this,
model = this.getMView().items.getAt(0).store.findRecord('sc_id', fVals.sc_id);
fVals.freq_count = '';
fVals.freq_period = '';
fVals.sc_till = '';
fVals.sc_selected = false;
fVals.sc_parent = '';
model.set(fVals);
me.scheduleEditView.close();
me.app.baloon('Priekšmets veiksmīgi saglabāts!');
},
lessonAddingPer: function(fDate,tDate,fVals, store) {
var me = this,
fqCount = parseInt(fVals.freq_count,10),
fqPeriod = parseInt(fVals.freq_period,10);
me.idParent = me.idParent + 1;
switch (fqPeriod) {
case 1: //Day
me.setPeriod(fqCount, fqPeriod, fDate, tDate, fVals, store);
break;
case 2: //Week
me.setPeriod(fqCount, fqPeriod, fDate, tDate, fVals, store);
break;
}
},
setPeriod: function(fqCount, fqPeriod, fDate, tDate, fVals, store){
var me = this;
while( fDate <= tDate ){
var wday = fDate.getDay(),
daySkeep = 0,
curDay,
month = parseInt(fDate.getMonth(),10)+1,
plusDays = fqCount*(fqPeriod == 1 ? 1:5);
while(daySkeep < plusDays) {
if(wday+plusDays-daySkeep >= 6) plusDays++;
if(wday+plusDays-daySkeep >= 7) plusDays++;
daySkeep += 7;
}
fVals.sc_id = me.idStore++;
fVals.sc_date = (fDate.getDate()<10 ? '0':'')+fDate.getDate()+'.'+(month<10 ? '0':'')+month+'.'+fDate.getFullYear();
fVals.sc_parent = me.idParent;
store.add(fVals);
me.app.changeDate(fDate, plusDays);
}
},
setMonthPickerDate: function (cmp, e) {
if(cmp.setValue) cmp.setValue(new Date(this.curYear, this.curMonth, 1));
},
showError: function(text){
var me = this,
msgTxt = text;
Ext.Msg.show({
title:'Kļūda',
msg: msgTxt,
buttons: Ext.Msg.OK,
icon: Ext.Msg.ERROR
});
},
onDateSet: function(cmp, arr, e) {
var me = this,
dt = cmp.getValue();
//alert(dt+'; check:'+(dt[0] !== null ? dt[0]:me.curMonth));
me.curMonth = dt[0] !== null ? dt[0]:me.curMonth;
me.curYear = dt[1] || me.curYear;
me.setStartEndDate();
me.setShceduleInterval();
me.getMView().items.getAt(0).store.load();
me.filterSchedule();
},
// View handlers --------------------------- START
classSelector: function () {
var me = this;
me.setShceduleInterval();
this.getMView().items.getAt(0).store.loadData(me.getScheduleData());
//this.getMView().callParent();
me.filterSchedule();
},
nextButtonHandler: function(){
var me = this;
me.curMonth = me.curMonth + 1;
if ( me.curMonth > 11 ) {
me.curYear = me.curYear + 1;
me.curMonth = 0;
}
me.setStartEndDate();
me.setShceduleInterval();
me.getMView().items.getAt(0).store.loadData(me.getScheduleData());
me.filterSchedule();
},
prevButtonHandler: function(){
var me = this;
if (!me.curMonth) {
me.curYear = me.curYear - 1;
me.curMonth = 12;
}
me.curMonth = me.curMonth - 1;
me.setStartEndDate();
me.setShceduleInterval();
me.getMView().items.getAt(0).store.load();
me.filterSchedule();
},
// View handlers --------------------------- END
beforeSchedileEditClose: function(panel, eOps){
this.getMView().setDisabled(false);
},
setStartEndDate: function(){
var me = this,
sDate = new Date(me.curYear, me.curMonth, 1),
sWDay = sDate.getDay(),
// Dienu skaits mēnesī
curMonth = new Date(sDate.getFullYear(),sDate.getMonth()+1,0).getDate(),
fDate = new Date(sDate.getFullYear(),sDate.getMonth(), curMonth);
fWday = fDate.getDay();
sWDay = sWDay == 0 ? 7:sWDay;
fWday = fWday == 0 ? 7:fWday;
// iegūstam mēneša perodu, kuru attēlosīm nosardības sarakstā
// Ipriekšejais mēnesis
if(sWDay > 1 && sWDay < 6) me.app.changeDate(sDate, 1-sWDay);
else if(sWDay == 6) me.app.changeDate(sDate, 2);
else if(sWDay == 7) me.app.changeDate(sDate, 1);
me.startSched = sDate;
// Nākamais mēnesis
if(fWday >= 1 && fWday < 6) me.app.changeDate(fDate, 5-fWday);
else if(fWday == 6) me.app.changeDate(fDate, -1);
else if(fWday == 7) me.app.changeDate(fDate, -2);
me.endSched = fDate;
},
filterSchedule: function () {
var me = this,
psstore = me.getMView().items.getAt(0).store;
if(psstore) {
psstore.clearFilter();
psstore.filter([{
filterFn: function(item) {
if( item.get('sc_date') >= me.startSched && item.get('sc_date') <= me.endSched )
return true;
}
}]);
}
}
});
|
var models = require('../models/models.js');
// Autoload :id
exports.load = function(req, res, next, quizId) {
models.Quiz.find({
where: {
id: Number(quizId)
},
// incluimos en req.quiz la propiedad Comments con todos los comentarios asociados al quiz
include: [{
model: models.Comment
}]
}).then(
function(quiz) {
if (quiz) {
req.quiz = quiz;
next();
} else {next(new Error('No existe quizId=' + quizId))}
}
).catch(function(error){next(error)});
};
// GET /quizes
// buscamos preguntas "/quizes?search=texto_a_buscar" o las listamos todas "/quizes"
exports.index = function(req, res) {
var search = req.query.search || "";
// reemplazar todos los espacios por %
search = "%" + search.replace(/ /g, "%") + "%";
// "models.Quiz.findAll().then(" busca todo en la tabla
// buscamos las preguntas ordenadas alfabéticamente por el campo "pregunta"
models.Quiz.findAll({where: ["lower(pregunta) like lower(?)", search], order: "lower(pregunta)"}).then(
function(quizes) {
res.render('quizes/index.ejs', {quizes: quizes, errors: []});
}
).catch(function(error){next(error)});
};
// GET /quizes/:id
exports.show = function(req, res) {
res.render('quizes/show', { quiz: req.quiz, errors: []});
}; // req.quiz: instancia de quiz cargada con autoload
// GET /quizes/:id/answer
exports.answer = function(req, res) {
var resultado = 'Incorrecto';
if (req.query.respuesta === req.quiz.respuesta) {
resultado = 'Correcto';
}
res.render(
'quizes/answer',
{ quiz: req.quiz,
respuesta: resultado,
errors: []
}
);
};
// GET /quizes/new
exports.new = function(req, res) {
var quiz = models.Quiz.build( // crea objeto quiz
{pregunta: "Pregunta", respuesta: "Respuesta", tema: "Otro"}
);
res.render('quizes/new', {quiz: quiz, errors: []});
};
// POST /quizes/create
exports.create = function(req, res) {
var quiz = models.Quiz.build( req.body.quiz );
// guarda en DB los campos pregunta y respuesta de quiz
quiz
.validate()
.then(
function(err){
if (err) {
res.render('quizes/new', {quiz: quiz, errors: err.errors});
} else {
quiz // save: guarda en DB campos pregunta y respuesta de quiz
.save({fields: ["pregunta", "respuesta", "tema"]})
.then( function(){ res.redirect('/quizes')})
} // res.redirect: Redirección HTTP a lista de preguntas
}
).catch(function(error){next(error)});
};
// GET /quizes/:id/edit
exports.edit = function(req, res) {
var quiz = req.quiz; // req.quiz: autoload de instancia de quiz
res.render('quizes/edit', {quiz: quiz, errors: []});
};
// PUT /quizes/:id
exports.update = function(req, res) {
req.quiz.pregunta = req.body.quiz.pregunta;
req.quiz.respuesta = req.body.quiz.respuesta;
req.quiz.tema = req.body.quiz.tema;
req.quiz
.validate()
.then(
function(err){
if (err) {
res.render('quizes/edit', {quiz: req.quiz, errors: err.errors});
} else {
req.quiz // save: guarda campos pregunta y respuesta en DB
.save( {fields: ["pregunta", "respuesta", "tema"]})
.then( function(){ res.redirect('/quizes');});
} // Redirección HTTP a lista de preguntas (URL relativo)
}
).catch(function(error){next(error)});
};
// DELETE /quizes/:id
exports.destroy = function(req, res) {
req.quiz.destroy().then( function() {
res.redirect('/quizes');
}).catch(function(error){next(error)});
};
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
const core_1 = require('@angular/core');
const router_1 = require('@angular/router');
const login_service_1 = require('../services/login.service');
const user_1 = require('../model/user');
let RegisterComponent = class RegisterComponent {
constructor(_loginService, _route, _router) {
this._loginService = _loginService;
this._route = _route;
this._router = _router;
this.titulo = "Registro";
}
ngOnInit() {
this.user = new user_1.User(1, "user", "", "", "", "", "");
}
onSubmit() {
console.log(this.user);
this._loginService.register(this.user).subscribe(response => {
this.status = response.status;
if (this.status != "success") {
this.status = "error";
}
}, error => {
this.errorMessage = error;
if (this.errorMessage != null) {
console.log(this.errorMessage);
alert("Error en la petición");
}
});
}
};
RegisterComponent = __decorate([
core_1.Component({
selector: 'register',
templateUrl: 'app/view/register.html',
directives: [router_1.ROUTER_DIRECTIVES],
providers: [login_service_1.LoginService]
}),
__metadata('design:paramtypes', [login_service_1.LoginService, router_1.ActivatedRoute, router_1.Router])
], RegisterComponent);
exports.RegisterComponent = RegisterComponent;
//# sourceMappingURL=register.component.js.map
|
if (typeof module !== 'undefined' && module.exports) {
var chai = require('chai');
var Papa = require('../papaparse.js');
}
var assert = chai.assert;
var RECORD_SEP = String.fromCharCode(30);
var UNIT_SEP = String.fromCharCode(31);
var FILES_ENABLED = false;
try {
new File([""], "");
FILES_ENABLED = true;
} catch (e) {} // safari, ie
var XHR_ENABLED = false;
try {
new XMLHttpRequest();
XHR_ENABLED = true;
} catch (e) {} // safari, ie
// Tests for the core parser using new Papa.Parser().parse() (CSV to JSON)
var CORE_PARSER_TESTS = [
{
description: "One row",
input: 'A,b,c',
expected: {
data: [['A', 'b', 'c']],
errors: []
}
},
{
description: "Two rows",
input: 'A,b,c\nd,E,f',
expected: {
data: [['A', 'b', 'c'], ['d', 'E', 'f']],
errors: []
}
},
{
description: "Three rows",
input: 'A,b,c\nd,E,f\nG,h,i',
expected: {
data: [['A', 'b', 'c'], ['d', 'E', 'f'], ['G', 'h', 'i']],
errors: []
}
},
{
description: "Whitespace at edges of unquoted field",
input: 'a, b ,c',
notes: "Extra whitespace should graciously be preserved",
expected: {
data: [['a', ' b ', 'c']],
errors: []
}
},
{
description: "Quoted field",
input: 'A,"B",C',
expected: {
data: [['A', 'B', 'C']],
errors: []
}
},
{
description: "Quoted field with extra whitespace on edges",
input: 'A," B ",C',
expected: {
data: [['A', ' B ', 'C']],
errors: []
}
},
{
description: "Quoted field with delimiter",
input: 'A,"B,B",C',
expected: {
data: [['A', 'B,B', 'C']],
errors: []
}
},
{
description: "Quoted field with line break",
input: 'A,"B\nB",C',
expected: {
data: [['A', 'B\nB', 'C']],
errors: []
}
},
{
description: "Quoted fields with line breaks",
input: 'A,"B\nB","C\nC\nC"',
expected: {
data: [['A', 'B\nB', 'C\nC\nC']],
errors: []
}
},
{
description: "Quoted fields at end of row with delimiter and line break",
input: 'a,b,"c,c\nc"\nd,e,f',
expected: {
data: [['a', 'b', 'c,c\nc'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Quoted field with escaped quotes",
input: 'A,"B""B""B",C',
expected: {
data: [['A', 'B"B"B', 'C']],
errors: []
}
},
{
description: "Quoted field with escaped quotes at boundaries",
input: 'A,"""B""",C',
expected: {
data: [['A', '"B"', 'C']],
errors: []
}
},
{
description: "Unquoted field with quotes at end of field",
notes: "The quotes character is misplaced, but shouldn't generate an error or break the parser",
input: 'A,B",C',
expected: {
data: [['A', 'B"', 'C']],
errors: []
}
},
{
description: "Quoted field with quotes around delimiter",
input: 'A,""",""",C',
notes: "For a boundary to exist immediately before the quotes, we must not already be in quotes",
expected: {
data: [['A', '","', 'C']],
errors: []
}
},
{
description: "Quoted field with quotes on right side of delimiter",
input: 'A,",""",C',
notes: "Similar to the test above but with quotes only after the comma",
expected: {
data: [['A', ',"', 'C']],
errors: []
}
},
{
description: "Quoted field with quotes on left side of delimiter",
input: 'A,""",",C',
notes: "Similar to the test above but with quotes only before the comma",
expected: {
data: [['A', '",', 'C']],
errors: []
}
},
{
description: "Quoted field with 5 quotes in a row and a delimiter in there, too",
input: '"1","cnonce="""",nc=""""","2"',
notes: "Actual input reported in issue #121",
expected: {
data: [['1', 'cnonce="",nc=""', '2']],
errors: []
}
},
{
description: "Quoted field with whitespace around quotes",
input: 'A, "B" ,C',
notes: "The quotes must be immediately adjacent to the delimiter to indicate a quoted field",
expected: {
data: [['A', ' "B" ', 'C']],
errors: []
}
},
{
description: "Misplaced quotes in data, not as opening quotes",
input: 'A,B "B",C',
notes: "The input is technically malformed, but this syntax should not cause an error",
expected: {
data: [['A', 'B "B"', 'C']],
errors: []
}
},
{
description: "Quoted field has no closing quote",
input: 'a,"b,c\nd,e,f',
expected: {
data: [['a', 'b,c\nd,e,f']],
errors: [{
"type": "Quotes",
"code": "MissingQuotes",
"message": "Quoted field unterminated",
"row": 0,
"index": 3
}]
}
},
{
description: "Line starts with quoted field",
input: 'a,b,c\n"d",e,f',
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Line ends with quoted field",
input: 'a,b,c\nd,e,f\n"g","h","i"\n"j","k","l"',
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']],
errors: []
}
},
{
description: "Quoted field at end of row (but not at EOF) has quotes",
input: 'a,b,"c""c"""\nd,e,f',
expected: {
data: [['a', 'b', 'c"c"'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Empty quoted field at EOF is empty",
input: 'a,b,""\na,b,""',
expected: {
data: [['a', 'b', ''], ['a', 'b', '']],
errors: []
}
},
{
description: "Multiple consecutive empty fields",
input: 'a,b,,,c,d\n,,e,,,f',
expected: {
data: [['a', 'b', '', '', 'c', 'd'], ['', '', 'e', '', '', 'f']],
errors: []
}
},
{
description: "Empty input string",
input: '',
expected: {
data: [],
errors: []
}
},
{
description: "Input is just the delimiter (2 empty fields)",
input: ',',
expected: {
data: [['', '']],
errors: []
}
},
{
description: "Input is just empty fields",
input: ',,\n,,,',
expected: {
data: [['', '', ''], ['', '', '', '']],
errors: []
}
},
{
description: "Input is just a string (a single field)",
input: 'Abc def',
expected: {
data: [['Abc def']],
errors: []
}
},
{
description: "Commented line at beginning",
input: '# Comment!\na,b,c',
config: { comments: true },
expected: {
data: [['a', 'b', 'c']],
errors: []
}
},
{
description: "Commented line in middle",
input: 'a,b,c\n# Comment\nd,e,f',
config: { comments: true },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Commented line at end",
input: 'a,true,false\n# Comment',
config: { comments: true },
expected: {
data: [['a', 'true', 'false']],
errors: []
}
},
{
description: "Two comment lines consecutively",
input: 'a,b,c\n#comment1\n#comment2\nd,e,f',
config: { comments: true },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Two comment lines consecutively at end of file",
input: 'a,b,c\n#comment1\n#comment2',
config: { comments: true },
expected: {
data: [['a', 'b', 'c']],
errors: []
}
},
{
description: "Three comment lines consecutively at beginning of file",
input: '#comment1\n#comment2\n#comment3\na,b,c',
config: { comments: true },
expected: {
data: [['a', 'b', 'c']],
errors: []
}
},
{
description: "Entire file is comment lines",
input: '#comment1\n#comment2\n#comment3',
config: { comments: true },
expected: {
data: [],
errors: []
}
},
{
description: "Comment with non-default character",
input: 'a,b,c\n!Comment goes here\nd,e,f',
config: { comments: '!' },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Bad comments value specified",
notes: "Should silently disable comment parsing",
input: 'a,b,c\n5comment\nd,e,f',
config: { comments: 5 },
expected: {
data: [['a', 'b', 'c'], ['5comment'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Multi-character comment string",
input: 'a,b,c\n=N(Comment)\nd,e,f',
config: { comments: "=N(" },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Input with only a commented line",
input: '#commented line',
config: { comments: true, delimiter: ',' },
expected: {
data: [],
errors: []
}
},
{
description: "Input with only a commented line and blank line after",
input: '#commented line\n',
config: { comments: true, delimiter: ',' },
expected: {
data: [['']],
errors: []
}
},
{
description: "Input with only a commented line, without comments enabled",
input: '#commented line',
config: { delimiter: ',' },
expected: {
data: [['#commented line']],
errors: []
}
},
{
description: "Input without comments with line starting with whitespace",
input: 'a\n b\nc',
config: { delimiter: ',' },
notes: "\" \" == false, but \" \" !== false, so === comparison is required",
expected: {
data: [['a'], [' b'], ['c']],
errors: []
}
},
{
description: "Multiple rows, one column (no delimiter found)",
input: 'a\nb\nc\nd\ne',
expected: {
data: [['a'], ['b'], ['c'], ['d'], ['e']],
errors: []
}
},
{
description: "One column input with empty fields",
input: 'a\nb\n\n\nc\nd\ne\n',
expected: {
data: [['a'], ['b'], [''], [''], ['c'], ['d'], ['e'], ['']],
errors: []
}
},
{
description: "Fast mode, basic",
input: 'a,b,c\nd,e,f',
config: { fastMode: true },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Fast mode with comments",
input: '// Commented line\na,b,c',
config: { fastMode: true, comments: "//" },
expected: {
data: [['a', 'b', 'c']],
errors: []
}
},
{
description: "Fast mode with preview",
input: 'a,b,c\nd,e,f\nh,j,i\n',
config: { fastMode: true, preview: 2 },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Fast mode with blank line at end",
input: 'a,b,c\n',
config: { fastMode: true },
expected: {
data: [['a', 'b', 'c'], ['']],
errors: []
}
}
];
describe('Core Parser Tests', function() {
function generateTest(test) {
(test.disabled ? it.skip : it)(test.description, function() {
var actual = new Papa.Parser(test.config).parse(test.input);
assert.deepEqual(JSON.stringify(actual.errors), JSON.stringify(test.expected.errors));
assert.deepEqual(actual.data, test.expected.data);
});
}
for (var i = 0; i < CORE_PARSER_TESTS.length; i++) {
generateTest(CORE_PARSER_TESTS[i]);
}
});
// Tests for Papa.parse() function -- high-level wrapped parser (CSV to JSON)
var PARSE_TESTS = [
{
description: "Two rows, just \\r",
input: 'A,b,c\rd,E,f',
expected: {
data: [['A', 'b', 'c'], ['d', 'E', 'f']],
errors: []
}
},
{
description: "Two rows, \\r\\n",
input: 'A,b,c\r\nd,E,f',
expected: {
data: [['A', 'b', 'c'], ['d', 'E', 'f']],
errors: []
}
},
{
description: "Quoted field with \\r\\n",
input: 'A,"B\r\nB",C',
expected: {
data: [['A', 'B\r\nB', 'C']],
errors: []
}
},
{
description: "Quoted field with \\r",
input: 'A,"B\rB",C',
expected: {
data: [['A', 'B\rB', 'C']],
errors: []
}
},
{
description: "Quoted field with \\n",
input: 'A,"B\nB",C',
expected: {
data: [['A', 'B\nB', 'C']],
errors: []
}
},
{
description: "Mixed slash n and slash r should choose first as precident",
input: 'a,b,c\nd,e,f\rg,h,i\n',
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f\rg', 'h', 'i'], ['']],
errors: []
}
},
{
description: "Header row with one row of data",
input: 'A,B,C\r\na,b,c',
config: { header: true },
expected: {
data: [{"A": "a", "B": "b", "C": "c"}],
errors: []
}
},
{
description: "Header row only",
input: 'A,B,C',
config: { header: true },
expected: {
data: [],
errors: []
}
},
{
description: "Row with too few fields",
input: 'A,B,C\r\na,b',
config: { header: true },
expected: {
data: [{"A": "a", "B": "b"}],
errors: [{
"type": "FieldMismatch",
"code": "TooFewFields",
"message": "Too few fields: expected 3 fields but parsed 2",
"row": 0
}]
}
},
{
description: "Row with too many fields",
input: 'A,B,C\r\na,b,c,d,e\r\nf,g,h',
config: { header: true },
expected: {
data: [{"A": "a", "B": "b", "C": "c", "__parsed_extra": ["d", "e"]}, {"A": "f", "B": "g", "C": "h"}],
errors: [{
"type": "FieldMismatch",
"code": "TooManyFields",
"message": "Too many fields: expected 3 fields but parsed 5",
"row": 0
}]
}
},
{
description: "Row with enough fields but blank field at end",
input: 'A,B,C\r\na,b,',
config: { header: true },
expected: {
data: [{"A": "a", "B": "b", "C": ""}],
errors: []
}
},
{
description: "Tab delimiter",
input: 'a\tb\tc\r\nd\te\tf',
config: { delimiter: "\t" },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Pipe delimiter",
input: 'a|b|c\r\nd|e|f',
config: { delimiter: "|" },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "ASCII 30 delimiter",
input: 'a'+RECORD_SEP+'b'+RECORD_SEP+'c\r\nd'+RECORD_SEP+'e'+RECORD_SEP+'f',
config: { delimiter: RECORD_SEP },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "ASCII 31 delimiter",
input: 'a'+UNIT_SEP+'b'+UNIT_SEP+'c\r\nd'+UNIT_SEP+'e'+UNIT_SEP+'f',
config: { delimiter: UNIT_SEP },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Bad delimiter (\\n)",
input: 'a,b,c',
config: { delimiter: "\n" },
notes: "Should silently default to comma",
expected: {
data: [['a', 'b', 'c']],
errors: []
}
},
{
description: "Multi-character delimiter",
input: 'a, b, c',
config: { delimiter: ", " },
expected: {
data: [['a', 'b', 'c']],
errors: []
}
},
{
description: "Dynamic typing converts numeric literals",
input: '1,2.2,1e3\r\n-4,-4.5,-4e-5\r\n-,5a,5-2',
config: { dynamicTyping: true },
expected: {
data: [[1, 2.2, 1000], [-4, -4.5, -0.00004], ["-", "5a", "5-2"]],
errors: []
}
},
{
description: "Dynamic typing converts boolean literals",
input: 'true,false,T,F,TRUE,FALSE,True,False',
config: { dynamicTyping: true },
expected: {
data: [[true, false, "T", "F", true, false, "True", "False"]],
errors: []
}
},
{
description: "Dynamic typing doesn't convert other types",
input: 'A,B,C\r\nundefined,null,[\r\nvar,float,if',
config: { dynamicTyping: true },
expected: {
data: [["A", "B", "C"], ["undefined", "null", "["], ["var", "float", "if"]],
errors: []
}
},
{
description: "Dynamic typing applies to specific columns",
input: 'A,B,C\r\n1,2.2,1e3\r\n-4,-4.5,-4e-5',
config: { header: true, dynamicTyping: { A: true, C: true } },
expected: {
data: [{"A": 1, "B": "2.2", "C": 1000}, {"A": -4, "B": "-4.5", "C": -0.00004}],
errors: []
}
},
{
description: "Dynamic typing applies to specific columns by index",
input: '1,2.2,1e3\r\n-4,-4.5,-4e-5\r\n-,5a,5-2',
config: { dynamicTyping: { 1: true } },
expected: {
data: [["1", 2.2, "1e3"], ["-4", -4.5, "-4e-5"], ["-", "5a", "5-2"]],
errors: []
}
},
{
description: "Dynamic typing can be applied to `__parsed_extra`",
input: 'A,B,C\r\n1,2.2,1e3,5.5\r\n-4,-4.5,-4e-5',
config: { header: true, dynamicTyping: { A: true, C: true, __parsed_extra: true } },
expected: {
data: [{"A": 1, "B": "2.2", "C": 1000, "__parsed_extra": [ 5.5 ]}, {"A": -4, "B": "-4.5", "C": -0.00004}],
errors: [{
"type": "FieldMismatch",
"code": "TooManyFields",
"message": "Too many fields: expected 3 fields but parsed 4",
"row": 0
}]
}
},
{
description: "Blank line at beginning",
input: '\r\na,b,c\r\nd,e,f',
config: { newline: '\r\n' },
expected: {
data: [[''], ['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Blank line in middle",
input: 'a,b,c\r\n\r\nd,e,f',
config: { newline: '\r\n' },
expected: {
data: [['a', 'b', 'c'], [''], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Blank lines at end",
input: 'a,b,c\nd,e,f\n\n',
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f'], [''], ['']],
errors: []
}
},
{
description: "Blank line in middle with whitespace",
input: 'a,b,c\r\n \r\nd,e,f',
expected: {
data: [['a', 'b', 'c'], [" "], ['d', 'e', 'f']],
errors: []
}
},
{
description: "First field of a line is empty",
input: 'a,b,c\r\n,e,f',
expected: {
data: [['a', 'b', 'c'], ['', 'e', 'f']],
errors: []
}
},
{
description: "Last field of a line is empty",
input: 'a,b,\r\nd,e,f',
expected: {
data: [['a', 'b', ''], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Other fields are empty",
input: 'a,,c\r\n,,',
expected: {
data: [['a', '', 'c'], ['', '', '']],
errors: []
}
},
{
description: "Empty input string",
input: '',
expected: {
data: [],
errors: [{
"type": "Delimiter",
"code": "UndetectableDelimiter",
"message": "Unable to auto-detect delimiting character; defaulted to ','"
}]
}
},
{
description: "Input is just the delimiter (2 empty fields)",
input: ',',
expected: {
data: [['', '']],
errors: []
}
},
{
description: "Input is just a string (a single field)",
input: 'Abc def',
expected: {
data: [['Abc def']],
errors: [
{
"type": "Delimiter",
"code": "UndetectableDelimiter",
"message": "Unable to auto-detect delimiting character; defaulted to ','"
}
]
}
},
{
description: "Preview 0 rows should default to parsing all",
input: 'a,b,c\r\nd,e,f\r\ng,h,i',
config: { preview: 0 },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']],
errors: []
}
},
{
description: "Preview 1 row",
input: 'a,b,c\r\nd,e,f\r\ng,h,i',
config: { preview: 1 },
expected: {
data: [['a', 'b', 'c']],
errors: []
}
},
{
description: "Preview 2 rows",
input: 'a,b,c\r\nd,e,f\r\ng,h,i',
config: { preview: 2 },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Preview all (3) rows",
input: 'a,b,c\r\nd,e,f\r\ng,h,i',
config: { preview: 3 },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']],
errors: []
}
},
{
description: "Preview more rows than input has",
input: 'a,b,c\r\nd,e,f\r\ng,h,i',
config: { preview: 4 },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']],
errors: []
}
},
{
description: "Preview should count rows, not lines",
input: 'a,b,c\r\nd,e,"f\r\nf",g,h,i',
config: { preview: 2 },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f\r\nf', 'g', 'h', 'i']],
errors: []
}
},
{
description: "Preview with header row",
notes: "Preview is defined to be number of rows of input not including header row",
input: 'a,b,c\r\nd,e,f\r\ng,h,i\r\nj,k,l',
config: { header: true, preview: 2 },
expected: {
data: [{"a": "d", "b": "e", "c": "f"}, {"a": "g", "b": "h", "c": "i"}],
errors: []
}
},
{
description: "Empty lines",
input: '\na,b,c\n\nd,e,f\n\n',
config: { delimiter: ',' },
expected: {
data: [[''], ['a', 'b', 'c'], [''], ['d', 'e', 'f'], [''], ['']],
errors: []
}
},
{
description: "Skip empty lines",
input: 'a,b,c\n\nd,e,f',
config: { skipEmptyLines: true },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Skip empty lines, with newline at end of input",
input: 'a,b,c\r\n\r\nd,e,f\r\n',
config: { skipEmptyLines: true },
expected: {
data: [['a', 'b', 'c'], ['d', 'e', 'f']],
errors: []
}
},
{
description: "Skip empty lines, with empty input",
input: '',
config: { skipEmptyLines: true },
expected: {
data: [],
errors: [
{
"type": "Delimiter",
"code": "UndetectableDelimiter",
"message": "Unable to auto-detect delimiting character; defaulted to ','"
}
]
}
},
{
description: "Skip empty lines, with first line only whitespace",
notes: "A line must be absolutely empty to be considered empty",
input: ' \na,b,c',
config: { skipEmptyLines: true, delimiter: ',' },
expected: {
data: [[" "], ['a', 'b', 'c']],
errors: []
}
},
{
description: "Single quote as quote character",
notes: "Must parse correctly when single quote is specified as a quote character",
input: "a,b,'c,d'",
config: { quoteChar: "'"},
expected: {
data: [['a', 'b', 'c,d']],
errors: []
}
}
];
describe('Parse Tests', function() {
function generateTest(test) {
(test.disabled ? it.skip : it)(test.description, function() {
var actual = Papa.parse(test.input, test.config);
assert.deepEqual(JSON.stringify(actual.errors), JSON.stringify(test.expected.errors));
assert.deepEqual(actual.data, test.expected.data);
});
}
for (var i = 0; i < PARSE_TESTS.length; i++) {
generateTest(PARSE_TESTS[i]);
}
});
// Tests for Papa.parse() that involve asynchronous operation
var PARSE_ASYNC_TESTS = [
{
description: "Simple worker",
input: "A,B,C\nX,Y,Z",
config: {
worker: true,
},
expected: {
data: [['A','B','C'],['X','Y','Z']],
errors: []
}
},
{
description: "Simple download",
input: "sample.csv",
config: {
download: true
},
disabled: !XHR_ENABLED,
expected: {
data: [['A','B','C'],['X','Y','Z']],
errors: []
}
},
{
description: "Simple download + worker",
input: "tests/sample.csv",
config: {
worker: true,
download: true
},
disabled: !XHR_ENABLED,
expected: {
data: [['A','B','C'],['X','Y','Z']],
errors: []
}
},
{
description: "Simple file",
disabled: !FILES_ENABLED,
input: FILES_ENABLED ? new File(["A,B,C\nX,Y,Z"], "sample.csv") : false,
config: {
},
expected: {
data: [['A','B','C'],['X','Y','Z']],
errors: []
}
},
{
description: "Simple file + worker",
disabled: !FILES_ENABLED,
input: FILES_ENABLED ? new File(["A,B,C\nX,Y,Z"], "sample.csv") : false,
config: {
worker: true,
},
expected: {
data: [['A','B','C'],['X','Y','Z']],
errors: []
}
}
];
describe('Parse Async Tests', function() {
function generateTest(test) {
(test.disabled ? it.skip : it)(test.description, function(done) {
var config = test.config;
config.complete = function(actual) {
assert.deepEqual(JSON.stringify(actual.errors), JSON.stringify(test.expected.errors));
assert.deepEqual(actual.data, test.expected.data);
done();
};
config.error = function(err) {
throw err;
};
Papa.parse(test.input, config);
});
}
for (var i = 0; i < PARSE_ASYNC_TESTS.length; i++) {
generateTest(PARSE_ASYNC_TESTS[i]);
}
});
// Tests for Papa.unparse() function (JSON to CSV)
var UNPARSE_TESTS = [
{
description: "A simple row",
notes: "Comma should be default delimiter",
input: [['A', 'b', 'c']],
expected: 'A,b,c'
},
{
description: "Two rows",
input: [['A', 'b', 'c'], ['d', 'E', 'f']],
expected: 'A,b,c\r\nd,E,f'
},
{
description: "Data with quotes",
input: [['a', '"b"', 'c'], ['"d"', 'e', 'f']],
expected: 'a,"""b""",c\r\n"""d""",e,f'
},
{
description: "Data with newlines",
input: [['a', 'b\nb', 'c'], ['d', 'e', 'f\r\nf']],
expected: 'a,"b\nb",c\r\nd,e,"f\r\nf"'
},
{
description: "Array of objects (header row)",
input: [{ "Col1": "a", "Col2": "b", "Col3": "c" }, { "Col1": "d", "Col2": "e", "Col3": "f" }],
expected: 'Col1,Col2,Col3\r\na,b,c\r\nd,e,f'
},
{
description: "With header row, missing a field in a row",
input: [{ "Col1": "a", "Col2": "b", "Col3": "c" }, { "Col1": "d", "Col3": "f" }],
expected: 'Col1,Col2,Col3\r\na,b,c\r\nd,,f'
},
{
description: "With header row, with extra field in a row",
notes: "Extra field should be ignored; first object in array dictates header row",
input: [{ "Col1": "a", "Col2": "b", "Col3": "c" }, { "Col1": "d", "Col2": "e", "Extra": "g", "Col3": "f" }],
expected: 'Col1,Col2,Col3\r\na,b,c\r\nd,e,f'
},
{
description: "Specifying column names and data separately",
input: { fields: ["Col1", "Col2", "Col3"], data: [["a", "b", "c"], ["d", "e", "f"]] },
expected: 'Col1,Col2,Col3\r\na,b,c\r\nd,e,f'
},
{
description: "Specifying column names only (no data)",
notes: "Papa should add a data property that is an empty array to prevent errors (no copy is made)",
input: { fields: ["Col1", "Col2", "Col3"] },
expected: 'Col1,Col2,Col3'
},
{
description: "Specifying data only (no field names), improperly",
notes: "A single array for a single row is wrong, but it can be compensated.<br>Papa should add empty fields property to prevent errors.",
input: { data: ["abc", "d", "ef"] },
expected: 'abc,d,ef'
},
{
description: "Specifying data only (no field names), properly",
notes: "An array of arrays, even if just a single row.<br>Papa should add empty fields property to prevent errors.",
input: { data: [["a", "b", "c"]] },
expected: 'a,b,c'
},
{
description: "Custom delimiter (semicolon)",
input: [['A', 'b', 'c'], ['d', 'e', 'f']],
config: { delimiter: ';' },
expected: 'A;b;c\r\nd;e;f'
},
{
description: "Custom delimiter (tab)",
input: [['Ab', 'cd', 'ef'], ['g', 'h', 'ij']],
config: { delimiter: '\t' },
expected: 'Ab\tcd\tef\r\ng\th\tij'
},
{
description: "Custom delimiter (ASCII 30)",
input: [['a', 'b', 'c'], ['d', 'e', 'f']],
config: { delimiter: RECORD_SEP },
expected: 'a'+RECORD_SEP+'b'+RECORD_SEP+'c\r\nd'+RECORD_SEP+'e'+RECORD_SEP+'f'
},
{
description: "Bad delimiter (\\n)",
notes: "Should default to comma",
input: [['a', 'b', 'c'], ['d', 'e', 'f']],
config: { delimiter: '\n' },
expected: 'a,b,c\r\nd,e,f'
},
{
description: "Custom line ending (\\r)",
input: [['a', 'b', 'c'], ['d', 'e', 'f']],
config: { newline: '\r' },
expected: 'a,b,c\rd,e,f'
},
{
description: "Custom line ending (\\n)",
input: [['a', 'b', 'c'], ['d', 'e', 'f']],
config: { newline: '\n' },
expected: 'a,b,c\nd,e,f'
},
{
description: "Custom, but strange, line ending ($)",
input: [['a', 'b', 'c'], ['d', 'e', 'f']],
config: { newline: '$' },
expected: 'a,b,c$d,e,f'
},
{
description: "Force quotes around all fields",
input: [['a', 'b', 'c'], ['d', 'e', 'f']],
config: { quotes: true },
expected: '"a","b","c"\r\n"d","e","f"'
},
{
description: "Force quotes around all fields (with header row)",
input: [{ "Col1": "a", "Col2": "b", "Col3": "c" }, { "Col1": "d", "Col2": "e", "Col3": "f" }],
config: { quotes: true },
expected: '"Col1","Col2","Col3"\r\n"a","b","c"\r\n"d","e","f"'
},
{
description: "Force quotes around certain fields only",
input: [['a', 'b', 'c'], ['d', 'e', 'f']],
config: { quotes: [true, false, true] },
expected: '"a",b,"c"\r\n"d",e,"f"'
},
{
description: "Force quotes around certain fields only (with header row)",
input: [{ "Col1": "a", "Col2": "b", "Col3": "c" }, { "Col1": "d", "Col2": "e", "Col3": "f" }],
config: { quotes: [true, false, true] },
expected: '"Col1",Col2,"Col3"\r\n"a",b,"c"\r\n"d",e,"f"'
},
{
description: "Empty input",
input: [],
expected: ''
},
{
description: "Mismatched field counts in rows",
input: [['a', 'b', 'c'], ['d', 'e'], ['f']],
expected: 'a,b,c\r\nd,e\r\nf'
},
{
description: "JSON null is treated as empty value",
input: [{ "Col1": "a", "Col2": null, "Col3": "c" }],
expected: 'Col1,Col2,Col3\r\na,,c'
}
];
describe('Unparse Tests', function() {
function generateTest(test) {
(test.disabled ? it.skip : it)(test.description, function() {
var actual;
try {
actual = Papa.unparse(test.input, test.config);
} catch (e) {
if (e instanceof Error) {
throw e;
}
actual = e;
}
assert.strictEqual(actual, test.expected);
});
}
for (var i = 0; i < UNPARSE_TESTS.length; i++) {
generateTest(UNPARSE_TESTS[i]);
}
});
var CUSTOM_TESTS = [
{
description: "Complete is called with all results if neither step nor chunk is defined",
expected: [['A', 'b', 'c'], ['d', 'E', 'f'], ['G', 'h', 'i']],
disabled: !FILES_ENABLED,
run: function(callback) {
Papa.parse(new File(['A,b,c\nd,E,f\nG,h,i'], 'sample.csv'), {
chunkSize: 3,
complete: function(response) {
callback(response.data);
}
});
}
},
{
description: "Step is called for each row",
expected: 2,
run: function(callback) {
var callCount = 0;
Papa.parse('A,b,c\nd,E,f', {
step: function() {
callCount++;
},
complete: function() {
callback(callCount);
}
});
}
},
{
description: "Step is called with the contents of the row",
expected: ['A', 'b', 'c'],
run: function(callback) {
Papa.parse('A,b,c', {
step: function(response) {
callback(response.data[0]);
}
});
}
},
{
description: "Step is called with the last cursor position",
expected: [6, 12, 17],
run: function(callback) {
var updates = [];
Papa.parse('A,b,c\nd,E,f\nG,h,i', {
step: function(response) {
updates.push(response.meta.cursor);
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "Step exposes cursor for downloads",
expected: [129, 287, 452, 595, 727, 865, 1031, 1209],
disabled: !XHR_ENABLED,
run: function(callback) {
var updates = [];
Papa.parse("/tests/long-sample.csv", {
download: true,
step: function(response) {
updates.push(response.meta.cursor);
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "Step exposes cursor for chunked downloads",
expected: [129, 287, 452, 595, 727, 865, 1031, 1209],
disabled: !XHR_ENABLED,
run: function(callback) {
var updates = [];
Papa.parse("/tests/long-sample.csv", {
download: true,
chunkSize: 500,
step: function(response) {
updates.push(response.meta.cursor);
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "Step exposes cursor for workers",
expected: [452, 452, 452, 865, 865, 865, 1209, 1209],
disabled: !XHR_ENABLED,
run: function(callback) {
var updates = [];
Papa.parse("/tests/long-sample.csv", {
download: true,
chunkSize: 500,
worker: true,
step: function(response) {
updates.push(response.meta.cursor);
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "Chunk is called for each chunk",
expected: [3, 3, 2],
disabled: !XHR_ENABLED,
run: function(callback) {
var updates = [];
Papa.parse("/tests/long-sample.csv", {
download: true,
chunkSize: 500,
chunk: function(response) {
updates.push(response.data.length);
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "Chunk is called with cursor position",
expected: [452, 865, 1209],
disabled: !XHR_ENABLED,
run: function(callback) {
var updates = [];
Papa.parse("/tests/long-sample.csv", {
download: true,
chunkSize: 500,
chunk: function(response) {
updates.push(response.meta.cursor);
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "Step exposes indexes for files",
expected: [6, 12, 17],
disabled: !FILES_ENABLED,
run: function(callback) {
var updates = [];
Papa.parse(new File(['A,b,c\nd,E,f\nG,h,i'], 'sample.csv'), {
download: true,
step: function(response) {
updates.push(response.meta.cursor);
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "Step exposes indexes for chunked files",
expected: [6, 12, 17],
disabled: !FILES_ENABLED,
run: function(callback) {
var updates = [];
Papa.parse(new File(['A,b,c\nd,E,f\nG,h,i'], 'sample.csv'), {
chunkSize: 3,
step: function(response) {
updates.push(response.meta.cursor);
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "Quoted line breaks near chunk boundaries are handled",
expected: [['A', 'B', 'C'], ['X', 'Y\n1\n2\n3', 'Z']],
disabled: !FILES_ENABLED,
run: function(callback) {
var updates = [];
Papa.parse(new File(['A,B,C\nX,"Y\n1\n2\n3",Z'], 'sample.csv'), {
chunkSize: 3,
step: function(response) {
updates.push(response.data[0]);
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "Step functions can abort parsing",
expected: [['A', 'b', 'c']],
run: function(callback) {
var updates = [];
Papa.parse('A,b,c\nd,E,f\nG,h,i', {
step: function(response, handle) {
updates.push(response.data[0]);
handle.abort();
callback(updates);
},
chunkSize: 6
});
}
},
{
description: "Complete is called after aborting",
expected: true,
run: function(callback) {
var updates = [];
Papa.parse('A,b,c\nd,E,f\nG,h,i', {
step: function(response, handle) {
handle.abort();
},
chunkSize: 6,
complete: function (response) {
callback(response.meta.aborted);
}
});
}
},
{
description: "Step functions can pause parsing",
expected: [['A', 'b', 'c']],
run: function(callback) {
var updates = [];
Papa.parse('A,b,c\nd,E,f\nG,h,i', {
step: function(response, handle) {
updates.push(response.data[0]);
handle.pause();
callback(updates);
},
complete: function() {
callback('incorrect complete callback');
}
});
}
},
{
description: "Step functions can resume parsing",
expected: [['A', 'b', 'c'], ['d', 'E', 'f'], ['G', 'h', 'i']],
run: function(callback) {
var updates = [];
var handle = null;
var first = true;
Papa.parse('A,b,c\nd,E,f\nG,h,i', {
step: function(response, h) {
updates.push(response.data[0]);
if (!first) return;
handle = h;
handle.pause();
first = false;
},
complete: function() {
callback(updates);
}
});
setTimeout(function() {
handle.resume();
}, 500);
}
},
{
description: "Step functions can abort workers",
expected: 1,
disabled: !XHR_ENABLED,
run: function(callback) {
var updates = 0;
Papa.parse("/tests/long-sample.csv", {
worker: true,
download: true,
chunkSize: 500,
step: function(response, handle) {
updates++;
handle.abort();
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "beforeFirstChunk manipulates only first chunk",
expected: 7,
disabled: !XHR_ENABLED,
run: function(callback) {
var updates = 0;
Papa.parse("/tests/long-sample.csv", {
download: true,
chunkSize: 500,
beforeFirstChunk: function(chunk) {
return chunk.replace(/.*?\n/, '');
},
step: function(response) {
updates++;
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "First chunk not modified if beforeFirstChunk returns nothing",
expected: 8,
disabled: !XHR_ENABLED,
run: function(callback) {
var updates = 0;
Papa.parse("/tests/long-sample.csv", {
download: true,
chunkSize: 500,
beforeFirstChunk: function(chunk) {
},
step: function(response) {
updates++;
},
complete: function() {
callback(updates);
}
});
}
},
{
description: "Should not assume we own the worker unless papaworker is in the search string",
disabled: typeof Worker === 'undefined',
expected: [false, true, true, true, true],
run: function(callback) {
var searchStrings = [
'',
'?papaworker',
'?x=1&papaworker',
'?x=1&papaworker&y=1',
'?x=1&papaworker=1'
];
var results = searchStrings.map(function () { return false; });
var workers = [];
// Give it .5s to do something
setTimeout(function () {
workers.forEach(function (w) { w.terminate(); });
callback(results);
}, 500);
searchStrings.forEach(function (searchString, idx) {
var w = new Worker('../papaparse.js' + searchString);
workers.push(w);
w.addEventListener('message', function () {
results[idx] = true;
});
w.postMessage({input: 'a,b,c\n1,2,3'});
});
}
}
];
describe('Custom Tests', function() {
function generateTest(test) {
(test.disabled ? it.skip : it)(test.description, function(done) {
test.run(function (actual) {
assert.deepEqual(JSON.stringify(actual), JSON.stringify(test.expected));
done();
});
});
}
for (var i = 0; i < CUSTOM_TESTS.length; i++) {
generateTest(CUSTOM_TESTS[i]);
}
});
|
var expect = require('expect.js');
var rfid = require('../rfid');
var sinon = require('sinon');
describe('Commands',function() {
beforeEach(function(done) {
rfid.init({debug: "debug"});
done();
});
it('should issue an initialize command', function() {
rfid.reader.emit('initialize', "01020304", function(err, result) {
expect(err).to.be.null;
});
});
it('should issue an initialize command', function() {
rfid.reader.emit('initialize', "01020304", function(err, result) {
expect(err).to.be.null;
});
});
});
|
import React, { Component } from 'react';
import { sparqlConnect } from '../sparql/configure-sparql';
import { LOADING, FAILED } from 'sparql-connect';
import ItemCorrespondences from './item-correspondences';
class SelectItemOptions extends Component {
constructor(props) {
super(props);
this.state = {
selectedItem: '',
};
this.handleChange = () => {
this.setState({ selectedItem: this.refs.refSelectItem.value });
};
}
render() {
if (this.props.loaded === LOADING)
return <span>loading items for {this.props.classificationId}</span>;
if (this.props.loaded === FAILED)
return (
<span>Failed loading results for {this.props.classificationId}</span>
);
if (this.state.selectedItem === '') {
console.log('aucune selection');
return (
<span>
<label>Select an item from {this.props.classificationCode}:</label>
<select
onChange={this.handleChange}
value={this.state.selectedItem}
ref="refSelectItem"
>
{this.props.items.map(({ item, code, label }) => (
<option value={item} key={item}>
{code} - {label} - ({item})
</option>
))}
</select>
<br />
</span>
);
} else {
console.log('un selectedItem : -' + this.state.selectedItem + '-');
const hash = this.state.selectedItem + '||' + this.props.correspondence;
return (
<span>
<label>Select an item from {this.props.classificationCode}:</label>
<select
onChange={this.handleChange}
value={this.state.selectedItem}
ref="refSelectItem"
>
{this.props.items.map(({ item, code, label }) => (
<option value={item} key={item}>
{code} - {label} - ({item})
</option>
))}
</select>
<br />
<ItemCorrespondences
item={this.state.selectedItem}
classification={this.props.classificationId}
hash={hash}
/>
</span>
);
}
}
}
export default sparqlConnect.classificationItems(SelectItemOptions);
|
var contants = require('../../constants');
var User = require('../models/userModel');
var Q = require('q');
var findAll = Q.nbind(User.find, User);
var findUser = Q.nbind(User.findOne, User);
var createUser = Q.nbind(User.create, User);
module.exports = {
keepalive: function (req, res, next){
res.status(200).json({message: "all ok from the server"});
},
getUsers: function(req, res, next){
findAll()
.then(function(users){
res.status(200).json(users);
})
.fail(function(error){
next(error);
});
},
findByLinkedInId: function(id){
return findUser({linkedinId: id});
},
create: function(user){
return createUser(user);
},
addInterests: function(req, res, next){
var userId = req.body.id;
var interests = req.body.interests;
findUser({ _id : userId })
.then(function(user){
if (user){
user.interests = interests;
user.save();
return res.sendStatus(200);
} else {
return res.sendStatus(400);
}
})
.fail(function (error) {
next(error);
});
},
interestedInMe: function(req, res, next){
var userId = req.body.id;
if (!userId){
res.sendStatus(400);
}
findAll({
peopleInterested: userId
})
.then(function(users){
res.status(200).json(users);
})
.fail(function(error){
next(error);
});
},
sharedInterests: function(req, res, next){
var userId = req.body.id;
var interests = req.body.interests;
if (!userId || !interests){
res.sendStatus(400);
}
var orCondition = [];
for (var i=0; i<interests.length; i++){
if (interests[i] && interests[i] !== ""){
orCondition.push({ interests: interests[i]});
}
}
findAll({
_id: { $ne: userId },
$or: orCondition
})
.then(function(usersWithSharedInterests){
res.status(200).json(usersWithSharedInterests);
})
.fail(function(error){
next(error);
});
},
imInterestInYou: function(req, res, next){
var userId = req.body.id;
var userImInterestInId = req.body.userImInterestInId;
var myUser;
findUser({ _id: userId })
.then(function(user){
if (user){
myUser = user;
return findUser({ _id: userImInterestInId });
} else {
res.sendStatus(400);
}
})
.then(function (userImInterestIn){
if (userImInterestIn){
myUser.peopleInterested.push(userImInterestIn);
myUser.save();
res.sendStatus(200);
} else {
res.sendStatus(400);
}
})
.fail(function (error) {
next(error);
});
},
imNotInterestInYou: function(req, res, next){
var userId = req.body.id;
var userImNotInterestInId = req.body.userImNotInterestInId;
var myUser;
findUser({ _id: userId })
.then(function(user){
if (user){
myUser = user;
return findUser({ _id: userImNotInterestInId });
} else {
res.sendStatus(400);
}
})
.then(function (userImNotInterestIn){
if (userImNotInterestIn){
myUser.peopleNotInterested.push(userImNotInterestIn);
myUser.save();
res.sendStatus(200);
} else {
res.sendStatus(400);
}
})
.fail(function (error) {
next(error);
});
},
insertTestData: function(req, res, next){
var myUser = findUser({ _id: "568c6e69e304a70300dcb55d"})
.then(function(user){
createUser({
linkedinId: "1",
email: "test@test.com",
name: "Tim Cook",
picture: "http://images.apple.com/pr/bios/images/cook_thumb.jpg",
publicProfileUrl: "https://www.linkedin.com/in/cpenarrieta",
headline: "CEO Apple",
summary: "Tim Cook is the CEO of Apple and serves on its Board of Directors.",
location: "San Francisco",
interests: ["react", "android", ""],
peopleInterested: [user]
})
.then(function(newUser){
})
.fail(function (error) {
next(error);
});
createUser({
linkedinId: "2",
email: "test@test.com",
name: "Jonathan Ive",
picture: "http://images.apple.com/pr/bios/images/ive_thumb20110204.jpg",
publicProfileUrl: "https://www.linkedin.com/in/cpenarrieta",
headline: "Chief Design Officer Apple",
summary: "Jonathan Ive is Apple’s Chief Design Officer, reporting to CEO Tim Cook.",
location: "San Francisco",
interests: ["swift", "mongo db", "design for dummies"],
})
.then(function(newUser){
})
.fail(function (error) {
next(error);
});
createUser({
linkedinId: "3",
email: "test@test.com",
name: "Philip Schiller",
picture: "http://images.apple.com/pr/bios/images/schiller_thumb20110204.jpg",
publicProfileUrl: "https://www.linkedin.com/in/cpenarrieta",
headline: "Senior Vice President of Worldwide Marketing Apple",
summary: "Philip Schiller is Apple’s senior vice president of Worldwide Marketing reporting to CEO Tim Cook.",
location: "San Francisco",
interests: ["javascript", "marketing 101", "swift"],
})
.then(function(newUser){
})
.fail(function (error) {
next(error);
});
createUser({
linkedinId: "4",
email: "test@test.com",
name: "Eddy Cue",
picture: "http://images.apple.com/pr/bios/images/1501cue_thumb.jpg",
publicProfileUrl: "https://www.linkedin.com/in/cpenarrieta",
headline: "Senior Vice President of Internet Software and Services Apple",
summary: "Eddy Cue is Apple's senior vice president of Internet Software and Services, reporting to CEO Tim Cook.",
location: "San Francisco",
interests: ["javascript", "marketing 101", ""],
peopleInterested: [user]
})
.then(function(newUser){
return res.json(newUser);
})
.fail(function (error) {
next(error);
});
return res.sendStatus(200);
});
}
};
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("path", {
d: "M12 3C5.3 3 .8 6.7.4 7l3.2 3.9L12 21.5l3.5-4.3v-2.6c0-2.2 1.4-4 3.3-4.7.3-.1.5-.2.8-.2.3-.1.6-.1.9-.1.4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4z",
opacity: ".3"
}), h("path", {
d: "M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16zm-10 5.5l3.5-4.3v-2.6c0-2.2 1.4-4 3.3-4.7C17.3 9 14.9 8 12 8c-4.8 0-8 2.6-8.5 2.9"
})), 'SignalWifi3BarLock');
|
'use strict';
describe("ngAnimate $animateCss", function() {
beforeEach(module('ngAnimate'));
beforeEach(module('ngAnimateMock'));
function assertAnimationRunning(element, not) {
var className = element.attr('class');
var regex = /\b\w+-active\b/;
not ? expect(className).toMatch(regex)
: expect(className).not.toMatch(regex);
}
function getPossiblyPrefixedStyleValue(element, styleProp) {
var value = element.css(prefix + styleProp);
if (isUndefined(value)) value = element.css(styleProp);
return value;
}
function keyframeProgress(element, duration, delay) {
browserTrigger(element, 'animationend',
{ timeStamp: Date.now() + ((delay || 1) * 1000), elapsedTime: duration });
}
function transitionProgress(element, duration, delay) {
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now() + ((delay || 1) * 1000), elapsedTime: duration });
}
function isPromiseLike(p) {
return !!(p && p.then);
}
var fakeStyle = {
color: 'blue'
};
var ss, prefix, triggerAnimationStartFrame;
beforeEach(module(function() {
return function($document, $sniffer, $$rAF, $animate) {
prefix = '-' + $sniffer.vendorPrefix.toLowerCase() + '-';
ss = createMockStyleSheet($document, prefix);
$animate.enabled(true);
triggerAnimationStartFrame = function() {
$$rAF.flush();
};
};
}));
afterEach(function() {
if (ss) {
ss.destroy();
}
});
it("should return false if neither transitions or keyframes are supported by the browser",
inject(function($animateCss, $sniffer, $rootElement, $document) {
var animator;
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
$sniffer.transitions = $sniffer.animations = false;
animator = $animateCss(element, {
duration: 10,
to: { 'background': 'red' }
});
expect(animator.$$willAnimate).toBeFalsy();
}));
describe('when active', function() {
if (!browserSupportsCssAnimations()) return;
it("should not attempt an animation if animations are globally disabled",
inject(function($animateCss, $animate, $rootElement, $document) {
$animate.enabled(false);
var animator, element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
animator = $animateCss(element, {
duration: 10,
to: { 'height': '100px' }
});
expect(animator.$$willAnimate).toBeFalsy();
}));
it("should silently quit the animation and not throw when an element has no parent during preparation",
inject(function($animateCss, $rootScope, $document, $rootElement) {
var element = angular.element('<div></div>');
expect(function() {
$animateCss(element, {
duration: 1000,
event: 'fake',
to: fakeStyle
}).start();
}).not.toThrow();
expect(element).not.toHaveClass('fake');
triggerAnimationStartFrame();
expect(element).not.toHaveClass('fake-active');
}));
it("should silently quit the animation and not throw when an element has no parent before starting",
inject(function($animateCss, $$rAF, $rootScope, $document, $rootElement) {
var element = angular.element('<div></div>');
angular.element($document[0].body).append($rootElement);
$rootElement.append(element);
$animateCss(element, {
duration: 1000,
addClass: 'wait-for-it',
to: fakeStyle
}).start();
element.remove();
expect(function() {
triggerAnimationStartFrame();
}).not.toThrow();
}));
describe("rAF usage", function() {
it("should buffer all requests into a single requestAnimationFrame call",
inject(function($animateCss, $$rAF, $rootScope, $document, $rootElement) {
angular.element($document[0].body).append($rootElement);
var count = 0;
var runners = [];
function makeRequest() {
var element = angular.element('<div></div>');
$rootElement.append(element);
var runner = $animateCss(element, { duration: 5, to: fakeStyle }).start();
runner.then(function() {
count++;
});
runners.push(runner);
}
makeRequest();
makeRequest();
makeRequest();
expect(count).toBe(0);
triggerAnimationStartFrame();
forEach(runners, function(runner) {
runner.end();
});
$rootScope.$digest();
expect(count).toBe(3);
}));
it("should cancel previous requests to rAF to avoid premature flushing", function() {
var count = 0;
module(function($provide) {
$provide.value('$$rAF', function() {
return function cancellationFn() {
count++;
};
});
});
inject(function($animateCss, $$rAF, $document, $rootElement) {
angular.element($document[0].body).append($rootElement);
function makeRequest() {
var element = angular.element('<div></div>');
$rootElement.append(element);
$animateCss(element, { duration: 5, to: fakeStyle }).start();
}
makeRequest();
makeRequest();
makeRequest();
expect(count).toBe(2);
});
});
});
describe("animator and runner", function() {
var animationDuration = 5;
var element, animator;
beforeEach(inject(function($animateCss, $rootElement, $document) {
element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
animator = $animateCss(element, {
event: 'enter',
structural: true,
duration: animationDuration,
to: fakeStyle
});
}));
it('should expose start and end functions for the animator object', inject(function() {
expect(typeof animator.start).toBe('function');
expect(typeof animator.end).toBe('function');
}));
it('should expose end, cancel, resume and pause methods on the runner object', inject(function() {
var runner = animator.start();
triggerAnimationStartFrame();
expect(typeof runner.end).toBe('function');
expect(typeof runner.cancel).toBe('function');
expect(typeof runner.resume).toBe('function');
expect(typeof runner.pause).toBe('function');
}));
it('should start the animation', inject(function() {
expect(element).not.toHaveClass('ng-enter-active');
animator.start();
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-enter-active');
}));
it('should end the animation when called from the animator object', inject(function() {
animator.start();
triggerAnimationStartFrame();
animator.end();
expect(element).not.toHaveClass('ng-enter-active');
}));
it('should end the animation when called from the runner object', inject(function() {
var runner = animator.start();
triggerAnimationStartFrame();
runner.end();
expect(element).not.toHaveClass('ng-enter-active');
}));
it('should permanently close the animation if closed before the next rAF runs', inject(function() {
var runner = animator.start();
runner.end();
triggerAnimationStartFrame();
expect(element).not.toHaveClass('ng-enter-active');
}));
it('should return a runner object at the start of the animation that contains a `then` method',
inject(function($rootScope) {
var runner = animator.start();
triggerAnimationStartFrame();
expect(isPromiseLike(runner)).toBeTruthy();
var resolved;
runner.then(function() {
resolved = true;
});
runner.end();
$rootScope.$digest();
expect(resolved).toBeTruthy();
}));
it('should cancel the animation and reject', inject(function($rootScope) {
var rejected;
var runner = animator.start();
triggerAnimationStartFrame();
runner.then(noop, function() {
rejected = true;
});
runner.cancel();
$rootScope.$digest();
expect(rejected).toBeTruthy();
}));
it('should run pause, but not effect the transition animation', inject(function() {
var blockingDelay = '-' + animationDuration + 's';
expect(element.css('transition-delay')).toEqual(blockingDelay);
var runner = animator.start();
triggerAnimationStartFrame();
expect(element.css('transition-delay')).not.toEqual(blockingDelay);
runner.pause();
expect(element.css('transition-delay')).not.toEqual(blockingDelay);
}));
it('should pause the transition, have no effect, but not end it', inject(function() {
var runner = animator.start();
triggerAnimationStartFrame();
runner.pause();
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now(), elapsedTime: 5 });
expect(element).toHaveClass('ng-enter-active');
}));
it('should resume the animation', inject(function() {
var runner = animator.start();
triggerAnimationStartFrame();
runner.pause();
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now(), elapsedTime: 5 });
expect(element).toHaveClass('ng-enter-active');
runner.resume();
expect(element).not.toHaveClass('ng-enter-active');
}));
it('should pause and resume a keyframe animation using animation-play-state',
inject(function($animateCss) {
element.attr('style', '');
ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' +
'animation:1.5s keyframe_animation;');
animator = $animateCss(element, {
event: 'enter',
structural: true
});
var runner = animator.start();
triggerAnimationStartFrame();
runner.pause();
expect(getPossiblyPrefixedStyleValue(element, 'animation-play-state')).toEqual('paused');
runner.resume();
expect(element.attr('style')).toBeFalsy();
}));
it('should remove the animation-play-state style if the animation is closed',
inject(function($animateCss) {
element.attr('style', '');
ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' +
'animation:1.5s keyframe_animation;');
animator = $animateCss(element, {
event: 'enter',
structural: true
});
var runner = animator.start();
triggerAnimationStartFrame();
runner.pause();
expect(getPossiblyPrefixedStyleValue(element, 'animation-play-state')).toEqual('paused');
runner.end();
expect(element.attr('style')).toBeFalsy();
}));
});
describe("CSS", function() {
describe("detected styles", function() {
var element, options;
function assertAnimationComplete(bool) {
var assert = expect(element);
if (bool) {
assert = assert.not;
}
assert.toHaveClass('ng-enter');
assert.toHaveClass('ng-enter-active');
}
beforeEach(inject(function($rootElement, $document) {
element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
options = { event: 'enter', structural: true };
}));
it("should always return an object even if no animation is detected",
inject(function($animateCss) {
ss.addRule('.some-animation', 'background:red;');
element.addClass('some-animation');
var animator = $animateCss(element, options);
expect(animator).toBeTruthy();
expect(isFunction(animator.start)).toBeTruthy();
expect(animator.end).toBeTruthy();
expect(animator.$$willAnimate).toBe(false);
}));
it("should close the animation immediately, but still return an animator object if no animation is detected",
inject(function($animateCss) {
ss.addRule('.another-fake-animation', 'background:blue;');
element.addClass('another-fake-animation');
var animator = $animateCss(element, {
event: 'enter',
structural: true
});
expect(element).not.toHaveClass('ng-enter');
expect(isFunction(animator.start)).toBeTruthy();
}));
they("should close the animation, but still accept $prop callbacks if no animation is detected",
['done', 'then'], function(method) {
inject(function($animateCss, $animate, $rootScope) {
ss.addRule('.the-third-fake-animation', 'background:green;');
element.addClass('another-fake-animation');
var animator = $animateCss(element, {
event: 'enter',
structural: true
});
var done = false;
animator.start()[method](function() {
done = true;
});
expect(done).toBe(false);
$animate.flush();
if (method === 'then') {
$rootScope.$digest();
}
expect(done).toBe(true);
});
});
they("should close the animation, but still accept recognize runner.$prop if no animation is detected",
['done(cancel)', 'catch'], function(method) {
inject(function($animateCss, $rootScope) {
ss.addRule('.the-third-fake-animation', 'background:green;');
element.addClass('another-fake-animation');
var animator = $animateCss(element, {
event: 'enter',
structural: true
});
var cancelled = false;
var runner = animator.start();
if (method === 'catch') {
runner.catch(function() {
cancelled = true;
});
} else {
runner.done(function(status) {
cancelled = status === false;
});
}
expect(cancelled).toBe(false);
runner.cancel();
if (method === 'catch') {
$rootScope.$digest();
}
expect(cancelled).toBe(true);
});
});
it("should use the highest transition duration value detected in the CSS class", inject(function($animateCss) {
ss.addRule('.ng-enter', 'transition:1s linear all;' +
'transition-duration:10s, 15s, 20s;');
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
transitionProgress(element, 10);
assertAnimationComplete(false);
transitionProgress(element, 15);
assertAnimationComplete(false);
transitionProgress(element, 20);
assertAnimationComplete(true);
}));
it("should use the highest transition delay value detected in the CSS class", inject(function($animateCss) {
ss.addRule('.ng-enter', 'transition:1s linear all;' +
'transition-delay:10s, 15s, 20s;');
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
transitionProgress(element, 1, 10);
assertAnimationComplete(false);
transitionProgress(element, 1, 15);
assertAnimationComplete(false);
transitionProgress(element, 1, 20);
assertAnimationComplete(true);
}));
it("should only close when both the animation delay and duration have passed",
inject(function($animateCss) {
ss.addRule('.ng-enter', 'transition:10s 5s linear all;');
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
transitionProgress(element, 10, 2);
assertAnimationComplete(false);
transitionProgress(element, 9, 6);
assertAnimationComplete(false);
transitionProgress(element, 10, 5);
assertAnimationComplete(true);
}));
it("should use the highest keyframe duration value detected in the CSS class", inject(function($animateCss) {
ss.addRule('.ng-enter', 'animation:animation 1s, animation 2s, animation 3s;' +
'-webkit-animation:animation 1s, animation 2s, animation 3s;');
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
keyframeProgress(element, 1);
assertAnimationComplete(false);
keyframeProgress(element, 2);
assertAnimationComplete(false);
keyframeProgress(element, 3);
assertAnimationComplete(true);
}));
it("should use the highest keyframe delay value detected in the CSS class", inject(function($animateCss) {
ss.addRule('.ng-enter', 'animation:animation 1s 2s, animation 1s 10s, animation 1s 1000ms;' +
'-webkit-animation:animation 1s 2s, animation 1s 10s, animation 1s 1000ms;');
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
keyframeProgress(element, 1, 1);
assertAnimationComplete(false);
keyframeProgress(element, 1, 2);
assertAnimationComplete(false);
keyframeProgress(element, 1, 10);
assertAnimationComplete(true);
}));
it("should use the highest keyframe duration value detected in the CSS class with respect to the animation-iteration-count property", inject(function($animateCss) {
ss.addRule('.ng-enter',
'animation:animation 1s 2s 3, animation 1s 10s 2, animation 1s 1000ms infinite;' +
'-webkit-animation:animation 1s 2s 3, animation 1s 10s 2, animation 1s 1000ms infinite;');
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
keyframeProgress(element, 1, 1);
assertAnimationComplete(false);
keyframeProgress(element, 1, 2);
assertAnimationComplete(false);
keyframeProgress(element, 3, 10);
assertAnimationComplete(true);
}));
it("should use the highest duration value when both transitions and keyframes are used", inject(function($animateCss) {
ss.addRule('.ng-enter', 'transition:1s linear all;' +
'transition-duration:10s, 15s, 20s;' +
'animation:animation 1s, animation 2s, animation 3s 0s 7;' +
'-webkit-animation:animation 1s, animation 2s, animation 3s 0s 7;');
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
transitionProgress(element, 10);
keyframeProgress(element, 10);
assertAnimationComplete(false);
transitionProgress(element, 15);
keyframeProgress(element, 15);
assertAnimationComplete(false);
transitionProgress(element, 20);
keyframeProgress(element, 20);
assertAnimationComplete(false);
// 7 * 3 = 21
transitionProgress(element, 21);
keyframeProgress(element, 21);
assertAnimationComplete(true);
}));
it("should use the highest delay value when both transitions and keyframes are used", inject(function($animateCss) {
ss.addRule('.ng-enter', 'transition:1s linear all;' +
'transition-delay:10s, 15s, 20s;' +
'animation:animation 1s 2s, animation 1s 16s, animation 1s 19s;' +
'-webkit-animation:animation 1s 2s, animation 1s 16s, animation 1s 19s;');
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
transitionProgress(element, 1, 10);
keyframeProgress(element, 1, 10);
assertAnimationComplete(false);
transitionProgress(element, 1, 16);
keyframeProgress(element, 1, 16);
assertAnimationComplete(false);
transitionProgress(element, 1, 19);
keyframeProgress(element, 1, 19);
assertAnimationComplete(false);
transitionProgress(element, 1, 20);
keyframeProgress(element, 1, 20);
assertAnimationComplete(true);
}));
});
describe("staggering", function() {
it("should apply a stagger based when an active ng-EVENT-stagger class with a transition-delay is detected",
inject(function($animateCss, $document, $rootElement, $timeout) {
angular.element($document[0].body).append($rootElement);
ss.addRule('.ng-enter-stagger', 'transition-delay:0.2s');
ss.addRule('.ng-enter', 'transition:2s linear all');
var elements = [];
var i;
var elm;
for (i = 0; i < 5; i++) {
elm = angular.element('<div></div>');
elements.push(elm);
$rootElement.append(elm);
$animateCss(elm, { event: 'enter', structural: true }).start();
expect(elm).not.toHaveClass('ng-enter-stagger');
expect(elm).toHaveClass('ng-enter');
}
triggerAnimationStartFrame();
expect(elements[0]).toHaveClass('ng-enter-active');
for (i = 1; i < 5; i++) {
elm = elements[i];
expect(elm).not.toHaveClass('ng-enter-active');
$timeout.flush(200);
expect(elm).toHaveClass('ng-enter-active');
browserTrigger(elm, 'transitionend',
{ timeStamp: Date.now() + 1000, elapsedTime: 2 });
expect(elm).not.toHaveClass('ng-enter');
expect(elm).not.toHaveClass('ng-enter-active');
expect(elm).not.toHaveClass('ng-enter-stagger');
}
}));
it("should apply a stagger based when for all provided addClass/removeClass CSS classes",
inject(function($animateCss, $document, $rootElement, $timeout) {
angular.element($document[0].body).append($rootElement);
ss.addRule('.red-add-stagger,' +
'.blue-remove-stagger,' +
'.green-add-stagger', 'transition-delay:0.2s');
ss.addRule('.red-add,' +
'.blue-remove,' +
'.green-add', 'transition:2s linear all');
var elements = [];
var i;
var elm;
for (i = 0; i < 5; i++) {
elm = angular.element('<div class="blue"></div>');
elements.push(elm);
$rootElement.append(elm);
$animateCss(elm, {
addClass: 'red green',
removeClass: 'blue'
}).start();
}
triggerAnimationStartFrame();
for (i = 0; i < 5; i++) {
elm = elements[i];
expect(elm).not.toHaveClass('red-add-stagger');
expect(elm).not.toHaveClass('green-add-stagger');
expect(elm).not.toHaveClass('blue-remove-stagger');
expect(elm).toHaveClass('red-add');
expect(elm).toHaveClass('green-add');
expect(elm).toHaveClass('blue-remove');
}
expect(elements[0]).toHaveClass('red-add-active');
expect(elements[0]).toHaveClass('green-add-active');
expect(elements[0]).toHaveClass('blue-remove-active');
for (i = 1; i < 5; i++) {
elm = elements[i];
expect(elm).not.toHaveClass('red-add-active');
expect(elm).not.toHaveClass('green-add-active');
expect(elm).not.toHaveClass('blue-remove-active');
$timeout.flush(200);
expect(elm).toHaveClass('red-add-active');
expect(elm).toHaveClass('green-add-active');
expect(elm).toHaveClass('blue-remove-active');
browserTrigger(elm, 'transitionend',
{ timeStamp: Date.now() + 1000, elapsedTime: 2 });
expect(elm).not.toHaveClass('red-add-active');
expect(elm).not.toHaveClass('green-add-active');
expect(elm).not.toHaveClass('blue-remove-active');
expect(elm).not.toHaveClass('red-add-stagger');
expect(elm).not.toHaveClass('green-add-stagger');
expect(elm).not.toHaveClass('blue-remove-stagger');
}
}));
it("should block the transition animation between start and animate when staggered",
inject(function($animateCss, $document, $rootElement) {
angular.element($document[0].body).append($rootElement);
ss.addRule('.ng-enter-stagger', 'transition-delay:0.2s');
ss.addRule('.ng-enter', 'transition:2s linear all;');
var element;
var i;
var elms = [];
for (i = 0; i < 5; i++) {
element = angular.element('<div class="transition-animation"></div>');
$rootElement.append(element);
$animateCss(element, { event: 'enter', structural: true }).start();
elms.push(element);
}
triggerAnimationStartFrame();
for (i = 0; i < 5; i++) {
element = elms[i];
if (i === 0) {
expect(element.attr('style')).toBeFalsy();
} else {
expect(element.css('transition-delay')).toContain('-2s');
}
}
}));
it("should block (pause) the keyframe animation between start and animate when staggered",
inject(function($animateCss, $document, $rootElement) {
angular.element($document[0].body).append($rootElement);
ss.addPossiblyPrefixedRule('.ng-enter-stagger', 'animation-delay:0.2s');
ss.addPossiblyPrefixedRule('.ng-enter', 'animation:my_animation 2s;');
var i, element, elements = [];
for (i = 0; i < 5; i++) {
element = angular.element('<div class="transition-animation"></div>');
$rootElement.append(element);
$animateCss(element, { event: 'enter', structural: true }).start();
elements.push(element);
}
triggerAnimationStartFrame();
for (i = 0; i < 5; i++) {
element = elements[i];
if (i === 0) { // the first element is always run right away
expect(element.attr('style')).toBeFalsy();
} else {
expect(getPossiblyPrefixedStyleValue(element, 'animation-play-state')).toBe('paused');
}
}
}));
it("should not apply a stagger if the transition delay value is inherited from a earlier CSS class",
inject(function($animateCss, $document, $rootElement) {
angular.element($document[0].body).append($rootElement);
ss.addRule('.transition-animation', 'transition:2s 5s linear all;');
for (var i = 0; i < 5; i++) {
var element = angular.element('<div class="transition-animation"></div>');
$rootElement.append(element);
$animateCss(element, { event: 'enter', structural: true }).start();
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-enter-active');
}
}));
it("should apply a stagger only if the transition duration value is zero when inherited from a earlier CSS class",
inject(function($animateCss, $document, $rootElement) {
angular.element($document[0].body).append($rootElement);
ss.addRule('.transition-animation', 'transition:2s 5s linear all;');
ss.addRule('.transition-animation.ng-enter-stagger',
'transition-duration:0s; transition-delay:0.2s;');
var element, i, elms = [];
for (i = 0; i < 5; i++) {
element = angular.element('<div class="transition-animation"></div>');
$rootElement.append(element);
elms.push(element);
$animateCss(element, { event: 'enter', structural: true }).start();
}
triggerAnimationStartFrame();
for (i = 1; i < 5; i++) {
element = elms[i];
expect(element).not.toHaveClass('ng-enter-active');
}
}));
it("should ignore animation staggers if only transition animations were detected",
inject(function($animateCss, $document, $rootElement) {
angular.element($document[0].body).append($rootElement);
ss.addRule('.ng-enter-stagger', prefix + 'animation-delay:0.2s');
ss.addRule('.transition-animation', 'transition:2s 5s linear all;');
for (var i = 0; i < 5; i++) {
var element = angular.element('<div class="transition-animation"></div>');
$rootElement.append(element);
$animateCss(element, { event: 'enter', structural: true }).start();
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-enter-active');
}
}));
it("should ignore transition staggers if only keyframe animations were detected",
inject(function($animateCss, $document, $rootElement) {
angular.element($document[0].body).append($rootElement);
ss.addRule('.ng-enter-stagger', 'transition-delay:0.2s');
ss.addPossiblyPrefixedRule('.transition-animation', 'animation: 2s 5s my_animation;');
for (var i = 0; i < 5; i++) {
var elm = angular.element('<div class="transition-animation"></div>');
$rootElement.append(elm);
var animator = $animateCss(elm, { event: 'enter', structural: true }).start();
triggerAnimationStartFrame();
expect(elm).toHaveClass('ng-enter-active');
}
}));
it("should start on the highest stagger value if both transition and keyframe staggers are used together",
inject(function($animateCss, $document, $rootElement, $timeout, $browser) {
angular.element($document[0].body).append($rootElement);
ss.addPossiblyPrefixedRule('.ng-enter-stagger', 'transition-delay: 0.5s; ' +
'animation-delay: 1s');
ss.addPossiblyPrefixedRule('.ng-enter', 'transition: 10s linear all; ' +
'animation: 20s my_animation');
var i, elm, elements = [];
for (i = 0; i < 5; i++) {
elm = angular.element('<div></div>');
elements.push(elm);
$rootElement.append(elm);
$animateCss(elm, { event: 'enter', structural: true }).start();
expect(elm).toHaveClass('ng-enter');
}
triggerAnimationStartFrame();
expect(elements[0]).toHaveClass('ng-enter-active');
for (i = 1; i < 5; i++) {
elm = elements[i];
expect(elm).not.toHaveClass('ng-enter-active');
$timeout.flush(500);
expect(elm).not.toHaveClass('ng-enter-active');
$timeout.flush(500);
expect(elm).toHaveClass('ng-enter-active');
}
}));
it("should apply the closing timeout ontop of the stagger timeout",
inject(function($animateCss, $document, $rootElement, $timeout, $browser) {
angular.element($document[0].body).append($rootElement);
ss.addRule('.ng-enter-stagger', 'transition-delay:1s;');
ss.addRule('.ng-enter', 'transition:10s linear all;');
var elm, i, elms = [];
for (i = 0; i < 5; i++) {
elm = angular.element('<div></div>');
elms.push(elm);
$rootElement.append(elm);
$animateCss(elm, { event: 'enter', structural: true }).start();
triggerAnimationStartFrame();
}
for (i = 1; i < 2; i++) {
elm = elms[i];
expect(elm).toHaveClass('ng-enter');
$timeout.flush(1000);
$timeout.flush(15000);
expect(elm).not.toHaveClass('ng-enter');
}
}));
it("should apply the closing timeout ontop of the stagger timeout with an added delay",
inject(function($animateCss, $document, $rootElement, $timeout, $browser) {
angular.element($document[0].body).append($rootElement);
ss.addRule('.ng-enter-stagger', 'transition-delay:1s;');
ss.addRule('.ng-enter', 'transition:10s linear all; transition-delay:50s;');
var elm, i, elms = [];
for (i = 0; i < 5; i++) {
elm = angular.element('<div></div>');
elms.push(elm);
$rootElement.append(elm);
$animateCss(elm, { event: 'enter', structural: true }).start();
triggerAnimationStartFrame();
}
for (i = 1; i < 2; i++) {
elm = elms[i];
expect(elm).toHaveClass('ng-enter');
$timeout.flush(1000);
$timeout.flush(65000);
expect(elm).not.toHaveClass('ng-enter');
}
}));
it("should issue a stagger if a stagger value is provided in the options",
inject(function($animateCss, $document, $rootElement, $timeout) {
angular.element($document[0].body).append($rootElement);
ss.addRule('.ng-enter', 'transition:2s linear all');
var elm, i, elements = [];
for (i = 0; i < 5; i++) {
elm = angular.element('<div></div>');
elements.push(elm);
$rootElement.append(elm);
$animateCss(elm, {
event: 'enter',
structural: true,
stagger: 0.5
}).start();
expect(elm).toHaveClass('ng-enter');
}
triggerAnimationStartFrame();
expect(elements[0]).toHaveClass('ng-enter-active');
for (i = 1; i < 5; i++) {
elm = elements[i];
expect(elm).not.toHaveClass('ng-enter-active');
$timeout.flush(500);
expect(elm).toHaveClass('ng-enter-active');
browserTrigger(elm, 'transitionend',
{ timeStamp: Date.now() + 1000, elapsedTime: 2 });
expect(elm).not.toHaveClass('ng-enter');
expect(elm).not.toHaveClass('ng-enter-active');
expect(elm).not.toHaveClass('ng-enter-stagger');
}
}));
it("should only add/remove classes once the stagger timeout has passed",
inject(function($animateCss, $document, $rootElement, $timeout) {
angular.element($document[0].body).append($rootElement);
var element = angular.element('<div class="green"></div>');
$rootElement.append(element);
$animateCss(element, {
addClass: 'red',
removeClass: 'green',
duration: 5,
stagger: 0.5,
staggerIndex: 3
}).start();
triggerAnimationStartFrame();
expect(element).toHaveClass('green');
expect(element).not.toHaveClass('red');
$timeout.flush(1500);
expect(element).not.toHaveClass('green');
expect(element).toHaveClass('red');
}));
});
describe("closing timeout", function() {
it("should close off the animation after 150% of the animation time has passed",
inject(function($animateCss, $document, $rootElement, $timeout) {
ss.addRule('.ng-enter', 'transition:10s linear all;');
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var animator = $animateCss(element, { event: 'enter', structural: true });
animator.start();
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-enter');
expect(element).toHaveClass('ng-enter-active');
$timeout.flush(15000);
expect(element).not.toHaveClass('ng-enter');
expect(element).not.toHaveClass('ng-enter-active');
}));
it("should close off the animation after 150% of the animation time has passed and consider the detected delay value",
inject(function($animateCss, $document, $rootElement, $timeout) {
ss.addRule('.ng-enter', 'transition:10s linear all; transition-delay:30s;');
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var animator = $animateCss(element, { event: 'enter', structural: true });
animator.start();
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-enter');
expect(element).toHaveClass('ng-enter-active');
$timeout.flush(45000);
expect(element).not.toHaveClass('ng-enter');
expect(element).not.toHaveClass('ng-enter-active');
}));
it("should still resolve the animation once expired",
inject(function($animateCss, $document, $rootElement, $timeout, $animate, $rootScope) {
ss.addRule('.ng-enter', 'transition:10s linear all;');
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var animator = $animateCss(element, { event: 'enter', structural: true });
var failed, passed;
animator.start().then(function() {
passed = true;
}, function() {
failed = true;
});
triggerAnimationStartFrame();
$timeout.flush(15000);
$animate.flush();
$rootScope.$digest();
expect(passed).toBe(true);
}));
it("should not resolve/reject after passing if the animation completed successfully",
inject(function($animateCss, $document, $rootElement, $timeout, $rootScope, $animate) {
ss.addRule('.ng-enter', 'transition:10s linear all;');
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var animator = $animateCss(element, { event: 'enter', structural: true });
var failed, passed;
animator.start().then(
function() {
passed = true;
},
function() {
failed = true;
}
);
triggerAnimationStartFrame();
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now() + 1000, elapsedTime: 10 });
$animate.flush();
$rootScope.$digest();
expect(passed).toBe(true);
expect(failed).not.toBe(true);
$timeout.flush(15000);
expect(passed).toBe(true);
expect(failed).not.toBe(true);
}));
it("should close all stacked animations after the last timeout runs on the same element",
inject(function($animateCss, $document, $rootElement, $timeout, $animate) {
var now = 0;
spyOn(Date, 'now').and.callFake(function() {
return now;
});
var cancelSpy = spyOn($timeout, 'cancel').and.callThrough();
var doneSpy = jasmine.createSpy();
ss.addRule('.elm', 'transition:1s linear all;');
ss.addRule('.elm.red', 'background:red;');
ss.addRule('.elm.blue', 'transition:2s linear all; background:blue;');
ss.addRule('.elm.green', 'background:green;');
var element = angular.element('<div class="elm"></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
// timeout will be at 1500s
animate(element, 'red', doneSpy);
expect(doneSpy).not.toHaveBeenCalled();
fastForwardClock(500); //1000s left to go
// timeout will not be at 500 + 3000s = 3500s
animate(element, 'blue', doneSpy);
expect(doneSpy).not.toHaveBeenCalled();
expect(cancelSpy).toHaveBeenCalled();
cancelSpy.calls.reset();
// timeout will not be set again since the former animation is longer
animate(element, 'green', doneSpy);
expect(doneSpy).not.toHaveBeenCalled();
expect(cancelSpy).not.toHaveBeenCalled();
// this will close the animations fully
fastForwardClock(3500);
$animate.flush();
expect(doneSpy).toHaveBeenCalled();
expect(doneSpy).toHaveBeenCalledTimes(3);
function fastForwardClock(time) {
now += time;
$timeout.flush(time);
}
function animate(element, klass, onDone) {
var animator = $animateCss(element, { addClass: klass }).start();
animator.done(onDone);
triggerAnimationStartFrame();
return animator;
}
}));
it("should not throw an error any pending timeout requests resolve after the element has already been removed",
inject(function($animateCss, $document, $rootElement, $timeout, $animate) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
ss.addRule('.red', 'transition:1s linear all;');
$animateCss(element, { addClass: 'red' }).start();
triggerAnimationStartFrame();
element.remove();
expect(function() {
$timeout.flush();
}).not.toThrow();
}));
it("should consider a positive options.delay value for the closing timeout",
inject(function($animateCss, $rootElement, $timeout, $document) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var options = {
delay: 3,
duration: 3,
to: {
height: '100px'
}
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
// At this point, the animation should still be running (closing timeout is 7500ms ... duration * 1.5 + delay => 7.5)
$timeout.flush(7000);
expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).toBe('3s');
expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).toBe('3s');
// Let's flush the remaining amount of time for the timeout timer to kick in
$timeout.flush(500);
expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).toBeOneOf('', '0s');
expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).toBeOneOf('', '0s');
}));
it("should ignore a boolean options.delay value for the closing timeout",
inject(function($animateCss, $rootElement, $timeout, $document) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var options = {
delay: true,
duration: 3,
to: {
height: '100px'
}
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
// At this point, the animation should still be running (closing timeout is 4500ms ... duration * 1.5 => 4.5)
$timeout.flush(4000);
expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).toBeOneOf('initial', '0s');
expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).toBe('3s');
// Let's flush the remaining amount of time for the timeout timer to kick in
$timeout.flush(500);
expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).toBeOneOf('', '0s');
expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).toBeOneOf('', '0s');
}));
it("should cancel the timeout when the animation is ended normally",
inject(function($animateCss, $document, $rootElement, $timeout) {
ss.addRule('.ng-enter', 'transition:10s linear all;');
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var animator = $animateCss(element, { event: 'enter', structural: true });
animator.start();
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-enter');
expect(element).toHaveClass('ng-enter-active');
animator.end();
expect(element.data(ANIMATE_TIMER_KEY)).toBeUndefined();
expect(function() {$timeout.verifyNoPendingTasks();}).not.toThrow();
}));
});
describe("getComputedStyle", function() {
var count;
var acceptableTimingsData = {
transitionDuration: "10s"
};
beforeEach(module(function($provide) {
count = {};
$provide.value('$window', extend({}, window, {
document: angular.element(window.document),
getComputedStyle: function(node) {
var key = node.className.indexOf('stagger') >= 0
? 'stagger' : 'normal';
count[key] = count[key] || 0;
count[key]++;
return acceptableTimingsData;
}
}));
return function($document, $rootElement) {
angular.element($document[0].body).append($rootElement);
};
}));
it("should cache frequent calls to getComputedStyle before the next animation frame kicks in",
inject(function($animateCss, $document, $rootElement) {
var i, elm, animator;
for (i = 0; i < 5; i++) {
elm = angular.element('<div></div>');
$rootElement.append(elm);
animator = $animateCss(elm, { event: 'enter', structural: true });
var runner = animator.start();
}
expect(count.normal).toBe(1);
for (i = 0; i < 5; i++) {
elm = angular.element('<div></div>');
$rootElement.append(elm);
animator = $animateCss(elm, { event: 'enter', structural: true });
animator.start();
}
expect(count.normal).toBe(1);
triggerAnimationStartFrame();
expect(count.normal).toBe(2);
for (i = 0; i < 5; i++) {
elm = angular.element('<div></div>');
$rootElement.append(elm);
animator = $animateCss(elm, { event: 'enter', structural: true });
animator.start();
}
expect(count.normal).toBe(3);
}));
it("should cache frequent calls to getComputedStyle for stagger animations before the next animation frame kicks in",
inject(function($animateCss, $document, $rootElement, $$rAF) {
var element = angular.element('<div></div>');
$rootElement.append(element);
var animator = $animateCss(element, { event: 'enter', structural: true });
animator.start();
triggerAnimationStartFrame();
expect(count.stagger).toBeUndefined();
var i, elm;
for (i = 0; i < 5; i++) {
elm = angular.element('<div></div>');
$rootElement.append(elm);
animator = $animateCss(elm, { event: 'enter', structural: true });
animator.start();
}
expect(count.stagger).toBe(1);
for (i = 0; i < 5; i++) {
elm = angular.element('<div></div>');
$rootElement.append(elm);
animator = $animateCss(elm, { event: 'enter', structural: true });
animator.start();
}
expect(count.stagger).toBe(1);
$$rAF.flush();
for (i = 0; i < 5; i++) {
elm = angular.element('<div></div>');
$rootElement.append(elm);
animator = $animateCss(elm, { event: 'enter', structural: true });
animator.start();
}
triggerAnimationStartFrame();
expect(count.stagger).toBe(2);
}));
});
describe('transitionend/animationend event listeners', function() {
var element, elementOnSpy, elementOffSpy, progress;
function setStyles(event) {
switch (event) {
case TRANSITIONEND_EVENT:
ss.addRule('.ng-enter', 'transition: 10s linear all;');
progress = transitionProgress;
break;
case ANIMATIONEND_EVENT:
ss.addRule('.ng-enter', '-webkit-animation: animation 10s;' +
'animation: animation 10s;');
progress = keyframeProgress;
break;
}
}
beforeEach(inject(function($rootElement, $document) {
element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
elementOnSpy = spyOn(element, 'on').and.callThrough();
elementOffSpy = spyOn(element, 'off').and.callThrough();
}));
they('should remove the $prop event listeners on cancel',
[TRANSITIONEND_EVENT, ANIMATIONEND_EVENT], function(event) {
inject(function($animateCss) {
setStyles(event);
var animator = $animateCss(element, {
event: 'enter',
structural: true
});
var runner = animator.start();
triggerAnimationStartFrame();
expect(elementOnSpy).toHaveBeenCalledOnce();
expect(elementOnSpy.calls.mostRecent().args[0]).toBe(event);
runner.cancel();
expect(elementOffSpy).toHaveBeenCalledOnce();
expect(elementOffSpy.calls.mostRecent().args[0]).toBe(event);
});
});
they("should remove the $prop event listener when the animation is closed",
[TRANSITIONEND_EVENT, ANIMATIONEND_EVENT], function(event) {
inject(function($animateCss) {
setStyles(event);
var animator = $animateCss(element, {
event: 'enter',
structural: true
});
var runner = animator.start();
triggerAnimationStartFrame();
expect(elementOnSpy).toHaveBeenCalledOnce();
expect(elementOnSpy.calls.mostRecent().args[0]).toBe(event);
progress(element, 10);
expect(elementOffSpy).toHaveBeenCalledOnce();
expect(elementOffSpy.calls.mostRecent().args[0]).toBe(event);
});
});
they("should remove the $prop event listener when the closing timeout occurs",
[TRANSITIONEND_EVENT, ANIMATIONEND_EVENT], function(event) {
inject(function($animateCss, $timeout) {
setStyles(event);
var animator = $animateCss(element, {
event: 'enter',
structural: true
});
animator.start();
triggerAnimationStartFrame();
expect(elementOnSpy).toHaveBeenCalledOnce();
expect(elementOnSpy.calls.mostRecent().args[0]).toBe(event);
$timeout.flush(15000);
expect(elementOffSpy).toHaveBeenCalledOnce();
expect(elementOffSpy.calls.mostRecent().args[0]).toBe(event);
});
});
they("should not add or remove $prop event listeners when no animation styles are detected",
[TRANSITIONEND_EVENT, ANIMATIONEND_EVENT], function(event) {
inject(function($animateCss, $timeout) {
progress = event === TRANSITIONEND_EVENT ? transitionProgress : keyframeProgress;
// Make sure other event listeners are not affected
var otherEndSpy = jasmine.createSpy('otherEndSpy');
element.on(event, otherEndSpy);
expect(elementOnSpy).toHaveBeenCalledOnce();
elementOnSpy.calls.reset();
var animator = $animateCss(element, {
event: 'enter',
structural: true
});
expect(animator.$$willAnimate).toBeFalsy();
// This will close the animation because no styles have been detected
var runner = animator.start();
triggerAnimationStartFrame();
expect(elementOnSpy).not.toHaveBeenCalled();
expect(elementOffSpy).not.toHaveBeenCalled();
progress(element, 10);
expect(otherEndSpy).toHaveBeenCalledOnce();
});
});
});
});
it('should avoid applying the same cache to an element a follow-up animation is run on the same element',
inject(function($animateCss, $rootElement, $document) {
function endTransition(element, elapsedTime) {
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now(), elapsedTime: elapsedTime });
}
function startAnimation(element, duration, color) {
$animateCss(element, {
duration: duration,
to: { background: color }
}).start();
triggerAnimationStartFrame();
}
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
startAnimation(element, 0.5, 'red');
expect(element.attr('style')).toContain('transition');
endTransition(element, 0.5);
expect(element.attr('style')).not.toContain('transition');
startAnimation(element, 0.8, 'blue');
expect(element.attr('style')).toContain('transition');
// Trigger an extra transitionend event that matches the original transition
endTransition(element, 0.5);
expect(element.attr('style')).toContain('transition');
endTransition(element, 0.8);
expect(element.attr('style')).not.toContain('transition');
}));
it("should clear cache if no animation so follow-up animation on the same element will not be from cache",
inject(function($animateCss, $rootElement, $document, $$rAF) {
var element = angular.element('<div class="rclass"></div>');
var options = {
event: 'enter',
structural: true
};
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var animator = $animateCss(element, options);
expect(animator.$$willAnimate).toBeFalsy();
$$rAF.flush();
ss.addRule('.ng-enter', '-webkit-animation:3.5s keyframe_animation;' +
'animation:3.5s keyframe_animation;');
animator = $animateCss(element, options);
expect(animator.$$willAnimate).toBeTruthy();
}));
it('should apply a custom temporary class when a non-structural animation is used',
inject(function($animateCss, $rootElement, $document) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
$animateCss(element, {
event: 'super',
duration: 1000,
to: fakeStyle
}).start();
expect(element).toHaveClass('super');
triggerAnimationStartFrame();
expect(element).toHaveClass('super-active');
}));
describe("structural animations", function() {
they('should decorate the element with the ng-$prop CSS class',
['enter', 'leave', 'move'], function(event) {
inject(function($animateCss, $rootElement, $document) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
$animateCss(element, {
event: event,
structural: true,
duration: 1000,
to: fakeStyle
});
expect(element).toHaveClass('ng-' + event);
});
});
they('should decorate the element with the ng-$prop-active CSS class',
['enter', 'leave', 'move'], function(event) {
inject(function($animateCss, $rootElement, $document) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var animator = $animateCss(element, {
event: event,
structural: true,
duration: 1000,
to: fakeStyle
});
animator.start();
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-' + event + '-active');
});
});
they('should remove the ng-$prop and ng-$prop-active CSS classes from the element once the animation is done',
['enter', 'leave', 'move'], function(event) {
inject(function($animateCss, $rootElement, $document) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var animator = $animateCss(element, {
event: event,
structural: true,
duration: 1,
to: fakeStyle
});
animator.start();
triggerAnimationStartFrame();
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now() + 1000, elapsedTime: 1 });
expect(element).not.toHaveClass('ng-' + event);
expect(element).not.toHaveClass('ng-' + event + '-active');
});
});
they('should allow additional CSS classes to be added and removed alongside the $prop animation',
['enter', 'leave', 'move'], function(event) {
inject(function($animateCss, $rootElement) {
var element = angular.element('<div class="green"></div>');
$rootElement.append(element);
var animator = $animateCss(element, {
event: event,
structural: true,
duration: 1,
to: fakeStyle,
addClass: 'red',
removeClass: 'green'
});
animator.start();
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-' + event);
expect(element).toHaveClass('ng-' + event + '-active');
expect(element).toHaveClass('red');
expect(element).toHaveClass('red-add');
expect(element).toHaveClass('red-add-active');
expect(element).not.toHaveClass('green');
expect(element).toHaveClass('green-remove');
expect(element).toHaveClass('green-remove-active');
});
});
they('should place a CSS transition block after the preparation function to block accidental style changes',
['enter', 'leave', 'move', 'addClass', 'removeClass'], function(event) {
inject(function($animateCss, $rootElement, $document) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
ss.addRule('.cool-animation', 'transition:1.5s linear all;');
element.addClass('cool-animation');
var data = {};
if (event === 'addClass') {
data.addClass = 'green';
} else if (event === 'removeClass') {
element.addClass('red');
data.removeClass = 'red';
} else {
data.event = event;
}
var animator = $animateCss(element, data);
expect(element.css('transition-delay')).toMatch('-1.5s');
animator.start();
triggerAnimationStartFrame();
expect(element.attr('style')).toBeFalsy();
});
});
they('should not place a CSS transition block if options.skipBlocking is provided',
['enter', 'leave', 'move', 'addClass', 'removeClass'], function(event) {
inject(function($animateCss, $rootElement, $document, $window) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
ss.addRule('.cool-animation', 'transition:1.5s linear all;');
element.addClass('cool-animation');
var data = {};
if (event === 'addClass') {
data.addClass = 'green';
} else if (event === 'removeClass') {
element.addClass('red');
data.removeClass = 'red';
} else {
data.event = event;
}
var blockSpy = spyOn($window, 'blockTransitions').and.callThrough();
data.skipBlocking = true;
var animator = $animateCss(element, data);
expect(blockSpy).not.toHaveBeenCalled();
expect(element.attr('style')).toBeFalsy();
animator.start();
triggerAnimationStartFrame();
expect(element.attr('style')).toBeFalsy();
// just to prove it works
data.skipBlocking = false;
$animateCss(element, { addClass: 'test' });
expect(blockSpy).toHaveBeenCalled();
});
});
they('should place a CSS transition block after the preparation function even if a duration is provided',
['enter', 'leave', 'move', 'addClass', 'removeClass'], function(event) {
inject(function($animateCss, $rootElement, $document) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
ss.addRule('.cool-animation', 'transition:1.5s linear all;');
element.addClass('cool-animation');
var data = {};
if (event === 'addClass') {
data.addClass = 'green';
} else if (event === 'removeClass') {
element.addClass('red');
data.removeClass = 'red';
} else {
data.event = event;
}
data.duration = 10;
var animator = $animateCss(element, data);
expect(element.css('transition-delay')).toMatch('-10s');
expect(element.css('transition-duration')).toMatch('');
animator.start();
triggerAnimationStartFrame();
expect(element.attr('style')).not.toContain('transition-delay');
expect(element.css('transition-property')).toContain('all');
expect(element.css('transition-duration')).toContain('10s');
});
});
it('should allow multiple events to be animated at the same time',
inject(function($animateCss, $rootElement, $document) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
$animateCss(element, {
event: ['enter', 'leave', 'move'],
structural: true,
duration: 1,
to: fakeStyle
}).start();
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-enter');
expect(element).toHaveClass('ng-leave');
expect(element).toHaveClass('ng-move');
expect(element).toHaveClass('ng-enter-active');
expect(element).toHaveClass('ng-leave-active');
expect(element).toHaveClass('ng-move-active');
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now() + 1000, elapsedTime: 1 });
expect(element).not.toHaveClass('ng-enter');
expect(element).not.toHaveClass('ng-leave');
expect(element).not.toHaveClass('ng-move');
expect(element).not.toHaveClass('ng-enter-active');
expect(element).not.toHaveClass('ng-leave-active');
expect(element).not.toHaveClass('ng-move-active');
}));
it('should not break when running anchored animations without duration',
inject(function($animate, $document, $rootElement) {
var element1 = angular.element('<div class="item" ng-animate-ref="test">Item 1</div>');
var element2 = angular.element('<div class="item" ng-animate-ref="test">Item 2</div>');
angular.element($document[0].body).append($rootElement);
$rootElement.append(element1);
expect($rootElement.text()).toBe('Item 1');
$animate.leave(element1);
$animate.enter(element2, $rootElement);
$animate.flush();
expect($rootElement.text()).toBe('Item 2');
})
);
});
describe("class-based animations", function() {
they('should decorate the element with the class-$prop CSS class',
['add', 'remove'], function(event) {
inject(function($animateCss, $rootElement) {
var element = angular.element('<div></div>');
$rootElement.append(element);
var options = {};
options[event + 'Class'] = 'class';
options.duration = 1000;
options.to = fakeStyle;
$animateCss(element, options);
expect(element).toHaveClass('class-' + event);
});
});
they('should decorate the element with the class-$prop-active CSS class',
['add', 'remove'], function(event) {
inject(function($animateCss, $rootElement) {
var element = angular.element('<div></div>');
$rootElement.append(element);
var options = {};
options[event + 'Class'] = 'class';
options.duration = 1000;
options.to = fakeStyle;
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
expect(element).toHaveClass('class-' + event + '-active');
});
});
they('should remove the class-$prop-add and class-$prop-active CSS classes from the element once the animation is done',
['enter', 'leave', 'move'], function(event) {
inject(function($animateCss, $rootElement, $document) {
var element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var options = {};
options.event = event;
options.duration = 10;
options.to = fakeStyle;
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now() + 1000, elapsedTime: 10 });
expect(element).not.toHaveClass('ng-' + event);
expect(element).not.toHaveClass('ng-' + event + '-active');
});
});
they('should allow the class duration styles to be recalculated once started if the CSS classes being applied result new transition styles',
['add', 'remove'], function(event) {
inject(function($animateCss, $rootElement, $document) {
var element = angular.element('<div></div>');
if (event == 'add') {
ss.addRule('.natural-class', 'transition:1s linear all;');
} else {
ss.addRule('.natural-class', 'transition:0s linear none;');
ss.addRule('.base-class', 'transition:1s linear none;');
element.addClass('base-class');
element.addClass('natural-class');
}
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var options = {};
options[event + 'Class'] = 'natural-class';
var runner = $animateCss(element, options);
runner.start();
triggerAnimationStartFrame();
expect(element).toHaveClass('natural-class-' + event);
expect(element).toHaveClass('natural-class-' + event + '-active');
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now(), elapsedTime: 1 });
expect(element).not.toHaveClass('natural-class-' + event);
expect(element).not.toHaveClass('natural-class-' + event + '-active');
});
});
they('should force the class-based values to be applied early if no options.applyClassEarly is used as an option',
['enter', 'leave', 'move'], function(event) {
inject(function($animateCss, $rootElement, $document) {
ss.addRule('.blue.ng-' + event, 'transition:2s linear all;');
var element = angular.element('<div class="red"></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
var runner = $animateCss(element, {
addClass: 'blue',
applyClassesEarly: true,
removeClass: 'red',
event: event,
structural: true
});
runner.start();
expect(element).toHaveClass('ng-' + event);
expect(element).toHaveClass('blue');
expect(element).not.toHaveClass('red');
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-' + event);
expect(element).toHaveClass('ng-' + event + '-active');
expect(element).toHaveClass('blue');
expect(element).not.toHaveClass('red');
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now(), elapsedTime: 2 });
expect(element).not.toHaveClass('ng-' + event);
expect(element).not.toHaveClass('ng-' + event + '-active');
expect(element).toHaveClass('blue');
expect(element).not.toHaveClass('red');
});
});
});
describe("options", function() {
var element;
beforeEach(module(function() {
return function($rootElement, $document) {
angular.element($document[0].body).append($rootElement);
element = angular.element('<div></div>');
$rootElement.append(element);
};
}));
it("should not alter the provided options input in any way throughout the animation", inject(function($animateCss) {
var initialOptions = {
from: { height: '50px' },
to: { width: '50px' },
addClass: 'one',
removeClass: 'two',
duration: 10,
delay: 10,
structural: true,
keyframeStyle: '1s rotate',
transitionStyle: '1s linear',
stagger: 0.5,
staggerIndex: 3
};
var copiedOptions = copy(initialOptions);
expect(copiedOptions).toEqual(initialOptions);
var animator = $animateCss(element, copiedOptions);
expect(copiedOptions).toEqual(initialOptions);
var runner = animator.start();
expect(copiedOptions).toEqual(initialOptions);
triggerAnimationStartFrame();
expect(copiedOptions).toEqual(initialOptions);
runner.end();
expect(copiedOptions).toEqual(initialOptions);
}));
it("should not create a copy of the provided options if they have already been prepared earlier",
inject(function($animate, $animateCss) {
var options = {
from: { height: '50px' },
to: { width: '50px' },
addClass: 'one',
removeClass: 'two'
};
options.$$prepared = true;
var runner = $animateCss(element, options).start();
runner.end();
$animate.flush();
expect(options.addClass).toBeFalsy();
expect(options.removeClass).toBeFalsy();
expect(options.to).toBeFalsy();
expect(options.from).toBeFalsy();
}));
describe("[$$skipPreparationClasses]", function() {
it('should not apply and remove the preparation classes to the element when true',
inject(function($animateCss) {
var options = {
duration: 3000,
to: fakeStyle,
event: 'event',
structural: true,
addClass: 'klass',
$$skipPreparationClasses: true
};
var animator = $animateCss(element, options);
expect(element).not.toHaveClass('klass-add');
expect(element).not.toHaveClass('ng-event');
var runner = animator.start();
triggerAnimationStartFrame();
expect(element).not.toHaveClass('klass-add');
expect(element).not.toHaveClass('ng-event');
expect(element).toHaveClass('klass-add-active');
expect(element).toHaveClass('ng-event-active');
element.addClass('klass-add ng-event');
runner.end();
expect(element).toHaveClass('klass-add');
expect(element).toHaveClass('ng-event');
expect(element).not.toHaveClass('klass-add-active');
expect(element).not.toHaveClass('ng-event-active');
}));
});
describe("[duration]", function() {
it("should be applied for a transition directly", inject(function($animateCss, $rootElement) {
var element = angular.element('<div></div>');
$rootElement.append(element);
var options = {
duration: 3000,
to: fakeStyle,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var style = element.attr('style');
expect(style).toContain('3000s');
expect(style).toContain('linear');
}));
it("should be applied to a CSS keyframe animation directly if keyframes are detected within the CSS class",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' +
'animation:1.5s keyframe_animation;');
var options = {
duration: 5,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
expect(getPossiblyPrefixedStyleValue(element, 'animation-duration')).toEqual('5s');
}));
it("should remove all inline keyframe styling when an animation completes if a custom duration was applied",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' +
'animation:1.5s keyframe_animation;');
var options = {
duration: 5,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
browserTrigger(element, 'animationend',
{ timeStamp: Date.now() + 5000, elapsedTime: 5 });
expect(element.attr('style')).toBeFalsy();
}));
it("should remove all inline keyframe delay styling when an animation completes if a custom duration was applied",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' +
'animation:1.5s keyframe_animation;');
var options = {
delay: 5,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('5s');
browserTrigger(element, 'animationend',
{ timeStamp: Date.now() + 5000, elapsedTime: 1.5 });
expect(element.attr('style')).toBeFalsy();
}));
it("should not prepare the animation at all if a duration of zero is provided",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', '-webkit-transition:1s linear all;' +
'transition:1s linear all;');
var options = {
duration: 0,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
expect(animator.$$willAnimate).toBeFalsy();
}));
it("should apply a transition and keyframe duration directly if both transitions and keyframe classes are detected",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', '-webkit-animation:3s keyframe_animation;' +
'animation:3s keyframe_animation;' +
'transition:5s linear all;');
var options = {
duration: 4,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var style = element.attr('style');
expect(style).toMatch(/animation(?:-duration)?:\s*4s/);
expect(element.css('transition-duration')).toMatch('4s');
expect(element.css('transition-property')).toMatch('all');
expect(style).toContain('linear');
}));
});
describe("[delay]", function() {
it("should be applied for a transition directly", inject(function($animateCss, $rootElement) {
var element = angular.element('<div></div>');
$rootElement.append(element);
var options = {
duration: 3000,
delay: 500,
to: fakeStyle,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var prop = element.css('transition-delay');
expect(prop).toEqual('500s');
}));
it("should return false for the animator if a delay is provided but not a duration",
inject(function($animateCss, $rootElement) {
var element = angular.element('<div></div>');
$rootElement.append(element);
var options = {
delay: 500,
to: fakeStyle,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
expect(animator.$$willAnimate).toBeFalsy();
}));
it("should override the delay value present in the CSS class",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', '-webkit-transition:1s linear all;' +
'transition:1s linear all;' +
'-webkit-transition-delay:10s;' +
'transition-delay:10s;');
var element = angular.element('<div></div>');
$rootElement.append(element);
var options = {
delay: 500,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var prop = element.css('transition-delay');
expect(prop).toEqual('500s');
}));
it("should allow the delay value to zero if provided",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', '-webkit-transition:1s linear all;' +
'transition:1s linear all;' +
'-webkit-transition-delay:10s;' +
'transition-delay:10s;');
var element = angular.element('<div></div>');
$rootElement.append(element);
var options = {
delay: 0,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var prop = element.css('transition-delay');
expect(prop).toEqual('0s');
}));
it("should be applied to a CSS keyframe animation if detected within the CSS class",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', '-webkit-animation:1.5s keyframe_animation;' +
'animation:1.5s keyframe_animation;');
var options = {
delay: 400,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('400s');
expect(element.attr('style')).not.toContain('transition-delay');
}));
it("should apply a transition and keyframe delay if both transitions and keyframe classes are detected",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', '-webkit-animation:3s keyframe_animation;' +
'animation:3s keyframe_animation;' +
'transition:5s linear all;');
var options = {
delay: 10,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
expect(element.css('transition-delay')).toContain('-5s');
expect(element.attr('style')).not.toContain('animation-delay');
animator.start();
triggerAnimationStartFrame();
expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('10s');
expect(element.css('transition-delay')).toEqual('10s');
}));
it("should apply the keyframe and transition duration value before the CSS classes are applied", function() {
var classSpy = jasmine.createSpy();
module(function($provide) {
$provide.value('$$jqLite', {
addClass: function() {
classSpy();
},
removeClass: function() {
classSpy();
}
});
});
inject(function($animateCss, $rootElement) {
element.addClass('element');
ss.addRule('.element', '-webkit-animation:3s keyframe_animation;' +
'animation:3s keyframe_animation;' +
'transition:5s linear all;');
var options = {
delay: 2,
duration: 2,
addClass: 'superman',
$$skipPreparationClasses: true,
structural: true
};
var animator = $animateCss(element, options);
expect(element.attr('style') || '').not.toContain('animation-delay');
expect(element.attr('style') || '').not.toContain('transition-delay');
expect(classSpy).not.toHaveBeenCalled();
//redefine the classSpy to assert that the delay values have been
//applied before the classes are added
var assertionsRun = false;
classSpy = function() {
assertionsRun = true;
expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('2s');
expect(element.css('transition-delay')).toEqual('2s');
expect(element).not.toHaveClass('superman');
};
animator.start();
triggerAnimationStartFrame();
expect(assertionsRun).toBe(true);
});
});
it("should apply blocking before the animation starts, but then apply the detected delay when options.delay is true",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', 'transition:2s linear all; transition-delay: 1s;');
var options = {
delay: true,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
expect(element.css('transition-delay')).toEqual('-2s');
animator.start();
triggerAnimationStartFrame();
expect(element.attr('style') || '').not.toContain('transition-delay');
}));
it("should consider a negative value when delay:true is used with a keyframe animation",
inject(function($animateCss, $rootElement) {
ss.addPossiblyPrefixedRule('.ng-enter', 'animation: 2s keyframe_animation; ' +
'animation-delay: -1s;');
var options = {
delay: true,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toContain('-1s');
}));
they("should consider a negative value when a negative option delay is provided for a $prop animation", {
'transition': function() {
return {
prop: 'transition-delay',
css: 'transition:2s linear all'
};
},
'keyframe': function() {
return {
prop: 'animation-delay',
css: 'animation: 2s keyframe_animation'
};
}
}, function(testDetailsFactory) {
inject(function($animateCss, $rootElement) {
var testDetails = testDetailsFactory(prefix);
ss.addPossiblyPrefixedRule('.ng-enter', testDetails.css);
var options = {
delay: -2,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
expect(getPossiblyPrefixedStyleValue(element, testDetails.prop)).toContain('-2s');
});
});
they("should expect the $propend event to always return the full duration even when negative values are used", {
'transition': function() {
return {
event: 'transitionend',
css: 'transition:5s linear all; transition-delay: -2s'
};
},
'animation': function() {
return {
event: 'animationend',
css: 'animation: 5s keyframe_animation; animation-delay: -2s;'
};
}
}, function(testDetailsFactory) {
inject(function($animateCss, $rootElement) {
var testDetails = testDetailsFactory();
var event = testDetails.event;
ss.addPossiblyPrefixedRule('.ng-enter', testDetails.css);
var options = { event: 'enter', structural: true };
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
// 5 + (-2s) = 3
browserTrigger(element, event, { timeStamp: Date.now(), elapsedTime: 3 });
assertAnimationRunning(element, true);
// 5 seconds is the full animation
browserTrigger(element, event, { timeStamp: Date.now(), elapsedTime: 5 });
assertAnimationRunning(element);
});
});
});
describe("[transitionStyle]", function() {
it("should apply the transition directly onto the element and animate accordingly",
inject(function($animateCss, $rootElement) {
var options = {
transitionStyle: '5.5s linear all',
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var style = element.attr('style');
expect(element.css('transition-duration')).toMatch('5.5s');
expect(element.css('transition-property')).toMatch('all');
expect(style).toContain('linear');
expect(element).toHaveClass('ng-enter');
expect(element).toHaveClass('ng-enter-active');
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now() + 10000, elapsedTime: 5.5 });
expect(element).not.toHaveClass('ng-enter');
expect(element).not.toHaveClass('ng-enter-active');
expect(element.attr('style')).toBeFalsy();
}));
it("should give priority to the provided duration value, but only update the duration style itself",
inject(function($animateCss, $rootElement) {
var options = {
transitionStyle: '5.5s ease-in color',
duration: 4,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var style = element.attr('style');
expect(element.css('transition-duration')).toMatch('4s');
expect(element.css('transition-property')).toMatch('color');
expect(style).toContain('ease-in');
}));
it("should give priority to the provided delay value, but only update the delay style itself",
inject(function($animateCss, $rootElement) {
var options = {
transitionStyle: '5.5s 4s ease-in color',
delay: 20,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var style = element.attr('style');
expect(element.css('transition-delay')).toMatch('20s');
expect(element.css('transition-duration')).toMatch('5.5s');
expect(element.css('transition-property')).toMatch('color');
expect(style).toContain('ease-in');
}));
it("should execute the animation only if there is any provided CSS styling to go with the transition",
inject(function($animateCss, $rootElement) {
var options = {
transitionStyle: '6s 4s ease-out all'
};
$animateCss(element, options).start();
triggerAnimationStartFrame();
expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).not.toEqual('4s');
expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).not.toEqual('6s');
options.to = { color: 'brown' };
$animateCss(element, options).start();
triggerAnimationStartFrame();
expect(getPossiblyPrefixedStyleValue(element, 'transition-delay')).toEqual('4s');
expect(getPossiblyPrefixedStyleValue(element, 'transition-duration')).toEqual('6s');
}));
});
describe("[keyframeStyle]", function() {
it("should apply the keyframe animation directly onto the element and animate accordingly",
inject(function($animateCss, $rootElement) {
var options = {
keyframeStyle: 'my_animation 5.5s',
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var detectedStyle = element.attr('style');
expect(detectedStyle).toContain('5.5s');
expect(detectedStyle).toContain('my_animation');
expect(element).toHaveClass('ng-enter');
expect(element).toHaveClass('ng-enter-active');
browserTrigger(element, 'animationend',
{ timeStamp: Date.now() + 10000, elapsedTime: 5.5 });
expect(element).not.toHaveClass('ng-enter');
expect(element).not.toHaveClass('ng-enter-active');
expect(element.attr('style')).toBeFalsy();
}));
it("should give priority to the provided duration value, but only update the duration style itself",
inject(function($animateCss, $rootElement) {
var options = {
keyframeStyle: 'my_animation 5.5s',
duration: 50,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var detectedStyle = element.attr('style');
expect(detectedStyle).toContain('50s');
expect(detectedStyle).toContain('my_animation');
}));
it("should give priority to the provided delay value, but only update the duration style itself",
inject(function($animateCss, $rootElement) {
var options = {
keyframeStyle: 'my_animation 5.5s 10s',
delay: 50,
event: 'enter',
structural: true
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('50s');
expect(getPossiblyPrefixedStyleValue(element, 'animation-duration')).toEqual('5.5s');
expect(getPossiblyPrefixedStyleValue(element, 'animation-name')).toEqual('my_animation');
}));
it("should be able to execute the animation if it is the only provided value",
inject(function($animateCss, $rootElement) {
var options = {
keyframeStyle: 'my_animation 5.5s 10s'
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
expect(getPossiblyPrefixedStyleValue(element, 'animation-delay')).toEqual('10s');
expect(getPossiblyPrefixedStyleValue(element, 'animation-duration')).toEqual('5.5s');
expect(getPossiblyPrefixedStyleValue(element, 'animation-name')).toEqual('my_animation');
}));
});
describe("[from] and [to]", function() {
it("should apply from styles to an element during the preparation phase",
inject(function($animateCss, $rootElement) {
var options = {
duration: 2.5,
event: 'enter',
structural: true,
from: { width: '50px' },
to: { width: '100px' }
};
var animator = $animateCss(element, options);
expect(element.attr('style')).toMatch(/width:\s*50px/);
}));
it("should apply to styles to an element during the animation phase",
inject(function($animateCss, $rootElement) {
var options = {
duration: 2.5,
event: 'enter',
structural: true,
from: { width: '15px' },
to: { width: '25px' }
};
var animator = $animateCss(element, options);
var runner = animator.start();
triggerAnimationStartFrame();
runner.end();
expect(element.css('width')).toBe('25px');
}));
it("should apply the union of from and to styles to the element if no animation will be run",
inject(function($animateCss, $rootElement) {
var options = {
event: 'enter',
structural: true,
from: { 'width': '10px', height: '50px' },
to: { 'width': '15px' }
};
var animator = $animateCss(element, options);
expect(animator.$$willAnimate).toBeFalsy();
animator.start();
expect(element.css('width')).toBe('15px');
expect(element.css('height')).toBe('50px');
}));
it("should retain to and from styles on an element after an animation completes",
inject(function($animateCss, $rootElement) {
var options = {
event: 'enter',
structural: true,
duration: 10,
from: { 'width': '10px', height: '66px' },
to: { 'width': '5px' }
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now() + 10000, elapsedTime: 10 });
expect(element).not.toHaveClass('ng-enter');
expect(element.css('width')).toBe('5px');
expect(element.css('height')).toBe('66px');
}));
it("should always apply the from styles before the start function is called even if no transition is detected when started",
inject(function($animateCss, $rootElement) {
ss.addRule('.my-class', 'transition: 0s linear color');
var options = {
addClass: 'my-class',
from: { height: '26px' },
to: { height: '500px' }
};
var animator = $animateCss(element, options);
expect(element.css('height')).toBe('26px');
animator.start();
triggerAnimationStartFrame();
expect(element.css('height')).toBe('500px');
}));
it("should apply an inline transition if [to] styles and a duration are provided",
inject(function($animateCss, $rootElement) {
var options = {
event: 'enter',
structural: true,
duration: 2.5,
to: { background: 'red' }
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var style = element.attr('style');
expect(element.css('transition-duration')).toMatch('2.5s');
expect(element.css('transition-property')).toMatch('all');
expect(style).toContain('linear');
}));
it("should remove all inline transition styling when an animation completes",
inject(function($animateCss, $rootElement) {
var options = {
event: 'enter',
structural: true,
duration: 2.5,
to: { background: 'red' }
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var style = element.attr('style');
expect(style).toContain('transition');
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now() + 2500, elapsedTime: 2.5 });
style = element.attr('style');
expect(style).not.toContain('transition');
}));
it("should retain existing styles when an inline styled animation completes",
inject(function($animateCss, $rootElement) {
var options = {
event: 'enter',
structural: true,
duration: 2.5
};
element.css('font-size', '20px');
element.css('opacity', '0.5');
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var style = element.attr('style');
expect(style).toContain('transition');
animator.end();
style = element.attr('style');
expect(element.attr('style')).not.toContain('transition');
expect(element.css('opacity')).toEqual('0.5');
}));
it("should remove all inline transition delay styling when an animation completes",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', 'transition: 1s linear color');
var options = {
event: 'enter',
structural: true,
delay: 5
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
expect(element.css('transition-delay')).toEqual('5s');
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now() + 5000, elapsedTime: 1 });
expect(element.attr('style') || '').not.toContain('transition');
}));
it("should not apply an inline transition if only [from] styles and a duration are provided",
inject(function($animateCss, $rootElement) {
var options = {
duration: 3,
from: { background: 'blue' }
};
var animator = $animateCss(element, options);
expect(animator.$$willAnimate).toBeFalsy();
}));
it("should apply a transition if [from] styles are provided with a class that is added",
inject(function($animateCss, $rootElement) {
var options = {
addClass: 'superb',
from: { background: 'blue' }
};
var animator = $animateCss(element, options);
expect(isFunction(animator.start)).toBe(true);
}));
it("should apply an inline transition if only [from] styles, but classes are added or removed and a duration is provided",
inject(function($animateCss, $rootElement) {
var options = {
duration: 3,
addClass: 'sugar',
from: { background: 'yellow' }
};
var animator = $animateCss(element, options);
expect(animator.$$willAnimate).toBeTruthy();
}));
it("should not apply an inline transition if no styles are provided",
inject(function($animateCss, $rootElement) {
var emptyObject = {};
var options = {
duration: 3,
to: emptyObject,
from: emptyObject
};
var animator = $animateCss(element, options);
expect(animator.$$willAnimate).toBeFalsy();
}));
it("should apply a transition duration if the existing transition duration's property value is not 'all'",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', 'transition: 1s linear color');
var emptyObject = {};
var options = {
event: 'enter',
structural: true,
to: { background: 'blue' }
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
var style = element.attr('style');
expect(element.css('transition-duration')).toMatch('1s');
expect(element.css('transition-property')).toMatch('all');
expect(style).toContain('linear');
}));
it("should apply a transition duration and an animation duration if duration + styles options are provided for a matching keyframe animation",
inject(function($animateCss, $rootElement) {
ss.addRule('.ng-enter', '-webkit-animation:3.5s keyframe_animation;' +
'animation:3.5s keyframe_animation;');
var emptyObject = {};
var options = {
event: 'enter',
structural: true,
duration: 10,
to: {
background: 'blue'
}
};
var animator = $animateCss(element, options);
animator.start();
triggerAnimationStartFrame();
expect(element.css('transition-duration')).toMatch('10s');
expect(getPossiblyPrefixedStyleValue(element, 'animation-duration')).toEqual('10s');
}));
});
describe("[easing]", function() {
var element;
beforeEach(inject(function($document, $rootElement) {
element = angular.element('<div></div>');
$rootElement.append(element);
angular.element($document[0].body).append($rootElement);
}));
it("should apply easing to a transition animation if it exists", inject(function($animateCss) {
ss.addRule('.red', 'transition:1s linear all;');
var easing = 'ease-out';
var animator = $animateCss(element, { addClass: 'red', easing: easing });
animator.start();
triggerAnimationStartFrame();
var style = element.attr('style');
expect(style).toContain('ease-out');
}));
it("should not apply easing to transitions nor keyframes on an element animation if nothing is detected",
inject(function($animateCss) {
ss.addRule('.red', ';');
var easing = 'ease-out';
var animator = $animateCss(element, { addClass: 'red', easing: easing });
animator.start();
triggerAnimationStartFrame();
expect(element.attr('style')).toBeFalsy();
}));
it("should apply easing to both keyframes and transition animations if detected",
inject(function($animateCss) {
ss.addRule('.red', 'transition: 1s linear all;');
ss.addPossiblyPrefixedRule('.blue', 'animation: 1s my_keyframe;');
var easing = 'ease-out';
var animator = $animateCss(element, { addClass: 'red blue', easing: easing });
animator.start();
triggerAnimationStartFrame();
var style = element.attr('style');
expect(style).toMatch(/animation(?:-timing-function)?:\s*ease-out/);
expect(style).toMatch(/transition(?:-timing-function)?:\s*ease-out/);
}));
});
describe("[cleanupStyles]", function() {
it("should cleanup [from] and [to] styles that have been applied for the animation when true",
inject(function($animateCss) {
var runner = $animateCss(element, {
duration: 1,
from: { background: 'gold' },
to: { color: 'brown' },
cleanupStyles: true
}).start();
assertStyleIsPresent(element, 'background', true);
assertStyleIsPresent(element, 'color', false);
triggerAnimationStartFrame();
assertStyleIsPresent(element, 'background', true);
assertStyleIsPresent(element, 'color', true);
runner.end();
assertStyleIsPresent(element, 'background', false);
assertStyleIsPresent(element, 'color', false);
function assertStyleIsPresent(element, style, bool) {
expect(element[0].style[style])[bool ? 'toBeTruthy' : 'toBeFalsy']();
}
}));
it('should restore existing overidden styles already present on the element when true',
inject(function($animateCss) {
element.css('height', '100px');
element.css('width', '111px');
var runner = $animateCss(element, {
duration: 1,
from: { height: '200px', 'font-size':'66px' },
to: { height: '300px', 'font-size': '99px', width: '222px' },
cleanupStyles: true
}).start();
assertStyle(element, 'height', '200px');
assertStyle(element, 'font-size', '66px');
assertStyle(element, 'width', '111px');
triggerAnimationStartFrame();
assertStyle(element, 'height', '300px');
assertStyle(element, 'width', '222px');
assertStyle(element, 'font-size', '99px');
runner.end();
assertStyle(element, 'width', '111px');
assertStyle(element, 'height', '100px');
expect(element[0].style.getPropertyValue('font-size')).not.toBe('66px');
function assertStyle(element, prop, value) {
expect(element[0].style.getPropertyValue(prop)).toBe(value);
}
}));
});
it('should round up long elapsedTime values to close off a CSS3 animation',
inject(function($animateCss) {
ss.addRule('.millisecond-transition.ng-leave', '-webkit-transition:510ms linear all;' +
'transition:510ms linear all;');
element.addClass('millisecond-transition');
var animator = $animateCss(element, {
event: 'leave',
structural: true
});
animator.start();
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-leave-active');
browserTrigger(element, 'transitionend',
{ timeStamp: Date.now() + 1000, elapsedTime: 0.50999999991 });
expect(element).not.toHaveClass('ng-leave-active');
}));
});
describe('SVG', function() {
it('should properly apply transitions on an SVG element',
inject(function($animateCss, $rootScope, $compile, $document, $rootElement) {
var element = $compile('<svg width="500" height="500">' +
'<circle cx="15" cy="5" r="100" fill="orange" />' +
'</svg>')($rootScope);
angular.element($document[0].body).append($rootElement);
$rootElement.append(element);
$animateCss(element, {
event: 'enter',
structural: true,
duration: 10
}).start();
triggerAnimationStartFrame();
expect(element).toHaveClass('ng-enter');
expect(element).toHaveClass('ng-enter-active');
browserTrigger(element, 'transitionend', { timeStamp: Date.now() + 1000, elapsedTime: 10 });
expect(element).not.toHaveClass('ng-enter');
expect(element).not.toHaveClass('ng-enter-active');
}));
it('should properly remove classes from SVG elements', inject(function($animateCss) {
var element = angular.element('<svg width="500" height="500">' +
'<rect class="class-of-doom"></rect>' +
'</svg>');
var child = element.find('rect');
var animator = $animateCss(child, {
removeClass: 'class-of-doom',
duration: 0
});
animator.start();
var className = child[0].getAttribute('class');
expect(className).toBe('');
}));
});
});
});
|
var GedcomX = require('../'),
utils = require('../utils');
/**
* A name.
*
* @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#name-conclusion|GEDCOM X JSON Spec}
*
* @class
* @extends Conclusion
* @param {Object} [json]
*/
var Name = function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Name)){
return new Name(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Name.isInstance(json)){
return json;
}
this.init(json);
};
Name.prototype = Object.create(GedcomX.Conclusion.prototype);
Name._gedxClass = Name.prototype._gedxClass = 'GedcomX.Name';
Name.jsonProps = [
'type',
'date',
'nameForms'
];
/**
* Check whether the given object is an instance of this class.
*
* @param {Object} obj
* @returns {Boolean}
*/
Name.isInstance = function(obj){
return utils.isInstance(obj, this._gedxClass);
};
/**
* Initialize from JSON
*
* @param {Object}
* @return {Name} this
*/
Name.prototype.init = function(json){
GedcomX.Conclusion.prototype.init.call(this, json);
if(json){
this.setType(json.type);
this.setDate(json.date);
this.setNameForms(json.nameForms);
}
return this;
};
/**
* Get the name type
*
* @returns {String} type
*/
Name.prototype.getType = function(){
return this.type;
};
/**
* Set the name type
*
* @param {String} type
* @returns {Name} This instance
*/
Name.prototype.setType = function(type){
this.type = type;
return this;
};
/**
* Get the date
*
* @returns {Date} date
*/
Name.prototype.getDate = function(){
return this.date;
};
/**
* Set the date
*
* @param {Date|Object} date
* @returns {Fact} This instance
*/
Name.prototype.setDate = function(date){
if(date){
this.date = GedcomX.Date(date);
}
return this;
};
/**
* Get the name forms
*
* @return {NameForm[]}
*/
Name.prototype.getNameForms = function(){
return this.nameForms || [];
};
/**
* Set the name forms
*
* @param {NameForm[]|Object[]} nameForms
* @returns {Name} This instance
*/
Name.prototype.setNameForms = function(nameForms){
return this._setArray(nameForms, 'nameForms', 'addNameForm');
};
/**
* Add a name form
*
* @param {NameForm|Object} nameForm
* @returns {Name} This instance
*/
Name.prototype.addNameForm = function(nameForm){
return this._arrayPush(nameForm, 'nameForms', GedcomX.NameForm);
};
/**
* Export the object as JSON
*
* @return {Object} JSON object
*/
Name.prototype.toJSON = function(){
return this._toJSON(GedcomX.Conclusion, Name.jsonProps);
};
module.exports = Name;
|
import ResponsiveListItemController from '../global/ResponsiveListItemController';
export default class ItemController extends ResponsiveListItemController{
/*@ngInject*/
constructor($scope, $timeout, itemService) {
super($scope, $timeout);
this.itemService = itemService;
}
deleteItem() {
this.item.deleting = true;
this.itemService.deleteItemOfList(this.item, this.list)
.catch(() => {
this.item.deleting = false;
});
}
updateItem() {
this.itemService.updateItemOfList(this.item, this.list);
}
}
|
var React = require('react');
var ReactDOM = require('react-dom');
var ReactBootstrap = require('react-bootstrap');
var Col = ReactBootstrap.Col;
var Tabs = ReactBootstrap.Tabs;
var Tab = ReactBootstrap.Tab;
var Panel = ReactBootstrap.Panel;
var Modal = ReactBootstrap.Modal;
var Form = ReactBootstrap.Form;
var FormGroup = ReactBootstrap.FormGroup;
var FormControl = ReactBootstrap.FormControl;
var ControlLabel = ReactBootstrap.ControlLabel;
var Checkbox = ReactBootstrap.Checkbox;
var Button = ReactBootstrap.Button;
var ButtonGroup = ReactBootstrap.ButtonGroup;
var Combobox = require('react-widgets').Combobox;
var AccountCombobox = require('./AccountCombobox');
var models = require('../models');
var Account = models.Account;
var AccountType = models.AccountType;
var AccountTypeList = models.AccountTypeList;
class AddEditAccountModal extends React.Component {
getInitialState(props) {
var s = {
accountid: -1,
security: 1,
parentaccountid: -1,
type: 1,
name: "",
ofxurl: "",
ofxorg: "",
ofxfid: "",
ofxuser: "",
ofxbankid: "",
ofxacctid: "",
ofxaccttype: "CHECKING",
ofxclientuid: "",
ofxappid: "",
ofxappver: "",
ofxversion: "",
ofxnoindent: false,
};
if (!props) {
return s;
} else if (props.editAccount != null) {
s.accountid = props.editAccount.AccountId;
s.name = props.editAccount.Name;
s.security = props.editAccount.SecurityId;
s.parentaccountid = props.editAccount.ParentAccountId;
s.type = props.editAccount.Type;
s.ofxurl = props.editAccount.OFXURL;
s.ofxorg = props.editAccount.OFXORG;
s.ofxfid = props.editAccount.OFXFID;
s.ofxuser = props.editAccount.OFXUser;
s.ofxbankid = props.editAccount.OFXBankID;
s.ofxacctid = props.editAccount.OFXAcctID;
s.ofxaccttype = props.editAccount.OFXAcctType;
s.ofxclientuid = props.editAccount.OFXClientUID;
s.ofxappid = props.editAccount.OFXAppID;
s.ofxappver = props.editAccount.OFXAppVer;
s.ofxversion = props.editAccount.OFXVersion;
s.ofxnoindent = props.editAccount.OFXNoIndent;
} else if (props.initialParentAccount != null) {
s.security = props.initialParentAccount.SecurityId;
s.parentaccountid = props.initialParentAccount.AccountId;
s.type = props.initialParentAccount.Type;
}
return s;
}
constructor() {
super();
this.state = this.getInitialState();
this.onCancel = this.handleCancel.bind(this);
this.onChange = this.handleChange.bind(this);
this.onNoIndentClick = this.handleNoIndentClick.bind(this);
this.onSecurityChange = this.handleSecurityChange.bind(this);
this.onTypeChange = this.handleTypeChange.bind(this);
this.onParentChange = this.handleParentChange.bind(this);
this.onSubmit = this.handleSubmit.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps.show && !this.props.show) {
this.setState(this.getInitialState(nextProps));
}
}
handleCancel() {
if (this.props.onCancel != null)
this.props.onCancel();
}
handleChange() {
this.setState({
name: ReactDOM.findDOMNode(this.refs.name).value,
ofxurl: ReactDOM.findDOMNode(this.refs.ofxurl).value,
ofxorg: ReactDOM.findDOMNode(this.refs.ofxorg).value,
ofxfid: ReactDOM.findDOMNode(this.refs.ofxfid).value,
ofxuser: ReactDOM.findDOMNode(this.refs.ofxuser).value,
ofxbankid: ReactDOM.findDOMNode(this.refs.ofxbankid).value,
ofxacctid: ReactDOM.findDOMNode(this.refs.ofxacctid).value,
ofxclientuid: ReactDOM.findDOMNode(this.refs.ofxclientuid).value,
ofxappid: ReactDOM.findDOMNode(this.refs.ofxappid).value,
ofxappver: ReactDOM.findDOMNode(this.refs.ofxappver).value,
ofxversion: ReactDOM.findDOMNode(this.refs.ofxversion).value,
});
if (this.state.type != AccountType.Investment) {
this.setState({
ofxaccttype: ReactDOM.findDOMNode(this.refs.ofxaccttype).value,
});
}
}
handleNoIndentClick() {
this.setState({ofxnoindent: !this.state.ofxnoindent});
}
handleSecurityChange(security) {
if (security.hasOwnProperty('SecurityId'))
this.setState({
security: security.SecurityId
});
}
handleTypeChange(type) {
if (type.hasOwnProperty('TypeId'))
this.setState({
type: type.TypeId
});
}
handleParentChange(parentAccount) {
this.setState({parentaccountid: parentAccount.AccountId});
}
handleSubmit() {
var a = new Account();
if (this.props.editAccount != null)
a.AccountId = this.state.accountid;
a.Name = this.state.name;
a.ParentAccountId = this.state.parentaccountid;
a.SecurityId = this.state.security;
a.Type = this.state.type;
a.OFXURL = this.state.ofxurl;
a.OFXORG = this.state.ofxorg;
a.OFXFID = this.state.ofxfid;
a.OFXUser = this.state.ofxuser;
a.OFXBankID = this.state.ofxbankid;
a.OFXAcctID = this.state.ofxacctid;
a.OFXAcctType = this.state.ofxaccttype;
a.OFXClientUID = this.state.ofxclientuid;
a.OFXAppID = this.state.ofxappid;
a.OFXAppVer = this.state.ofxappver;
a.OFXVersion = this.state.ofxversion;
a.OFXNoIndent = this.state.ofxnoindent;
if (this.props.onSubmit != null)
this.props.onSubmit(a);
}
render() {
var headerText = (this.props.editAccount != null) ? "Edit" : "Create New";
var buttonText = (this.props.editAccount != null) ? "Save Changes" : "Create Account";
var rootName = (this.props.editAccount != null) ? "Top-level Account" : "New Top-level Account";
var ofxBankIdName = "Broker ID";
var ofxAcctType = [];
if (this.state.type != AccountType.Investment) {
ofxBankIdName = "Bank ID";
ofxAcctType = (
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>Account Type</Col>
<Col xs={10}>
<FormControl
componentClass="select"
placeholder="select"
value={this.state.ofxaccttype}
onChange={this.onChange}
ref="ofxaccttype">
<option value="CHECKING">Checking</option>
<option value="SAVINGS">Savings</option>
<option value="CC">Credit Card</option>
<option value="MONEYMRKT">Money Market</option>
<option value="CREDITLINE">Credit Line</option>
<option value="CD">CD</option>
</FormControl>
</Col>
</FormGroup>
);
}
var bankIdDisabled = (this.state.type != AccountType.Investment && this.state.ofxaccttype == "CC") ? true : false;
return (
<Modal show={this.props.show} onHide={this.onCancel}>
<Modal.Header closeButton>
<Modal.Title>{headerText} Account</Modal.Title>
</Modal.Header>
<Modal.Body>
<Tabs defaultActiveKey={1} id="editAccountTabs">
<Tab eventKey={1} title="General">
<Form horizontal onSubmit={this.onSubmit}>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>Name</Col>
<Col xs={10}>
<FormControl type="text"
value={this.state.name}
onChange={this.onChange}
ref="name"/>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>Parent Account</Col>
<Col xs={10}>
<AccountCombobox
accounts={this.props.accounts}
accountChildren={this.props.accountChildren}
value={this.state.parentaccountid}
rootName={rootName}
onChange={this.onParentChange}
ref="parent" />
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>Security</Col>
<Col xs={10}>
<Combobox
suggest
data={this.props.security_list}
valueField='SecurityId'
textField={item => typeof item === 'string' ? item : item.Name + " - " + item.Description}
defaultValue={this.state.security}
onChange={this.onSecurityChange}
ref="security" />
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>Account Type</Col>
<Col xs={10}>
<Combobox
suggest
data={AccountTypeList}
valueField='TypeId'
textField='Name'
defaultValue={this.state.type}
onChange={this.onTypeChange}
ref="type" />
</Col>
</FormGroup>
</Form>
</Tab>
<Tab eventKey={2} title="Sync (OFX)">
<Form horizontal onSubmit={this.onSubmit}>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>OFX URL</Col>
<Col xs={10}>
<FormControl type="text"
value={this.state.ofxurl}
onChange={this.onChange}
ref="ofxurl"/>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>ORG</Col>
<Col xs={10}>
<FormControl type="text"
value={this.state.ofxorg}
onChange={this.onChange}
ref="ofxorg"/>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>FID</Col>
<Col xs={10}>
<FormControl type="text"
value={this.state.ofxfid}
onChange={this.onChange}
ref="ofxfid"/>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>Username</Col>
<Col xs={10}>
<FormControl type="text"
value={this.state.ofxuser}
onChange={this.onChange}
ref="ofxuser"/>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>{ofxBankIdName}</Col>
<Col xs={10}>
<FormControl type="text"
disabled={bankIdDisabled}
value={this.state.ofxbankid}
onChange={this.onChange}
ref="ofxbankid"/>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>Account ID</Col>
<Col xs={10}>
<FormControl type="text"
value={this.state.ofxacctid}
onChange={this.onChange}
ref="ofxacctid"/>
</Col>
</FormGroup>
{ofxAcctType}
<Panel collapsible header="Advanced Settings">
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>Client UID</Col>
<Col xs={10}>
<FormControl type="text"
value={this.state.ofxclientuid}
onChange={this.onChange}
ref="ofxclientuid"/>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>App ID</Col>
<Col xs={10}>
<FormControl type="text"
value={this.state.ofxappid}
onChange={this.onChange}
ref="ofxappid"/>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>App Version</Col>
<Col xs={10}>
<FormControl type="text"
value={this.state.ofxappver}
onChange={this.onChange}
ref="ofxappver"/>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} xs={2}>OFX Version</Col>
<Col xs={10}>
<FormControl type="text"
value={this.state.ofxversion}
onChange={this.onChange}
ref="ofxversion"/>
</Col>
</FormGroup>
<FormGroup>
<Col xsOffset={2} xs={10}>
<Checkbox
checked={this.state.ofxnoindent ? "checked" : ""}
onClick={this.onNoIndentClick}>
Don't indent OFX request files
</Checkbox>
</Col>
</FormGroup>
</Panel>
</Form>
</Tab>
</Tabs>
</Modal.Body>
<Modal.Footer>
<ButtonGroup className="pull-right">
<Button onClick={this.onCancel} bsStyle="warning">Cancel</Button>
<Button onClick={this.onSubmit} bsStyle="success">{buttonText}</Button>
</ButtonGroup>
</Modal.Footer>
</Modal>
);
}
}
module.exports = AddEditAccountModal;
|
import React from 'react';
import {Table} from 'antd';
const columns = [{
title: "姓名",
dataIndex: "name",
}, {
title: "手机号码",
dataIndex: "phoneNo",
}, {
title: "备注",
dataIndex: "note",
}];
const rowKey = (record) => {
return record.id;
};
class UserList extends React.Component {
constructor(props) {
super(props);
console.log('[DEBUG] ---> UserList constructor, props: ', this.props);
this.rowSelection = {
type: 'radio',
onSelect: this.props.updateUserSelection
};
console.log('[DEBUG] ---> UserList constructor, this: ', this);
}
render() {
console.log('[DEBUG] ---> UserList render, props: ', this.props);
let {users} = this.props;
console.log('[DEBUG] ---> UserList this: ', this);
return (
<div>
<Table size="small" bordered
columns={columns} dataSource={users}
rowKey={rowKey} rowSelection={this.rowSelection}
/>
</div>
);
}
}
export default UserList;
|
var post = require('../lib/post.js');
var crypto = require('crypto');
var sublevel = require('subleveldown');
var bytewise = require('bytewise');
var through = require('through2');
var retricon = require('retricon');
var firstUser = false;
module.exports = function (users, auth, blob, argv, settings) {
users.list().pipe(through.obj(
function (row) { firstUser = false },
function () { firstUser = true }
));
return post(function (req, res, m) {
var id = crypto.randomBytes(16).toString('hex');
var img = retricon(id, { pixelSize: 15, tiles: 5 });
var w = img.pngStream().pipe(blob.createWriteStream());
w.on('error', function (err) { m.error(500, err) });
w.once('finish', function () { create(res, m, id, w.key) });
});
function create (res, m, id, avatar) {
var date = new Date().toISOString();
var opts = {
login: {
basic: {
username: m.params.name,
password: m.params.password
}
},
value: {
type: 'user',
id: id,
name: m.params.name,
email: m.params.email,
fullName: m.params['full-name'],
member: firstUser ? true : false, // TODO remove
visibility: m.params.visibility,
avatar: avatar,
created: date,
updated: date,
collectives: {}
}
};
// add first user to all collectives
// and grant user all available privileges for each collective
if(firstUser) {
var collective;
for(collective in settings.collectives) {
opts.value.collectives[collective] = {
privs: settings.collectives[collective].privs
}
}
}
firstUser = false;
users.create(id, opts, function (err) {
if (err) return m.error(400, err);
if(argv.debug) {
console.log('[debug] created user', m.params.name, 'with email', m.params.email, 'and password', m.params.password);
}
auth.login(res, { id: id, name: m.params.name }, onlogin);
});
function onlogin (err, session) {
if (err) return m.error(400, err);
res.writeHead(303, { location: '../../~' + m.params.name + '/welcome' });
res.end();
}
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:11f787878dcb96c18ee26baa6d35d4b43e19b9e9426f378b55b626ecec3aa28b
size 2358
|
/**
*
* @authors Your Name (you@example.org)
* @date 2015-07-23 10:30:04
* @version $Id$
*/
require.config({
//配置jquery的别名
paths: {
'jquery': 'jquery.min'
}
});
require(['jquery', 'backtop'], function($, backTop) {
//使用面向对象的方式调用
// var backtop = new backTop.BackTop($('#backTop'), {
// mode: 'go',
// speed: 1500,
// pos: 100
// });
// 使用jq的方法调用
$('#backTop').backTop({
mode: 'move', //返回顶部移动模式,动画或直接到达
speed: 800, //动画模式下返回顶部的速度
pos: 100 //当scrollTop大于pos时显示返回顶部按钮,否则不显示
});
});
|
'use strict';
process.env.DEBUG = `log,error,skip,${process.env.DEBUG || ''}`;
const co = require('co');
const _ = require('lodash');
const scripts = require('./scripts');
const logError = require('debug')('error');
var argv = require('yargs')
.version(function() {
return require('./package').version;
})
.usage('Usage: $0 <command> [options]')
.command('export', 'Get tags and alerts from a Logentries account', (yargs) => {
argv = yargs
.usage(`Usage: $0 export --account_key 123-asd-345 --output 'output.json'`)
.option('account_key', {
demand: true,
description: 'Account key to get the data from'
})
.option('output', {
demand: true,
description: 'Filename to export the data'
})
.help('help')
.argv
})
.command('import', 'Import tags and alerts into a Logentries account', (yargs) => {
argv = yargs
.usage(`Usage: $0 import --account_key 123-asd-345 --target_account_key 234-bda-543 --log_set 'Sample logset' --log 'Sample logs' --alert_emails 'sample@sample.com' --alert_rate_count 11 --alert_rate_range 'hour' --alert_limit_count 22 --alert_limit_range 'hour' --output 'backup.json'`)
.option('account_key', {
description: 'Account key to get the data from. This or the input argument should be provided!'
})
.option('output', {
description: 'Filename to dump the exported data to later use'
})
.option('input', {
description: 'Filename for import the data from. This or the account_key argument should be provided!'
})
.option('target_account_key', {
description: 'The account key to import the data'
})
.option('log_set', {
description: 'Add the alerts to the logs of the specified log set'
})
.option('log', {
description: 'Add the alerts to a log. The log_set argument should be provided to use this option!'
})
.option('alert_emails', {
description: `Set the direct mail alerts to the specified email instead of the exported one. It could contain multiple emails, eg. 'sample@sample.com,sample2@sample.com'`
})
.option('alert_rate_count', {
description: `Override the exported alert rate count`
})
.option('alert_rate_range', {
choices: ['day', 'hour'],
description: `Override the exported alert rate range`
})
.option('alert_limit_count', {
description: `Override the exported alert limit count`
})
.option('alert_limit_range', {
choices: ['day', 'hour'],
description: `Override the exported alert limit range`
})
.demand('target_account_key')
.argv
})
.demand(1)
.epilog('copyright 2016')
.argv;
let command = argv._[0];
let options = _.mapKeys(argv, (v, key) => _.camelCase(key));
co(function*() {
try {
yield scripts[command](options);
} catch(err) {
logError(err);
}
}).catch(function(err) {
logError(err);
});
|
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
window.location.hostname === '[::1]' ||
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
if ('serviceWorker' in navigator) {
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/sw.js`;
console.log(swUrl);
if (!isLocalhost) {
registerValidSW(swUrl);
} else {
checkValidServiceWorker(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(handleServiceWorkerRegistration)
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function handleServiceWorkerRegistration(registration) {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
console.log('New content is available; please refresh.');
} else {
console.log('Content is cached for offline use.');
}
}
};
};
// reg.pushManager.getSubscription()
// .then(function (subscription) {
// })
// .catch(function (err) {
// console.log('Error during getSubscription()', err);
// });
}
function checkValidServiceWorker(swUrl) {
fetch(swUrl)
.then(response => {
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
|
import { getPlugins } from "../src";
it("getPlugins", () => {
expect(
getPlugins(
[
["./export-default", { optKey: 10 }],
"./get-by-key[customKey]",
"./module-exports",
["./module-exports", { optKey: 20 }],
],
"./packages/util/get-plugins/test/fixtures"
)
).toEqual([
{
name: "./export-default",
key: "default",
plugin: { a: 10 },
options: { optKey: 10 },
},
{ name: "./get-by-key", key: "customKey", plugin: { a: 10 }, options: {} },
{
name: "./module-exports",
key: "default",
plugin: { a: 10 },
options: {},
},
{
name: "./module-exports",
key: "default",
plugin: { a: 10 },
options: { optKey: 20 },
},
]);
});
|
window.pdfMake = window.pdfMake || {}; window.pdfMake.fonts = {"Wallpoet":{"normal":"Wallpoet-Regular.ttf","bold":"Wallpoet-Regular.ttf","italics":"Wallpoet-Regular.ttf","bolditalics":"Wallpoet-Regular.ttf"}};
|
var IPTablesList = React.createClass({displayName: "IPTablesList",
getInitialState: function() {
return {list: ""}
},
componentDidMount: function() {
this.getList();
setInterval(function() {
this.getList();
}.bind(this), 10000);
},
getList: function() {
Ajax.get('/iptables/list').then(function(json) {
this.setState({list: json.list});
}.bind(this));
},
render: function() {
return (
React.createElement("pre", null,
this.state.list
)
);
}
});
|
export const top = {"viewBox":"0 0 8 8","children":[{"name":"path","attribs":{"d":"M2.47 0l-2.47 3h2v5h1v-5h2l-2.53-3z","transform":"translate(1)"}}]};
|
export const ic_text_fields_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M12.5 12h3v7h3v-7h3V9h-9zm3-8h-13v3h5v12h3V7h5z"},"children":[]}]};
|
function binarySearch1(A, x) {
console.assert(true, 'A has asc order');
var beg = 0, end = A.length - 1, mid;
while(beg < end) {
mid = Math.floor((beg + end) / 2);
if (A[mid] < x) {
beg = mid + 1;
} else {
end = mid;
}
}
if (A[beg] === x) {
return beg;
} else {
return -1;
}
}
module.exports = binarySearch1;
|
'use strict';
angular.module('appApp')
.controller('MainCtrl', function ($scope, $http, socket) {
$scope.awesomeThings = [];
$http.get('/api/things').success(function (awesomeThings) {
$scope.awesomeThings = awesomeThings;
socket.syncUpdates('thing', $scope.awesomeThings);
});
$scope.addThing = function () {
if ($scope.newThing === '') {
return;
}
$http.post('/api/things', {name: $scope.newThing});
$scope.newThing = '';
};
$scope.deleteThing = function (thing) {
$http.delete('/api/things/' + thing._id);
};
$scope.$on('$destroy', function () {
socket.unsyncUpdates('thing');
});
});
|
import { resolve } from 'path'
import fetch from 'node-fetch'
import { joinUrl, setup, teardown } from '../_testHelpers/index.js'
jest.setTimeout(60000)
// Could not find 'Java', skipping 'Java' tests.
const _describe = process.env.JAVA_DETECTED ? describe : describe.skip
_describe('Java tests', () => {
// init
beforeAll(() =>
setup({
servicePath: resolve(__dirname),
}),
)
// cleanup
afterAll(() => teardown())
//
;[
{
description: 'should work with java',
expected: {
message: 'Hello, Java!',
},
path: '/dev/hello',
},
].forEach(({ description, expected, path }) => {
test(description, async () => {
const url = joinUrl(TEST_BASE_URL, path)
const response = await fetch(url)
const json = await response.json()
expect(json).toEqual(expected)
})
})
})
|
import React, {
createContext,
useEffect,
useState,
useRef
} from 'react';
import Honeybadger from 'honeybadger-js';
const AppStateContext = createContext();
const { Provider } = AppStateContext;
const defaultState = {
fullVersion: '0.0.0.0',
isForm: false,
recordId: null,
logicalName: null
};
function getDynamicsState() {
let state = null;
try {
if (global.APPLICATION_VERSION === '5.0') {
state = {
context: window.top.frames[0],
version: global.APPLICATION_VERSION,
fullVersion: global.APPLICATION_VERSION
};
}
else if (/^[6,7,8]\.\d+$/.test(global.APPLICATION_VERSION)) {
var $iframe = $('#crmContentPanel iframe:not([style*=\'visibility: hidden\'])');
if ($iframe.length > 0 && $iframe[0].contentWindow.Xrm) {
state = {
context: $iframe[0].contentWindow,
version: global.APPLICATION_VERSION,
fullVersion: global.APPLICATION_VERSION
};
}
else {
console.log('[GotDibbs Toolbox for CRM 2013/2015/2016] Could not locate the entity form.');
return;
}
}
else if (global.Xrm && global.Xrm.Utility && global.Xrm.Utility.getGlobalContext &&
global.Xrm.Utility.getGlobalContext() && global.Xrm.Utility.getGlobalContext().getVersion &&
/^[9]\./.test(global.Xrm.Utility.getGlobalContext().getVersion())) {
state = {
context: global,
version: global.Xrm.Utility.getGlobalContext().getVersion().slice(0, 3),
fullVersion: global.Xrm.Utility.getGlobalContext().getVersion()
};
}
else if (global.Xrm && global.Xrm.Utility && global.Xrm.Utility.getGlobalContext &&
global.Xrm.Utility.getGlobalContext() && global.Xrm.Utility.getGlobalContext().getVersion) {
Honeybadger.notify('Unsupported D365 Version Detected', { context: {
version: global.Xrm.Utility.getGlobalContext().getVersion()
} });
console.log([
'[GotDibbs Toolbox for D365] ',
'Unsupported CRM Version Detected: ', global.APPLICATION_VERSION, '.',
' Please check for an updated version of this utility',
' or email webmaster@gotdibbs.net and let us know that this version of CRM',
' isn\'t working.'
].join(''));
return;
}
/* Fall back to checking older versions quick to report it, but moving this check
before the D365 check will result in false positives on legacy forms */
else if (global.APPLICATION_VERSION) {
Honeybadger.notify('Unsupported CRM Version Detected', { context: {
version: global.APPLICATION_VERSION
} });
console.log([
'[GotDibbs Toolbox] ',
'Unsupported Version Detected: ', global.APPLICATION_VERSION, '.',
' Please check for an updated version of this utility',
' or email webmaster@gotdibbs.net and let us know that this version of CRM',
' isn\'t working.'
].join(''));
return;
}
else {
// Notify honeybadger only if it looks like we might be in an actual CRM environment
if (/(dynamics|crm)/i.test(document.location.href) &&
!/(operations|retail|ax|home)\.dynamics/i.test(document.location.href) &&
!/pagetype=apps/i.test(document.location.href)) {
Honeybadger.notify('Failed to detect current CRM version', { context: {
xrm: !!global.Xrm,
xrmPage: !!(global.Xrm && global.Xrm.Page),
xrmUtility: !!(global.Xrm && global.Xrm.Utility)
} });
}
console.log('[GotDibbs Toolbox] Unable to detect current CRM Version.');
return;
}
return state;
}
catch (e) {
Honeybadger.notify(e, {
message: 'Error encountered while attempting to detect environment state'
});
}
}
function getAppState() {
try {
const dynamicsState = getDynamicsState();
if (!dynamicsState) {
return;
}
Honeybadger.setContext({
source: 'chrome_extension_content',
version: dynamicsState && dynamicsState.fullVersion
});
const majorVersion = dynamicsState.version ?
parseInt(dynamicsState.version.split('.')[0], 10) : 0;
const isForm = (dynamicsState.context && dynamicsState.context.Xrm &&
dynamicsState.context.Xrm.Page &&
dynamicsState.context.Xrm.Page.ui && dynamicsState.context.Xrm.Page.data &&
dynamicsState.context.Xrm.Page.data.entity);
let recordId,
logicalName;
if (isForm) {
const xrm = dynamicsState.context.Xrm;
logicalName = xrm.Page.data.entity.getEntityName && xrm.Page.data.entity.getEntityName();
try {
recordId = xrm.Page.data.entity.getId && xrm.Page.data.entity.getId();
}
catch (e) {
if (majorVersion < 9) {
// Swallow intermittent errors
return defaultState;
}
Honeybadger.notify(e, 'Failed to retrieve record ID while updating information panel');
}
}
return {
isForm,
recordId,
logicalName,
majorVersion,
...dynamicsState
};
}
catch (e) {
Honeybadger.notify(e, {
message: 'Error encountered while determining isForm'
});
}
}
const AppStateProvider = ({ children }) => {
const [appState, setAppState] = useState();
const previousAppState = useRef(defaultState);
useEffect(() => {
let interval = setInterval(() => {
let newState = getAppState();
if (newState.fullVersion != previousAppState.current.fullVersion ||
newState.isForm != previousAppState.current.isForm ||
newState.recordId != previousAppState.current.recordId ||
newState.logicalName != previousAppState.current.logicalName) {
// Only update the state if a key value has changed
setAppState(newState);
previousAppState.current = newState;
}
}, 500);
return () => clearInterval(interval);
}, []);
return <Provider value={ appState }>{children}</Provider>;
}
export {
AppStateContext,
AppStateProvider
};
|
/**
*
* Created by 康武 on 2016/7/18.
*/
//导入模块
var http=require('http');
var url=require('url');
var fs=require('fs');
var path=require('path');
//创建一个服务器
var server=http.createServer(function(req,res){
//获取用户输入的pathname
var pathname=url.parse(req.url).pathname+'/';
//如果用户没有具体请求文件,使pathname等于index.html
if(pathname.indexOf('.')==-1){
pathname +='index.html';
}
//获取文件拓展名
var extname=path.extname(pathname);
var fileUrl='./'+pathname;
fs.readFile(fileUrl,function(err,data){
if(err){
//没有找到这个文件
res.writeHead(404,{'Content-Type':'text/html;charset=utf-8'});
res.end('没有找到页面');
}
getMime(extname,function(mime){
res.writeHead(200,{'content-type':mime});
res.end(data);
})
})
})
function getMime(extname,callback){
fs.readFile('./mime.json',function(err,data){
if(err){
throw Error('找不到json文件');
return;
}
var mimeJson=JSON.parse(data);
var mime=mimeJson[extname] ||'text/plain';
callback(mime);
})
}
server.listen(8080,'localhost');
|
import { createSelector } from 'reselect';
export const itemEntitiesSelector = state => state.entities.medias;
export const directoryEntitiesSelector = state => state.entities.directories;
export const filtersSelector = state => state.media.filters;
export const selectedSelector = state => state.media.selected;
export const itemsSelector = state => state.media.items;
export const directoriesSelector = state => state.media.directories;
export const directorySelector = state => state.media.directory;
export const activeItemsSelector = createSelector(
itemsSelector,
itemEntitiesSelector,
directorySelector,
filtersSelector,
(ids, items, dir, filters) => {
if (!ids || !items) {
return [];
}
const medias = ids
.map(id => items[id])
.filter(i => i);
if (dir || !filters.search) {
return medias.filter(item => item.directory_id === dir || (!item.directory_id && !dir));
}
return medias;
}
);
export const activeDirectoriesSelector = createSelector(
directoryEntitiesSelector,
directorySelector,
filtersSelector,
(directories, dir, filters) => {
// Hide directories while searching the global state
if (!dir && filters.search) {
return [];
}
return directories ? Object.keys(directories).filter(i => directories[i].parent_id === dir || (!directories[i].parent_id && !dir)).map(i => directories[i]) : [];
}
);
export const currentDirectorySelector = createSelector(
directoryEntitiesSelector,
directorySelector,
(directories, dir) => (dir) ? directories[dir] : null
);
export const parentDirectorySelector = createSelector(
directoryEntitiesSelector,
currentDirectorySelector,
(directories, directory) => (directory && directory.parent_id) ? directories[directory.parent_id] : null
);
|
var fs = require('fs');
var path= require('path');
var vm = require('vm');
var soyutils = path.join(__dirname, 'soyutils.js');
function merge() {
var target = Array.prototype.shift.call(arguments);
for(var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
for(var key in arg) {
if (Object.prototype.hasOwnProperty.call(arg, key)) {
target[key] = arg[key];
}
}
}
return target;
}
function SoyRenderer(options) {
this.setOptions(options, true);
}
SoyRenderer.defaults = {
runInSeparateContext : false,
cacheTemplates : true
};
SoyRenderer.prototype.setOptions = function(options, internal_force) {
options = merge({}, SoyRenderer.defaults, this._options || {}, options);
if (internal_force || options.runInSeparateContext != this._options.runInSeparateContext) {
this._cache = {};
if (options.runInSeparateContext) {
this._context = vm.createContext();
vm.runInContext(fs.readFileSync(soyutils, 'utf8'), this._context, soyutils);
} else {
vm.runInThisContext(fs.readFileSync(soyutils, 'utf8'), soyutils);
}
}
if (!options.cacheTemplates) {
this._cache = null;
}
this._options = options;
}
//page/index-thing.soy.js => soy.page.indexThing
function mapFileNameToTemplateName(file) {
return 'soy.' + file.replace(/[\\\/]|-.|\.js$/g, function(str) {
switch(str[0]) {
case '.': //.js
return '';
case '\\':
case '/':
return '.';
case '-': //-
return str[1].toUpperCase();
}
});
}
SoyRenderer.prototype._evalAndCache = function(script, templateName, filepath) {
if (this._context) {
vm.runInContext(script, this._context, filepath);
} else {
vm.runInThisContext(script, filepath);
}
var steps = templateName.split('.');
var curr = this._context || global;
while(curr && steps.length) {
curr = curr[steps.shift()];
}
if (curr) {
return this._cache ? (this._cache[templateName] = curr) : curr;
}
throw new Error("Template '" + templateName + "' was not found after evaluating script at " + filepath);
};
SoyRenderer.prototype.loadTemplateSync = function(filepath, templateName) {
return this._evalAndCache(fs.readFileSync(filepath, 'utf8'), templateName, filepath);
};
SoyRenderer.prototype.loadTemplate = function(filepath, templateName, callback) {
var self = this;
fs.readFile(filepath, 'utf8', function(err, data) {
if (err) {
callback(err);
}
callback(null, self._evalAndCache(data, templateName, filepath));
});
};
SoyRenderer.prototype.loadTemplateDir = function(dirpath, callback, mapFilenameToTemplateName, filter, root) {
var self = this;
fs.readdir(dirpath, function(err, files) {
var count = 0;
function end() {
if (!--count && callback) {
callback();
}
}
files.forEach(function(file) {
count++;
var filepath = path.join(dirpath,file);
fs.stat(filepath, function(err, stat) {
if (stat.isDirectory()) {
self.loadTemplateDir(filepath, end, mapFilenameToTemplateName, filter, root || dirpath);
} else if (!filter || filter(filepath)) {
self.loadTemplate(filepath, (mapFilenameToTemplateName || mapFileNameToTemplateName)(path.relative(root || dirpath, filepath)), end);
}
});
});
});
};
SoyRenderer.prototype.loadTemplateDirSync = function(dirpath, mapFilenameToTemplateName, filter, root) {
var self = this;
var subdirs = [];
fs.readdirSync(dirpath).forEach(function(file) {
var filepath = path.join(dirpath,file);
if (fs.statSync(filepath).isDirectory()) {
subdirs.push(filepath);
} else if (!filter || filter(filepath)) {
self.loadTemplateSync(filepath, (mapFilenameToTemplateName || mapFileNameToTemplateName)(path.relative(root || dirpath, filepath)));
}
});
subdirs.forEach(function(filepath) {
self.loadTemplateDirSync(filepath, mapFilenameToTemplateName, filter, root || dirpath);
});
};
function withIj(template, options) {
return function(data, ij) {
return template.call(this, merge({}, options, data), undefined, merge({}, options.ij, ij));
}
};
SoyRenderer.prototype.compile = function (str, options) {
var templateName = (options.mapFilenameToTemplateName || mapFileNameToTemplateName)(path.relative(options.root, options.filename));
if (this._cache && this._cache[templateName]) {
return withIj(this._cache[templateName], options);
}
console.log(templateName + ' not in cache.');
console.dir(this._options);
return withIj(this._evalAndCache(str, templateName, options.filename), options);
};
SoyRenderer.prototype.__express = function(filename, options, fn) {
var templateName = (options.mapFilenameToTemplateName || mapFileNameToTemplateName)(path.relative(options.root, filename));
if (this._cache && this._cache[templateName]) {
fn(null, withIj(this._cache[templateName], options)());
return;
}
this.loadTemplate(filename, templateName, function(err, template) {
fn(err, template && withIj(template, options)());
});
};
module.exports = SoyRenderer;
|
"use strict";(self.webpackChunkrgb=self.webpackChunkrgb||[]).push([[883],{9616:function(e,t,a){a.r(t);var n=a(7294),l=a(1099),r=a(6179);t.default=({data:e,location:t})=>{const a=e.site.siteMetadata.title;return n.createElement(l.Z,{location:t,title:a},n.createElement(r.Z,{title:"404: Not Found"}),n.createElement("h1",null,"Not Found"),n.createElement("p",null,n.createElement("span",{role:"img","aria-label":"warning"},"⚠️")," ","You just hit a route that doesn't exist..."))}}}]);
//# sourceMappingURL=component---src-pages-404-js-c02cca09ae0e617b435f.js.map
|
'use strict';
angular.module('myApp.view1', ['ngRoute', 'ngToast'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', ['$scope', '$modal', '$interval', 'ngToast', function($scope, $modal, $interval) {
$scope.amount = '1';
$scope.cashSources = [{
order: 1,
name: "Limonadenstand",
cash: 1,
price: 4,
amount: 1,
exp: 1.07,
loadtime: 6,
loaded: 0,
ismanaged: false
}, {
order: 2,
name: "Zeitungsstand",
cash: 60,
price: 60,
amount: 0,
exp: 1.15,
loadtime: 30,
loaded: 0,
ismanaged: false
}, {
order: 3,
name: "Autowaschanlage",
cash: 540,
price: 720,
amount: 0,
exp: 1.14,
loadtime: 60,
loaded: 0,
ismanaged: false
}, {
order: 4,
name: "Pizzeria",
cash: 4320,
price: 8640,
amount: 0,
exp: 1.13,
loadtime: 120,
loaded: 0,
ismanaged: false
}, {
order: 5,
name: "Shrimp Kutter",
cash: 51840,
price: 103680,
amount: 0,
exp: 1.12,
loadtime: 240,
loaded: 0,
ismanaged: false
}, {
order: 6,
name: "Schokoladenfabrik",
cash: 622080,
price: 1244160,
amount: 0,
exp: 1.11,
loadtime: 960,
loaded: 0,
ismanaged: false
}, {
order: 7,
name: "Fußball Team",
cash: 7464960,
price: 14929920,
amount: 0,
exp: 1.10,
loadtime: 3840,
loaded: 0,
ismanaged: false
}, {
order: 8,
name: "Film Studio",
cash: 89579520,
price: 179159040,
amount: 0,
exp: 1.09,
loadtime: 15360,
loaded: 0,
ismanaged: false
}, {
order: 9,
name: "Bank",
cash: 2149908480,
price: 1074954240,
amount: 0,
exp: 1.08,
loadtime: 61440,
loaded: 0,
ismanaged: false
}, {
order: 10,
name: "Öl Gesellschaft",
cash: 29668737024,
price: 25798901760,
amount: 0,
exp: 1.07,
loadtime: 36864,
loaded: 0,
ismanaged: false
}]
$scope.manager = [{
name: "John Lemon",
description: "Er kümmert sich gewissenhaft um deine Limonadenstände!",
price: "100",
isBought: false,
sourceID: 0
}, {
name: "Springer Axel",
description: "Bringt deine Zeitungen an den Mann!",
price: "1000",
isBought: false,
sourceID: 1
}, {
name: "Walther Weiß",
description: "Hat viel Erfahrungen im Autowaschen!",
price: "100000",
isBought: false,
sourceID: 2
}, {
name: "Luigi",
description: "Wer sollte sich sonst um deine Pizza kümmern?",
price: "500000",
isBought: false,
sourceID: 3
}, {
name: "Gubba Bump",
description: "Er fischt nicht im Trüben, sondern hält deine Schrimp Kutter am Laufen!",
price: "1000000",
isBought: false,
sourceID: 4
}, {
name: "Wolli Wonka",
description: "Er und seine Umpa-Lumpas kümmern sich um deine Schokoladenfabrik.",
price: "111111111",
isBought: false,
sourceID: 5
}, {
name: "Logi Jöw",
description: "De beschde Träiner wo gibbd!",
price: "555555555",
isBought: false,
sourceID: 6
}, {
name: "Stefan Spiel-Berg",
description: "Hält das Film-Business am Laufen.",
price: "10000000000",
isBought: false,
sourceID: 7
}]
$scope.money = 0;
$scope.reduceMoney = function(amount) {
$scope.money -= amount;
}
$scope.addMoney = function(amount) {
$scope.money += amount;
}
$scope.getMoney = function() {
return $scope.money;
}
$scope.activateManager = function(sourceID) {
$scope.cashSources[sourceID].ismanaged = true;
}
$scope.openModal = function(size, templateUrl) {
$scope.money
var modalInstance = $modal.open({
templateUrl: templateUrl,
controller: 'ModalInstanceCtrl',
scope: $scope,
size: size
});
};
}])
.directive("columnwrapper", function() {
return {
restrict: "E",
scope: {
money: '='
},
link: function(scope) {
}
};
})
.directive('cashSource', ['$interval', function() {
return {
restrict: 'E',
scope: {
source: '=model',
reduceMoney: '&',
addMoney: '&',
getMoney: '&',
amount: '='
},
controller: function($scope, $interval, ngToast) {
var tick;
$scope.buy = function(amount) {
console.log(amount)
for (var i = 1; i <= amount; i++) {
if ($scope.isAffordable()) {
$scope.source.amount++;
$scope.reduceMoney()($scope.source.price);
$scope.source.price = $scope.source.price * $scope.source.exp
// half the time
if ([25, 50, 100].indexOf($scope.source.amount) > -1) {
$scope.halfTime();
}
}
}
}
$scope.halfTime = function() {
$scope.source.loadtime *= 0.5;
ngToast.create('<strong>Du hast ' + $scope.source.amount + ' x ' + $scope.source.name + ' </strong> Produktivität verdoppelt!');
}
$scope.activate = function() {
// prevent double activation
if (angular.isDefined(tick) || $scope.source.amount == 0) return;
$scope.source.loaded = 0;
var timeto = 100;
tick = $interval(function() {
if ($scope.source.loaded < timeto) {
$scope.source.loaded++;
} else {
var amount = $scope.source.amount * $scope.source.cash
$scope.addMoney()(amount)
$scope.source.loaded = 0;
if (!$scope.source.ismanaged) {
$scope.stopTick();
return;
}
}
}, $scope.source.loadtime);
}
$scope.stopTick = function() {
if (angular.isDefined(tick)) {
$interval.cancel(tick);
tick = undefined;
}
}
$scope.isAffordable = function() {
return ($scope.getMoney() >= $scope.source.price)
}
this.activateManager = function() {
$scope.scope.ismanaged = true;
}
$scope.$on('$destroy', function() {
// Make sure that the interval is destroyed too
$scope.stopFight();
});
},
templateUrl: 'view1/cash-source.html'
};
}])
.directive('cashManager', function() {
return {
restrict: 'E',
scope: {
manager: '=model',
reduceMoney: '&',
getMoney: '&',
activateManager: '&'
},
controller: function($scope) {
$scope.buy = function() {
if ($scope.isAffordable()) {
$scope.reduceMoney()($scope.manager.price);
$scope.manager.isBought = true;
$scope.activateManager()($scope.manager.sourceID)
}
}
$scope.isAffordable = function() {
return ($scope.getMoney() >= $scope.manager.price)
}
},
templateUrl: 'view1/manager.html'
}
})
.filter('buyamount', function() {
return function(base, exp, amount) {
console.log(exp)
console.log(amount)
var total = base;
var temp = base;
for (var i = 1; i < amount; i++) {
temp = temp * exp;
total += temp;
}
return total;
}
})
.controller('ModalInstanceCtrl', function($scope, $modalInstance) {
$scope.ok = function() {
$modalInstance.close();
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
})
|
---
layout: null
---
$(document).ready(function () {
$('a.blog-button').click(function (e) {
if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
currentWidth = $('.panel-cover').width()
if (currentWidth < 960) {
$('.panel-cover').addClass('panel-cover--collapsed')
$('.content-wrapper').addClass('animated slideInRight')
} else {
$('.panel-cover').css('max-width', currentWidth)
$('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {})
}
})
/* if (window.location.hash && window.location.hash == '#blog') {
$('.panel-cover').addClass('panel-cover--collapsed')
}*/
/* N0TE: alert(window.location.pathname) gives things without site.url, so like /posts/ and /about/ not www.williamcapecchi.com/posts/
so we keep site.baseurl below (which is at time of writing this set to baseurl = '')*/
if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}/index.html') {
$('.panel-cover').addClass('panel-cover--collapsed')
}
$('.btn-mobile-menu').click(function () {
$('.navigation-wrapper').toggleClass('visible animated bounceInDown')
$('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
})
$('.navigation-wrapper .blog-button').click(function () {
$('.navigation-wrapper').toggleClass('visible')
$('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
})
})
|
"use strict";
(function () {
require("../src/icon.png");
require("../src/manifest.json");
var _contextMenuId = "timeConverter--ContextMenu";
browser.contextMenus.create({
id: _contextMenuId,
title: "Test context menu",
contexts: ["selection"],
onclick: function () {
Notify("clicked!");
}
});
browser.runtime.onMessage.addListener(function (request, sender, sendResponse) {
var result = Execute(request.action, request.data);
sendResponse({
message: result
});
});
//#region Private
function UpdateContextMenu(options) {
browser.contextMenus.update(_contextMenuId, options);
}
function Execute(action, data) {
var result = "";
switch (action) {
case "textSelected":
UpdateContextMenu({ title: data.text });
break;
default:
result = "Unsupported action: " + action;
break;
}
return result;
}
function Notify(message, title) {
browser.notifications.create({
type: "basic",
iconUrl: browser.extension.getURL("link.png"),
title: title ? title : "Time Converter",
message: message
});
}
function GetCurrentTimeZoneOffset() {
return new Date().getTimezoneOffset();
}
var timeZonePatterns = [];
function GetTime(input) {
var timePatterns = /(\d{1,2}:\d{1,2}(?::\d{1,2})*) *((?:am|a.m|pm|p.m))*/ig; // ex: 5:37 a.m or 15:33:44 pm
var result = "";
var matches = timePatterns.exec(input);
if (!Array.isArray(matches) || matches.length <= 0) {
return;
}
var time = matches[1];
var timePeriod = matches[2];
var hour = time.split(":")[0];
var minute = time.split(":")[1];
//var second = time.split(":")[2];
if (timePeriod) {
hour = Number(hour);
if (["PM", "P.M", "pm", "p.m"].indexOf(timePeriod) >= 0 && hour < 12) {
hour += 12;
}
} else {
hour = hour[1] ? "0" + hour[0] : hour;
}
minute = minute[1] ? "0" + minute[1] : minute;
return hour + ":" + minute;
}
function GetTimeZone(){
var custom = /(PST|EDT)/ig;
var standard = /(GMT|UTC)/ig;
}
function AnalyzeText(input) {
// detect time
var time = GetTime(input);
// detect time zone
// detect date
// desired output format: YYYY-MM-DDTHH:mm:ss.sssZ
// convert to current time zone
}
//#endregion
})();
|
var http = require( 'http' );
http.createServer(function( req, res ) {
var html = '<!doctype html>' +
'<html><head><title>Hello world</title></head>' +
'<body><h1>Hello, world!</h1></body></html>';
res.writeHead( 200, {
// set the type of content we're returning
'Content-Type': 'text/html',
// set the length of our content
'Content-Length': html.length
});
// end the response, sending it and returning our HTML
res.end( html );
}).listen( 8000, '127.0.0.1' );
|
module.exports = {"NotoSansTaiTham":{"normal":"NotoSansTaiTham-Regular.ttf","bold":"NotoSansTaiTham-Regular.ttf","italics":"NotoSansTaiTham-Regular.ttf","bolditalics":"NotoSansTaiTham-Regular.ttf"}};
|
let btnCheckalts = document.getElementById('btnCheckalts');
function storeCheckAltsStatus(strStatus) {
// Get current tab ID
browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
// Get a11y.css stored status
let getStatus = browser.storage.local.get("checkAltsStatus");
getStatus.then(
// when we got something
(item) => {
let checkAltsStatus = [];
if (item && item.checkAltsStatus) {
checkAltsStatus = item.checkAltsStatus;
}
// Add or replace current tab's value
checkAltsStatus[tabs[0].id] = {"status": strStatus};
// And set it back to the storage
let setting = browser.storage.local.set({ checkAltsStatus });
setting.then(null, onError); // just in case
}
);
});
}
btnCheckalts.addEventListener('click', function () {
let icons = {
ok: browser.extension.getURL("/icons/ok.svg"),
ko: browser.extension.getURL("/icons/ko.svg"),
info: browser.extension.getURL("/icons/info.svg")
};
let strings = {
ok: _t("altOK"),
ko: _t("altMissing"),
info: _t("altEmpty")
};
browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
browser.tabs.sendMessage(tabs[0].id, {
a11ycss_action: "checkalts",
icons: icons,
strings: strings
});
});
var checked = this.getAttribute('aria-checked') === 'true' || false;
this.setAttribute('aria-checked', !checked);
storeCheckAltsStatus(!checked);
});
function checkAltsOnload() {
let getStatus = browser.storage.local.get("checkAltsStatus");
getStatus.then(
// when we got something
(item) => {
if (item && item.checkAltsStatus) {
browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
// If a setting is found for this tab
if (item.checkAltsStatus[tabs[0].id]) {
btnCheckalts.setAttribute('aria-checked', item.checkAltsStatus[tabs[0].id].status);
}
});
}
},
// we got nothing
onError
);
}
checkAltsOnload();
|
export default () => <div>
<h1>Reset your password</h1>
<p>Check your email for a link to reset your password. If it doesn't appear within a few minutes, check your spam folder. </p>
<hr /><a href='/'>back to home</a>
</div>
|
/**
* Default class for create Classes
*/
export default class Class{
/**
* constructor of the class
* @method constructor
* @param {[type]} options [description]
* @param {[type]} Base [description]
* @return {[type]} [description]
*/
constructor(options, Base){
const isObject = typeof options === 'object';
const isArray = options instanceof Array;
const self = Base || this;
if(!isObject || isArray){
return false;
}
Object.keys(options).map((property) => {
const symbol = Symbol.for(`${self.constructor.name}.${property}`);
self[symbol] = options[property];
});
return self;
}
/**
* Get the value of a specific property
* @method get
* @param {[type]} property [description]
* @return {[type]} [description]
*/
get(property){
return this[Symbol.for(`${this.constructor.name}.${property}`)];
}
/**
* Set the value to a specific property
* @method set
* @param {[type]} property [description]
* @param {[type]} val [description]
* @return {[type]} [description]
*/
set(property, val){
return this[Symbol.for(`${this.constructor.name}.${property}`)] = val;
}
}
|
/**
* @class LoginController
* @classdesc
* @ngInject
*/
function LoginController($scope, $state, $auth, emailRegex, IdentityService) {
$scope.emailRegex = emailRegex;
$scope.data = {};
$scope.login = function() {
$auth.login(
{
email: $scope.email || $scope.data.email,
password: $scope.password || $scope.data.password
}
)
.then(function() {
$state.go(IdentityService.authenticatedState);
toastr.success('You have successfully logged in');
})
.catch(function(err) {
toastr.error(err.data.error || err.data.message || err.data.errorMessage, 'cannot login');
});
};
$scope.authenticate = function(provider) {
$auth.authenticate(provider, null)
.then(function() {
toastr.success('You have successfully authenticated');
$state.go(IdentityService.authenticatedState);
})
.catch(function(err) {
toastr.error(err.data.error || err.data.message || err.data.errorMessage, 'cannot authenticate');
});
};
}
/**
* @class LogoutController
* @classdesc
* @ngInject
*/
function LogoutController($scope, $state, $auth, IdentityService) {
IdentityService.logout();
$auth.logout()
.then(function() {
toastr.success('You have been logged out');
});
}
/**
* @class SignupController
* @classdesc
* @ngInject
*/
function SignupController($scope, $state, $log, $auth,
emailRegex, IdentityService) {
$scope.emailRegex = emailRegex;
$scope.signup = function() {
$auth.signup(
{
name: $scope.name,
email: $scope.email,
password: $scope.password
})
.then(function(data) {
// automatically login on signup
$auth.setToken(data.data.token);
toastr.success('You have successfully signed up');
$state.go(IdentityService.authenticatedState);
})
.catch(function(err) {
toastr.error(err.data.error || err.data.message || err.data.errorMessage, 'cannot signup');
});
};
$scope.authenticate = function(provider) {
$auth.authenticate(provider, null)
.then(function() {
toastr.success('You have successfully signed up');
$state.go(IdentityService.authenticatedState);
})
.catch(function(err) {
toastr.error(err.data.error || err.data.message || err.data.errorMessage, 'cannot authenticate');
});
};
}
/**
* @class ForgotController
* @classdesc
* @ngInject
*/
function ForgotController($scope, $log, emailRegex, IdentityService) {
$scope.emailRegex = emailRegex;
$scope.forgot = function() {
IdentityService.forgotPassword($scope.email)
.then(
function() {
toastr.success('Sent email with password reset');
},
function(err) {
toastr.error(err.error, 'cannot reset password');
}
);
};
}
/**
* @class ResetController
* @classdesc
* @ngInject
*/
function ResetController($auth, $stateParams, $state, IdentityService) {
$auth.login({ email: $stateParams.email, reset: $stateParams.reset},
IdentityService.authenticatedPath)
.then(
function() {
$state.go(IdentityService.authenticatedState);
toastr.success('logged in with reset');
},
function(err) {
toastr.error(err.error, 'cannot login with reset');
}
);
}
/**
* @class NavbarController
* @classdesc
* @ngInject
*/
function NavbarController($scope, $auth) {
$scope.isAuthenticated = function() {
return $auth.isAuthenticated();
};
}
angular.module('auth-controllers', ['identityService','commonConstants'])
.controller('LoginController', LoginController)
.controller('LogoutController', LogoutController)
.controller('SignupController', SignupController)
.controller('ForgotController', ForgotController)
.controller('ResetController', ResetController)
.controller('NavbarController', NavbarController)
;
|
import { Class, logToConsole } from '../common';
var SurfaceFactory = (function (Class) {
function SurfaceFactory() {
Class.call(this);
this._items = [];
}
if ( Class ) SurfaceFactory.__proto__ = Class;
SurfaceFactory.prototype = Object.create( Class && Class.prototype );
SurfaceFactory.prototype.constructor = SurfaceFactory;
SurfaceFactory.prototype.register = function register (name, type, order) {
var items = this._items;
var first = items[0];
var entry = {
name: name,
type: type,
order: order
};
if (!first || order < first.order) {
items.unshift(entry);
} else {
items.push(entry);
}
};
SurfaceFactory.prototype.create = function create (element, options) {
var items = this._items;
var match = items[0];
if (options && options.type) {
var preferred = options.type.toLowerCase();
for (var i = 0; i < items.length; i++) {
if (items[i].name === preferred) {
match = items[i];
break;
}
}
}
if (match) {
return new match.type(element, options);
}
logToConsole(
"Warning: Unable to create Kendo UI Drawing Surface. Possible causes:\n" +
"- The browser does not support SVG and Canvas. User agent: " + (navigator.userAgent));
};
return SurfaceFactory;
}(Class));
SurfaceFactory.current = new SurfaceFactory();
export default SurfaceFactory;
//# sourceMappingURL=surface-factory.js.map
|
// Copyright (c) 2015 Uber Technologies, Inc.
//
// 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.
'use strict';
var bufrw = require('bufrw');
var TYPE = require('./TYPE');
var I32RW = bufrw.Int32BE;
function ThriftI32() { }
ThriftI32.prototype.rw = I32RW;
ThriftI32.prototype.name = 'i32';
ThriftI32.prototype.typeid = TYPE.I32;
ThriftI32.prototype.surface = Number;
module.exports.I32RW = I32RW;
module.exports.ThriftI32 = ThriftI32;
|
import React from 'react'
import rcPopover from 'rc-popover'
import StyleSelector from './styleSelector'
class legend extends React.Component {
constructor() {
super()
this.state = {}
}
render() {
// var popoverTitle = React.createElement('span', {className: 'legendPopoverTitle'}, this.props.label)
return React.createElement('div', {className: 'legend'},
React.createElement('div', {},
React.createElement('div', {className: 'legendLabel'}, this.props.label),
React.createElement(rcPopover, {
title: '', // popoverTitle,
content: this.props.description,
trigger: 'click'},
React.createElement('a', {href: 'javascript:void(0);', className: 'description glyphicon glyphicon-question-sign'})
)
),
React.createElement('div', {className: 'styleSelectWrapper'},
React.createElement(StyleSelector, {
layerId: this.props.layerId,
styleId: this.props.styleId,
styles: this.props.styles,
selectStyle: this.props.selectStyle
})
)
)
}
}
export default legend
|
var $ = require('jquery');
var _ = require('underscore');
var Parse = require('parse').Parse;
require('backbone');
require('bootstrap/dist/css/bootstrap.css');
require('bootstrap/dist/css/clean-blog.css');
//var config = require('./config');
var Router = require('./router');
var containerTpl = require('./templates/container.hbs');
var app = {
init: function () {
Parse.initialize(
//app ID
'IRBLZAHv1xbYSmYxRHtUBvqJNKwzMQyyV1g7csiD',
// JS Key
'qs5zS5o45UFwV3iTG8ayjpmA8gjr7IoTNDtajktH'
);
$('body').append(containerTpl({
site_name: 'This is the site name',
routes: [{
url: '/',
name: 'Home'
},
{
url: '/cats',
name: 'Cats'
},
{
url: '/test',
name: 'Test'
}],
footer: '(c) 2015 Your name'
}));
this.router = new Router();
Backbone.history.start({
pushState: true
});
}
};
$(function () {
app.init();
});
|
define('dojorama/layers/nls/home_hu',{
'dojorama/ui/_global/widget/nls/NavigationWidget':{"labelHome":"Dojorama","labelStorage":"Storage","labelReleaseIndex":"Releases"}
,
'dojorama/ui/_global/widget/nls/FooterWidget':{}
});
|
var CoffeeBeans = function() {
var beans = {};
var commands = new Commands();
commands.fetch();
var curr = commands.size(); // current command
var error_state = false;
var puts_node = document.getElementById('puts');
window.editor = CodeMirror.fromTextArea(document.getElementById("input"), {
mode: 'coffeescript',
theme: 'idle',
onChange: test_compile,
extraKeys: {
"Enter": CodeMirror.commands.newlineAndIndent,
"Shift-Enter": go,
"Up": up,
"Down": down,
"Tab": autocomplete,
"Shift-Right": CodeMirror.commands.indentMore,
"Shift-Left": CodeMirror.commands.indentLess
}
});
editor.focus();
// highlight examples
$('.highlight').each(function() {
var code = $(this).text();
highlight_coffee(this, code);
code_buttons(this, code);
});
function code_buttons(el, code) {
$(el).append('<div class="buttons"><svg class="button copier"><path transform="scale(0.6)" d="M10.129,22.186 16.316,15.999 10.129,9.812 13.665,6.276 23.389,15.999 13.665,25.725z"></svg></div>');
$(el).children('.buttons').children('.copier').on('click', function() {
editor.setValue(code);
editor.focus();
});
}
function autocomplete(cm) {
CodeMirror.simpleHint(cm, CodeMirror.coffeescriptHint);
}
function test_compile(cm) {
try {
error_state = false;
CoffeeScript.compile(editor.getValue());
$('#coffee-error').hide();
} catch (err) {
error_state = true;
$('#coffee-error').removeClass('tried');
$('#coffee-error #compile-error').text(err.message);
$('#coffee-error').show();
}
}
function up(cm) {
if (curr > 0 && topline()) {
curr -= 1;
var command = commands.at(curr);
editor.setValue(command.get('contents'));
} else {
CodeMirror.commands.goLineUp(cm);
}
};
function down(cm) {
if (curr < commands.size() && botline()) {
curr += 1;
if (curr != commands.size()) {
var command = commands.at(curr);
editor.setValue(command.get('contents'));
} else {
editor.setValue("");
}
} else {
CodeMirror.commands.goLineDown(cm);
}
};
function topline() {
return coords().line == 0;
};
function botline() {
var lines = editor.lineCount();
return coords().line == lines - 1;
};
function coords() {
var cursor = editor.cursorCoords();
return editor.coordsChar(cursor);
};
function go() {
if (error_state) {
$('#coffee-error').addClass('tried');
return;
}
var code = editor.getValue();
editor.setValue("");
var command = commands.create({
contents: code
});
var command_view = new CommandView({
model: command
});
command_view.render();
jscode = command.compile();
if (jscode.type == "success") {
try {
var result = eval.call(null, jscode.result);
try {
puts(result);
} catch (error) {
puts_error("Result: " + result);
puts_error("Puts error: " + error.message);
}
} catch (error) {
// JavaScript runtime error
puts_error(error.message);
}
} else if (jscode.type == "error") {
puts_error("CoffeeScript error: " + jscode.result.message);
}
curr = commands.size();
};
function puts_print(txt, className) {
var txt_node = document.createElement('pre');
txt_node.className = className;
puts_node.appendChild(txt_node);
if (className == 'input' || className == 'puts') {
highlight_js(txt_node, txt);
} else if (className == 'beans-puts-coffee') {
highlight_coffee(txt_node, txt);
} else {
$(txt_node).text(txt);
}
toBottom();
};
function toBottom() {
// scroll to bottom
$('#puts').animate({scrollTop: $('#puts')[0].scrollHeight}, 0);
};
window.puts = function(result) {
switch (type(result)) {
case "array":
try {
result = JSON.stringify(result);
} catch (error) {
result = result.toString();
}
break;
case "function":
result = js2coffee(result);
puts_print(result, "beans-puts-coffee");
return;
case "object":
try {
result = JSON.stringify(result);
} catch (err) {
puts_error("Print error: " + err.message);
return;
}
break;
case "number":
result = result.toString();
break;
case "boolean":
result = result.toString();
break;
case "string":
result = result;
break;
case "undefined":
result = "undefined";
return; // do nothing
case "null":
result = "null";
break;
case "NaN":
result = "NaN";
break;
case "date":
result = result.toString();
break;
case "RegExp":
result = result.toString();
break;
case "element":
$(puts_node).append(result);
setTimeout(function() { toBottom(); }, 40);
return;
break;
default:
result = result.toString();
}
//var coffee_result = Js2coffee.build(result + "");
puts_print(result, "puts");
};
function puts_error(result) {
puts_print(result, "error");
};
function highlight_coffee(node, code) {
$(node).addClass('cm-s-idle');
CodeMirror.runMode(code, "coffeescript", node);
};
function highlight_js(node, code) {
$(node).addClass('cm-s-idle');
CodeMirror.runMode(code, "javascript", node);
};
var globals = {
//log: function() { console.log.apply(console, arguments) },
after: '_.after',
all: '_.all',
any: '_.any',
bindAll: '_.bindAll',
bind: '_.bind',
clone: '_.clone',
coffee2js: coffee2js,
Collection: 'Backbone.Collection',
compact: '_.compact',
compose: '_.compose',
debounce: '_.debounce',
defaults: '_.defaults',
defer: '_.defer',
delay: '_.delay',
difference: '_.difference',
each: '_.each',
'escape': '_.escape',
Events: 'Backbone.Events',
extend: '_.extend',
filter: '_.filter',
find: '_.find',
first: '_.first',
flatten: '_.flatten',
functions: '_.functions',
groupBy: '_.groupBy',
has: '_.has',
html: html,
identity: '_.identity',
include: '_.include',
indexOf: '_.indexOf',
initial: '_.initial',
intersection: '_.intersection',
invoke: '_.invoke',
isArguments: '_.isArguments',
isArray: '_.isArray',
isBoolean: '_.isBoolean',
isDate: '_.isDate',
isElement: '_.isElement',
isEmpty: '_.isEmpty',
isEqual: '_.isEqual',
isFunction: '_.isFunction',
isNaN: '_.isNaN',
isNull: '_.isNull',
isNumber: '_.isNumber',
isRegExp: '_.isRegExp',
isString: '_.isString',
isUndefined: '_.isUndefined',
js2coffee: js2coffee,
json: '$.getJSON',
keys: '_.keys',
lastIndexOf: '_.lastIndexOf',
last: '_.last',
map: '_.map',
max: '_.max',
memoize: '_.memoize',
min: '_.min',
Model: 'Backbone.Model',
once: '_.once',
pluck: '_.pluck',
pretty: pretty,
range: '_.range',
reduce: '_.reduce',
reduceRight: '_.reduceRight',
reject: '_.reject',
repeat: repeat,
rest: '_.rest',
Router: 'Backbone.Router',
shuffle: '_.shuffle',
size: '_.size',
sortBy: '_.sortBy',
sortedIndex: '_.sortedIndex',
tap: '_.tap',
template: '_.template',
throttle: '_.throttle',
times: '_.times',
toArray: '_.toArray',
type: type,
union: '_.union',
uniq: '_.uniq',
values: '_.values',
View: 'Backbone.View',
without: '_.without',
wrap: '_.wrap',
zip: '_.zip'
};
/* global functions */
function type(object) {
if (_.isFunction(object)) return "function";
if (_.isArray(object)) return "array";
if (_.isElement(object)) return "element";
if (_.isNull(object)) return "null";
if (_.isNaN(object)) return "NaN";
if (_.isDate(object)) return "date";
if (_.isArguments(object)) return "arguments";
if (_.isUndefined(object)) return "undefined";
if (_.isRegExp(object)) {
return "RegExp";
} else {
return typeof object;
}
};
function html(str) {
return $(str)[0];
};
function pretty(obj) {
return JSON.stringify(obj, undefined, 2);
};
function repeat(func, interval) {
func();
setTimeout(function() {
repeat(func, interval);
}, interval);
};
function js2coffee(obj) {
if ('function' == type(obj)) {
var str = "var $_$_$ = " + obj.toString();
var compiled = Js2coffee.build(str);
return compiled.slice(8)
}
};
function coffee2js(str) {
return CoffeeScript.compile(str).slice(16,-17);
};
beans.addGlobal = function(v,k) {
if (_.isString(v)) {
var func = eval(v);
window[k] = function() { return func.apply(this, arguments); };
window[k].toString = function() { return v; } ;
return;
}
if (_.isFunction(v)) {
window[k] = v;
}
};
// forgive me
_(globals).each(beans.addGlobal);
// log
window['log'] = function() { console.log.apply(console, arguments); };
window['log'].toString = function() { return "console.log"; };
return beans;
};
|
(function() {
var app = angular.module('weather', []);
app.controller('WeatherController', ['$http', function($http) {
var weather = this;
weather.forecast = 'Looking out the window...';
$http.get('/weather').then(function(res) {
weather.morning = res.data.morning;
weather.low = res.data.low;
weather.high = res.data.high;
weather.description = res.data.description;
});
}]);
})();
|
const assert = require("assert");
const {
stringToArrayBuffer,
arrayBufferToHex
} = require("../src/stringEncoding");
describe("stringEncoding", () => {
it("stringToArrayBuffer", () => {
assert.equal(stringToArrayBuffer("ȧ")[0], 200);
assert.equal(stringToArrayBuffer("ȧ")[1], 167);
});
it("arrayBufferToHex", () => {
assert.equal(arrayBufferToHex(new Uint8Array([200, 167])), "c8a7");
});
});
|
exports.seed = (knex, Promise) => {
return knex("units")
.del()
.then(() => {
return knex("units").insert([
{id: 1, title: "Productivity", location_url: "https://learn.galvanize.com/cohorts/236/units/2632"},
{id: 2, title: "Development Environment", location_url: "https://learn.galvanize.com/cohorts/236/units/2633"},
{id: 3, title: "Javascript Language and Concepts", location_url: "https://learn.galvanize.com/cohorts/236/units/2634"},
{id: 4, title: "Javascript - Functional Programming", location_url: "https://learn.galvanize.com/cohorts/236/units/2635"},
{id: 5, title: "HTML", location_url: "https://learn.galvanize.com/cohorts/236/units/2636"},
{id: 6, title: "CSS", location_url: "https://learn.galvanize.com/cohorts/236/units/2637"},
{id: 7, title: "The DOM", location_url: "https://learn.galvanize.com/cohorts/236/units/2638"},
{id: 8, title: "jQuery", location_url: "https://learn.galvanize.com/cohorts/236/units/2639"},
{id: 9, title: "HTTP and AJAX", location_url: "https://learn.galvanize.com/cohorts/236/units/2640"},
{id: 10, title: "Node and Express", location_url: "https://learn.galvanize.com/cohorts/236/units/2641"},
{id: 11, title: "Javascript Accumulator Pattern", location_url: "https://learn.galvanize.com/cohorts/236/units/2642"},
{id: 12, title: "Javascript Object Creation", location_url: "https://learn.galvanize.com/cohorts/236/units/2643"},
{id: 13, title: "SQL", location_url: "https://learn.galvanize.com/cohorts/236/units/2644"},
{id: 14, title: "Knex and Express", location_url: "https://learn.galvanize.com/cohorts/236/units/2645"},
{id: 15, title: "Promises and Validation", location_url: "https://learn.galvanize.com/cohorts/236/units/2646/"},
{id: 16, title: "Intro to React", location_url: "https://learn.galvanize.com/cohorts/236/units/2647"},
{id: 17, title: "React - Modern Javascript", location_url: "https://learn.galvanize.com/cohorts/236/units/2648"},
{id: 18, title: "React Components", location_url: "https://learn.galvanize.com/cohorts/236/units/2649"},
{id: 19, title: "React - Integrating with APIs", location_url: "https://learn.galvanize.com/cohorts/236/units/2650"},
{id: 20, title: "React - Redux"},
{id: 21, title: "React Router"},
{id: 22, title: "React - Testing"},
{id: 23, title: "Angular - Building Apps"},
{id: 24, title: "Angular - API Integration"},
{id: 25, title: "Angular - Organizing Code"},
{id: 26, title: "Angular - Deploying"},
{id: 27, title: "Computer Science"},
{id: 28, title: "Java"},
{id: 29, title: "Elective - C#"},
{id: 30, title: "Checkpoints"}
]);
});
};
|
unittest.testInterface = function() {
module('Kiso.Interface Tests');
test('Create Interface', function() {
expect(1);
var testInterface = kiso.Interface(['foo', 'bar', 'baz']);
deepEqual(testInterface.getMethods(), ['foo', 'bar', 'baz']);
});
test('Extend Interface', function() {
var parentInterface = kiso.Interface(['foo', 'bar']);
var extendedInterface = kiso.Interface(parentInterface, ['baz', 'tim']);
expect(1);
deepEqual(extendedInterface.getMethods(), ['foo', 'bar', 'baz', 'tim']);
});
};
|
var cheerio = require("cheerio");
module.exports = function(html) {
// Grab the heading to reinsert later.
var title = cheerio.load(html)("#firstHeading");
// Clean the content of wikipedia stuff.
var $ = cheerio.load(cheerio.load(html)("#mw-content-text").html());
// Remove comments.
$.root().contents().each(function() {
if (this.type === "comment") {
$(this).remove();
}
});
// Get rid if internal wiki links.
$("a").each(function() {
if ($(this).attr("href").indexOf("/") === 0) {
$(this).replaceWith($(this).html());
}
});
$("script").each(function(i, el) {
$(el).remove();
});
$("noscript").each(function(i, el) {
$(el).remove();
});
$("table").each(function(i, el) {
$(el).remove();
});
$("#toc").each(function(i, el) {
$(el).remove();
});
$("#siteSub, #contentSub, .mw-jump, .hatnote, .thumb.tright, .printfooter, #catlinks, .visualClear").each(function(i, el) {
$(el).remove();
});
$(".mw-editsection").each(function(i, el) {
$(el).remove();
});
$(".reference").each(function(i, el) {
$(el).remove();
});
$(".noprint.Inline-Template.Template-Fact").each(function(i, el) {
$(el).remove();
});
$("h1,h2,h3,h4,h5,h6").each(function(i, el) {
$(el).html($(el).text());
});
$(".references > *").each(function(i, el) {
$(el).html($(el).text());
});
// Unwrap silly columns.
$(".columns").each(function() {
$(this).replaceWith($(this).html());
});
// Add the title back in.
$.root().prepend(title);
return $.html();
};
|
// Generated by CoffeeScript 1.6.3
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
define(['config', 'chaplin', 'views/site-view', 'views/header-view', 'models/base/collection', 'models/photo', 'views/photos-collection-view'], function(Config, Chaplin, SiteView, HeaderView, Collection, Photo, PhotosCollectionView) {
'use strict';
var Controller, _ref;
return Controller = (function(_super) {
__extends(Controller, _super);
function Controller() {
_ref = Controller.__super__.constructor.apply(this, arguments);
return _ref;
}
Controller.prototype.beforeAction = function(params, route) {
this.compose('site', SiteView);
this.compose('header', HeaderView);
return this.compose('navigation', function() {
this.photos = new Collection(null, {
model: Photo
});
this.photos.url = Config.methodList === 'YQL' ? Config.urlListYQL() : Config.urlList;
this.photos.parse = function(response) {
if (Config.methodList === 'YQL') {
return response.query.results.photo;
} else {
return response.photos.photo;
}
};
this.photosView = new PhotosCollectionView({
collection: this.photos,
region: 'leftSide'
});
return this.photos.fetch();
});
};
return Controller;
})(Chaplin.Controller);
});
|
'use strict';
var BowerTask = require('./bower'),
path = require('path'),
bower = cb_require('utils/bower');
class BowerAddTask extends BowerTask {
run(cloudbridge, argv) {
var packages = this.getPackages(argv);
return this.install(packages);
}
install(packages) {
var _this = this,
config = { directory: path.join(this.projectDir, 'build', 'bower') };
return bower.install(packages, null, config)
.then(function(result) {
if (_this.options.save)
return _this.save(packages, result);
})
.then(function(result) {
return _this.updateMain();
});
}
save(packages, bowerResult) {
var silent = this.options.silent,
components = this.project.get('components') || {},
bowerComponents = components.bower || {},
originalData = this.objectify(packages),
message = '';
Object.keys(bowerResult).forEach(function(value, index) {
var source = bowerResult[value].endpoint.source || value,
version = bowerResult[value].pkgMeta.version,
modifier = '^';
if (originalData[source] !== '') {
var m = originalData[source][0];
if ((m === '^') || (m === '~'))
modifier = m;
else
modifier = '';
}
bowerComponents[value] = modifier + version;
if (!silent)
message += 'The bower package ' + value.bold + '#' + version.bold + ' has been successfully added to your project!\n';
});
components.bower = bowerComponents;
this.project.set('components', components);
this.project.save();
if (message !== '') {
console.log('\n' + message);
}
}
objectify(packages) {
var result = {};
for (var i = 0; i < packages.length; i++) {
var element = this.split(packages[i]);
result[element.name] = element.version;
}
return result;
}
split(data) {
var splitter = data.indexOf('#') !== -1 ? '#' : data.indexOf('@') !== -1 ? '@' : '',
result = {};
if (splitter !== '') {
var parts = data.split(splitter);
result.name = parts[0];
result.version = parts[1];
}
else {
result.name = data;
result.version = '';
}
return result;
}
}
module.exports = BowerAddTask;
|
/*!
* Connect
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter
, proto = require('./proto')
, utils = require('./utils')
, path = require('path')
, basename = path.basename
, fs = require('fs');
// node patches
require('./patch');
// expose createServer() as the module
exports = module.exports = createServer;
/**
* Framework version.
*/
exports.version = '2.2.0';
/**
* Expose the prototype.
*/
exports.proto = proto;
/**
* Auto-load middleware getters.
*/
exports.middleware = {};
/**
* Expose utilities.
*/
exports.utils = utils;
/**
* Create a new connect server.
*
* @return {Function}
* @api public
*/
function createServer() {
function app(req, res){ app.handle(req, res); }
utils.merge(app, proto);
utils.merge(app, EventEmitter.prototype);
app.route = '/';
app.stack = [];
for (var i = 0; i < arguments.length; ++i) {
app.use(arguments[i]);
}
return app;
};
/**
* Support old `.createServer()` method.
*/
createServer.createServer = createServer;
/**
* Auto-load bundled middleware with getters.
*/
fs.readdirSync(__dirname + '/middleware').forEach(function(filename){
if (!/\.js$/.test(filename)) return;
var name = basename(filename, '.js');
function load(){ return require('./middleware/' + name); }
exports.middleware.__defineGetter__(name, load);
exports.__defineGetter__(name, load);
});
|
'use strict';
var jwt = require('jsonwebtoken');
var User = require('../models/user');
var Book = require('../models/book');
var Config = require('../../config/secret');
var Helpers = require('../helpers');
function BooksController () { }
BooksController.getAll = function(req, res) {
var token = Helpers.getToken(req.headers);
if (!token)
return res.status(403).send({success: false, msg: 'No token provided.'});
var decoded = jwt.decode(token, Config.secret);
User.findOne({
'email': decoded._doc.email
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
}
else
{
Book.find({ owner_id : { $ne: user._id }, traded : false})
.populate('trades')
.exec(function(err, books) {
var booksReturned = [];
books.forEach(function(book){
var yetProposed = false;
book.trades.forEach(function(trade){
if (trade._requester.toString() == user._id.toString())
yetProposed = true;
});
booksReturned.push({
_id : book._id,
owner_name : book.owner_name,
yet_proposed : yetProposed,
owner_id : book.owner_id,
image_url : book.image_url,
title : book.title,
trades : book.trades
});
});
res.json({success: true, books : booksReturned});
});
}
});
}
BooksController.getMy = function(req, res) {
var token = Helpers.getToken(req.headers);
if (!token)
return res.status(403).send({success: false, msg: 'No token provided.'});
var decoded = jwt.decode(token, Config.secret);
User.findOne({
'email': decoded._doc.email
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
}
else
{
Book.find({ owner_id : user._id, traded : false})
.populate('trades')
.exec(function(err, books) {
var booksReturned = [];
books.forEach(function(book){
var yetProposed = false;
book.trades.forEach(function(trade){
if (trade._requester.toString() == user._id.toString())
yetProposed = true;
});
booksReturned.push({
_id : book._id,
owner_name : book.owner_name,
yet_proposed : yetProposed,
owner_id : book.owner_id,
image_url : book.image_url,
title : book.title,
trades : book.trades
});
});
res.json({success: true, books : booksReturned});
});
}
});
}
BooksController.new = function(req, res) {
var token = Helpers.getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, Config.secret);
User.findOne({
'email': decoded._doc.email
}, function(err, user) {
if (err)
throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
}
else
{
var ownerName = user.getName();
var book = new Book( {
title : req.body.name,
owner_id : user._id,
owner_name : ownerName,
image_url : req.body.image_url,
traded : false });
book.save(function(err){
if (err)
throw err;
res.json({success: true});
})
}
});
}
else
{
return res.status(403).send({success: false, msg: 'No token provided.'});
}
}
BooksController.destroy = function(req, res) {
var token = Helpers.getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, Config.secret);
User.findOne({
'email': decoded._doc.email
}, function(err, user) {
if (err)
throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
}
else
{
Book.find({ _id: req.body.id }).remove().exec(function (err, book) {
if (err)
throw err;
return res.json({success: true});
});
}
});
}
else
{
return res.status(403).send({success: false, msg: 'No token provided.'});
}
}
module.exports = BooksController;
|
import_module('Athena.Math');
q = new Athena.Math.Quaternion(10, 0, 0, 0);
length = q.normalise();
CHECK_CLOSE(10, length);
CHECK_CLOSE(1, q.w);
CHECK_CLOSE(0, q.x);
CHECK_CLOSE(0, q.y);
CHECK_CLOSE(0, q.z);
|
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('todolistApp'));
var MainCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
// it('should attach a list of awesomeThings to the scope', function () {
// expect(scope.awesomeThings.length).toBe(3);
// });
});
|
if ('undefined' == typeof window.beefTranslations) {
window.beefTranslations = {
minLength: "Please type more than [min] chars",
minCount: "Please set more than [min] entries ([currentLength] provided)"
};
}
|
'use strict';
//var mongoose = require('mongoose');
exports.ifAuth = function(req, res, next) {
//req.query.account = mongoose.Types.ObjectId();
next();
};
exports.generateToken = function() {
};
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { MainSidebar } from '../../Sidebar';
import { EWalletTopUpModalWidget, EWalletCreateTransactionModalWidget } from '../../Widgets';
import styles from './styles.scss';
export class MainAppContainer extends Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: PropTypes.node.isRequired,
};
render() {
return (
<div className={styles.page}>
<div className={styles.pageSidebar}>
<MainSidebar />
</div>
<div className={styles.pageContent}>
<div className={styles.pageContentWrapper}>
{this.props.children}
</div>
</div>
<EWalletTopUpModalWidget />
<EWalletCreateTransactionModalWidget />
</div>
);
}
}
export default connect(() => ({}), {})(MainAppContainer);
|
/*
* Kendo UI Complete v2012.3.1114 (http://kendoui.com)
* Copyright 2012 Telerik AD. All rights reserved.
*
* Kendo UI Complete commercial licenses may be obtained at
* https://www.kendoui.com/purchase/license-agreement/kendo-ui-complete-commercial.aspx
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function( window, undefined ) {
kendo.cultures["fr-FR"] = {
name: "fr-FR",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["-n $","n $"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "€"
}
},
calendars: {
standard: {
days: {
names: ["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"],
namesAbbr: ["dim.","lun.","mar.","mer.","jeu.","ven.","sam."],
namesShort: ["di","lu","ma","me","je","ve","sa"]
},
months: {
names: ["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre",""],
namesAbbr: ["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc.",""]
},
AM: [""],
PM: [""],
patterns: {
d: "dd/MM/yyyy",
D: "dddd d MMMM yyyy",
F: "dddd d MMMM yyyy HH:mm:ss",
g: "dd/MM/yyyy HH:mm",
G: "dd/MM/yyyy HH:mm:ss",
m: "d MMMM",
M: "d MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 1
}
}
}
})(this);
|
/**
* A key/value entry in a map.
*
* @private
*/
export class Entry {
/**
* Create a new entry.
*
* @param {String|Number} key
* @param {*} value
* @private
*/
constructor(key, value) {
this.key = key;
this.value = value;
}
}
|
var User = require('../../../models/user'),
arrayRest = require('../../../controllers/api/v0/nestedArrayRest')(User, 'quotes'),
checkDB = require('../../../middleware/checkDB');
module.exports = function (app) {
app.get('/api/v0/users/:id/quotes', arrayRest.get);
app.post('/api/v0/users/:id/quotes', arrayRest.post);
app.put('/api/v0/users/:id/quotes', arrayRest.put);
app.delete('/api/v0/users/:id/quotes', arrayRest.delete);
};
|
import { createSelector, createStructuredSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import uniqBy from 'lodash/uniqBy';
import sumBy from 'lodash/sumBy';
import sortBy from 'lodash/sortBy';
import { format } from 'd3-format';
// get list data
const getGain = (state) => state.data && state.data.gain;
const getExtent = (state) => state.data && state.data.extent;
const getSettings = (state) => state.settings;
const getIndicator = (state) => state.indicator;
const getLocationsMeta = (state) => state.childData;
const getLocationName = (state) => state.locationLabel;
const getColors = (state) => state.colors;
const getSentences = (state) => state.sentences;
export const getSortedData = createSelector(
[getGain, getExtent, getSettings, getLocationsMeta, getColors],
(data, extent, settings, meta, colors) => {
if (isEmpty(data) || isEmpty(meta)) return null;
const dataMapped = [];
data.forEach((d) => {
const region = meta[d.id];
if (region) {
const locationExtent = extent.find((l) => l.id === parseInt(d.id, 10));
const percentage = locationExtent
? (d.gain / locationExtent.extent) * 100
: 0;
dataMapped.push({
label: (region && region.label) || '',
gain: d.gain,
percentage,
value: settings.unit === 'ha' ? d.gain : percentage,
color: colors.main,
});
}
});
return sortBy(dataMapped, 'gain');
}
);
export const parseData = createSelector([getSortedData], (data) => {
if (!data || !data.length) return null;
return sortBy(uniqBy(data, 'label'), 'value').reverse();
});
export const parseSentence = createSelector(
[
getSortedData,
parseData,
getSettings,
getIndicator,
getLocationName,
getSentences,
],
(data, sortedData, settings, indicator, locationName, sentences) => {
if (!data || !locationName) return null;
const {
initial,
withIndicator,
initialPercent,
withIndicatorPercent,
} = sentences;
const totalGain = sumBy(data, 'gain') || 0;
const topRegion = (sortedData && sortedData.length && sortedData[0]) || {};
const avgGainPercentage = sumBy(data, 'percentage') || 0 / data.length;
const avgGain = (sumBy(data, 'gain') || 0) / data.length;
let percentileGain = 0;
let percentileLength = 0;
while (
sortedData &&
percentileLength < sortedData.length &&
percentileGain / totalGain < 0.5 &&
percentileLength !== 10
) {
percentileGain += sortedData[percentileLength].gain;
percentileLength += 1;
}
const topGain = (percentileGain / totalGain) * 100 || 0;
let sentence = !indicator ? initialPercent : withIndicatorPercent;
if (settings.unit !== '%') {
sentence = !indicator ? initial : withIndicator;
}
const valueFormat = topRegion.gain < 1 ? '.3r' : '.3s';
const aveFormat = avgGain < 1 ? '.3r' : '.3s';
const params = {
indicator: indicator && indicator.label,
location: locationName,
topGain: `${format('.2r')(topGain)}%`,
percentileLength: percentileLength || '0',
region: percentileLength > 1 ? topRegion.label : 'This region',
value:
topRegion.percentage > 0 && settings.unit === '%'
? `${format('.2r')(topRegion.percentage)}%`
: `${format(valueFormat)(topRegion.gain)}ha`,
average:
topRegion.percentage > 0 && settings.unit === '%'
? `${format('.2r')(avgGainPercentage)}%`
: `${format(aveFormat)(avgGain)}ha`,
};
return {
sentence,
params,
};
}
);
export default createStructuredSelector({
data: parseData,
sentence: parseSentence,
});
|
var f = require('util').format,
data = require('../../data');
// Process the province select step
module.exports = function(interview, input, number, strings) {
var message = '';
// Confirm province choice
if (input.toLowerCase() === strings.yes) {
interview.provinceFound = true;
interview.step = 'city';
message = f(strings.provinceFound, interview.matchedProvince, data.getExampleMuni(interview.matchedProvince));
} else {
interview.provinceFound = false;
interview.matchedProvince = null;
interview.enteredProvince = null;
interview.step = 'province';
message = f(i18n(interview.language).province, 'Iloilo');
}
return message;
};
|
import React from 'react'
import App from 'next/app'
import Link from 'next/link'
import NProgress from 'nprogress'
import Router from 'next/router'
import Head from 'next/head'
Router.events.on('routeChangeStart', url => {
console.log(`Loading: ${url}`)
NProgress.start()
})
Router.events.on('routeChangeComplete', () => NProgress.done())
Router.events.on('routeChangeError', () => NProgress.done())
export default class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return (
<>
<Head>
{/* Import CSS for nprogress */}
<link rel='stylesheet' type='text/css' href='/nprogress.css' />
</Head>
<nav>
<style jsx>{`
a {
margin: 0 10px 0 0;
}
`}</style>
<Link href='/'>
<a>Home</a>
</Link>
<Link href='/about'>
<a>About</a>
</Link>
<Link href='/forever'>
<a>Forever</a>
</Link>
<a href='/non-existing'>Non Existing Page</a>
</nav>
<Component {...pageProps} />
</>
)
}
}
|
/**
* Archivo.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models
*/
module.exports = {
attributes: {
// Nombre como se muestra el Archivo
nombre: {
type: 'string',
required: true
},
canonical: {
type: 'string'
},
descripcion: {
type: 'text'
},
// Nombre como se guardó el Archivo
filename: {
type: 'string',
unique: true,
required: true
},
// Src para acceder al Archivo
src: {
type: 'string',
unique: true,
required: true
},
// Tamaño del Archivo
size: {
type: 'float',
required: true
},
// Extensión del Archivo
ext: {
type: 'string',
maxLength: 5,
required: true
},
// Tipo del Archivo
tipo: {
model: 'tipo',
required: true
},
// Estado del Archivo
estado: {
model: 'estado'
},
// Pago donde está asignado el Archivo
pago: {
model: 'pago'
},
// Gasto donde está asignado el Archivo
gasto: {
model: 'gasto'
},
// Servicio donde está asignado el Archivo
servicio: {
model: 'servicio'
},
// Menú donde está asignado el Archivo
menu: {
model: 'menu'
},
// Página donde está asignado el Archivo
pagina: {
model: 'pagina',
via: 'archivos'
},
// Usuarios del Archivo
usuarios: {
collection: 'usuario',
via: 'archivos'
},
// Publicaciones del Archivo
publicaciones: {
collection: 'publicacion',
via: 'archivos'
},
// Etiquetas del Archivo
etiquetas: {
collection: 'etiqueta',
via: 'archivos',
dominant: true
}
}
};
|
import Immutable from "immutable";
import alt from "alt-instance";
import MarketsActions from "actions/MarketsActions";
import market_utils from "common/market_utils";
import ls from "common/localStorage";
import {ChainStore} from "bitsharesjs/es";
import utils from "common/utils";
import {LimitOrder, CallOrder, FeedPrice, SettleOrder, Asset,
didOrdersChange, Price} from "common/MarketClasses";
// import {
// SettleOrder
// }
// from "./tcomb_structs";
const nullPrice = {
getPrice: () => {return 0;},
sellPrice: () => {return nullPrice;},
toReal: () => {return 0;},
clone: () => {return nullPrice;},
isValid: () => {return false;}
};
let marketStorage = new ls("__graphene__");
class MarketsStore {
constructor() {
this.markets = Immutable.Map();
this.asset_symbol_to_id = {};
this.pendingOrders = Immutable.Map();
this.marketLimitOrders = Immutable.Map();
this.marketCallOrders = Immutable.Map();
this.allCallOrders = [];
this.feedPrice = null;
this.marketSettleOrders = Immutable.OrderedSet();
this.activeMarketHistory = Immutable.OrderedSet();
this.marketData = {
bids: [],
asks: [],
calls: [],
combinedBids: [],
highestBid: nullPrice,
combinedAsks: [],
lowestAsk: nullPrice,
flatBids: [],
flatAsks: [],
flatCalls: [],
flatSettles: []
};
this.totals = {
bid: 0,
ask: 0,
call: 0
};
this.priceData = [];
this.volumeData = [];
this.pendingCreateLimitOrders = [];
this.activeMarket = null;
this.quoteAsset = null;
this.pendingCounter = 0;
this.buckets = [15,60,300,3600,86400];
this.bucketSize = this._getBucketSize();
this.priceHistory = [];
this.lowestCallPrice = null;
this.marketBase = "BTS";
this.marketStats = Immutable.Map({
change: 0,
volumeBase: 0,
volumeQuote: 0
});
this.marketReady = false;
this.allMarketStats = Immutable.Map();
this.lowVolumeMarkets = Immutable.Map(marketStorage.get("lowVolumeMarkets", {}));
this.onlyStars = marketStorage.get("onlyStars", false);
this.baseAsset = {
id: "1.3.0",
symbol: "BTS",
precision: 5
};
this.coreAsset = {
id: "1.3.0",
symbol: "CORE",
precision: 5
};
this.bindListeners({
onSubscribeMarket: MarketsActions.subscribeMarket,
onUnSubscribeMarket: MarketsActions.unSubscribeMarket,
onChangeBase: MarketsActions.changeBase,
onChangeBucketSize: MarketsActions.changeBucketSize,
onCancelLimitOrderSuccess: MarketsActions.cancelLimitOrderSuccess,
onCloseCallOrderSuccess: MarketsActions.closeCallOrderSuccess,
onCallOrderUpdate: MarketsActions.callOrderUpdate,
onClearMarket: MarketsActions.clearMarket,
onGetMarketStats: MarketsActions.getMarketStats,
onSettleOrderUpdate: MarketsActions.settleOrderUpdate,
onSwitchMarket: MarketsActions.switchMarket,
onFeedUpdate: MarketsActions.feedUpdate,
onToggleStars: MarketsActions.toggleStars
});
}
onGetCollateralPositions(payload) {
this.borrowMarketState = {
totalDebt: payload.totalDebt,
totalCollateral: payload.totalCollateral
};
}
_getBucketSize() {
return parseInt(marketStorage.get("bucketSize", 4 * 3600));
}
_setBucketSize(size) {
this.bucketSize = size;
marketStorage.set("bucketSize", size);
}
onChangeBase(market) {
this.marketBase = market;
}
onChangeBucketSize(size) {
this._setBucketSize(size);
}
onToggleStars() {
this.onlyStars = !this.onlyStars;
marketStorage.set("onlyStars", this.onlyStars);
}
onUnSubscribeMarket(payload) {
// Optimistic removal of activeMarket
if (payload.unSub) {
this.activeMarket = null;
} else { // Unsub failed, restore activeMarket
this.activeMarket = payload.market;
}
}
onSwitchMarket() {
this.marketReady = false;
}
onClearMarket() {
this.activeMarket = null;
this.is_prediction_market = false;
this.marketLimitOrders = this.marketLimitOrders.clear();
this.marketCallOrders = this.marketCallOrders.clear();
this.allCallOrders = [];
this.feedPrice = null;
this.marketSettleOrders = this.marketSettleOrders.clear();
this.activeMarketHistory = this.activeMarketHistory.clear();
this.marketData = {
bids: [],
asks: [],
calls: [],
combinedBids: [],
highestBid: nullPrice,
combinedAsks: [],
lowestAsk: nullPrice,
flatBids: [],
flatAsks: [],
flatCalls: [],
flatSettles: []
};
this.totals = {
bid: 0,
ask: 0,
call: 0
};
this.lowestCallPrice = null;
this.pendingCreateLimitOrders = [];
this.priceHistory =[];
this.marketStats = Immutable.Map({
change: 0,
volumeBase: 0,
volumeQuote: 0
});
}
_marketHasCalls() {
const {quoteAsset, baseAsset} = this;
if (quoteAsset.has("bitasset") && quoteAsset.getIn(["bitasset", "options", "short_backing_asset"]) === baseAsset.get("id")) {
return true;
} else if (baseAsset.has("bitasset") && baseAsset.getIn(["bitasset", "options", "short_backing_asset"]) === quoteAsset.get("id")) {
return true;
}
return false;
}
onSubscribeMarket(result) {
if (result.switchMarket) {
this.marketReady = false;
return this.emitChange();
}
let limitsChanged = false, callsChanged = false;
this.invertedCalls = result.inverted;
// Get updated assets every time for updated feed data
this.quoteAsset = ChainStore.getAsset(result.quote.get("id"));
this.baseAsset = ChainStore.getAsset(result.base.get("id"));
const assets = {
[this.quoteAsset.get("id")]: {precision: this.quoteAsset.get("precision")},
[this.baseAsset.get("id")]: {precision: this.baseAsset.get("precision")}
};
if (result.market && (result.market !== this.activeMarket)) {
// console.log("switch active market from", this.activeMarket, "to", result.market);
this.onClearMarket();
this.activeMarket = result.market;
}
/* Set the feed price (null if not a bitasset market) */
this.feedPrice = this._getFeed();
if (result.buckets) {
this.buckets = result.buckets;
if (result.buckets.indexOf(this.bucketSize) === -1) {
this.bucketSize = result.buckets[result.buckets.length - 1];
}
}
if (result.buckets) {
this.buckets = result.buckets;
}
if (result.limits) {
// Keep an eye on this as the number of orders increases, it might not scale well
const oldmarketLimitOrders = this.marketLimitOrders;
this.marketLimitOrders = this.marketLimitOrders.clear();
// console.time("Create limit orders " + this.activeMarket);
result.limits.forEach(order => {
// ChainStore._updateObject(order, false, false);
if (typeof order.for_sale !== "number") {
order.for_sale = parseInt(order.for_sale, 10);
}
order.expiration = new Date(order.expiration);
this.marketLimitOrders = this.marketLimitOrders.set(
order.id,
new LimitOrder(order, assets, this.quoteAsset.get("id"))
);
});
limitsChanged = didOrdersChange(this.marketLimitOrders, oldmarketLimitOrders);
// Loop over pending orders to remove temp order from orders map and remove from pending
for (let i = this.pendingCreateLimitOrders.length - 1; i >= 0; i--) {
let myOrder = this.pendingCreateLimitOrders[i];
let order = this.marketLimitOrders.find(order => {
return myOrder.seller === order.seller && myOrder.expiration === order.expiration;
});
// If the order was found it has been confirmed, delete it from pending
if (order) {
this.pendingCreateLimitOrders.splice(i, 1);
}
}
// console.timeEnd("Create limit orders " + this.activeMarket);
if (this.pendingCreateLimitOrders.length === 0) {
this.pendingCounter = 0;
}
// console.log("time to process limit orders:", new Date() - limitStart, "ms");
}
if (result.calls) {
const oldmarketCallOrders = this.marketCallOrders;
this.allCallOrders = result.calls;
this.marketCallOrders = this.marketCallOrders.clear();
result.calls.forEach(call => {
// ChainStore._updateObject(call, false, false);
try {
let callOrder = new CallOrder(call, assets, this.quoteAsset.get("id"), this.feedPrice, this.is_prediction_market);
if (callOrder.isMarginCalled()) {
this.marketCallOrders = this.marketCallOrders.set(
call.id,
new CallOrder(call, assets, this.quoteAsset.get("id"), this.feedPrice)
);
}
} catch(err) {
console.error("Unable to construct calls array, invalid feed price or prediction market?");
}
});
callsChanged = didOrdersChange(this.marketCallOrders, oldmarketCallOrders);
}
this.updateSettleOrders(result);
if (result.history) {
this.activeMarketHistory = this.activeMarketHistory.clear();
result.history.forEach(order => {
order.op.time = order.time;
/* Only include history objects that aren't 'something for nothing' to avoid confusion */
if (!(order.op.receives.amount == 0 || order.op.pays.amount == 0)) {
this.activeMarketHistory = this.activeMarketHistory.add(
order.op
);
}
});
}
if (result.fillOrders) {
result.fillOrders.forEach(fill => {
// console.log("fill:", fill);
this.activeMarketHistory = this.activeMarketHistory.add(
fill[0][1]
);
});
}
if (result.recent && result.recent.length) {
let stats = this._calcMarketStats(result.recent, this.baseAsset, this.quoteAsset, result.history, this.quoteAsset.get("symbol") + "_" + this.baseAsset.get("symbol"));
this.marketStats = this.marketStats.set("change", stats.change);
this.marketStats = this.marketStats.set("volumeBase", stats.volumeBase);
this.marketStats = this.marketStats.set("volumeQuote", stats.volumeQuote);
if (stats.volumeBase) {
this.lowVolumeMarkets = this.lowVolumeMarkets.delete(result.market);
}
} else if (result.recent && !result.recent.length) {
this.lowVolumeMarkets = this.lowVolumeMarkets.set(result.market, true);
}
if (callsChanged || limitsChanged) {
// Update orderbook
this._orderBook(limitsChanged, callsChanged);
// Update depth chart data
this._depthChart();
}
// Update pricechart data
if (result.price) {
this.priceHistory = result.price;
this._priceChart();
}
marketStorage.set("lowVolumeMarkets", this.lowVolumeMarkets.toJS());
this.marketReady = true;
this.emitChange();
}
onCancelLimitOrderSuccess(cancellations) {
if (cancellations && cancellations.length) {
let didUpdate = false;
cancellations.forEach(orderID => {
if (orderID && this.marketLimitOrders.has(orderID)) {
didUpdate = true;
this.marketLimitOrders = this.marketLimitOrders.delete(orderID);
}
});
if (this.marketLimitOrders.size === 0) {
this.marketData.bids = [];
this.marketData.flatBids = [];
this.marketData.asks = [];
this.marketData.flatAsks = [];
}
if (didUpdate) {
// Update orderbook
this._orderBook(true, false);
// Update depth chart data
this._depthChart();
}
} else {
return false;
}
}
onCloseCallOrderSuccess(orderID) {
if (orderID && this.marketCallOrders.has(orderID)) {
this.marketCallOrders = this.marketCallOrders.delete(orderID);
if (this.marketCallOrders.size === 0) {
this.marketData.calls = [];
this.marketData.flatCalls = [];
}
// Update orderbook
this._orderBook(false, true);
// Update depth chart data
this._depthChart();
} else {
return false;
}
}
onCallOrderUpdate(call_order) {
if (call_order && this.quoteAsset && this.baseAsset) {
if (call_order.call_price.quote.asset_id === this.quoteAsset.get("id") || call_order.call_price.quote.asset_id === this.baseAsset.get("id")) {
const assets = {
[this.quoteAsset.get("id")]: {precision: this.quoteAsset.get("precision")},
[this.baseAsset.get("id")]: {precision: this.baseAsset.get("precision")}
};
try {
let callOrder = new CallOrder(call_order, assets, this.quoteAsset.get("id"), this.feedPrice);
// console.log("**** onCallOrderUpdate **", call_order, "isMarginCalled:", callOrder.isMarginCalled());
if (callOrder.isMarginCalled()) {
this.marketCallOrders = this.marketCallOrders.set(
call_order.id,
callOrder
);
// Update orderbook
this._orderBook(false, true);
// Update depth chart data
this._depthChart();
}
} catch(err) {
console.error("Unable to construct calls array, invalid feed price or prediction market?");
}
}
} else {
return false;
}
}
//
onFeedUpdate(asset) {
if (!this.quoteAsset || !this.baseAsset) {
return false;
}
if (asset.get("id") === this[this.invertedCalls ? "baseAsset" : "quoteAsset"].get("id")) {
this[this.invertedCalls ? "baseAsset" : "quoteAsset"] = asset;
} else {
return false;
}
let feedChanged = false;
let newFeed = this._getFeed();
if ((newFeed && !this.feedPrice) || (this.feedPrice) && this.feedPrice.ne(newFeed)) {
feedChanged = true;
}
if (feedChanged) {
this.feedPrice = newFeed;
const assets = {
[this.quoteAsset.get("id")]: {precision: this.quoteAsset.get("precision")},
[this.baseAsset.get("id")]: {precision: this.baseAsset.get("precision")}
};
/*
* If the feed price changed, we need to check whether the orders
* being margin called have changed and filter accordingly. To do so
* we recreate the marketCallOrders map from scratch using the
* previously fetched data and the new feed price.
*/
this.marketCallOrders = this.marketCallOrders.clear();
this.allCallOrders.forEach(call => {
// ChainStore._updateObject(call, false, false);
try {
let callOrder = new CallOrder(call, assets, this.quoteAsset.get("id"), this.feedPrice, this.is_prediction_market);
if (callOrder.isMarginCalled()) {
this.marketCallOrders = this.marketCallOrders.set(
call.id,
new CallOrder(call, assets, this.quoteAsset.get("id"), this.feedPrice)
);
}
} catch(err) {
console.error("Unable to construct calls array, invalid feed price or prediction market?");
}
});
// this.marketCallOrders = this.marketCallOrders.withMutations(callOrder => {
// if (callOrder && callOrder.first()) {
// callOrder.first().setFeed(this.feedPrice);
// }
// });
// this.marketCallOrders = this.marketCallOrders.filter(callOrder => {
// if (callOrder) {
// return callOrder.isMarginCalled();
// } else {
// return false;
// }
// });
// Update orderbook
this._orderBook(true, true);
// Update depth chart data
this._depthChart();
}
}
_getFeed() {
if (!this._marketHasCalls()) {
this.bitasset_options = null;
this.is_prediction_market = false;
return null;
}
const assets = {
[this.quoteAsset.get("id")]: {precision: this.quoteAsset.get("precision")},
[this.baseAsset.get("id")]: {precision: this.baseAsset.get("precision")}
};
let settlePrice = this[this.invertedCalls ? "baseAsset" : "quoteAsset"].getIn(["bitasset", "current_feed", "settlement_price"]);
try {
let sqr = this[this.invertedCalls ? "baseAsset" : "quoteAsset"].getIn(["bitasset", "current_feed", "maximum_short_squeeze_ratio"]);
this.is_prediction_market = this[this.invertedCalls ? "baseAsset" : "quoteAsset"].getIn(["bitasset", "is_prediction_market"], false);
this.bitasset_options = this[this.invertedCalls ? "baseAsset" : "quoteAsset"].getIn(["bitasset", "options"]).toJS();
/* Prediction markets don't need feeds for shorting, so the settlement price can be set to 1:1 */
if (this.is_prediction_market && settlePrice.getIn(["base", "asset_id"]) === settlePrice.getIn(["quote", "asset_id"])) {
const backingAsset = this.bitasset_options.short_backing_asset;
if (!assets[backingAsset]) assets[backingAsset] = {precision: this.quoteAsset.get("precision")};
settlePrice = settlePrice.setIn(["base", "amount"], 1);
settlePrice = settlePrice.setIn(["base", "asset_id"], backingAsset);
settlePrice = settlePrice.setIn(["quote", "amount"], 1);
settlePrice = settlePrice.setIn(["quote", "asset_id"], this.quoteAsset.get("id"));
sqr = 1000;
}
const feedPrice = new FeedPrice({
priceObject: settlePrice,
market_base: this.quoteAsset.get("id"),
sqr,
assets
});
return feedPrice;
} catch(err) {
console.error(this.activeMarket, "does not have a properly configured feed price");
return null;
}
}
_priceChart() {
let volumeData = [];
let prices = [];
let open, high, low, close, volume;
let addTime = (time, i, bucketSize) => {
return new Date(time.getTime() + i * bucketSize * 1000);
}
for (let i = 0; i < this.priceHistory.length; i++) {
let current = this.priceHistory[i];
let date = new Date(current.key.open + "+00:00");
if (this.quoteAsset.get("id") === current.key.quote) {
high = utils.get_asset_price(current.high_base, this.baseAsset, current.high_quote, this.quoteAsset);
low = utils.get_asset_price(current.low_base, this.baseAsset, current.low_quote, this.quoteAsset);
open = utils.get_asset_price(current.open_base, this.baseAsset, current.open_quote, this.quoteAsset);
close = utils.get_asset_price(current.close_base, this.baseAsset, current.close_quote, this.quoteAsset);
volume = utils.get_asset_amount(current.quote_volume, this.quoteAsset);
} else {
low = utils.get_asset_price(current.high_quote, this.baseAsset, current.high_base, this.quoteAsset);
high = utils.get_asset_price(current.low_quote, this.baseAsset, current.low_base, this.quoteAsset);
open = utils.get_asset_price(current.open_quote, this.baseAsset, current.open_base, this.quoteAsset);
close = utils.get_asset_price(current.close_quote, this.baseAsset, current.close_base, this.quoteAsset);
volume = utils.get_asset_amount(current.base_volume, this.quoteAsset);
}
function findMax(a, b) {
if (a !== Infinity && b !== Infinity) {
return Math.max(a, b);
} else if (a === Infinity) {
return b;
} else {
return a;
}
}
function findMin(a, b) {
if (a !== 0 && b !== 0) {
return Math.min(a, b);
} else if (a === 0) {
return b;
} else {
return a;
}
}
if (low === 0) {
low = findMin(open, close);
}
if (isNaN(high) || high === Infinity) {
high = findMax(open, close);
}
if (close === Infinity || close === 0) {
close = open;
}
if (open === Infinity || open === 0) {
open = close;
}
if (high > 1.3 * ((open + close) / 2)) {
high = findMax(open, close);
}
if (low < 0.7 * ((open + close) / 2)) {
low = findMin(open, close);
}
prices.push({date, open, high, low, close, volume});
volumeData.push([date, volume]);
}
// max buckets returned is 200, if we get less, fill in the gaps starting at the first data point
let priceLength = prices.length;
if (priceLength > 0 && priceLength < 200) {
let now = new Date().getTime();
// let firstDate = prices[0].date;
// ensure there's a final entry close to the current time
let i = 1;
while (addTime(prices[0].date, i, this.bucketSize).getTime() < now) {
i++;
}
let finalDate = addTime(prices[0].date, i - 1, this.bucketSize);
if (prices[priceLength - 1].date !== finalDate) {
if (priceLength === 1) {
prices.push({date: addTime(finalDate, -1, this.bucketSize), open: prices[0].close, high: prices[0].close, low: prices[0].close, close: prices[0].close, volume: 0});
prices.push({date: finalDate, open: prices[0].close, high: prices[0].close, low: prices[0].close, close: prices[0].close, volume: 0});
volumeData.push([addTime(finalDate, -1, this.bucketSize), 0]);
} else {
prices.push({date: finalDate, open: prices[priceLength - 1].close, high: prices[priceLength - 1].close, low: prices[priceLength - 1].close, close: prices[priceLength - 1].close, volume: 0});
}
volumeData.push([finalDate, 0]);
}
// Loop over the data and fill in any blank time periods
for (let ii = 0; ii < prices.length - 1; ii++) {
// If next date is beyond one bucket up
if (prices[ii+1].date.getTime() !== (addTime(prices[ii].date, 1, this.bucketSize).getTime())) {
// Break if next date is beyond now
if (addTime(prices[ii].date, 1, this.bucketSize).getTime() > now) {
break;
}
prices.splice(ii + 1, 0, {date: addTime(prices[ii].date, 1, this.bucketSize), open: prices[ii].close, high: prices[ii].close, low: prices[ii].close, close: prices[ii].close, volume: 0});
volumeData.splice(ii + 1, 0, [addTime(prices[ii].date, 1, this.bucketSize), 0]);
}
};
}
this.priceData = prices;
this.volumeData = volumeData;
}
_orderBook(limitsChanged = true, callsChanged = false) {
// Loop over limit orders and return array containing bids
let constructBids = (orderArray) => {
let bids = orderArray.filter(a => {
return a.isBid();
}).sort((a, b) => {
return a.getPrice() - b.getPrice();
}).map(order => {
return order;
}).toArray();
// Sum bids at same price
if (bids.length > 1) {
for (let i = bids.length - 2; i >= 0; i--) {
if (bids[i].getPrice() === bids[i + 1].getPrice()) {
bids[i] = bids[i].sum(bids[i + 1]);
bids.splice(i + 1, 1);
}
}
}
return bids;
};
// Loop over limit orders and return array containing asks
let constructAsks = (orderArray) => {
let asks = orderArray.filter(a => {
return !a.isBid();
}).sort((a, b) => {
return a.getPrice() - b.getPrice();
}).map(order => {
return order;
}).toArray();
// Sum asks at same price
if (asks.length > 1) {
for (let i = asks.length - 2; i >= 0; i--) {
if (asks[i].getPrice() === asks[i + 1].getPrice()) {
asks[i] = asks[i].sum(asks[i + 1]);
asks.splice(i + 1, 1);
}
}
}
return asks;
};
// Assign to store variables
if (limitsChanged) {
if (__DEV__) console.time("Construct limit orders " + this.activeMarket);
this.marketData.bids = constructBids(this.marketLimitOrders);
this.marketData.asks = constructAsks(this.marketLimitOrders);
if (!callsChanged) {
this._combineOrders();
}
if (__DEV__) console.timeEnd("Construct limit orders " + this.activeMarket);
}
if (callsChanged) {
if (__DEV__) console.time("Construct calls " + this.activeMarket);
this.marketData.calls = this.constructCalls(this.marketCallOrders);
this._combineOrders();
if (__DEV__) console.timeEnd("Construct calls " + this.activeMarket);
}
// console.log("time to construct orderbook:", new Date() - orderBookStart, "ms");
}
constructCalls (callsArray) {
let calls = [];
if (callsArray.size) {
calls = callsArray
.sort((a, b) => {
return a.getPrice() - b.getPrice();
}).map(order => {
if (this.invertedCalls) {
this.lowestCallPrice = !this.lowestCallPrice ? order.getPrice(false) : Math.max(this.lowestCallPrice, order.getPrice(false));
} else {
this.lowestCallPrice = !this.lowestCallPrice ? order.getPrice(false) : Math.min(this.lowestCallPrice, order.getPrice(false));
}
return order;
}).toArray();
// Sum calls at same price
if (calls.length > 1) {
for (let i = calls.length - 2; i >= 0; i--) {
calls[i] = calls[i].sum(calls[i + 1]);
calls.splice(i + 1, 1);
}
}
} else {
this.lowestCallPrice = null;
}
return calls;
}
_combineOrders() {
const hasCalls = !!this.marketCallOrders.size;
const isBid = hasCalls && this.marketCallOrders.first().isBid();
let combinedBids, combinedAsks;
if (isBid) {
combinedBids = this.marketData.bids.concat(this.marketData.calls);
combinedAsks = this.marketData.asks.concat([]);
} else {
combinedBids = this.marketData.bids.concat([]);
combinedAsks = this.marketData.asks.concat(this.marketData.calls);
}
let totalToReceive = new Asset({
asset_id: this.quoteAsset.get("id"),
precision: this.quoteAsset.get("precision")
});
let totalForSale = new Asset({
asset_id: this.baseAsset.get("id"),
precision: this.baseAsset.get("precision")
});
combinedBids.sort((a, b) => {
return b.getPrice() - a.getPrice();
}).forEach(a => {
totalToReceive.plus(a.amountToReceive(false));
totalForSale.plus(a.amountForSale());
a.setTotalForSale(totalForSale.clone());
a.setTotalToReceive(totalToReceive.clone());
});
totalToReceive = new Asset({
asset_id: this.baseAsset.get("id"),
precision: this.baseAsset.get("precision")
});
totalForSale = new Asset({
asset_id: this.quoteAsset.get("id"),
precision: this.quoteAsset.get("precision")
});
combinedAsks.sort((a, b) => {
return a.getPrice() - b.getPrice();
}).forEach(a => {
totalForSale.plus(a.amountForSale());
totalToReceive.plus(a.amountToReceive(true));
a.setTotalForSale(totalForSale.clone());
a.setTotalToReceive(totalToReceive.clone());
});
this.marketData.lowestAsk = !combinedAsks.length ? nullPrice :
combinedAsks[0];
this.marketData.highestBid = !combinedBids.length ? nullPrice :
combinedBids[0];
this.marketData.combinedBids = combinedBids;
this.marketData.combinedAsks = combinedAsks;
}
_depthChart() {
let bids = [], asks = [], calls= [], totalBids = 0, totalAsks = 0, totalCalls = 0;
let flat_bids = [], flat_asks = [], flat_calls = [], flat_settles = [];
if (this.marketLimitOrders.size) {
this.marketData.bids.forEach(order => {
bids.push([order.getPrice(), order.amountToReceive().getAmount({real: true})]);
totalBids += order.amountForSale().getAmount({real: true});
});
this.marketData.asks.forEach(order => {
asks.push([order.getPrice(), order.amountForSale().getAmount({real: true})]);
});
// Make sure the arrays are sorted properly
asks.sort((a, b) => {
return a[0] - b[0];
});
bids.sort((a, b) => {
return a[0] - b[0];
});
// Flatten the arrays to get the step plot look
flat_bids = market_utils.flatten_orderbookchart_highcharts(bids, true, true, 1000);
if (flat_bids.length) {
flat_bids.unshift([0, flat_bids[0][1]]);
}
flat_asks = market_utils.flatten_orderbookchart_highcharts(asks, true, false, 1000);
if (flat_asks.length) {
flat_asks.push([flat_asks[flat_asks.length - 1][0] * 1.5, flat_asks[flat_asks.length - 1][1]]);
totalAsks = flat_asks[flat_asks.length - 1][1];
}
}
/* Flatten call orders if there any */
if (this.marketData.calls.length) {
let callsAsBids = this.marketData.calls[0].isBid();
this.marketData.calls.forEach(order => {
calls.push([order.getSqueezePrice(), order[order.isBid() ? "amountToReceive" : "amountForSale"]().getAmount({real: true})]);
});
// Calculate total value of call orders
calls.forEach(call => {
if (this.invertedCalls) {
totalCalls += call[1];
} else {
totalCalls += call[1] * call[0];
}
});
if (callsAsBids) {
totalBids += totalCalls;
} else {
totalAsks += totalCalls;
}
// Make sure the array is sorted properly
calls.sort((a, b) => {
return a[0] - b[0];
});
// Flatten the array to get the step plot look
if (this.invertedCalls) {
flat_calls = market_utils.flatten_orderbookchart_highcharts(calls, true, false, 1000);
if (flat_asks.length && (flat_calls[flat_calls.length - 1][0] < flat_asks[flat_asks.length - 1][0])) {
flat_calls.push([flat_asks[flat_asks.length - 1][0], flat_calls[flat_calls.length - 1][1]]);
}
} else {
flat_calls = market_utils.flatten_orderbookchart_highcharts(calls, true, true, 1000);
if (flat_calls.length > 0) {
flat_calls.unshift([0, flat_calls[0][1]]);
}
}
}
/* Flatten settle orders if there are any */
if (this.marketSettleOrders.size) {
flat_settles = this.marketSettleOrders.reduce((final, a) => {
if (!final) {
return [[a.getPrice(), a[!a.isBid() ? "amountForSale" : "amountToReceive"]().getAmount({real: true})]];
} else {
final[0][1] = final[0][1] + a[!a.isBid() ? "amountForSale" : "amountToReceive"]().getAmount({real: true});
return final;
}
}, null);
if (!this.feedPrice.inverted) {
flat_settles.unshift([0, flat_settles[0][1]]);
} else {
flat_settles.push([flat_asks[flat_asks.length-1][0], flat_settles[0][1]]);
}
}
// Assign to store variables
this.marketData.flatAsks = flat_asks;
this.marketData.flatBids = flat_bids;
this.marketData.flatCalls = flat_calls;
this.marketData.flatSettles = flat_settles;
this.totals = {
bid: totalBids,
ask: totalAsks,
call: totalCalls
};
}
_calcMarketStats(history, baseAsset, quoteAsset, recent, market) {
let yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
yesterday = yesterday.getTime();
let volumeBase = 0,
volumeQuote = 0,
change = 0,
last = {close_quote: null, close_base: null},
invert,
latestPrice,
noTrades = true;
if (history.length) {
let first;
history.forEach((bucket, i) => {
let date = new Date(bucket.key.open + "+00:00").getTime();
if (date > yesterday) {
noTrades = false;
if (!first) {
first = history[i > 0 ? i - 1 : i];
invert = first.key.base === baseAsset.get("id");
}
if (invert) {
volumeBase += parseInt(bucket.base_volume, 10);
volumeQuote += parseInt(bucket.quote_volume, 10);
} else {
volumeQuote += parseInt(bucket.base_volume, 10);
volumeBase += parseInt(bucket.quote_volume, 10);
}
}
});
if (!first) {
first = history[0];
}
last = history[history.length -1];
let open, close;
if (invert) {
open = utils.get_asset_price(first.open_quote, quoteAsset, first.open_base, baseAsset, invert);
close = utils.get_asset_price(last.close_quote, quoteAsset, last.close_base, baseAsset, invert);
} else {
open = utils.get_asset_price(first.open_quote, baseAsset, first.open_base, quoteAsset, invert);
close = utils.get_asset_price(last.close_quote, baseAsset, last.close_base, quoteAsset, invert);
}
change = noTrades ? 0 : Math.round(10000 * (close - open) / open) / 100;
if (!isFinite(change) || isNaN(change)) {
change = 0;
}
}
if (recent && recent.length && recent.length > 1) {
let order = recent[1].op;
let paysAsset, receivesAsset, isAsk = false;
if (order.pays.asset_id === baseAsset.get("id")) {
paysAsset = baseAsset;
receivesAsset = quoteAsset;
isAsk = true;
} else {
paysAsset = quoteAsset;
receivesAsset = baseAsset;
}
let flipped = baseAsset.get("id").split(".")[2] > quoteAsset.get("id").split(".")[2];
latestPrice = market_utils.parse_order_history(order, paysAsset, receivesAsset, isAsk, flipped).full;
}
let price;
if (last.close_base && last.close_quote) {
let invert = last.key.base !== baseAsset.get("id");
let base = new Asset({amount: last[invert ? "close_quote" : "close_base"], asset_id: last.key[invert ? "quote" : "base"], precision: baseAsset.get("precision")});
let quote = new Asset({amount: last[!invert ? "close_quote" : "close_base"], asset_id: last.key[!invert ? "quote" : "base"], precision: quoteAsset.get("precision")});
price = new Price({base, quote});
}
let close = last.close_base && last.close_quote ? {
quote: {
amount: invert ? last.close_quote : last.close_base,
asset_id: invert ? last.key.quote : last.key.base
},
base: {
amount: invert ? last.close_base : last.close_quote,
asset_id: invert ? last.key.base : last.key.quote
}
} : null;
let volumeBaseAsset = new Asset({amount: volumeBase, asset_id: baseAsset.get("id"), precision: baseAsset.get("precision")});
let volumeQuoteAsset = new Asset({amount: volumeQuote, asset_id: quoteAsset.get("id"), precision: quoteAsset.get("precision")});
volumeBase = utils.get_asset_amount(volumeBase, baseAsset);
volumeQuote = utils.get_asset_amount(volumeQuote, quoteAsset);
let coreVolume = volumeBaseAsset.asset_id === "1.3.0" ? volumeBaseAsset.getAmount({real: true}) :
volumeQuoteAsset.asset_id === "1.3.0" ? volumeQuoteAsset.getAmount({real: true}) : null;
let usdVolume = !!coreVolume ? null : volumeBaseAsset.asset_id === "1.3.121" ? volumeBaseAsset.getAmount({real: true}) :
volumeQuoteAsset.asset_id === "1.3.121" ? volumeQuoteAsset.getAmount({real: true}) : null;
let btcVolume = (!!coreVolume || !!usdVolume) ? null : (volumeBaseAsset.asset_id === "1.3.861" || volumeBaseAsset.asset_id === "1.3.103") ? volumeBaseAsset.getAmount({real: true}) :
(volumeQuoteAsset.asset_id === "1.3.861" || volumeQuoteAsset.asset_id === "1.3.103") ? volumeQuoteAsset.getAmount({real: true}) : null;
if (market) {
if ((coreVolume && coreVolume <= 1000) || (usdVolume && usdVolume < 10) || (btcVolume && btcVolume < 0.01) || !Math.floor(volumeBase * 100)) {
this.lowVolumeMarkets = this.lowVolumeMarkets.set(market, true);
// console.log("lowVolume:", market, coreVolume, usdVolume, btcVolume, volumeBase);
} else {
this.lowVolumeMarkets = this.lowVolumeMarkets.delete(market);
/* Clear both market directions from the list */
let invertedMarket = market.split("_");
this.lowVolumeMarkets = this.lowVolumeMarkets.delete(invertedMarket[1] + "_" + invertedMarket[0]);
}
marketStorage.set("lowVolumeMarkets", this.lowVolumeMarkets.toJS());
}
return {
change: change.toFixed(2),
volumeBase,
volumeQuote,
close: close,
latestPrice,
price,
volumeBaseAsset,
volumeQuoteAsset
};
}
onGetMarketStats(payload) {
if (payload) {
let stats = this._calcMarketStats(payload.history, payload.base, payload.quote, payload.last, payload.market);
this.allMarketStats = this.allMarketStats.set(payload.market, stats);
}
}
onSettleOrderUpdate(result) {
this.updateSettleOrders(result);
}
updateSettleOrders(result) {
if (result.settles && result.settles.length) {
const assets = {
[this.quoteAsset.get("id")]: {precision: this.quoteAsset.get("precision")},
[this.baseAsset.get("id")]: {precision: this.baseAsset.get("precision")}
};
this.marketSettleOrders = this.marketSettleOrders.clear();
result.settles.forEach(settle => {
// let key = settle.owner + "_" + settle.balance.asset_id;
settle.settlement_date = new Date(settle.settlement_date);
this.marketSettleOrders = this.marketSettleOrders.add(
new SettleOrder(settle, assets, this.quoteAsset.get("id"), this.feedPrice, this.bitasset_options)
);
});
}
}
}
export default alt.createStore(MarketsStore, "MarketsStore");
|
export const LOGIN_REQUEST = 'LOGIN_REQUEST';
export function loginRequest(returnPath = '/') {
return {
type: LOGIN_REQUEST,
returnPath,
};
}
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export function loginSuccess(idToken, idTokenExpiry) {
return {
type: LOGIN_SUCCESS,
idToken,
idTokenExpiry,
};
}
export const LOGIN_FAILURE = 'LOGIN_FAILURE';
export function loginFailure(error) {
return {
type: LOGIN_FAILURE,
error,
};
}
export const LOGOUT = 'LOGOUT';
export function logout() {
return {
type: LOGOUT,
};
}
|
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module', './aui/polyfills/placeholder', './aui/banner', './aui/button', './aui/checkbox-multiselect', './aui/dialog2', './aui/expander', './aui/flag', './aui/form-validation', './aui/label', './aui/progress-indicator', './aui/progressive-data-set', './aui/query-input', './aui/restful-table', './aui/result-set', './aui/results-list', './aui/select', './aui/select2', './aui/sidebar', './aui/spin', './aui/tables-sortable', './aui/tipsy', './aui/toggle', './aui/tooltip', './aui/trigger', './aui/truncating-progressive-data-set'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module, require('./aui/polyfills/placeholder'), require('./aui/banner'), require('./aui/button'), require('./aui/checkbox-multiselect'), require('./aui/dialog2'), require('./aui/expander'), require('./aui/flag'), require('./aui/form-validation'), require('./aui/label'), require('./aui/progress-indicator'), require('./aui/progressive-data-set'), require('./aui/query-input'), require('./aui/restful-table'), require('./aui/result-set'), require('./aui/results-list'), require('./aui/select'), require('./aui/select2'), require('./aui/sidebar'), require('./aui/spin'), require('./aui/tables-sortable'), require('./aui/tipsy'), require('./aui/toggle'), require('./aui/tooltip'), require('./aui/trigger'), require('./aui/truncating-progressive-data-set'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod, global.placeholder, global.banner, global.button, global.checkboxMultiselect, global.dialog2, global.expander, global.flag, global.formValidation, global.label, global.progressIndicator, global.progressiveDataSet, global.queryInput, global.restfulTable, global.resultSet, global.resultsList, global.select, global.select2, global.sidebar, global.spin, global.tablesSortable, global.tipsy, global.toggle, global.tooltip, global.trigger, global.truncatingProgressiveDataSet);
global.auiExperimental = mod.exports;
}
})(this, function (exports, module, _auiPolyfillsPlaceholder, _auiBanner, _auiButton, _auiCheckboxMultiselect, _auiDialog2, _auiExpander, _auiFlag, _auiFormValidation, _auiLabel, _auiProgressIndicator, _auiProgressiveDataSet, _auiQueryInput, _auiRestfulTable, _auiResultSet, _auiResultsList, _auiSelect, _auiSelect2, _auiSidebar, _auiSpin, _auiTablesSortable, _auiTipsy, _auiToggle, _auiTooltip, _auiTrigger, _auiTruncatingProgressiveDataSet) {
'use strict';
module.exports = window.AJS;
});
//# sourceMappingURL=../js/aui-experimental.js.map
|
// let and const
(function() {
'use strict';
class PersonClass {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayName() {
return `Hello, my name is ${this.name}`;
}
}
const jimHalpert = new PersonClass('Jim Halpert', 30);
console.log(jimHalpert.sayName()); // "Jim Halpert"
function PersonFunc(name, age) {
this.name = name;
this.age = age;
}
PersonFunc.prototype.sayName = function() {
return `Hello, my name is ${this.name}`;
}
const michaelScott = new PersonFunc('Michael Scott', 45);
console.log(michaelScott.sayName()); // "Michael Scott"
}());
|
module.exports = require('./lib/swagger/main');
|
import messageTypes from 'ringcentral-integration/enums/messageTypes';
export default {
addLog: 'Log',
editLog: 'Editar log',
viewDetails: 'Exibir detalhes',
addEntity: 'Criar novo',
call: 'Chamada',
conversation: 'Conversa',
groupConversation: 'Conversa em grupo',
text: 'Texto',
voiceMessage: 'Mensagens de voz',
[messageTypes.voiceMail]: 'Correio de voz',
mark: 'Marcar como não lido',
unmark: 'Marcar como lido',
delete: 'Excluir',
faxSent: 'Fax enviado',
faxReceived: 'Fax recebido',
pages: 'páginas',
preview: 'Exibir',
download: 'Baixar',
};
// @key: @#@"addLog"@#@ @source: @#@"Log"@#@
// @key: @#@"editLog"@#@ @source: @#@"Edit Log"@#@
// @key: @#@"viewDetails"@#@ @source: @#@"View Details"@#@
// @key: @#@"addEntity"@#@ @source: @#@"Create New"@#@
// @key: @#@"call"@#@ @source: @#@"Call"@#@
// @key: @#@"text"@#@ @source: @#@"Text"@#@
// @key: @#@"conversation"@#@ @source: @#@"Conversation"@#@
// @key: @#@"groupConversation"@#@ @source: @#@"Group Conversation"@#@
// @key: @#@"voiceMessage"@#@ @source: @#@"Voice message"@#@
// @key: @#@"[messageTypes.voiceMail]"@#@ @source: @#@"Voice Mail"@#@
// @key: @#@"mark"@#@ @source: @#@"Mark as Unread"@#@
// @key: @#@"unmark"@#@ @source: @#@"Mark as Read"@#@
// @key: @#@"delete"@#@ @source: @#@"Delete"@#@
// @key: @#@"faxSent"@#@ @source: @#@"Fax sent"@#@
// @key: @#@"faxReceived"@#@ @source: @#@"Fax received"@#@
// @key: @#@"pages"@#@ @source: @#@"pages"@#@
// @key: @#@"preview"@#@ @source: @#@"View"@#@
// @key: @#@"download"@#@ @source: @#@"Download"@#@
|
'use strict';
module.exports = {
client: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/paperkit/assets/css/ct-paper.css',
'public/paperkit/assets/css/demo.css',
'public/paperkit/assets/css/examples.css',
'public/lib/angular-spinkit/build/angular-spinkit.min.css',
'public/lib/jqcloud2/dist/jqcloud.min.css'
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-messages/angular-messages.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
'public/lib/angular-file-upload/angular-file-upload.js',
'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
'public/paperkit/assets/js/jquery-1.10.2.js',
'public/paperkit/assets/js/jquery-ui-1.10.4.custom.min.js',
'public/paperkit/bootstrap3/js/bootstrap.js',
'public/paperkit/assets/js/ct-paper-checkbox.js',
'public/lib/angular-spinkit/build/angular-spinkit.min.js',
'public/lib/chart.js/dist/Chart.min.js',
'public/lib/angular-chart.js/dist/angular-chart.min.js',
'public/lib/jqcloud2/dist/jqcloud.min.js',
'public/lib/angular-jqcloud/angular-jqcloud.js'
],
tests: ['public/lib/angular-mocks/angular-mocks.js']
},
css: [
'modules/*/client/css/*.css'
],
less: [
'modules/*/client/less/*.less'
],
sass: [
'modules/*/client/scss/*.scss'
],
js: [
'modules/core/client/app/config.js',
'modules/core/client/app/init.js',
'modules/*/client/*.js',
'modules/*/client/**/*.js'
],
views: ['modules/*/client/views/**/*.html'],
templates: ['build/templates.js']
},
server: {
gruntConfig: 'gruntfile.js',
gulpConfig: 'gulpfile.js',
allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'],
models: 'modules/*/server/models/**/*.js',
routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'],
sockets: 'modules/*/server/sockets/**/*.js',
config: 'modules/*/server/config/*.js',
policies: 'modules/*/server/policies/*.js',
views: 'modules/*/server/views/*.html'
}
};
|
import React from 'react';
import { Router } from 'react-router';
var SearchGithub = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
getRef: function(ref) {
this.usernameRef = ref;
},
handleSubmit: function () {
var username = this.usernameRef.value;
this.usernameRef.value = '';
this.context.router.push('/profile/' + username);
},
render: function() {
return (
<div className="col-sm-12">
<form onSubmit={this.handleSubmit}>
<div className="form-group col-sm-7">
<input type="text" className="form-control" ref={this.getRef} />
</div>
<div className="form-group col-sm-5">
<button type="submit" className="btn btn-block btn-primary">Search Github</button>
</div>
</form>
</div>
)
}
});
module.exports = SearchGithub;
|
!function(a,b){define("$rndrSorters",[],function(){return a.rndr.plugins.sorters=b()})}(this,function(){return new Map});
//# sourceMappingURL=sorters.min.js.map
|
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
PartyAllot = mongoose.model('PartyAllot');
/**
* Globals
*/
var user, partyAllot;
/**
* Unit tests
*/
describe('Party allot Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function() {
partyAllot = new PartyAllot({
name: 'Party allot Name',
user: user
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
return partyAllot.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without name', function(done) {
partyAllot.name = '';
return partyAllot.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
PartyAllot.remove().exec();
User.remove().exec();
done();
});
});
|
/**
* @ignore
* dd support for kissy
* @author yiminghe@gmail.com
*/
KISSY.add(function (S,require) {
var DDM = require('dd/ddm'),
Draggable = require('dd/draggable'),
DraggableDelegate = require('dd/draggable-delegate'),
DroppableDelegate = require('dd/droppable-delegate'),
Droppable = require('dd/droppable');
var DD = {
Draggable: Draggable,
DDM: DDM,
Droppable: Droppable,
DroppableDelegate: DroppableDelegate,
DraggableDelegate: DraggableDelegate
};
KISSY.DD = DD;
return DD;
});
|
var test = require('tape'),
parse = require('../src/parse'),
evaluate = require('../src/evaluate'),
Environment = require('../src/environment'),
Closure = require('../src/closure');
// This part is all about defining and using functions.
// We'll start by implementing the `lambda` form which is used to create
// function closures.
test('lambda evaluates to lambda', function(t) {
// The lambda form should evaluate to a Closure
t.plan(1);
var ast = ['lambda', [], 42];
t.ok(evaluate(ast) instanceof Closure);
});
test('lambda closure keeps defining env', function(t) {
// The closure should keep a copy of the environment where it was defined.
// Once we start calling functions later, we'll need access to the
// environment from when the function was created in order to resolve all
// free variables.
t.plan(1);
var env = new Environment({ foo: 1, bar: 2 });
var ast = ['lambda', [], 42];
t.equals(evaluate(ast, env).env, env);
});
test('lambda closure holds function', function(t) {
// The closure contains the parameter list and function body too.
t.plan(2);
var closure = evaluate(parse('(lambda (x y) (+ x y))'));
t.looseEquals(closure.params, [new String('x'), new String('y')]);
t.looseEquals(closure.body, [new String('+'), new String('x'),
new String('y')]);
});
test('lambda arguments are list', function(t) {
// The parameters of a `lambda` should be a list.
t.plan(1);
var closure = evaluate(parse('(lambda (x y) (+ x y))'));
t.ok(Array.isArray(closure.params));
});
test('lambda number of arguments', function(t) {
// The `lambda` form should expect exactly two arguments.
t.plan(1);
t.throws(function() {
evaluate(parse('(lambda (foo) (bar) (baz))'));
}, /Malformed lambda, too many arguments/);
});
test('lambda variable nubmber of arguments', function(t) {
t.plan(1);
var closure = evaluate(parse('(lambda args (length args))'));
t.ok(closure.params instanceof String);
});
test('lambda fails on invalid argument definition', function(t) {
t.plan(1);
t.throws(function() {
evaluate(parse('(lambda 55 (body of fn))'));
}, /Closure argument must be a list or symbol/);
});
test('defining lambda with error in body', function(t) {
// The function body should not be evaluated when the lambda is defined.
// The call to `lambda` should return a function closure holding, among
// other things the function body. The body should not be evaluated before
// the function is called.
t.plan(1);
var ast = parse('(lambda (x y) (function body ((that would never) work)))');
t.ok(evaluate(ast) instanceof Closure);
});
// Now that we have the `lambda` form implemented, let's see if we can call
// some functions.
// When evaluating ASTs which are lists, if the first element isn't one of the
// special forms we have been working with so far, it is a function call.
// The first element of the list is the function, and the rest of the elements
// are arguments.
test('evaluating call to closure', function(t) {
// The first case we'll handle is when the AST is a list with an actual
// closure as the first element.
// In this first test, we'll start with a closure with no arguments and no
// free variables. All we need to do is to evaluate and return the function
// body.
t.plan(1);
var closure = evaluate(parse('(lambda () (+ 1 2))'));
t.equals(evaluate([closure]), 3);
});
test('evaluating call to closure with arguments', function(t) {
// The function body must be evaluated in an environment where the
// parameters are bound.
// Create an environment where the function parameters (which are stored
// in the closure) are bound to the actual argument values in the function
// call. Use this environment when evaluating the function body.
t.plan(1);
var env = new Environment({});
var closure = evaluate(parse('(lambda (a b) (+ a b))'), env);
t.equals(evaluate([closure, 4, 5], env), 9);
});
test('evaluating call to closure with variable list of arguments', function(t) {
t.plan(1);
var env = new Environment();
var closure = evaluate(parse('(lambda args (+ (head args) (head (tail args))))'), env);
t.equals(evaluate([closure, 4, 5], env), 9);
});
test('call to function should evaluate arguments', function(t) {
// Call to function should evaluate all arguments.
// When a function is applied, the arguments should be evaluated before
// being bound to the parameter names.
t.plan(1);
var env = new Environment();
var closure = evaluate(parse('(lambda (a) (+ a 5))'), env);
var ast = [closure, parse('(if #f 0 (+ 10 10))')];
t.equals(evaluate(ast, env), 25);
});
test('evaluating call to closure with free variables', function(t) {
// The body should be evaluated in the environment from the closure.
// The function's free variables, i.e. those not specified as part of the
// parameter list, should be looked up in the environment from where the
// function was defined. This is the environment included in the closure.
// Make sure this environment is used when evaluating the body.
t.plan(1);
var closure = evaluate(parse('(lambda (x) (+ x y))'),
new Environment({ y: 1 }));
var ast = [closure, 0];
t.equals(evaluate(ast, new Environment({ y: 2 })), 1);
});
// Okay, now we're able to evaluate ASTs with closures as the first element.
// But normally the closures don't just happen to be there all by themselves.
// Generally we'll find some expression, evaluate it to a closure, and then
// evaluate a new AST with the closure just like we did above.
// (some-exp arg1 arg2 ...) -> (closure arg1 arg2 ...) -> result-of-function-call
test('calling very simple function in environment', function(t) {
// A call to a symbol corresponds to a call to its value in the environment.
// When a symbol is the first element of the AST list, it is resolved to its
// value in the environment (which should be a function closure). An AST
// with the variables replaced with its value should then be
// evaluated instead.
t.plan(2);
var env = new Environment();
evaluate(parse('(define add (lambda (x y) (+ x y)))'), env);
t.ok(env.lookup('add') instanceof Closure);
t.equals(evaluate(parse('(add 1 2)'), env), 3);
});
test('calling lambda directly', function(t) {
// It should be possible to define and call functions directly.
// A lambda definition in the call position of an AST should be evaluated,
// and then evaluated as before.
t.plan(1);
t.equals(evaluate(parse('((lambda (x) x) 42)'), new Environment()), 42);
});
test('calling complex expression which evaluates to function', function(t) {
// Actually, all ASTs that are not atoms should be evaluated and then
// called. In this test, a call is done to the if-expression. The `if`
// should be evaluated, which will result in a `lambda` expression.
// The lambda is evaluated, giving a closure. The result is an AST with a
// `closure` as the first element, which we already know how to evaluate.
t.plan(1);
var ast = parse('((if #f\
wont-evaluate-this-branch\
(lambda (x) (+ x y)))\
2)');
t.equals(evaluate(ast, new Environment({ y: 3 })), 5);
});
// Now that we have the happy cases working, let's see what should happen when
// function calls are done incorrectly.
test('calling atom raises exception', function(t) {
// A function call to a non-function should result in an error
t.plan(2);
t.throws(function() {
evaluate(parse("(#t 'foo 'bar)"), new Environment());
}, /not a function/);
t.throws(function() {
evaluate(parse('(42)'), new Environment());
}, /not a function/);
});
test('test make sure arguments to functions are evaluated', function(t) {
// The arguments passed to functions should be evaluated
// We should accept parameters that are produced through function
// calls.
t.plan(1);
t.equals(evaluate(parse('((lambda (x) x) (+ 1 2))'), new Environment()), 3);
});
test('calling with wrong number of arguments', function(t) {
// Functions should raise exceptions when called with wrong number of arguments.
t.plan(1);
var env = new Environment();
evaluate(parse("(define fn (lambda (p1 p2) 'whatever))"), env);
t.throws(function() {
evaluate(parse('(fn 1 2 3)'), env);
}, /Wrong number of arguments, expected 2 got 3/);
});
// One final test to see that recursive functions are working as expected.
// The good news: this should already be working by now :)
test('calling function recursively', function(t) {
// Tests that a named function is included in the environment
// where it is evaluated.
t.plan(2);
var env = new Environment();
evaluate(parse("(define my-fn\n\
;; A meaningless, but recursive, function\n\
(lambda (x)\n\
(if (eq x 0)\n\
42\n\
(my-fn (- x 1)))))"), env);
t.equals(evaluate(parse('(my-fn 0)'), env), 42);
t.equals(evaluate(parse('(my-fn 10)'), env), 42);
});
|
'use strict';
const request = require('request');
const pairs = [
'btc_usd',
'ltc_usd',
'ltc_btc',
'eth_usd',
'eth_btc',
'etc_btc',
'etc_usd',
'rrt_usd',
'rrt_btc',
'zec_usd',
'zec_btc',
'xmr_usd',
'xmr_btc',
'dsh_usd',
'dsh_btc',
'bcc_btc',
'bcu_btc',
'bcc_usd',
'bcu_usd',
'xrp_usd',
'xrp_btc',
'iot_usd',
'iot_btc'
];
module.exports = {
pairs,
ticker: (pair) => {
return new Promise((resolve, reject) => {
if(pairs.includes(pair)) {
const k = pair.split('_');
let bitfinex_pair;
bitfinex_pair = k.map((e) => { return e; }).join('');
request({
url: `https://api.bitfinex.com/v1/ticker/${bitfinex_pair}`,
timeout: 2000
}, (err, res, body) => {
if(!err && res.statusCode === 200) {
const x = JSON.parse(body);
console.log(x);
resolve({
exchange: 'bitfinex',
pair: pair,
timestamp: x.timestamp,
ask: parseFloat(x.ask),
bid: parseFloat(x.bid)
});
}
else {
resolve({
exchange: 'bitfinex',
pair: pair,
timestamp: undefined,
ask: undefined,
bid: undefined
});
}
});
}
else {
reject('pair is not supported');
}
});
}
};
|
// all common routines
let Common = require('./common.js')
const {parse, stringify} = require('flatted/cjs')
let tables = {}
TableMap = {
/*
* persistent schema for "next" future event
*/
set (tableId = null, schema = null, tableName = null) {
if (
tableId !== null
) {
tables[tableId] = {
schema: schema,
tableName: tableName
}
// Common.log('tablemap set tables['+ tableId +']: ' + stringify(tables[tableId], null, 2))
return tables[tableId]
}
},
/*
* persistent table for "next" future event
*/
get (tableId = null) {
let table = {
schema: null,
tableName: null
}
if (
tableId !== null
) {
table = tables[tableId]
}
// Common.log('tablemap get tableId: '+ tableId +', table: ' + stringify(table, null, 2))
return table
}
}
module.exports = TableMap
|
/**
* Created by jf on 15/12/10.
*/
"use strict";
import React from 'react';
import { ButtonArea,
Button,
Cells,
CellsTitle,
CellsTips,
Cell,
CellHeader,
CellBody,
CellFooter,
Form,
FormCell,
Icon,
Input,
Label,
TextArea,
Switch,
Radio,
Checkbox,
Select,
Uploader,
Toast,
Dialog
} from '../../../../../index';
const {Alert} = Dialog;
var Sentry = require('react-sentry');
import Page from '../../../components/page/index';
import './index.less';
export default React.createClass( {
mixins: [Sentry],
contextTypes: {
dataStore: React.PropTypes.object.isRequired,
router: React.PropTypes.object.isRequired
},
getInitialState(){
return {
loading:false,
pics:[],
note:"",
toast_title:"完成",
toast_show:false,
toastTimer:null,
showAlert:false,
alert: {
title: '',
buttons: [
{
label: '关闭',
onClick: this.hideAlert
}
]
}
}
},
onUploadChange(file,e){
let pics = this.state.pics;
pics.push({
url:file.data,
onRemove:(idx)=>{
let {pics} = this.state
pics = pics.filter((file,key)=>{
return idx !== key;
});
this.setState({pics});
}
});
this.setState({
pics
});
},
hideAlert() {
this.setState({showAlert: false});
},
componentDidMount(){
Utils.set_site_title("交任务");
},
doVerify(){
let {alert} = this.state;
if(this.state.pics.length == 0){
alert.title = "请先上传图片";
this.setState({
alert,
showAlert:true
});
return;
}
//if(this.state.note.length == 0){
// alert.title = "备注不能为空";
// this.setState({
// alert,
// showAlert:true
// });
// return;
//}
let $mession_id = this.props.params.id;
let $task_key = this.props.params.key;
let pics = [];
this.state.pics.map(pic=>{
pics.push(pic.url)
});
let $note = this.state.note;
this.setState({
loading:true
});
this.context.dataStore.do_verify($mession_id,$task_key,pics.join("|"),$note,(result,error)=>{
if(error){
//alert(result);
}else{
this.state.toastTimer = setTimeout(()=> {
this.setState({toast_show: false});
this.context.router.push("/mission/detail/" + this.props.params.id);
}, 1500);
this.setState({
loading:false,
toast_show:true,
toast_title:"提交成功"
});
}
})
},
componentWillUnmount() {
this.state.toastTimer && clearTimeout(this.state.toastTimer);
},
renderDetail(){
return (
<div>
<Form>
<FormCell>
<CellBody>
<Uploader
title="审核图片上传"
maxCount={6}
files={this.state.pics}
onError={msg => alert(msg)}
onChange={this.onUploadChange}
/>
</CellBody>
</FormCell>
<CellsTitle>备注</CellsTitle>
<FormCell>
<CellBody>
<TextArea valu={this.state.note} onChange={e=>{this.setState({note:e.target.value})}} placeholder="请输入备注" rows="3" maxlength="200" />
</CellBody>
</FormCell>
<div style={{margin:"16px 20px"}}>
<Button onClick={this.doVerify}>提交</Button>
</div>
</Form>
</div>
)
},
render() {
let detail = this.renderDetail();
return (
<Page className="mission-detail" goBack={()=>{
this.context.router.push("/mission/detail/"+this.props.params.id);
}} title="提交审核">
{detail}
<Toast icon="loading" show={this.state.loading}>提交中...</Toast>
<Toast show={this.state.toast_show}>{this.state.toast_title}</Toast>
<Alert title={this.state.alert.title} buttons={this.state.alert.buttons} show={this.state.showAlert} />
</Page>
);
}
});
|
module.exports = {
//'database': process.env.MONGOLAB_URI || 'mongodb://whatsapptonight:whatsapptonight@127.0.0.1:27017/whatsapptonight'
};
|
const init = (mongo_url) => new Promise((resolve, reject) => {
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
mongoose.connect(mongo_url, {
server: {
auto_reconnect: true,
reconnectTries: Number.MAX_VLUE,
reconnectInterval: 1000,
}
})
const connection = mongoose.connection
connection.on('error', (err) => {
// TODO : Handle error
if (err.message.code === 'ETIMEDOUT') {
debug.error(err)
// mongoose.createConnection(mongo_url)
}
reject(err)
})
connection.once('open', () => {
debug.info(`MongoDB : ${mongo_url}`)
resolve(mongoose)
})
})
module.exports = init
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new mongoose.Schema({
username: String,
password: String, //hash created from password
created_at: {type: Date, default: Date.now}
});
var postSchema = new mongoose.Schema({
created_by: {type: Schema.ObjectId, ref: 'User'},
created_at: {type: Date, default: Date.now},
text: String
});
mongoose.model('Post', postSchema);
mongoose.model('User', userSchema);
|
import React, {Component, PropTypes} from 'react'
import {Link} from 'react-router'
import style from './style.css'
import ReactFireMixin from 'reactfire'
let Challenge = React.createClass({
mixins: [ReactFireMixin],
propTypes: {
children: PropTypes.node,
user: PropTypes.object
},
getInitialState() {
return {
challenge: {}
}
},
componentDidMount() {
let ref = firebase.database().ref('challenges/' + this.props.params.challenge_id);
this.bindAsObject(ref, 'challenge');
},
render() {
setTimeout(function() {
console.log(this.state.challenge)
}.bind(this), 2000)
return (
<div>
<h1>{this.state.challenge.name}</h1>
<h2>{this.state.challenge.desc}</h2>
<input type="file" accept="image/*" capture="camera" id="file-upload" />
</div>
)
}
});
export default Challenge;
|
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var aurelia_dependency_injection_1 = require('aurelia-dependency-injection');
var utils_1 = require('marvelous-aurelia-core/utils');
var constants_1 = require('./constants');
var all_1 = require('./all');
// TODO: allow to create a global ComponentRegistration in the plugin configuration
var ComponentsArray = (function (_super) {
__extends(ComponentsArray, _super);
function ComponentsArray(container) {
_super.call(this);
this.componentsToBeDisplayed = {};
this.container = container;
}
ComponentsArray.prototype.init = function (grid) {
var _this = this;
this.grid = grid;
// stops all components instances on grid detach
var detached = this.grid.internals.subscribe('Detached', function () {
_this.forEach(function (x) {
x.getAllInstances().forEach(function (i) {
if (i.stop && i.stop instanceof Function) {
i.stop();
}
});
});
detached();
});
// add user defined components
// TODO: use OptionsReader so that it could be in the DOM
var customComponents = this.grid.options.codeBased.components || [];
customComponents.forEach(function (x) { return _this.add(x, false); });
// add default components
// these components then internally will specify
// whether are enabled or disabled
this.add(new ComponentRegistration({
name: 'm-filter-row',
type: all_1.FilterRowComponent,
view: './components/filter-row/filter-row.html',
position: constants_1.componentPosition.afterColumns,
layout: constants_1.componentLayout.forEachColumn
}), false);
this.add(new ComponentRegistration({
name: 'm-pagination',
type: all_1.PaginationComponent,
view: './components/pagination/pagination.html',
position: constants_1.componentPosition.footer,
layout: constants_1.componentLayout.full
}), false);
this.add(new ComponentRegistration({
name: 'm-toolbox',
type: all_1.ToolboxComponent,
view: './components/toolbox/toolbox.html',
position: constants_1.componentPosition.top,
layout: constants_1.componentLayout.full
}), false);
this.add(new ComponentRegistration({
name: 'm-grouping',
type: all_1.GroupingComponent,
view: './components/grouping/grouping.html',
position: constants_1.componentPosition.top,
layout: constants_1.componentLayout.full
}), false);
this.add(new ComponentRegistration({
name: 'm-query-language',
type: all_1.QueryLanguageComponent,
view: './components/query-language/query-language.html',
position: constants_1.componentPosition.afterColumns,
layout: constants_1.componentLayout.full
}), false);
this.add(new ComponentRegistration({
name: 'm-sorting',
type: all_1.SortingComponent,
position: constants_1.componentPosition.background
}), false);
this.add(new ComponentRegistration({
name: 'm-column-chooser',
type: all_1.ColumnChooserComponent,
view: './components/column-chooser/column-chooser.html',
position: constants_1.componentPosition.background
}), false);
this.add(new ComponentRegistration({
name: 'm-column-reordedring',
type: all_1.ColumnReorderingComponent,
position: constants_1.componentPosition.background
}), false);
this.add(new ComponentRegistration({
name: 'm-selection',
type: all_1.SelectionComponent,
position: constants_1.componentPosition.background
}));
this.forEach(function (x) { return x._load(); });
};
ComponentsArray.prototype.add = function (component, autoLoad) {
var _this = this;
if (autoLoad === void 0) { autoLoad = true; }
if (!(component instanceof ComponentRegistration)) {
throw new Error('Given component has to be an instance of Component type.');
}
this._checkNameUniqueness(component.name);
component._init(this.grid, this.container, function () { _this.refreshComponentsToBeDisplayed(); });
this.push(component);
if (autoLoad) {
component._load();
}
};
ComponentsArray.prototype._checkNameUniqueness = function (name) {
if (this.filter(function (x) { return x.name == name; }).length > 0) {
throw new Error("Component named as '" + name + "' is already defined.");
}
};
ComponentsArray.prototype.get = function (type) {
var components = this.filter(function (x) { return x.type === type; });
if (!components.length) {
return undefined;
}
return components[0];
};
ComponentsArray.prototype.getAllInstances = function () {
var instances = [];
this.forEach(function (component) {
if (component.instance) {
instances.push({
component: component,
instance: component.instance
});
}
if (component.instances) {
component.instances.forEach(function (x) {
instances.push({
component: component,
instance: x
});
});
}
});
return instances;
};
/**
* Invokes action for each instance with defined given method.
*/
ComponentsArray.prototype.forEachInstanceWithMethod = function (method, action) {
this.getAllInstances().forEach(function (x) {
if (x.instance && x.instance[method] instanceof Function) {
action(x);
}
});
};
ComponentsArray.prototype.refreshComponentsToBeDisplayed = function () {
var _this = this;
this.componentsToBeDisplayed = {};
// only enabled and with attached view are displayed on the screen
this.filter(function (x) { return x.enabled !== false && x.view; })
.forEach(function (x) {
_this.componentsToBeDisplayed[x.position] = _this.componentsToBeDisplayed[x.position] || [];
_this.componentsToBeDisplayed[x.position].push(x);
});
};
ComponentsArray = __decorate([
aurelia_dependency_injection_1.transient(),
aurelia_dependency_injection_1.inject(aurelia_dependency_injection_1.Container)
], ComponentsArray);
return ComponentsArray;
}(Array));
exports.ComponentsArray = ComponentsArray;
var ComponentRegistration = (function () {
function ComponentRegistration(component) {
this.type = undefined;
this.position = undefined;
this.view = undefined;
this.instance = undefined;
this.instances = undefined;
this.layout = undefined;
//order;
this.name = undefined;
this.enabled = false;
this._onEnabledChanged = utils_1.Utils.noop;
this._loaded = false;
if (!component.name) {
throw new Error("Component needs to declare its own name.");
}
var missingField = false;
if (component.position == constants_1.componentPosition.background) {
if (utils_1.Utils.allDefined(component, 'type') === false) {
missingField = true;
}
}
else if (utils_1.Utils.allDefined(component, 'type', 'position', 'view') === false) {
missingField = true;
}
if (missingField) {
throw new Error('Component is missing at least one required field.');
}
for (var variable in this) {
if (component[variable] !== undefined) {
this[variable] = component[variable];
}
}
if (component.position != constants_1.componentPosition.background) {
// default component layout is `full`, but only if component is not the background one
this.layout = this.layout || constants_1.componentLayout.full;
}
}
ComponentRegistration.prototype._init = function (grid, container, onEnabledChanged) {
this._onEnabledChanged = onEnabledChanged || this._onEnabledChanged;
this._grid = grid;
this._container = container;
};
ComponentRegistration.prototype._load = function () {
var _this = this;
if (this._loaded) {
return;
}
this._loaded = true;
this._createInstances();
switch (this.layout) {
case constants_1.componentLayout.forEachColumn:
this._grid.options.columns.forEach(function (x) {
var instance = _this.instances.get(x);
_this.enable(false);
});
break;
default:
var instance = this.instance;
this.enable(false);
break;
}
};
/**
* Enables the component.
*/
ComponentRegistration.prototype.enable = function (force) {
if (force === void 0) { force = true; }
this._ensureLoaded();
if (this.enabled) {
return;
}
for (var _i = 0, _a = this.getAllInstances(); _i < _a.length; _i++) {
var instance = _a[_i];
if (instance.tryEnable && instance.tryEnable instanceof Function) {
if (instance.tryEnable()) {
this.enabled = true;
}
else if (force && instance.start && instance.start instanceof Function) {
instance.start();
this.enabled = true;
}
if (this.enabled) {
this._onEnabledChanged();
}
}
}
};
/**
* Disables the component.
*/
ComponentRegistration.prototype.disable = function () {
this._ensureLoaded();
if (this.enabled == false) {
return;
}
for (var _i = 0, _a = this.getAllInstances(); _i < _a.length; _i++) {
var instance = _a[_i];
if (instance.disable && instance.disable instanceof Function) {
instance.disable();
this.enabled = false;
this._onEnabledChanged();
}
}
};
/**
* Gets all instances associated with current component.
*/
ComponentRegistration.prototype.getAllInstances = function () {
var instances = [];
if (this.instance) {
instances.push(this.instance);
}
else if (this.instances) {
this.instances.forEach(function (instance) { return instances.push(instance); });
}
return instances;
};
ComponentRegistration.prototype._ensureLoaded = function () {
if (this._loaded) {
return;
}
this._load();
};
/**
* Creates view models. Depending on the layout it may create a single view model
* or view models for each column.
*/
ComponentRegistration.prototype._createInstances = function () {
var _this = this;
switch (this.layout) {
case constants_1.componentLayout.forEachColumn:
// Creates instance for each column using column object reference as a key.
this.instances = new Map();
this._grid.options.columns.forEach(function (x) { return _this.instances.set(x, _this._resolveInstance(x)); });
break;
default:
this.instance = this._resolveInstance();
break;
}
};
ComponentRegistration.prototype._resolveInstance = function (column) {
if (column === void 0) { column = undefined; }
if (column) {
return this._grid.internals.getInstance(this.type, [column]);
}
return this._grid.internals.getInstance(this.type);
};
return ComponentRegistration;
}());
exports.ComponentRegistration = ComponentRegistration;
var GridComponent = (function () {
function GridComponent() {
this.subs = [];
}
/**
* Creates options and starts the component with `start` method.
* @returns boolean
*/
GridComponent.prototype.tryEnable = function () {
this.options = this.createOptions();
if (!this.options) {
return false;
}
this.start();
return true;
};
/**
* Called if component is about to disable.
*/
GridComponent.prototype.disable = function () {
this.stop();
};
/**
* Starts the component. Uses already created options if needed.
*/
GridComponent.prototype.start = function () {
};
/**
* Unregisters subs. Called on grid detach.
*/
GridComponent.prototype.stop = function () {
if (this.subs) {
this.subs.forEach(function (sub) { return sub(); });
this.subs = [];
}
};
/**
* In derived class creates component specific options. If `enable` method is not overriden
* then this method has to return object castable to `true` in order to make component enabled.
*/
GridComponent.prototype.createOptions = function () {
return {};
};
/**
* Saves the current state of a component so that it could be loaded some time in the future.
* This method should attach properties to the `state` parameter.
*/
GridComponent.prototype.saveState = function (state) {
};
/**
* Loads state.
*/
GridComponent.prototype.loadState = function (state) {
};
return GridComponent;
}());
exports.GridComponent = GridComponent;
|
(function () {
var controllerId = 'app.views.entries.create';
angular.module('app').controller(controllerId, [
'$rootScope',
'$scope',
'abp.services.mgmt.entry',
'$compile',
'$stateParams',
'$location',
function ($rootScope, $scope, entryService, $compile, $stateParams, $location) {
var vm = this;
vm.entry = {};
vm.pageform = undefined;
vm.save = function () {
entryService.createEntry(vm.entry).success(function () {
$location.path("entries");
});
};
}
]);
})();
|
import {
moduleFor,
test
} from 'ember-qunit';
moduleFor('route:trivia/index', 'TriviaIndexRoute', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
test('it exists', function() {
var route = this.subject();
ok(route);
});
|
/**
* Main JS file for Casper behaviours
*/
/*globals jQuery, document */
(function ($) {
"use strict";
$(document).ready(function(){
// On the home page, move the blog icon inside the header
// for better relative/absolute positioning.
//$("#blog-logo").prependTo("#site-head-content");
$("code.ghost-prism").each(function(index, element){
// Elementlerimizi ve verilerimizi toplayalım.
var $code = $(element),
$pre = $code.parent("pre"),
data = $code.data(),
html = $code.html().trim(),
classList = "";
// Prism Lang belittiysek class'ımızı oluşturalım ve ekleyelim.
if(data.prismLang) classList += " language-"+data.prismLang;
// Prism Line-Numbers belirttiysek class'ımızı ekleyelim.
if(data.prismLinenumbers === "true") classList += " line-numbers";
// Prism Line Higlight belirttiysek direkt olark attribute'muzu atayalım.
if(data.prismLinehighlight) $pre.attr("data-line", data.prismLinehighlight);
// Class listemizi ekleyelim.
$pre.addClass(classList);
// Markdown formatı sonlarda gereksiz yeni satırlar yaratabiliyor, bu nedenle trim edilmiş yeni html'imizi aktaralım.
$code.html(html);
// Çift çağrılara karşı "ghost-prism" class'ımızı silelim.
$code.removeClass("ghost-prism");
// Prism API'ımızı tetikleyelim.
Prism.highlightAll();
});
});
}(jQuery));
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import NavContainer from '../../common/containers/NavContainer';
import DynamicSliderContainer from '../../common/containers/DynamicSliderContainer';
import FooterContainer from '../../common/containers/FooterContainer';
// include actions as they are needed by each component
// they are called via dispatch()
const propTypes = {
dispatch: PropTypes.func,
content: PropTypes.object
};
// in here, we determine the props to be passed down to the specific component needed
class AppContainer extends Component {
componentDidMount () {
const { dispatch, componentContent } = this.props;
}
render () {
return (
<div>
<NavContainer />
<DynamicSliderContainer />
<FooterContainer />
</div>
);
}
}
AppContainer.propTypes = propTypes;
function mapStateToProps(state) {
const componentContent = state.content.project.components;
return {
componentContent
};
}
export default connect(mapStateToProps)(AppContainer);
|
'use strict';
var mongoose = require('mongoose');
var path = require('path');
var Schema = mongoose.Schema;
var jqUploads = require(path.join(__dirname, '../..'));
var ApplicantSchema = new Schema({
surname: {type: String, required: true, index: true},
forename: {type: String, index: true},
photo: {type: [new Schema(jqUploads.FileSchema)], form: {directive: 'fng-jq-upload-form', add: {sizeLimit: 50000000}}},
status: {type: String, default: 'Pending', enum: ['Pending', 'Rejected', 'Shortlist']}
});
var Applicant;
try {
Applicant = mongoose.model('Applicant');
} catch (e) {
Applicant = mongoose.model('Applicant', ApplicantSchema);
}
module.exports = Applicant;
|
Template.header.helpers({
isAdmin: function () {
return Meteor.user() && Meteor.user().username == 'Supervisor';
}
});
Template.header.events({
'click #logout-button': function(e,t) {
e.preventDefault();
Meteor.logout();
Router.go('daysList');
}
});
|
//
// Responsible file to do some issues dynamically that is common for all JS files
//
function get_important_data(data){
return {
"status": data["status"],
"statusText": data["statusText"],
"responseText": data["responseText"],
"extra": "extra" in data ? data["extra"] : "",
};
}
function get_tornado_cookie(name) {
// http://www.tornadoweb.org/en/stable/guide/security.html
var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
return r ? r[1] : undefined;
}
// other functions
function require(script) {
//
// Responsible function to ...
//
// Args:
// Nothing until the moment
//
// Returns:
// Nothing until the moment
//
// Raises:
// Nothing until the moment
//
// require("/static/not_own/FileSaver/FileSaver.js");
$.ajax({
url: script,
dataType: "script",
async: false, // <-- This is the key
success: function () {
// all good...
},
error: function () {
throw new Error("Could not load script " + script);
}
});
}
String.prototype.capitalizeFirstLetter = function() {
//
// Responsible function to ...
//
// Args:
// Nothing until the moment
//
// Returns:
// Nothing until the moment
//
// Raises:
// Nothing until the moment
//
// Insert the function capitalizeFirstLetter for all strings existents
return this.charAt(0).toUpperCase() + this.slice(1);
}
String.prototype.replaceAt = function(index, char) {
var a = this.split("");
a[index] = char;
return a.join("");
}
String.prototype.isNumber = function (){
// int
if(this.match(/^\d+$/))
return true;
// float
if(this.match(/^\d+\.\d+$/))
return true;
return false;
}
function isInteger(n){
return Number(n) === n && n % 1 === 0;
}
function isFloat(n){
return Number(n) === n && n % 1 !== 0;
}
function remove_underscore_and_capitalize_first_letter(word){
//
// Responsible function to ...
//
// Args:
// Nothing until the moment
//
// Returns:
// Nothing until the moment
//
// Raises:
// Nothing until the moment
//
// replace all ocurrences of "_" to " "
return word.replace(/_/g, " ").capitalizeFirstLetter();
}
function export_file(text_to_export, name_file, id){
//
// Responsible function to ...
//
// Args:
// Nothing until the moment
//
// Returns:
// Nothing until the moment
//
// Raises:
// Nothing until the moment
//
var a_link = $("#" + id)[0];
a_link.href = window.URL.createObjectURL(
new Blob(
[text_to_export],
{type: 'text/plain;charset=utf-8;'}
)
);
a_link.download = name_file;
}
function export_file_csv(text_to_export, name_file, id){
//
// Responsible function to ...
//
// Args:
// Nothing until the moment
//
// Returns:
// Nothing until the moment
//
// Raises:
// Nothing until the moment
//
var a_link = $("#" + id)[0];
a_link.href = window.URL.createObjectURL(
new Blob(
[text_to_export],
{type: "data:text/csv;charset=utf-8,"}
)
);
a_link.download = name_file;
}
function get_formated_date(date){
//
// Responsible function to ...
//
// Args:
// Nothing until the moment
//
// Returns:
// Nothing until the moment
//
// Raises:
// Nothing until the moment
//
var day = date.slice(0,2),
month = date.slice(2,4),
year = date.slice(4,8);
var new_date = new Date(month + "/" + day + "/" + year);
var monthNames = ["jan.", "fev.", "mar.", "abr.", "mai.", "jun.", "jul.", "ago.", "set.", "out.", "nov.", "dez."];
var day = new_date.getDate();
var monthIndex = new_date.getMonth();
var year = new_date.getFullYear();
if(day < 10)
day = '0' + day;
formated_date = day + " " + monthNames[monthIndex] + " " + year;
return formated_date;
}
function get_actual_date(){
//
// Responsible function to ...
//
// Args:
// Nothing until the moment
//
// Returns:
// Nothing until the moment
//
// Raises:
// Nothing until the moment
//
var today = new Date(),
dd = today.getDate(),
mm = today.getMonth() + 1, // January is 0
yyyy = today.getFullYear();
if(dd < 10)
dd = '0' + dd;
if(mm < 10)
mm = '0' + mm;
actual_date = dd + '/' + mm + '/' + yyyy;
actual_hour = today.getHours() + "h" + today.getMinutes();
return {"actual_date": actual_date, "actual_hour": actual_hour};
}
|
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
const path = require('path');
const srcPath = path.resolve(__dirname, 'src');
const distPath = path.resolve(__dirname, 'dist');
function makeTemplate(name, obj) {
const template = {
alwaysWriteToDisk: true,
inject: 'body',
filename: `${name}.html`,
template: `${srcPath}/${name}.html`,
hash: 'true',
cache: 'true',
chunks: [name],
};
return Object.assign({}, template, obj);
}
module.exports = {
entry: {
index: `${srcPath}/index.js`,
},
output: {
filename: '[name].js',
path: distPath,
publicPath: '/',
},
module: {
rules: [{
test: /\.js$/,
include: /(src)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'stage-0', 'react'],
},
},
}, {
test: /\.svg/,
use: [{
loader: 'url-loader',
options: {
stripdeclarations: true,
},
}],
}, {
test: /(\.scss)$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
}, {
loader: 'css-loader',
options: {
sourceMap: true,
modules: true,
importLoaders: 1,
localIdentName: '[local]___[hash:base64:5]',
minimize: true,
},
}, {
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
}],
},
devServer: {
hot: true,
port: 3000,
contentBase: 'dist',
},
devtool: 'source-map',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin(makeTemplate('index')),
new HtmlWebpackHarddiskPlugin({
outputPath: distPath,
}),
new CopyWebpackPlugin([{
from: `${srcPath}/assets`,
to: `${distPath}/assets`,
}]),
],
};
|
/**
* Created by TAM on 4/17/2016.
*/
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
target: 'web',
devServer: {
contentBase: './build',
hot: true,
port: 8080,
publicPath: '/',
historyApiFallback: true
},
devtool: 'source-map',
context: path.join(__dirname, 'src'),
entry: {
core: ['./core']
},
output: {
filename: '[name].[hash].js',
path: path.join(__dirname, 'build'),
publicPath: '/'
},
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loaders: ['react-hot', 'babel'],
exclude: /node_modules/
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader'],
exclude: /.*bootstrap\.css/
},
{
test: /.*bootstrap\.css/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
},
{
test: /\.(ttf|woff|woff2|svg|eot)$/,
loader: 'file-loader'
},
{
test: /\.(png|jpg|jpeg|gif)$/,
loader: 'url-loader'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
title: 'Your app title here',
inject: true,
template: path.join(__dirname, 'src/index.html'),
mobile: true
}),
new ExtractTextPlugin('bootstrap.css')
]
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.