code
stringlengths 2
1.05M
|
---|
$(document).ready(function() {
$('#logout-button').click(function(e) {
console.log('you like that dont you');
$.ajax({
type: 'POST',
url: '/api/processLogout',
data: {},
success: function(data) {
if (data.success) {
window.location.href = '/';
}
}
});
});
$('#header-create-review-btn, #create-review-btn, #modal-overlay, #modal-close').click(function() {
var elementHref = $(this).parent().attr('href') || $(this).attr('href') || '';
if (elementHref.length === 0) {
toggleReviewModal();
}
});
$('#game-search').on('input', function() {
var search = document.getElementById('game-search').value;
$('#modal-window li').each(function(i, e) {
if ($(e).text().toLowerCase().indexOf(search.toLowerCase()) > -1) {
console.log($(e).text());
$(e).css({
'display': 'block'
});
}
else {
$(e).css({
'display': 'none'
});
}
});
});
var modalShow = false;
var toggleReviewModal = function() {
if (!modalShow) {
$('#modal-overlay').css({
'display': 'block'
});
$('#modal-window').css({
'display': 'block'
});
setTimeout(function() {
$('#modal-overlay').addClass('show');
$('#modal-window').addClass('show');
},10);
//$('#game-search').focus();
modalShow = true;
}
else {
$('#modal-overlay').removeClass('show');
$('#modal-window').removeClass('show');
setTimeout(function() {
$('#modal-overlay').css({
'display': 'none'
});
$('#modal-window').css({
'display': 'none'
});
},160); // 10ms + animation time
modalShow = false;
}
};
});
|
const _ = require('lodash'),
Promise = require('bluebird'),
validator = require('validator'),
ObjectId = require('bson-objectid'),
ghostBookshelf = require('./base'),
baseUtils = require('./base/utils'),
common = require('../lib/common'),
security = require('../lib/security'),
imageLib = require('../lib/image'),
pipeline = require('../lib/promise/pipeline'),
validation = require('../data/validation'),
permissions = require('../services/permissions'),
activeStates = ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4'],
/**
* inactive: owner user before blog setup, suspended users
* locked user: imported users, they get a random passport
*/
inactiveStates = ['inactive', 'locked'],
allStates = activeStates.concat(inactiveStates);
let User, Users;
User = ghostBookshelf.Model.extend({
tableName: 'users',
defaults: function defaults() {
return {
password: security.identifier.uid(50),
visibility: 'public',
status: 'active'
};
},
emitChange: function emitChange(event, options) {
const eventToTrigger = 'user' + '.' + event;
ghostBookshelf.Model.prototype.emitChange.bind(this)(this, eventToTrigger, options);
},
/**
* @TODO:
*
* The user model does not use bookshelf-relations yet.
* Therefor we have to remove the relations manually.
*/
onDestroying(model, options) {
ghostBookshelf.Model.prototype.onDestroying.apply(this, arguments);
return (options.transacting || ghostBookshelf.knex)('roles_users')
.where('user_id', model.id)
.del();
},
onDestroyed: function onDestroyed(model, options) {
ghostBookshelf.Model.prototype.onDestroyed.apply(this, arguments);
if (_.includes(activeStates, model.previous('status'))) {
model.emitChange('deactivated', options);
}
model.emitChange('deleted', options);
},
onCreated: function onCreated(model, attrs, options) {
ghostBookshelf.Model.prototype.onCreated.apply(this, arguments);
model.emitChange('added', options);
// active is the default state, so if status isn't provided, this will be an active user
if (!model.get('status') || _.includes(activeStates, model.get('status'))) {
model.emitChange('activated', options);
}
},
onUpdated: function onUpdated(model, response, options) {
ghostBookshelf.Model.prototype.onUpdated.apply(this, arguments);
model.statusChanging = model.get('status') !== model.previous('status');
model.isActive = _.includes(activeStates, model.get('status'));
if (model.statusChanging) {
model.emitChange(model.isActive ? 'activated' : 'deactivated', options);
} else {
if (model.isActive) {
model.emitChange('activated.edited', options);
}
}
model.emitChange('edited', options);
},
isActive: function isActive() {
return activeStates.indexOf(this.get('status')) !== -1;
},
isLocked: function isLocked() {
return this.get('status') === 'locked';
},
isInactive: function isInactive() {
return this.get('status') === 'inactive';
},
/**
* Lookup Gravatar if email changes to update image url
* Generating a slug requires a db call to look for conflicting slugs
*/
onSaving: function onSaving(newPage, attr, options) {
var self = this,
tasks = [],
passwordValidation = {};
ghostBookshelf.Model.prototype.onSaving.apply(this, arguments);
/**
* Bookshelf call order:
* - onSaving
* - onValidate (validates the model against the schema)
*
* Before we can generate a slug, we have to ensure that the name is not blank.
*/
if (!this.get('name')) {
throw new common.errors.ValidationError({
message: common.i18n.t('notices.data.validation.index.valueCannotBeBlank', {
tableName: this.tableName,
columnKey: 'name'
})
});
}
// If the user's email is set & has changed & we are not importing
if (self.hasChanged('email') && self.get('email') && !options.importing) {
tasks.gravatar = (function lookUpGravatar() {
return imageLib.gravatar.lookup({
email: self.get('email')
}).then(function (response) {
if (response && response.image) {
self.set('profile_image', response.image);
}
});
})();
}
if (this.hasChanged('slug') || !this.get('slug')) {
tasks.slug = (function generateSlug() {
return ghostBookshelf.Model.generateSlug(
User,
self.get('slug') || self.get('name'),
{
status: 'all',
transacting: options.transacting,
shortSlug: !self.get('slug')
})
.then(function then(slug) {
self.set({slug: slug});
});
})();
}
/**
* CASE: add model, hash password
* CASE: update model, hash password
*
* Important:
* - Password hashing happens when we import a database
* - we do some pre-validation checks, because onValidate is called AFTER onSaving
* - when importing, we set the password to a random uid and don't validate, just hash it and lock the user
* - when importing with `importPersistUser` we check if the password is a bcrypt hash already and fall back to
* normal behaviour if not (set random password, lock user, and hash password)
* - no validations should run, when importing
*/
if (self.hasChanged('password')) {
this.set('password', String(this.get('password')));
// CASE: import with `importPersistUser` should always be an bcrypt password already,
// and won't re-hash or overwrite it.
// In case the password is not bcrypt hashed we fall back to the standard behaviour.
if (options.importPersistUser && this.get('password').match(/^\$2[ayb]\$.{56}$/i)) {
return;
}
if (options.importing) {
// always set password to a random uid when importing
this.set('password', security.identifier.uid(50));
// lock users so they have to follow the password reset flow
if (this.get('status') !== 'inactive') {
this.set('status', 'locked');
}
} else {
// CASE: we're not importing data, run the validations
passwordValidation = validation.validatePassword(this.get('password'), this.get('email'));
if (!passwordValidation.isValid) {
return Promise.reject(new common.errors.ValidationError({
message: passwordValidation.message
}));
}
}
tasks.hashPassword = (function hashPassword() {
return security.password.hash(self.get('password'))
.then(function (hash) {
self.set('password', hash);
});
})();
}
return Promise.props(tasks);
},
toJSON: function toJSON(unfilteredOptions) {
var options = User.filterOptions(unfilteredOptions, 'toJSON'),
attrs = ghostBookshelf.Model.prototype.toJSON.call(this, options);
// remove password hash for security reasons
delete attrs.password;
delete attrs.ghost_auth_access_token;
// NOTE: We don't expose the email address for for external, app and public context.
// @TODO: Why? External+Public is actually the same context? Was also mentioned here https://github.com/TryGhost/Ghost/issues/9043
// @TODO: move to api serialization when we drop v0.1
if (!options || !options.context || (!options.context.user && !options.context.internal && (!options.context.api_key || options.context.api_key.type === 'content'))) {
delete attrs.email;
}
// @TODO remove this when we remove v0.1 API as its handled in serialization for v2
// We don't expose these fields when fetching data via the public API.
if (options && options.context && options.context.public) {
delete attrs.created_at;
delete attrs.created_by;
delete attrs.updated_at;
delete attrs.updated_by;
delete attrs.last_seen;
delete attrs.status;
delete attrs.ghost_auth_id;
}
return attrs;
},
format: function format(options) {
if (!_.isEmpty(options.website) &&
!validator.isURL(options.website, {
require_protocol: true,
protocols: ['http', 'https']
})) {
options.website = 'http://' + options.website;
}
return ghostBookshelf.Model.prototype.format.call(this, options);
},
posts: function posts() {
return this.hasMany('Posts', 'created_by');
},
sessions: function sessions() {
return this.hasMany('Sessions');
},
roles: function roles() {
return this.belongsToMany('Role');
},
permissions: function permissions() {
return this.belongsToMany('Permission');
},
hasRole: function hasRole(roleName) {
var roles = this.related('roles');
return roles.some(function getRole(role) {
return role.get('name') === roleName;
});
},
updateLastSeen: function updateLastSeen() {
this.set({last_seen: new Date()});
return this.save();
},
enforcedFilters: function enforcedFilters(options) {
if (options.context && options.context.internal) {
return null;
}
return options.context && options.context.public ? 'status:[' + allStates.join(',') + ']' : null;
},
defaultFilters: function defaultFilters(options) {
if (options.context && options.context.internal) {
return null;
}
return options.context && options.context.public ? null : 'status:[' + allStates.join(',') + ']';
},
/**
* You can pass an extra `status=VALUES` field.
* Long-Term: We should deprecate these short cuts and force users to use the filter param.
*/
extraFilters: function extraFilters(options) {
if (!options.status) {
return null;
}
let filter = null;
// CASE: Check if the incoming status value is valid, otherwise fallback to "active"
if (options.status !== 'all') {
options.status = allStates.indexOf(options.status) > -1 ? options.status : 'active';
}
if (options.status === 'active') {
filter = `status:[${activeStates}]`;
} else if (options.status === 'all') {
filter = `status:[${allStates}]`;
} else {
filter = `status:${options.status}`;
}
delete options.status;
return filter;
}
}, {
orderDefaultOptions: function orderDefaultOptions() {
return {
last_seen: 'DESC',
name: 'ASC',
created_at: 'DESC'
};
},
/**
* Returns an array of keys permitted in a method's `options` hash, depending on the current method.
* @param {String} methodName The name of the method to check valid options for.
* @return {Array} Keys allowed in the `options` hash of the model's method.
*/
permittedOptions: function permittedOptions(methodName, options) {
var permittedOptionsToReturn = ghostBookshelf.Model.permittedOptions.call(this, methodName),
// whitelists for the `options` hash argument on methods, by method name.
// these are the only options that can be passed to Bookshelf / Knex.
validOptions = {
findOne: ['withRelated', 'status'],
setup: ['id'],
edit: ['withRelated', 'importPersistUser'],
add: ['importPersistUser'],
findPage: ['status'],
findAll: ['filter']
};
if (validOptions[methodName]) {
permittedOptionsToReturn = permittedOptionsToReturn.concat(validOptions[methodName]);
}
// CASE: The `withRelated` parameter is allowed when using the public API, but not the `roles` value.
// Otherwise we expose too much information.
// @TODO: the target controller should define the allowed includes, but not the model layer O_O (https://github.com/TryGhost/Ghost/issues/10106)
if (options && options.context && options.context.public) {
if (options.withRelated && options.withRelated.indexOf('roles') !== -1) {
options.withRelated.splice(options.withRelated.indexOf('roles'), 1);
}
}
return permittedOptionsToReturn;
},
/**
* ### Find One
*
* We have to clone the data, because we remove values from this object.
* This is not expected from outside!
*
* @TODO: use base class
*
* @extends ghostBookshelf.Model.findOne to include roles
* **See:** [ghostBookshelf.Model.findOne](base.js.html#Find%20One)
*/
findOne: function findOne(dataToClone, unfilteredOptions) {
var options = this.filterOptions(unfilteredOptions, 'findOne'),
query,
status,
data = _.cloneDeep(dataToClone),
lookupRole = data.role;
// Ensure only valid fields/columns are added to query
if (options.columns) {
options.columns = _.intersection(options.columns, this.prototype.permittedAttributes());
}
delete data.role;
data = _.defaults(data || {}, {
status: 'all'
});
status = data.status;
delete data.status;
data = this.filterData(data);
// Support finding by role
if (lookupRole) {
options.withRelated = _.union(options.withRelated, ['roles']);
query = this.forge(data);
query.query('join', 'roles_users', 'users.id', '=', 'roles_users.user_id');
query.query('join', 'roles', 'roles_users.role_id', '=', 'roles.id');
query.query('where', 'roles.name', '=', lookupRole);
} else {
query = this.forge(data);
}
if (status === 'active') {
query.query('whereIn', 'status', activeStates);
} else if (status !== 'all') {
query.query('where', {status: status});
}
return query.fetch(options);
},
/**
* ### Edit
*
* Note: In case of login the last_seen attribute gets updated.
*
* @extends ghostBookshelf.Model.edit to handle returning the full object
* **See:** [ghostBookshelf.Model.edit](base.js.html#edit)
*/
edit: function edit(data, unfilteredOptions) {
var options = this.filterOptions(unfilteredOptions, 'edit'),
self = this,
ops = [];
if (data.roles && data.roles.length > 1) {
return Promise.reject(
new common.errors.ValidationError({
message: common.i18n.t('errors.models.user.onlyOneRolePerUserSupported')
})
);
}
if (data.email) {
ops.push(function checkForDuplicateEmail() {
return self.getByEmail(data.email, options).then(function then(user) {
if (user && user.id !== options.id) {
return Promise.reject(new common.errors.ValidationError({
message: common.i18n.t('errors.models.user.userUpdateError.emailIsAlreadyInUse')
}));
}
});
});
}
ops.push(function update() {
return ghostBookshelf.Model.edit.call(self, data, options).then((user) => {
var roleId;
if (!data.roles) {
return user;
}
roleId = data.roles[0].id || data.roles[0];
return user.roles().fetch().then((roles) => {
// return if the role is already assigned
if (roles.models[0].id === roleId) {
return;
}
return ghostBookshelf.model('Role').findOne({id: roleId});
}).then((roleToAssign) => {
if (roleToAssign && roleToAssign.get('name') === 'Owner') {
return Promise.reject(
new common.errors.ValidationError({
message: common.i18n.t('errors.models.user.methodDoesNotSupportOwnerRole')
})
);
} else {
// assign all other roles
return user.roles().updatePivot({role_id: roleId});
}
}).then(() => {
options.status = 'all';
return self.findOne({id: user.id}, options);
}).then((model) => {
model._changed = user._changed;
return model;
});
});
});
return pipeline(ops);
},
/**
* ## Add
* Naive user add
* Hashes the password provided before saving to the database.
*
* We have to clone the data, because we remove values from this object.
* This is not expected from outside!
*
* @param {object} dataToClone
* @param {object} unfilteredOptions
* @extends ghostBookshelf.Model.add to manage all aspects of user signup
* **See:** [ghostBookshelf.Model.add](base.js.html#Add)
*/
add: function add(dataToClone, unfilteredOptions) {
var options = this.filterOptions(unfilteredOptions, 'add'),
self = this,
data = _.cloneDeep(dataToClone),
userData = this.filterData(data),
roles;
// check for too many roles
if (data.roles && data.roles.length > 1) {
return Promise.reject(new common.errors.ValidationError({
message: common.i18n.t('errors.models.user.onlyOneRolePerUserSupported')
}));
}
function getAuthorRole() {
return ghostBookshelf.model('Role').findOne({name: 'Author'}, _.pick(options, 'transacting'))
.then(function then(authorRole) {
return [authorRole.get('id')];
});
}
/**
* We need this default author role because of the following Ghost feature:
* You setup your blog and you can invite people instantly, but without choosing a role.
* roles: [] -> no default role (used for owner creation, see fixtures.json)
* roles: undefined -> default role
*/
roles = data.roles;
delete data.roles;
return ghostBookshelf.Model.add.call(self, userData, options)
.then(function then(addedUser) {
// Assign the userData to our created user so we can pass it back
userData = addedUser;
})
.then(function () {
if (!roles) {
return getAuthorRole();
}
return Promise.resolve(roles);
})
.then(function (_roles) {
roles = _roles;
// CASE: it is possible to add roles by name, by id or by object
if (_.isString(roles[0]) && !ObjectId.isValid(roles[0])) {
return Promise.map(roles, function (roleName) {
return ghostBookshelf.model('Role').findOne({
name: roleName
}, options);
}).then(function (roleModels) {
roles = [];
_.each(roleModels, function (roleModel) {
roles.push(roleModel.id);
});
});
}
return Promise.resolve();
})
.then(function () {
return baseUtils.attach(User, userData.id, 'roles', roles, options);
})
.then(function then() {
// find and return the added user
return self.findOne({id: userData.id, status: 'all'}, options);
});
},
destroy: function destroy(unfilteredOptions) {
const options = this.filterOptions(unfilteredOptions, 'destroy', {extraAllowedProperties: ['id']});
const destroyUser = () => {
return ghostBookshelf.Model.destroy.call(this, options);
};
if (!options.transacting) {
return ghostBookshelf.transaction((transacting) => {
options.transacting = transacting;
return destroyUser();
});
}
return destroyUser();
},
/**
* We override the owner!
* Owner already has a slug -> force setting a new one by setting slug to null
* @TODO: kill setup function?
*/
setup: function setup(data, unfilteredOptions) {
var options = this.filterOptions(unfilteredOptions, 'setup'),
self = this,
userData = this.filterData(data),
passwordValidation = {};
passwordValidation = validation.validatePassword(userData.password, userData.email, data.blogTitle);
if (!passwordValidation.isValid) {
return Promise.reject(new common.errors.ValidationError({
message: passwordValidation.message
}));
}
userData.slug = null;
return self.edit(userData, options);
},
/**
* Right now the setup of the blog depends on the user status.
* Only if the owner user is `inactive`, then the blog is not setup.
* e.g. if you transfer ownership to a locked user, you blog is still setup.
*
* @TODO: Rename `inactive` status to something else, it's confusing. e.g. requires-setup
* @TODO: Depending on the user status results in https://github.com/TryGhost/Ghost/issues/8003
*/
isSetup: function isSetup(options) {
return this.getOwnerUser(options)
.then(function (owner) {
return owner.get('status') !== 'inactive';
});
},
getOwnerUser: function getOwnerUser(options) {
options = options || {};
return this.findOne({
role: 'Owner',
status: 'all'
}, options).then(function (owner) {
if (!owner) {
return Promise.reject(new common.errors.NotFoundError({
message: common.i18n.t('errors.models.user.ownerNotFound')
}));
}
return owner;
});
},
permissible: function permissible(userModelOrId, action, context, unsafeAttrs, loadedPermissions, hasUserPermission, hasAppPermission, hasApiKeyPermission) {
var self = this,
userModel = userModelOrId,
origArgs;
// If we passed in a model without its related roles, we need to fetch it again
if (_.isObject(userModelOrId) && !_.isObject(userModelOrId.related('roles'))) {
userModelOrId = userModelOrId.id;
}
// If we passed in an id instead of a model get the model first
if (_.isNumber(userModelOrId) || _.isString(userModelOrId)) {
// Grab the original args without the first one
origArgs = _.toArray(arguments).slice(1);
// Get the actual user model
return this.findOne({
id: userModelOrId,
status: 'all'
}, {withRelated: ['roles']}).then(function then(foundUserModel) {
if (!foundUserModel) {
throw new common.errors.NotFoundError({
message: common.i18n.t('errors.models.user.userNotFound')
});
}
// Build up the original args but substitute with actual model
var newArgs = [foundUserModel].concat(origArgs);
return self.permissible.apply(self, newArgs);
});
}
if (action === 'edit') {
// Users with the role 'Editor', 'Author', and 'Contributor' have complex permissions when the action === 'edit'
// We now have all the info we need to construct the permissions
if (context.user === userModel.get('id')) {
// If this is the same user that requests the operation allow it.
hasUserPermission = true;
} else if (loadedPermissions.user && userModel.hasRole('Owner')) {
// Owner can only be edited by owner
hasUserPermission = loadedPermissions.user && _.some(loadedPermissions.user.roles, {name: 'Owner'});
} else if (loadedPermissions.user && _.some(loadedPermissions.user.roles, {name: 'Editor'})) {
// If the user we are trying to edit is an Author or Contributor, allow it
hasUserPermission = userModel.hasRole('Author') || userModel.hasRole('Contributor');
}
}
if (action === 'destroy') {
// Owner cannot be deleted EVER
if (userModel.hasRole('Owner')) {
return Promise.reject(new common.errors.NoPermissionError({
message: common.i18n.t('errors.models.user.notEnoughPermission')
}));
}
// Users with the role 'Editor' have complex permissions when the action === 'destroy'
if (loadedPermissions.user && _.some(loadedPermissions.user.roles, {name: 'Editor'})) {
// Alternatively, if the user we are trying to edit is an Author, allow it
hasUserPermission = context.user === userModel.get('id') || userModel.hasRole('Author') || userModel.hasRole('Contributor');
}
}
// CASE: can't edit my own status to inactive or locked
if (action === 'edit' && userModel.id === context.user) {
if (User.inactiveStates.indexOf(unsafeAttrs.status) !== -1) {
return Promise.reject(new common.errors.NoPermissionError({
message: common.i18n.t('errors.api.users.cannotChangeStatus')
}));
}
}
// CASE: i want to edit roles
if (action === 'edit' && unsafeAttrs.roles && unsafeAttrs.roles[0]) {
let role = unsafeAttrs.roles[0];
let roleId = role.id || role;
let editedUserId = userModel.id;
// @NOTE: role id of logged in user
let contextRoleId = loadedPermissions.user.roles[0].id;
if (roleId !== contextRoleId && editedUserId === context.user) {
return Promise.reject(new common.errors.NoPermissionError({
message: common.i18n.t('errors.api.users.cannotChangeOwnRole')
}));
}
return User.getOwnerUser()
.then((owner) => {
// CASE: owner can assign role to any user
if (context.user === owner.id) {
if (hasUserPermission && hasApiKeyPermission && hasAppPermission) {
return Promise.resolve();
}
return Promise.reject(new common.errors.NoPermissionError({
message: common.i18n.t('errors.models.user.notEnoughPermission')
}));
}
// CASE: You try to change the role of the owner user
if (editedUserId === owner.id) {
if (owner.related('roles').at(0).id !== roleId) {
return Promise.reject(new common.errors.NoPermissionError({
message: common.i18n.t('errors.api.users.cannotChangeOwnersRole')
}));
}
} else if (roleId !== contextRoleId) {
// CASE: you are trying to change a role, but you are not owner
// @NOTE: your role is not the same than the role you try to change (!)
// e.g. admin can assign admin role to a user, but not owner
return permissions.canThis(context).assign.role(role)
.then(() => {
if (hasUserPermission && hasApiKeyPermission && hasAppPermission) {
return Promise.resolve();
}
return Promise.reject(new common.errors.NoPermissionError({
message: common.i18n.t('errors.models.user.notEnoughPermission')
}));
});
}
if (hasUserPermission && hasApiKeyPermission && hasAppPermission) {
return Promise.resolve();
}
return Promise.reject(new common.errors.NoPermissionError({
message: common.i18n.t('errors.models.user.notEnoughPermission')
}));
});
}
if (hasUserPermission && hasApiKeyPermission && hasAppPermission) {
return Promise.resolve();
}
return Promise.reject(new common.errors.NoPermissionError({
message: common.i18n.t('errors.models.user.notEnoughPermission')
}));
},
// Finds the user by email, and checks the password
// @TODO: shorten this function and rename...
check: function check(object) {
var self = this;
return this.getByEmail(object.email)
.then((user) => {
if (!user) {
throw new common.errors.NotFoundError({
message: common.i18n.t('errors.models.user.noUserWithEnteredEmailAddr')
});
}
if (user.isLocked()) {
throw new common.errors.NoPermissionError({
message: common.i18n.t('errors.models.user.accountLocked')
});
}
if (user.isInactive()) {
throw new common.errors.NoPermissionError({
message: common.i18n.t('errors.models.user.accountSuspended')
});
}
return self.isPasswordCorrect({plainPassword: object.password, hashedPassword: user.get('password')})
.then(() => {
return user.updateLastSeen();
})
.then(() => {
user.set({status: 'active'});
return user.save();
});
})
.catch((err) => {
if (err.message === 'NotFound' || err.message === 'EmptyResponse') {
throw new common.errors.NotFoundError({
message: common.i18n.t('errors.models.user.noUserWithEnteredEmailAddr')
});
}
throw err;
});
},
isPasswordCorrect: function isPasswordCorrect(object) {
var plainPassword = object.plainPassword,
hashedPassword = object.hashedPassword;
if (!plainPassword || !hashedPassword) {
return Promise.reject(new common.errors.ValidationError({
message: common.i18n.t('errors.models.user.passwordRequiredForOperation')
}));
}
return security.password.compare(plainPassword, hashedPassword)
.then(function (matched) {
if (matched) {
return;
}
return Promise.reject(new common.errors.ValidationError({
context: common.i18n.t('errors.models.user.incorrectPassword'),
message: common.i18n.t('errors.models.user.incorrectPassword'),
help: common.i18n.t('errors.models.user.userUpdateError.help'),
code: 'PASSWORD_INCORRECT'
}));
});
},
/**
* Naive change password method
* @param {Object} object
* @param {Object} unfilteredOptions
*/
changePassword: function changePassword(object, unfilteredOptions) {
var options = this.filterOptions(unfilteredOptions, 'changePassword'),
self = this,
newPassword = object.newPassword,
userId = object.user_id,
oldPassword = object.oldPassword,
isLoggedInUser = userId === options.context.user,
user;
options.require = true;
return self.forge({id: userId}).fetch(options)
.then(function then(_user) {
user = _user;
if (isLoggedInUser) {
return self.isPasswordCorrect({
plainPassword: oldPassword,
hashedPassword: user.get('password')
});
}
})
.then(function then() {
return user.save({password: newPassword});
});
},
transferOwnership: function transferOwnership(object, unfilteredOptions) {
const options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'transferOwnership');
let ownerRole;
let contextUser;
return Promise.join(
ghostBookshelf.model('Role').findOne({name: 'Owner'}),
User.findOne({id: options.context.user}, {withRelated: ['roles']})
)
.then((results) => {
ownerRole = results[0];
contextUser = results[1];
// check if user has the owner role
const currentRoles = contextUser.toJSON(options).roles;
if (!_.some(currentRoles, {id: ownerRole.id})) {
return Promise.reject(new common.errors.NoPermissionError({
message: common.i18n.t('errors.models.user.onlyOwnerCanTransferOwnerRole')
}));
}
return Promise.join(ghostBookshelf.model('Role').findOne({name: 'Administrator'}),
User.findOne({id: object.id}, {withRelated: ['roles']}));
})
.then((results) => {
const adminRole = results[0];
const user = results[1];
if (!user) {
return Promise.reject(new common.errors.NotFoundError({
message: common.i18n.t('errors.models.user.userNotFound')
}));
}
const {roles: currentRoles, status} = user.toJSON(options);
if (!_.some(currentRoles, {id: adminRole.id})) {
return Promise.reject(new common.errors.ValidationError({
message: common.i18n.t('errors.models.user.onlyAdmCanBeAssignedOwnerRole')
}));
}
if (status !== 'active') {
return Promise.reject(new common.errors.ValidationError({
message: common.i18n.t('errors.models.user.onlyActiveAdmCanBeAssignedOwnerRole')
}));
}
// convert owner to admin
return Promise.join(contextUser.roles().updatePivot({role_id: adminRole.id}),
user.roles().updatePivot({role_id: ownerRole.id}),
user.id);
})
.then((results) => {
return Users.forge()
.query('whereIn', 'id', [contextUser.id, results[2]])
.fetch({withRelated: ['roles']});
});
},
// Get the user by email address, enforces case insensitivity rejects if the user is not found
// When multi-user support is added, email addresses must be deduplicated with case insensitivity, so that
// joe@bloggs.com and JOE@BLOGGS.COM cannot be created as two separate users.
getByEmail: function getByEmail(email, unfilteredOptions) {
var options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'getByEmail');
// We fetch all users and process them in JS as there is no easy way to make this query across all DBs
// Although they all support `lower()`, sqlite can't case transform unicode characters
// This is somewhat mute, as validator.isEmail() also doesn't support unicode, but this is much easier / more
// likely to be fixed in the near future.
options.require = true;
return Users.forge().fetch(options).then(function then(users) {
var userWithEmail = users.find(function findUser(user) {
return user.get('email').toLowerCase() === email.toLowerCase();
});
if (userWithEmail) {
return userWithEmail;
}
});
},
inactiveStates: inactiveStates
});
Users = ghostBookshelf.Collection.extend({
model: User
});
module.exports = {
User: ghostBookshelf.model('User', User),
Users: ghostBookshelf.collection('Users', Users)
};
|
describe('$.fn.player', function () {
'use strict';
it('is a function', function () {
$.isFunction($.fn.player).should.be.true;
});
it('can be called as a jquery plugin', function () {
var o = $('<div/>');
o.player().should.equal(o);
});
it('generates id if necessary', function () {
$('<div/>').player().attr('id').should.match(/jquery-tube-player-\d/);
});
});
|
import {
BufferAttribute,
BufferGeometry,
FileLoader,
Loader
} from './three.module.js';
var DRACOLoader = function ( manager ) {
Loader.call( this, manager );
this.decoderPath = '';
this.decoderConfig = {};
this.decoderBinary = null;
this.decoderPending = null;
this.workerLimit = 4;
this.workerPool = [];
this.workerNextTaskID = 1;
this.workerSourceURL = '';
this.defaultAttributeIDs = {
position: 'POSITION',
normal: 'NORMAL',
color: 'COLOR',
uv: 'TEX_COORD'
};
this.defaultAttributeTypes = {
position: 'Float32Array',
normal: 'Float32Array',
color: 'Float32Array',
uv: 'Float32Array'
};
};
DRACOLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: DRACOLoader,
setDecoderPath: function ( path ) {
this.decoderPath = path;
return this;
},
setDecoderConfig: function ( config ) {
this.decoderConfig = config;
return this;
},
setWorkerLimit: function ( workerLimit ) {
this.workerLimit = workerLimit;
return this;
},
/** @deprecated */
setVerbosity: function () {
console.warn( 'THREE.DRACOLoader: The .setVerbosity() method has been removed.' );
},
/** @deprecated */
setDrawMode: function () {
console.warn( 'THREE.DRACOLoader: The .setDrawMode() method has been removed.' );
},
/** @deprecated */
setSkipDequantization: function () {
console.warn( 'THREE.DRACOLoader: The .setSkipDequantization() method has been removed.' );
},
load: function ( url, onLoad, onProgress, onError ) {
var loader = new FileLoader( this.manager );
loader.setPath( this.path );
loader.setResponseType( 'arraybuffer' );
loader.setRequestHeader( this.requestHeader );
loader.setWithCredentials( this.withCredentials );
loader.load( url, ( buffer ) => {
var taskConfig = {
attributeIDs: this.defaultAttributeIDs,
attributeTypes: this.defaultAttributeTypes,
useUniqueIDs: false
};
this.decodeGeometry( buffer, taskConfig )
.then( onLoad )
.catch( onError );
}, onProgress, onError );
},
/** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
decodeDracoFile: function ( buffer, callback, attributeIDs, attributeTypes ) {
var taskConfig = {
attributeIDs: attributeIDs || this.defaultAttributeIDs,
attributeTypes: attributeTypes || this.defaultAttributeTypes,
useUniqueIDs: !! attributeIDs
};
this.decodeGeometry( buffer, taskConfig ).then( callback );
},
decodeGeometry: function ( buffer, taskConfig ) {
// TODO: For backward-compatibility, support 'attributeTypes' objects containing
// references (rather than names) to typed array constructors. These must be
// serialized before sending them to the worker.
for ( var attribute in taskConfig.attributeTypes ) {
var type = taskConfig.attributeTypes[ attribute ];
if ( type.BYTES_PER_ELEMENT !== undefined ) {
taskConfig.attributeTypes[ attribute ] = type.name;
}
}
//
var taskKey = JSON.stringify( taskConfig );
// Check for an existing task using this buffer. A transferred buffer cannot be transferred
// again from this thread.
if ( DRACOLoader.taskCache.has( buffer ) ) {
var cachedTask = DRACOLoader.taskCache.get( buffer );
if ( cachedTask.key === taskKey ) {
return cachedTask.promise;
} else if ( buffer.byteLength === 0 ) {
// Technically, it would be possible to wait for the previous task to complete,
// transfer the buffer back, and decode again with the second configuration. That
// is complex, and I don't know of any reason to decode a Draco buffer twice in
// different ways, so this is left unimplemented.
throw new Error(
'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
'settings. Buffer has already been transferred.'
);
}
}
//
var worker;
var taskID = this.workerNextTaskID ++;
var taskCost = buffer.byteLength;
// Obtain a worker and assign a task, and construct a geometry instance
// when the task completes.
var geometryPending = this._getWorker( taskID, taskCost )
.then( ( _worker ) => {
worker = _worker;
return new Promise( ( resolve, reject ) => {
worker._callbacks[ taskID ] = { resolve, reject };
worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
// this.debug();
} );
} )
.then( ( message ) => this._createGeometry( message.geometry ) );
// Remove task from the task list.
// Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
geometryPending
.catch( () => true )
.then( () => {
if ( worker && taskID ) {
this._releaseTask( worker, taskID );
// this.debug();
}
} );
// Cache the task result.
DRACOLoader.taskCache.set( buffer, {
key: taskKey,
promise: geometryPending
} );
return geometryPending;
},
_createGeometry: function ( geometryData ) {
var geometry = new BufferGeometry();
if ( geometryData.index ) {
geometry.setIndex( new BufferAttribute( geometryData.index.array, 1 ) );
}
for ( var i = 0; i < geometryData.attributes.length; i ++ ) {
var attribute = geometryData.attributes[ i ];
var name = attribute.name;
var array = attribute.array;
var itemSize = attribute.itemSize;
geometry.setAttribute( name, new BufferAttribute( array, itemSize ) );
}
return geometry;
},
_loadLibrary: function ( url, responseType ) {
var loader = new FileLoader( this.manager );
loader.setPath( this.decoderPath );
loader.setResponseType( responseType );
loader.setWithCredentials( this.withCredentials );
return new Promise( ( resolve, reject ) => {
loader.load( url, resolve, undefined, reject );
} );
},
preload: function () {
this._initDecoder();
return this;
},
_initDecoder: function () {
if ( this.decoderPending ) return this.decoderPending;
var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
var librariesPending = [];
if ( useJS ) {
librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
} else {
librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
}
this.decoderPending = Promise.all( librariesPending )
.then( ( libraries ) => {
var jsContent = libraries[ 0 ];
if ( ! useJS ) {
this.decoderConfig.wasmBinary = libraries[ 1 ];
}
var fn = DRACOLoader.DRACOWorker.toString();
var body = [
'/* draco decoder */',
jsContent,
'',
'/* worker */',
fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
].join( '\n' );
this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
} );
return this.decoderPending;
},
_getWorker: function ( taskID, taskCost ) {
return this._initDecoder().then( () => {
if ( this.workerPool.length < this.workerLimit ) {
var worker = new Worker( this.workerSourceURL );
worker._callbacks = {};
worker._taskCosts = {};
worker._taskLoad = 0;
worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
worker.onmessage = function ( e ) {
var message = e.data;
switch ( message.type ) {
case 'decode':
worker._callbacks[ message.id ].resolve( message );
break;
case 'error':
worker._callbacks[ message.id ].reject( message );
break;
default:
console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
}
};
this.workerPool.push( worker );
} else {
this.workerPool.sort( function ( a, b ) {
return a._taskLoad > b._taskLoad ? - 1 : 1;
} );
}
var worker = this.workerPool[ this.workerPool.length - 1 ];
worker._taskCosts[ taskID ] = taskCost;
worker._taskLoad += taskCost;
return worker;
} );
},
_releaseTask: function ( worker, taskID ) {
worker._taskLoad -= worker._taskCosts[ taskID ];
delete worker._callbacks[ taskID ];
delete worker._taskCosts[ taskID ];
},
debug: function () {
console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
},
dispose: function () {
for ( var i = 0; i < this.workerPool.length; ++ i ) {
this.workerPool[ i ].terminate();
}
this.workerPool.length = 0;
return this;
}
} );
/* WEB WORKER */
DRACOLoader.DRACOWorker = function () {
var decoderConfig;
var decoderPending;
onmessage = function ( e ) {
var message = e.data;
switch ( message.type ) {
case 'init':
decoderConfig = message.decoderConfig;
decoderPending = new Promise( function ( resolve/*, reject*/ ) {
decoderConfig.onModuleLoaded = function ( draco ) {
// Module is Promise-like. Wrap before resolving to avoid loop.
resolve( { draco: draco } );
};
DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
} );
break;
case 'decode':
var buffer = message.buffer;
var taskConfig = message.taskConfig;
decoderPending.then( ( module ) => {
var draco = module.draco;
var decoder = new draco.Decoder();
var decoderBuffer = new draco.DecoderBuffer();
decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
try {
var geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
var buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
if ( geometry.index ) buffers.push( geometry.index.array.buffer );
self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
} catch ( error ) {
console.error( error );
self.postMessage( { type: 'error', id: message.id, error: error.message } );
} finally {
draco.destroy( decoderBuffer );
draco.destroy( decoder );
}
} );
break;
}
};
function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
var attributeIDs = taskConfig.attributeIDs;
var attributeTypes = taskConfig.attributeTypes;
var dracoGeometry;
var decodingStatus;
var geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
if ( geometryType === draco.TRIANGULAR_MESH ) {
dracoGeometry = new draco.Mesh();
decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
} else if ( geometryType === draco.POINT_CLOUD ) {
dracoGeometry = new draco.PointCloud();
decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
} else {
throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
}
if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
}
var geometry = { index: null, attributes: [] };
// Gather all vertex attributes.
for ( var attributeName in attributeIDs ) {
var attributeType = self[ attributeTypes[ attributeName ] ];
var attribute;
var attributeID;
// A Draco file may be created with default vertex attributes, whose attribute IDs
// are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
// a Draco file may contain a custom set of attributes, identified by known unique
// IDs. glTF files always do the latter, and `.drc` files typically do the former.
if ( taskConfig.useUniqueIDs ) {
attributeID = attributeIDs[ attributeName ];
attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
} else {
attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
if ( attributeID === - 1 ) continue;
attribute = decoder.GetAttribute( dracoGeometry, attributeID );
}
geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
}
// Add index.
if ( geometryType === draco.TRIANGULAR_MESH ) {
geometry.index = decodeIndex( draco, decoder, dracoGeometry );
}
draco.destroy( dracoGeometry );
return geometry;
}
function decodeIndex( draco, decoder, dracoGeometry ) {
var numFaces = dracoGeometry.num_faces();
var numIndices = numFaces * 3;
var byteLength = numIndices * 4;
var ptr = draco._malloc( byteLength );
decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
var index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
draco._free( ptr );
return { array: index, itemSize: 1 };
}
function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
var numComponents = attribute.num_components();
var numPoints = dracoGeometry.num_points();
var numValues = numPoints * numComponents;
var byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
var dataType = getDracoDataType( draco, attributeType );
var ptr = draco._malloc( byteLength );
decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
var array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
draco._free( ptr );
return {
name: attributeName,
array: array,
itemSize: numComponents
};
}
function getDracoDataType( draco, attributeType ) {
switch ( attributeType ) {
case Float32Array: return draco.DT_FLOAT32;
case Int8Array: return draco.DT_INT8;
case Int16Array: return draco.DT_INT16;
case Int32Array: return draco.DT_INT32;
case Uint8Array: return draco.DT_UINT8;
case Uint16Array: return draco.DT_UINT16;
case Uint32Array: return draco.DT_UINT32;
}
}
};
DRACOLoader.taskCache = new WeakMap();
/** Deprecated static methods */
/** @deprecated */
DRACOLoader.setDecoderPath = function () {
console.warn( 'THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.' );
};
/** @deprecated */
DRACOLoader.setDecoderConfig = function () {
console.warn( 'THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.' );
};
/** @deprecated */
DRACOLoader.releaseDecoderModule = function () {
console.warn( 'THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.' );
};
/** @deprecated */
DRACOLoader.getDecoderModule = function () {
console.warn( 'THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.' );
};
export { DRACOLoader };
|
// Do not edit this file; automatically generated by build.py.
'use strict';
// Copyright 2012 Google Inc. Apache License 2.0
Blockly.Blocks.colour={};Blockly.Blocks.colour.HUE=20;Blockly.Blocks.colour_picker={init:function(){this.jsonInit({message0:"%1",args0:[{type:"field_colour",name:"COLOUR",colour:"#ff0000"}],output:"Colour",colour:Blockly.Blocks.colour.HUE,helpUrl:Blockly.Msg.COLOUR_PICKER_HELPURL});var a=this;this.setTooltip(function(){var b=a.getParent();return b&&b.getInputsInline()&&b.tooltip||Blockly.Msg.COLOUR_PICKER_TOOLTIP})}};
Blockly.Blocks.colour_random={init:function(){this.jsonInit({message0:Blockly.Msg.COLOUR_RANDOM_TITLE,output:"Colour",colour:Blockly.Blocks.colour.HUE,tooltip:Blockly.Msg.COLOUR_RANDOM_TOOLTIP,helpUrl:Blockly.Msg.COLOUR_RANDOM_HELPURL})}};
Blockly.Blocks.colour_rgb={init:function(){this.setHelpUrl(Blockly.Msg.COLOUR_RGB_HELPURL);this.setColour(Blockly.Blocks.colour.HUE);this.appendValueInput("RED").setCheck("Number").setAlign(Blockly.ALIGN_RIGHT).appendField(Blockly.Msg.COLOUR_RGB_TITLE).appendField(Blockly.Msg.COLOUR_RGB_RED);this.appendValueInput("GREEN").setCheck("Number").setAlign(Blockly.ALIGN_RIGHT).appendField(Blockly.Msg.COLOUR_RGB_GREEN);this.appendValueInput("BLUE").setCheck("Number").setAlign(Blockly.ALIGN_RIGHT).appendField(Blockly.Msg.COLOUR_RGB_BLUE);
this.setOutput(!0,"Colour");this.setTooltip(Blockly.Msg.COLOUR_RGB_TOOLTIP)}};
Blockly.Blocks.colour_blend={init:function(){this.setHelpUrl(Blockly.Msg.COLOUR_BLEND_HELPURL);this.setColour(Blockly.Blocks.colour.HUE);this.appendValueInput("COLOUR1").setCheck("Colour").setAlign(Blockly.ALIGN_RIGHT).appendField(Blockly.Msg.COLOUR_BLEND_TITLE).appendField(Blockly.Msg.COLOUR_BLEND_COLOUR1);this.appendValueInput("COLOUR2").setCheck("Colour").setAlign(Blockly.ALIGN_RIGHT).appendField(Blockly.Msg.COLOUR_BLEND_COLOUR2);this.appendValueInput("RATIO").setCheck("Number").setAlign(Blockly.ALIGN_RIGHT).appendField(Blockly.Msg.COLOUR_BLEND_RATIO);
this.setOutput(!0,"Colour");this.setTooltip(Blockly.Msg.COLOUR_BLEND_TOOLTIP)}};Blockly.Blocks.custom={};Blockly.Blocks.module={init:function(){this.appendDummyInput().appendField("Module").appendField(new Blockly.FieldTextInput("'id'"),"ID");this.appendStatementInput("Input").setCheck(["main","vars","funcs"]);this.setColour(330);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.main={init:function(){this.appendDummyInput().appendField("Main");this.appendStatementInput("main_method").setCheck(null);this.setPreviousStatement(!0,null);this.setColour(300);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.function_params={init:function(){this.appendValueInput("PARAMS").setCheck(null).appendField("func").appendField(new Blockly.FieldDropdown([["bool","bool"],["int","int"],["float","float"],["string","string"],["void","void"]]),"TYPE").appendField(new Blockly.FieldTextInput("id"),"ID");this.appendStatementInput("NAME").setCheck(null);this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(230);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.function_without_params={init:function(){this.appendDummyInput().appendField("func").appendField(new Blockly.FieldDropdown([["bool","bool"],["int","int"],["float","float"],["string","string"],["void","void"]]),"TYPE").appendField(new Blockly.FieldTextInput("id"),"ID");this.appendStatementInput("NAME").setCheck(null);this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(230);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.parameter_no_comma={init:function(){this.appendDummyInput().appendField(new Blockly.FieldDropdown([["bool","bool"],["int","int"],["float","float"],["string","string"]]),"TYPE").appendField(new Blockly.FieldTextInput("'name'"),"name_param");this.setOutput(!0,null);this.setColour(210);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.param_comma={init:function(){this.appendValueInput("params_with_comma").setCheck(null).appendField(new Blockly.FieldDropdown([["bool","bool"],["int","int"],["float","float"],["string","string"]]),"TYPE").appendField(new Blockly.FieldTextInput("' name' "),"name_param");this.setOutput(!0,null);this.setColour(300);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.function_call_params={init:function(){this.appendValueInput("NAME").setCheck(null).appendField(new Blockly.FieldTextInput("'functionID'"),"FUNCNAME");this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(230);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.function_call_no_param={init:function(){this.appendDummyInput().appendField(new Blockly.FieldTextInput("'functionID'"),"FUNCNAME");this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(230);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.function_return_params={init:function(){this.appendValueInput("function").setCheck(null).appendField(new Blockly.FieldTextInput("func"),"FUNC");this.setOutput(!0,null);this.setColour(330);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};Blockly.Blocks["return"]={init:function(){this.appendValueInput("RETURN").setCheck(null).appendField("Return");this.setPreviousStatement(!0,null);this.setColour(255);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.variable_definition={init:function(){this.appendDummyInput().appendField(new Blockly.FieldDropdown([["bool","bool"],["int","int"],["string","string"],["float","float"]]),"TYPE").appendField(new Blockly.FieldTextInput("id"),"ID").appendField("=").appendField(new Blockly.FieldTextInput("value"),"VALUE");this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(230);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.variable_with_comma={init:function(){this.appendValueInput("NAME").setCheck(null).appendField(new Blockly.FieldDropdown([["bool","bool"],["int","int"],["string","string"],["float","float"]]),"TYPE").appendField(new Blockly.FieldTextInput("id"),"ID").appendField("=").appendField(new Blockly.FieldTextInput("value"),"VALUE");this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(230);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.variable_comma={init:function(){this.appendValueInput("NAME").setCheck(null).appendField(new Blockly.FieldTextInput("id"),"ID").appendField("=").appendField(new Blockly.FieldTextInput("value"),"VALUE");this.setOutput(!0,null);this.setColour(230);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.variable_comma_end={init:function(){this.appendDummyInput().appendField(new Blockly.FieldTextInput("id"),"ID").appendField("=").appendField(new Blockly.FieldTextInput("value"),"VALUE");this.setOutput(!0,null);this.setColour(230);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.variable_asignation={init:function(){this.appendValueInput("NAME").setCheck(null).appendField(new Blockly.FieldTextInput("id"),"ID").appendField("=");this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(230);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.id_without_comma={init:function(){this.appendDummyInput().appendField(new Blockly.FieldTextInput("'id'"),"ID");this.setOutput(!0,null);this.setColour(330);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};Blockly.Blocks.id_with_comma={init:function(){this.appendValueInput("NAME").setCheck(null).appendField(new Blockly.FieldTextInput("id"),"ID");this.setOutput(!0,null);this.setColour(330);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.numerical_const_comma={init:function(){this.appendValueInput("CONSN").setCheck(null).appendField(new Blockly.FieldNumber(0),"NAME");this.setOutput(!0,null);this.setColour(330);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};Blockly.Blocks.numerical_const_no_comma={init:function(){this.appendDummyInput().appendField(new Blockly.FieldNumber(0),"CONSN");this.setOutput(!0,null);this.setColour(330);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.array_definition={init:function(){this.appendValueInput("NAME").setCheck(null).appendField(new Blockly.FieldDropdown([["bool","bool"],["int","int"],["string","string"],["float","float"]]),"TYPE").appendField(new Blockly.FieldTextInput("id"),"ID").appendField("[").appendField(new Blockly.FieldNumber(0,1),"SIZE").appendField("]").appendField("=");this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(225);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.array_asignation={init:function(){this.appendValueInput("NAME").setCheck(null).appendField(new Blockly.FieldTextInput("id"),"ID").appendField("[").appendField(new Blockly.FieldNumber(0,1),"PLACE").appendField("]").appendField("=");this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(225);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.array_access={init:function(){this.appendDummyInput().appendField(new Blockly.FieldTextInput("id"),"ID").appendField("[").appendField(new Blockly.FieldNumber(0,1),"SIZE").appendField("]");this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(225);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.read={init:function(){this.appendDummyInput().appendField("read").appendField(new Blockly.FieldTextInput("id"),"ID").appendField("=").appendField(new Blockly.FieldTextInput("value"),"VALUE");this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(250);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};
Blockly.Blocks.print={init:function(){this.appendValueInput("VALUE").setCheck(null).appendField("print");this.setPreviousStatement(!0,null);this.setNextStatement(!0,null);this.setColour(250);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};Blockly.Blocks.parentesis={init:function(){this.appendValueInput("VALUE").setCheck(null).appendField("(");this.appendDummyInput().appendField(")");this.setInputsInline(!0);this.setOutput(!0,null);this.setColour(120);this.setTooltip("");this.setHelpUrl("http://www.example.com/")}};Blockly.Blocks.lists={};Blockly.Blocks.lists.HUE=260;Blockly.Blocks.lists_create_empty={init:function(){this.jsonInit({message0:Blockly.Msg.LISTS_CREATE_EMPTY_TITLE,output:"Array",colour:Blockly.Blocks.lists.HUE,tooltip:Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP,helpUrl:Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL})}};
Blockly.Blocks.lists_create_with={init:function(){this.setHelpUrl(Blockly.Msg.LISTS_CREATE_WITH_HELPURL);this.setColour(Blockly.Blocks.lists.HUE);this.itemCount_=3;this.updateShape_();this.setOutput(!0,"Array");this.setMutator(new Blockly.Mutator(["lists_create_with_item"]));this.setTooltip(Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP)},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("items",this.itemCount_);return a},domToMutation:function(a){this.itemCount_=parseInt(a.getAttribute("items"),
10);this.updateShape_()},decompose:function(a){var b=a.newBlock("lists_create_with_container");b.initSvg();for(var c=b.getInput("STACK").connection,e=0;e<this.itemCount_;e++){var d=a.newBlock("lists_create_with_item");d.initSvg();c.connect(d.previousConnection);c=d.nextConnection}return b},compose:function(a){var b=a.getInputTargetBlock("STACK");for(a=[];b;)a.push(b.valueConnection_),b=b.nextConnection&&b.nextConnection.targetBlock();for(b=0;b<this.itemCount_;b++){var c=this.getInput("ADD"+b).connection.targetConnection;
c&&-1==a.indexOf(c)&&c.disconnect()}this.itemCount_=a.length;this.updateShape_();for(b=0;b<this.itemCount_;b++)Blockly.Mutator.reconnect(a[b],this,"ADD"+b)},saveConnections:function(a){a=a.getInputTargetBlock("STACK");for(var b=0;a;){var c=this.getInput("ADD"+b);a.valueConnection_=c&&c.connection.targetConnection;b++;a=a.nextConnection&&a.nextConnection.targetBlock()}},updateShape_:function(){this.itemCount_&&this.getInput("EMPTY")?this.removeInput("EMPTY"):this.itemCount_||this.getInput("EMPTY")||
this.appendDummyInput("EMPTY").appendField(Blockly.Msg.LISTS_CREATE_EMPTY_TITLE);for(var a=0;a<this.itemCount_;a++)if(!this.getInput("ADD"+a)){var b=this.appendValueInput("ADD"+a);0==a&&b.appendField(Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH)}for(;this.getInput("ADD"+a);)this.removeInput("ADD"+a),a++}};
Blockly.Blocks.lists_create_with_container={init:function(){this.setColour(Blockly.Blocks.lists.HUE);this.appendDummyInput().appendField(Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD);this.appendStatementInput("STACK");this.setTooltip(Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.lists_create_with_item={init:function(){this.setColour(Blockly.Blocks.lists.HUE);this.appendDummyInput().appendField(Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE);this.setPreviousStatement(!0);this.setNextStatement(!0);this.setTooltip(Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.lists_repeat={init:function(){this.jsonInit({message0:Blockly.Msg.LISTS_REPEAT_TITLE,args0:[{type:"input_value",name:"ITEM"},{type:"input_value",name:"NUM",check:"Number"}],output:"Array",colour:Blockly.Blocks.lists.HUE,tooltip:Blockly.Msg.LISTS_REPEAT_TOOLTIP,helpUrl:Blockly.Msg.LISTS_REPEAT_HELPURL})}};
Blockly.Blocks.lists_length={init:function(){this.jsonInit({message0:Blockly.Msg.LISTS_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Number",colour:Blockly.Blocks.lists.HUE,tooltip:Blockly.Msg.LISTS_LENGTH_TOOLTIP,helpUrl:Blockly.Msg.LISTS_LENGTH_HELPURL})}};
Blockly.Blocks.lists_isEmpty={init:function(){this.jsonInit({message0:Blockly.Msg.LISTS_ISEMPTY_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Boolean",colour:Blockly.Blocks.lists.HUE,tooltip:Blockly.Msg.LISTS_ISEMPTY_TOOLTIP,helpUrl:Blockly.Msg.LISTS_ISEMPTY_HELPURL})}};
Blockly.Blocks.lists_indexOf={init:function(){var a=[[Blockly.Msg.LISTS_INDEX_OF_FIRST,"FIRST"],[Blockly.Msg.LISTS_INDEX_OF_LAST,"LAST"]];this.setHelpUrl(Blockly.Msg.LISTS_INDEX_OF_HELPURL);this.setColour(Blockly.Blocks.lists.HUE);this.setOutput(!0,"Number");this.appendValueInput("VALUE").setCheck("Array").appendField(Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST);this.appendValueInput("FIND").appendField(new Blockly.FieldDropdown(a),"END");this.setInputsInline(!0);a=Blockly.Msg.LISTS_INDEX_OF_TOOLTIP.replace("%1",
Blockly.Blocks.ONE_BASED_INDEXING?"0":"-1");this.setTooltip(a)}};
Blockly.Blocks.lists_getIndex={init:function(){var a=[[Blockly.Msg.LISTS_GET_INDEX_GET,"GET"],[Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE,"GET_REMOVE"],[Blockly.Msg.LISTS_GET_INDEX_REMOVE,"REMOVE"]];this.WHERE_OPTIONS=[[Blockly.Msg.LISTS_GET_INDEX_FROM_START,"FROM_START"],[Blockly.Msg.LISTS_GET_INDEX_FROM_END,"FROM_END"],[Blockly.Msg.LISTS_GET_INDEX_FIRST,"FIRST"],[Blockly.Msg.LISTS_GET_INDEX_LAST,"LAST"],[Blockly.Msg.LISTS_GET_INDEX_RANDOM,"RANDOM"]];this.setHelpUrl(Blockly.Msg.LISTS_GET_INDEX_HELPURL);
this.setColour(Blockly.Blocks.lists.HUE);a=new Blockly.FieldDropdown(a,function(a){this.sourceBlock_.updateStatement_("REMOVE"==a)});this.appendValueInput("VALUE").setCheck("Array").appendField(Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST);this.appendDummyInput().appendField(a,"MODE").appendField("","SPACE");this.appendDummyInput("AT");Blockly.Msg.LISTS_GET_INDEX_TAIL&&this.appendDummyInput("TAIL").appendField(Blockly.Msg.LISTS_GET_INDEX_TAIL);this.setInputsInline(!0);this.setOutput(!0);this.updateAt_(!0);
var b=this;this.setTooltip(function(){var a=b.getFieldValue("MODE"),e=b.getFieldValue("WHERE"),d="";switch(a+" "+e){case "GET FROM_START":case "GET FROM_END":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM;break;case "GET FIRST":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST;break;case "GET LAST":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST;break;case "GET RANDOM":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM;break;case "GET_REMOVE FROM_START":case "GET_REMOVE FROM_END":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM;
break;case "GET_REMOVE FIRST":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST;break;case "GET_REMOVE LAST":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST;break;case "GET_REMOVE RANDOM":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM;break;case "REMOVE FROM_START":case "REMOVE FROM_END":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM;break;case "REMOVE FIRST":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST;break;case "REMOVE LAST":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST;
break;case "REMOVE RANDOM":d=Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM}if("FROM_START"==e||"FROM_END"==e)d+=" "+Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP.replace("%1",Blockly.Blocks.ONE_BASED_INDEXING?"#1":"#0");return d})},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("statement",!this.outputConnection);var b=this.getInput("AT").type==Blockly.INPUT_VALUE;a.setAttribute("at",b);return a},domToMutation:function(a){var b="true"==a.getAttribute("statement");
this.updateStatement_(b);a="false"!=a.getAttribute("at");this.updateAt_(a)},updateStatement_:function(a){a!=!this.outputConnection&&(this.unplug(!0,!0),a?(this.setOutput(!1),this.setPreviousStatement(!0),this.setNextStatement(!0)):(this.setPreviousStatement(!1),this.setNextStatement(!1),this.setOutput(!0)))},updateAt_:function(a){this.removeInput("AT");this.removeInput("ORDINAL",!0);a?(this.appendValueInput("AT").setCheck("Number"),Blockly.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX)):
this.appendDummyInput("AT");var b=new Blockly.FieldDropdown(this.WHERE_OPTIONS,function(b){var c="FROM_START"==b||"FROM_END"==b;if(c!=a){var d=this.sourceBlock_;d.updateAt_(c);d.setFieldValue(b,"WHERE");return null}});this.getInput("AT").appendField(b,"WHERE");Blockly.Msg.LISTS_GET_INDEX_TAIL&&this.moveInputBefore("TAIL",null)}};
Blockly.Blocks.lists_setIndex={init:function(){var a=[[Blockly.Msg.LISTS_SET_INDEX_SET,"SET"],[Blockly.Msg.LISTS_SET_INDEX_INSERT,"INSERT"]];this.WHERE_OPTIONS=[[Blockly.Msg.LISTS_GET_INDEX_FROM_START,"FROM_START"],[Blockly.Msg.LISTS_GET_INDEX_FROM_END,"FROM_END"],[Blockly.Msg.LISTS_GET_INDEX_FIRST,"FIRST"],[Blockly.Msg.LISTS_GET_INDEX_LAST,"LAST"],[Blockly.Msg.LISTS_GET_INDEX_RANDOM,"RANDOM"]];this.setHelpUrl(Blockly.Msg.LISTS_SET_INDEX_HELPURL);this.setColour(Blockly.Blocks.lists.HUE);this.appendValueInput("LIST").setCheck("Array").appendField(Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST);
this.appendDummyInput().appendField(new Blockly.FieldDropdown(a),"MODE").appendField("","SPACE");this.appendDummyInput("AT");this.appendValueInput("TO").appendField(Blockly.Msg.LISTS_SET_INDEX_INPUT_TO);this.setInputsInline(!0);this.setPreviousStatement(!0);this.setNextStatement(!0);this.setTooltip(Blockly.Msg.LISTS_SET_INDEX_TOOLTIP);this.updateAt_(!0);var b=this;this.setTooltip(function(){var a=b.getFieldValue("MODE"),e=b.getFieldValue("WHERE"),d="";switch(a+" "+e){case "SET FROM_START":case "SET FROM_END":d=
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM;break;case "SET FIRST":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST;break;case "SET LAST":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST;break;case "SET RANDOM":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM;break;case "INSERT FROM_START":case "INSERT FROM_END":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM;break;case "INSERT FIRST":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST;break;case "INSERT LAST":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST;
break;case "INSERT RANDOM":d=Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM}if("FROM_START"==e||"FROM_END"==e)d+=" "+Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP.replace("%1",Blockly.Blocks.ONE_BASED_INDEXING?"#1":"#0");return d})},mutationToDom:function(){var a=document.createElement("mutation"),b=this.getInput("AT").type==Blockly.INPUT_VALUE;a.setAttribute("at",b);return a},domToMutation:function(a){a="false"!=a.getAttribute("at");this.updateAt_(a)},updateAt_:function(a){this.removeInput("AT");
this.removeInput("ORDINAL",!0);a?(this.appendValueInput("AT").setCheck("Number"),Blockly.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT");var b=new Blockly.FieldDropdown(this.WHERE_OPTIONS,function(b){var c="FROM_START"==b||"FROM_END"==b;if(c!=a){var d=this.sourceBlock_;d.updateAt_(c);d.setFieldValue(b,"WHERE");return null}});this.moveInputBefore("AT","TO");this.getInput("ORDINAL")&&this.moveInputBefore("ORDINAL",
"TO");this.getInput("AT").appendField(b,"WHERE")}};
Blockly.Blocks.lists_getSublist={init:function(){this.WHERE_OPTIONS_1=[[Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START,"FROM_START"],[Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END,"FROM_END"],[Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST,"FIRST"]];this.WHERE_OPTIONS_2=[[Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START,"FROM_START"],[Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END,"FROM_END"],[Blockly.Msg.LISTS_GET_SUBLIST_END_LAST,"LAST"]];this.setHelpUrl(Blockly.Msg.LISTS_GET_SUBLIST_HELPURL);this.setColour(Blockly.Blocks.lists.HUE);
this.appendValueInput("LIST").setCheck("Array").appendField(Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST);this.appendDummyInput("AT1");this.appendDummyInput("AT2");Blockly.Msg.LISTS_GET_SUBLIST_TAIL&&this.appendDummyInput("TAIL").appendField(Blockly.Msg.LISTS_GET_SUBLIST_TAIL);this.setInputsInline(!0);this.setOutput(!0,"Array");this.updateAt_(1,!0);this.updateAt_(2,!0);this.setTooltip(Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP)},mutationToDom:function(){var a=document.createElement("mutation"),b=this.getInput("AT1").type==
Blockly.INPUT_VALUE;a.setAttribute("at1",b);b=this.getInput("AT2").type==Blockly.INPUT_VALUE;a.setAttribute("at2",b);return a},domToMutation:function(a){var b="true"==a.getAttribute("at1");a="true"==a.getAttribute("at2");this.updateAt_(1,b);this.updateAt_(2,a)},updateAt_:function(a,b){this.removeInput("AT"+a);this.removeInput("ORDINAL"+a,!0);b?(this.appendValueInput("AT"+a).setCheck("Number"),Blockly.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL"+a).appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX)):
this.appendDummyInput("AT"+a);var c=new Blockly.FieldDropdown(this["WHERE_OPTIONS_"+a],function(c){var d="FROM_START"==c||"FROM_END"==c;if(d!=b){var e=this.sourceBlock_;e.updateAt_(a,d);e.setFieldValue(c,"WHERE"+a);return null}});this.getInput("AT"+a).appendField(c,"WHERE"+a);1==a&&(this.moveInputBefore("AT1","AT2"),this.getInput("ORDINAL1")&&this.moveInputBefore("ORDINAL1","AT2"));Blockly.Msg.LISTS_GET_SUBLIST_TAIL&&this.moveInputBefore("TAIL",null)}};
Blockly.Blocks.lists_sort={init:function(){this.jsonInit({message0:Blockly.Msg.LISTS_SORT_TITLE,args0:[{type:"field_dropdown",name:"TYPE",options:[[Blockly.Msg.LISTS_SORT_TYPE_NUMERIC,"NUMERIC"],[Blockly.Msg.LISTS_SORT_TYPE_TEXT,"TEXT"],[Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE,"IGNORE_CASE"]]},{type:"field_dropdown",name:"DIRECTION",options:[[Blockly.Msg.LISTS_SORT_ORDER_ASCENDING,"1"],[Blockly.Msg.LISTS_SORT_ORDER_DESCENDING,"-1"]]},{type:"input_value",name:"LIST",check:"Array"}],output:"Array",colour:Blockly.Blocks.lists.HUE,
tooltip:Blockly.Msg.LISTS_SORT_TOOLTIP,helpUrl:Blockly.Msg.LISTS_SORT_HELPURL})}};
Blockly.Blocks.lists_split={init:function(){var a=this,b=new Blockly.FieldDropdown([[Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT,"SPLIT"],[Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST,"JOIN"]],function(b){a.updateType_(b)});this.setHelpUrl(Blockly.Msg.LISTS_SPLIT_HELPURL);this.setColour(Blockly.Blocks.lists.HUE);this.appendValueInput("INPUT").setCheck("String").appendField(b,"MODE");this.appendValueInput("DELIM").setCheck("String").appendField(Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER);this.setInputsInline(!0);
this.setOutput(!0,"Array");this.setTooltip(function(){var b=a.getFieldValue("MODE");if("SPLIT"==b)return Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT;if("JOIN"==b)return Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN;throw"Unknown mode: "+b;})},updateType_:function(a){"SPLIT"==a?(this.outputConnection.setCheck("Array"),this.getInput("INPUT").setCheck("String")):(this.outputConnection.setCheck("String"),this.getInput("INPUT").setCheck("Array"))},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("mode",
this.getFieldValue("MODE"));return a},domToMutation:function(a){this.updateType_(a.getAttribute("mode"))}};Blockly.Blocks.logic={};Blockly.Blocks.logic.HUE=210;
Blockly.Blocks.controls_if={init:function(){this.setHelpUrl(Blockly.Msg.CONTROLS_IF_HELPURL);this.setColour(Blockly.Blocks.logic.HUE);this.appendValueInput("IF0").setCheck("Boolean").appendField(Blockly.Msg.CONTROLS_IF_MSG_IF);this.appendStatementInput("DO0").appendField(Blockly.Msg.CONTROLS_IF_MSG_THEN);this.setPreviousStatement(!0);this.setNextStatement(!0);this.setMutator(new Blockly.Mutator(["controls_if_elseif","controls_if_else"]));var a=this;this.setTooltip(function(){if(a.elseifCount_||a.elseCount_){if(!a.elseifCount_&&
a.elseCount_)return Blockly.Msg.CONTROLS_IF_TOOLTIP_2;if(a.elseifCount_&&!a.elseCount_)return Blockly.Msg.CONTROLS_IF_TOOLTIP_3;if(a.elseifCount_&&a.elseCount_)return Blockly.Msg.CONTROLS_IF_TOOLTIP_4}else return Blockly.Msg.CONTROLS_IF_TOOLTIP_1;return""});this.elseCount_=this.elseifCount_=0},mutationToDom:function(){if(!this.elseifCount_&&!this.elseCount_)return null;var a=document.createElement("mutation");this.elseifCount_&&a.setAttribute("elseif",this.elseifCount_);this.elseCount_&&a.setAttribute("else",
1);return a},domToMutation:function(a){this.elseifCount_=parseInt(a.getAttribute("elseif"),10)||0;this.elseCount_=parseInt(a.getAttribute("else"),10)||0;this.updateShape_()},decompose:function(a){var b=a.newBlock("controls_if_if");b.initSvg();for(var c=b.nextConnection,e=1;e<=this.elseifCount_;e++){var d=a.newBlock("controls_if_elseif");d.initSvg();c.connect(d.previousConnection);c=d.nextConnection}this.elseCount_&&(a=a.newBlock("controls_if_else"),a.initSvg(),c.connect(a.previousConnection));return b},
compose:function(a){var b=a.nextConnection.targetBlock();this.elseCount_=this.elseifCount_=0;a=[null];for(var c=[null],e=null;b;){switch(b.type){case "controls_if_elseif":this.elseifCount_++;a.push(b.valueConnection_);c.push(b.statementConnection_);break;case "controls_if_else":this.elseCount_++;e=b.statementConnection_;break;default:throw"Unknown block type.";}b=b.nextConnection&&b.nextConnection.targetBlock()}this.updateShape_();for(b=1;b<=this.elseifCount_;b++)Blockly.Mutator.reconnect(a[b],this,
"IF"+b),Blockly.Mutator.reconnect(c[b],this,"DO"+b);Blockly.Mutator.reconnect(e,this,"ELSE")},saveConnections:function(a){a=a.nextConnection.targetBlock();for(var b=1;a;){switch(a.type){case "controls_if_elseif":var c=this.getInput("IF"+b),e=this.getInput("DO"+b);a.valueConnection_=c&&c.connection.targetConnection;a.statementConnection_=e&&e.connection.targetConnection;b++;break;case "controls_if_else":e=this.getInput("ELSE");a.statementConnection_=e&&e.connection.targetConnection;break;default:throw"Unknown block type.";
}a=a.nextConnection&&a.nextConnection.targetBlock()}},updateShape_:function(){this.getInput("ELSE")&&this.removeInput("ELSE");for(var a=1;this.getInput("IF"+a);)this.removeInput("IF"+a),this.removeInput("DO"+a),a++;for(a=1;a<=this.elseifCount_;a++)this.appendValueInput("IF"+a).setCheck("Boolean").appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSEIF),this.appendStatementInput("DO"+a).appendField(Blockly.Msg.CONTROLS_IF_MSG_THEN);this.elseCount_&&this.appendStatementInput("ELSE").appendField(Blockly.Msg.CONTROLS_IF_MSG_ELSE)}};
Blockly.Blocks.controls_if_if={init:function(){this.setColour(Blockly.Blocks.logic.HUE);this.appendDummyInput().appendField(Blockly.Msg.CONTROLS_IF_IF_TITLE_IF);this.setNextStatement(!0);this.setTooltip(Blockly.Msg.CONTROLS_IF_IF_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.controls_if_elseif={init:function(){this.setColour(Blockly.Blocks.logic.HUE);this.appendDummyInput().appendField(Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF);this.setPreviousStatement(!0);this.setNextStatement(!0);this.setTooltip(Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.controls_if_else={init:function(){this.setColour(Blockly.Blocks.logic.HUE);this.appendDummyInput().appendField(Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE);this.setPreviousStatement(!0);this.setTooltip(Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.logic_compare={init:function(){var a=[["=","EQ"],["\u2260","NEQ"],["\u200f<\u200f","LT"],["\u200f\u2264\u200f","LTE"],["\u200f>\u200f","GT"],["\u200f\u2265\u200f","GTE"]],b=[["=","EQ"],["\u2260","NEQ"],["<","LT"],["\u2264","LTE"],[">","GT"],["\u2265","GTE"]],a=this.RTL?a:b;this.setHelpUrl(Blockly.Msg.LOGIC_COMPARE_HELPURL);this.setColour(Blockly.Blocks.logic.HUE);this.setOutput(!0,"Boolean");this.appendValueInput("A");this.appendValueInput("B").appendField(new Blockly.FieldDropdown(a),
"OP");this.setInputsInline(!0);var c=this;this.setTooltip(function(){var a=c.getFieldValue("OP");return{EQ:Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ,NEQ:Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ,LT:Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT,LTE:Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE,GT:Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT,GTE:Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE}[a]});this.prevBlocks_=[null,null]},onchange:function(a){var b=this.getInputTargetBlock("A"),c=this.getInputTargetBlock("B");if(b&&c&&!b.outputConnection.checkType_(c.outputConnection)){Blockly.Events.setGroup(a.group);
for(a=0;a<this.prevBlocks_.length;a++){var e=this.prevBlocks_[a];if(e===b||e===c)e.unplug(),e.bumpNeighbours_()}Blockly.Events.setGroup(!1)}this.prevBlocks_[0]=b;this.prevBlocks_[1]=c}};
Blockly.Blocks.logic_operation={init:function(){var a=[[Blockly.Msg.LOGIC_OPERATION_AND,"AND"],[Blockly.Msg.LOGIC_OPERATION_OR,"OR"]];this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);this.setColour(Blockly.Blocks.logic.HUE);this.setOutput(!0,"Boolean");this.appendValueInput("A").setCheck("Boolean");this.appendValueInput("B").setCheck("Boolean").appendField(new Blockly.FieldDropdown(a),"OP");this.setInputsInline(!0);var b=this;this.setTooltip(function(){var a=b.getFieldValue("OP");return{AND:Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND,
OR:Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR}[a]})}};Blockly.Blocks.logic_negate={init:function(){this.jsonInit({message0:Blockly.Msg.LOGIC_NEGATE_TITLE,args0:[{type:"input_value",name:"BOOL",check:"Boolean"}],output:"Boolean",colour:Blockly.Blocks.logic.HUE,tooltip:Blockly.Msg.LOGIC_NEGATE_TOOLTIP,helpUrl:Blockly.Msg.LOGIC_NEGATE_HELPURL})}};
Blockly.Blocks.logic_boolean={init:function(){this.jsonInit({message0:"%1",args0:[{type:"field_dropdown",name:"BOOL",options:[[Blockly.Msg.LOGIC_BOOLEAN_TRUE,"TRUE"],[Blockly.Msg.LOGIC_BOOLEAN_FALSE,"FALSE"]]}],output:"Boolean",colour:Blockly.Blocks.logic.HUE,tooltip:Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP,helpUrl:Blockly.Msg.LOGIC_BOOLEAN_HELPURL})}};
Blockly.Blocks.logic_null={init:function(){this.jsonInit({message0:Blockly.Msg.LOGIC_NULL,output:null,colour:Blockly.Blocks.logic.HUE,tooltip:Blockly.Msg.LOGIC_NULL_TOOLTIP,helpUrl:Blockly.Msg.LOGIC_NULL_HELPURL})}};
Blockly.Blocks.logic_ternary={init:function(){this.setHelpUrl(Blockly.Msg.LOGIC_TERNARY_HELPURL);this.setColour(Blockly.Blocks.logic.HUE);this.appendValueInput("IF").setCheck("Boolean").appendField(Blockly.Msg.LOGIC_TERNARY_CONDITION);this.appendValueInput("THEN").appendField(Blockly.Msg.LOGIC_TERNARY_IF_TRUE);this.appendValueInput("ELSE").appendField(Blockly.Msg.LOGIC_TERNARY_IF_FALSE);this.setOutput(!0);this.setTooltip(Blockly.Msg.LOGIC_TERNARY_TOOLTIP);this.prevParentConnection_=null},onchange:function(a){var b=
this.getInputTargetBlock("THEN"),c=this.getInputTargetBlock("ELSE"),e=this.outputConnection.targetConnection;if((b||c)&&e)for(var d=0;2>d;d++){var f=1==d?b:c;f&&!f.outputConnection.checkType_(e)&&(Blockly.Events.setGroup(a.group),e===this.prevParentConnection_?(this.unplug(),e.getSourceBlock().bumpNeighbours_()):(f.unplug(),f.bumpNeighbours_()),Blockly.Events.setGroup(!1))}this.prevParentConnection_=e}};Blockly.Blocks.loops={};Blockly.Blocks.loops.HUE=120;Blockly.Blocks.controls_repeat_ext={init:function(){this.jsonInit({message0:Blockly.Msg.CONTROLS_REPEAT_TITLE,args0:[{type:"input_value",name:"TIMES",check:"Number"}],previousStatement:null,nextStatement:null,colour:Blockly.Blocks.loops.HUE,tooltip:Blockly.Msg.CONTROLS_REPEAT_TOOLTIP,helpUrl:Blockly.Msg.CONTROLS_REPEAT_HELPURL});this.appendStatementInput("DO").appendField(Blockly.Msg.CONTROLS_REPEAT_INPUT_DO)}};
Blockly.Blocks.controls_repeat={init:function(){this.jsonInit({message0:Blockly.Msg.CONTROLS_REPEAT_TITLE,args0:[{type:"field_number",name:"TIMES",value:10,min:0,precision:1}],previousStatement:null,nextStatement:null,colour:Blockly.Blocks.loops.HUE,tooltip:Blockly.Msg.CONTROLS_REPEAT_TOOLTIP,helpUrl:Blockly.Msg.CONTROLS_REPEAT_HELPURL});this.appendStatementInput("DO").appendField(Blockly.Msg.CONTROLS_REPEAT_INPUT_DO)}};
Blockly.Blocks.controls_whileUntil={init:function(){var a=[[Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE,"WHILE"],[Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL,"UNTIL"]];this.setHelpUrl(Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL);this.setColour(Blockly.Blocks.loops.HUE);this.appendValueInput("BOOL").setCheck("Boolean").appendField(new Blockly.FieldDropdown(a),"MODE");this.appendStatementInput("DO").appendField(Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO);this.setPreviousStatement(!0);this.setNextStatement(!0);
var b=this;this.setTooltip(function(){var a=b.getFieldValue("MODE");return{WHILE:Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE,UNTIL:Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL}[a]})}};
Blockly.Blocks.controls_for={init:function(){this.jsonInit({message0:Blockly.Msg.CONTROLS_FOR_TITLE,args0:[{type:"field_variable",name:"VAR",variable:null},{type:"input_value",name:"FROM",check:"Number",align:"RIGHT"},{type:"input_value",name:"TO",check:"Number",align:"RIGHT"},{type:"input_value",name:"BY",check:"Number",align:"RIGHT"}],inputsInline:!0,previousStatement:null,nextStatement:null,colour:Blockly.Blocks.loops.HUE,helpUrl:Blockly.Msg.CONTROLS_FOR_HELPURL});this.appendStatementInput("DO").appendField(Blockly.Msg.CONTROLS_FOR_INPUT_DO);
var a=this;this.setTooltip(function(){return Blockly.Msg.CONTROLS_FOR_TOOLTIP.replace("%1",a.getFieldValue("VAR"))})},customContextMenu:function(a){if(!this.isCollapsed()){var b={enabled:!0},c=this.getFieldValue("VAR");b.text=Blockly.Msg.VARIABLES_SET_CREATE_GET.replace("%1",c);c=goog.dom.createDom("field",null,c);c.setAttribute("name","VAR");c=goog.dom.createDom("block",null,c);c.setAttribute("type","variables_get");b.callback=Blockly.ContextMenu.callbackFactory(this,c);a.push(b)}}};
Blockly.Blocks.controls_forEach={init:function(){this.jsonInit({message0:Blockly.Msg.CONTROLS_FOREACH_TITLE,args0:[{type:"field_variable",name:"VAR",variable:null},{type:"input_value",name:"LIST",check:"Array"}],previousStatement:null,nextStatement:null,colour:Blockly.Blocks.loops.HUE,helpUrl:Blockly.Msg.CONTROLS_FOREACH_HELPURL});this.appendStatementInput("DO").appendField(Blockly.Msg.CONTROLS_FOREACH_INPUT_DO);var a=this;this.setTooltip(function(){return Blockly.Msg.CONTROLS_FOREACH_TOOLTIP.replace("%1",
a.getFieldValue("VAR"))})},customContextMenu:Blockly.Blocks.controls_for.customContextMenu};
Blockly.Blocks.controls_flow_statements={init:function(){var a=[[Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK,"BREAK"],[Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE,"CONTINUE"]];this.setHelpUrl(Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL);this.setColour(Blockly.Blocks.loops.HUE);this.appendDummyInput().appendField(new Blockly.FieldDropdown(a),"FLOW");this.setPreviousStatement(!0);var b=this;this.setTooltip(function(){var a=b.getFieldValue("FLOW");return{BREAK:Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK,
CONTINUE:Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE}[a]})},onchange:function(a){a=!1;var b=this;do{if(-1!=this.LOOP_TYPES.indexOf(b.type)){a=!0;break}b=b.getSurroundParent()}while(b);a?this.setWarningText(null):this.setWarningText(Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING)},LOOP_TYPES:["controls_repeat","controls_repeat_ext","controls_forEach","controls_for","controls_whileUntil"]};Blockly.Blocks.math={};Blockly.Blocks.math.HUE=230;Blockly.Blocks.math_number={init:function(){this.setHelpUrl(Blockly.Msg.MATH_NUMBER_HELPURL);this.setColour(Blockly.Blocks.math.HUE);this.appendDummyInput().appendField(new Blockly.FieldNumber("0"),"NUM");this.setOutput(!0,"Number");var a=this;this.setTooltip(function(){var b=a.getParent();return b&&b.getInputsInline()&&b.tooltip||Blockly.Msg.MATH_NUMBER_TOOLTIP})}};
Blockly.Blocks.math_arithmetic={init:function(){this.jsonInit({message0:"%1 %2 %3",args0:[{type:"input_value",name:"A",check:"Number"},{type:"field_dropdown",name:"OP",options:[[Blockly.Msg.MATH_ADDITION_SYMBOL,"ADD"],[Blockly.Msg.MATH_SUBTRACTION_SYMBOL,"MINUS"],[Blockly.Msg.MATH_MULTIPLICATION_SYMBOL,"MULTIPLY"],[Blockly.Msg.MATH_DIVISION_SYMBOL,"DIVIDE"],[Blockly.Msg.MATH_POWER_SYMBOL,"POWER"]]},{type:"input_value",name:"B",check:"Number"}],inputsInline:!0,output:"Number",colour:Blockly.Blocks.math.HUE,
helpUrl:Blockly.Msg.MATH_ARITHMETIC_HELPURL});var a=this;this.setTooltip(function(){var b=a.getFieldValue("OP");return{ADD:Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD,MINUS:Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS,MULTIPLY:Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY,DIVIDE:Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE,POWER:Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER}[b]})}};
Blockly.Blocks.math_single={init:function(){this.jsonInit({message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[[Blockly.Msg.MATH_SINGLE_OP_ROOT,"ROOT"],[Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE,"ABS"],["-","NEG"],["ln","LN"],["log10","LOG10"],["e^","EXP"],["10^","POW10"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",colour:Blockly.Blocks.math.HUE,helpUrl:Blockly.Msg.MATH_SINGLE_HELPURL});var a=this;this.setTooltip(function(){var b=a.getFieldValue("OP");return{ROOT:Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT,
ABS:Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS,NEG:Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG,LN:Blockly.Msg.MATH_SINGLE_TOOLTIP_LN,LOG10:Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10,EXP:Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP,POW10:Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10}[b]})}};
Blockly.Blocks.math_trig={init:function(){this.jsonInit({message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[[Blockly.Msg.MATH_TRIG_SIN,"SIN"],[Blockly.Msg.MATH_TRIG_COS,"COS"],[Blockly.Msg.MATH_TRIG_TAN,"TAN"],[Blockly.Msg.MATH_TRIG_ASIN,"ASIN"],[Blockly.Msg.MATH_TRIG_ACOS,"ACOS"],[Blockly.Msg.MATH_TRIG_ATAN,"ATAN"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",colour:Blockly.Blocks.math.HUE,helpUrl:Blockly.Msg.MATH_TRIG_HELPURL});var a=this;this.setTooltip(function(){var b=
a.getFieldValue("OP");return{SIN:Blockly.Msg.MATH_TRIG_TOOLTIP_SIN,COS:Blockly.Msg.MATH_TRIG_TOOLTIP_COS,TAN:Blockly.Msg.MATH_TRIG_TOOLTIP_TAN,ASIN:Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN,ACOS:Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS,ATAN:Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN}[b]})}};
Blockly.Blocks.math_constant={init:function(){this.jsonInit({message0:"%1",args0:[{type:"field_dropdown",name:"CONSTANT",options:[["\u03c0","PI"],["e","E"],["\u03c6","GOLDEN_RATIO"],["sqrt(2)","SQRT2"],["sqrt(\u00bd)","SQRT1_2"],["\u221e","INFINITY"]]}],output:"Number",colour:Blockly.Blocks.math.HUE,tooltip:Blockly.Msg.MATH_CONSTANT_TOOLTIP,helpUrl:Blockly.Msg.MATH_CONSTANT_HELPURL})}};
Blockly.Blocks.math_number_property={init:function(){var a=[[Blockly.Msg.MATH_IS_EVEN,"EVEN"],[Blockly.Msg.MATH_IS_ODD,"ODD"],[Blockly.Msg.MATH_IS_PRIME,"PRIME"],[Blockly.Msg.MATH_IS_WHOLE,"WHOLE"],[Blockly.Msg.MATH_IS_POSITIVE,"POSITIVE"],[Blockly.Msg.MATH_IS_NEGATIVE,"NEGATIVE"],[Blockly.Msg.MATH_IS_DIVISIBLE_BY,"DIVISIBLE_BY"]];this.setColour(Blockly.Blocks.math.HUE);this.appendValueInput("NUMBER_TO_CHECK").setCheck("Number");a=new Blockly.FieldDropdown(a,function(a){this.sourceBlock_.updateShape_("DIVISIBLE_BY"==
a)});this.appendDummyInput().appendField(a,"PROPERTY");this.setInputsInline(!0);this.setOutput(!0,"Boolean");this.setTooltip(Blockly.Msg.MATH_IS_TOOLTIP)},mutationToDom:function(){var a=document.createElement("mutation"),b="DIVISIBLE_BY"==this.getFieldValue("PROPERTY");a.setAttribute("divisor_input",b);return a},domToMutation:function(a){a="true"==a.getAttribute("divisor_input");this.updateShape_(a)},updateShape_:function(a){var b=this.getInput("DIVISOR");a?b||this.appendValueInput("DIVISOR").setCheck("Number"):
b&&this.removeInput("DIVISOR")}};Blockly.Blocks.math_change={init:function(){this.jsonInit({message0:Blockly.Msg.MATH_CHANGE_TITLE,args0:[{type:"field_variable",name:"VAR",variable:Blockly.Msg.MATH_CHANGE_TITLE_ITEM},{type:"input_value",name:"DELTA",check:"Number"}],previousStatement:null,nextStatement:null,colour:Blockly.Blocks.variables.HUE,helpUrl:Blockly.Msg.MATH_CHANGE_HELPURL});var a=this;this.setTooltip(function(){return Blockly.Msg.MATH_CHANGE_TOOLTIP.replace("%1",a.getFieldValue("VAR"))})}};
Blockly.Blocks.math_round={init:function(){this.jsonInit({message0:"%1 %2",args0:[{type:"field_dropdown",name:"OP",options:[[Blockly.Msg.MATH_ROUND_OPERATOR_ROUND,"ROUND"],[Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP,"ROUNDUP"],[Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN,"ROUNDDOWN"]]},{type:"input_value",name:"NUM",check:"Number"}],output:"Number",colour:Blockly.Blocks.math.HUE,tooltip:Blockly.Msg.MATH_ROUND_TOOLTIP,helpUrl:Blockly.Msg.MATH_ROUND_HELPURL})}};
Blockly.Blocks.math_on_list={init:function(){var a=[[Blockly.Msg.MATH_ONLIST_OPERATOR_SUM,"SUM"],[Blockly.Msg.MATH_ONLIST_OPERATOR_MIN,"MIN"],[Blockly.Msg.MATH_ONLIST_OPERATOR_MAX,"MAX"],[Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE,"AVERAGE"],[Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN,"MEDIAN"],[Blockly.Msg.MATH_ONLIST_OPERATOR_MODE,"MODE"],[Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV,"STD_DEV"],[Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM,"RANDOM"]],b=this;this.setHelpUrl(Blockly.Msg.MATH_ONLIST_HELPURL);this.setColour(Blockly.Blocks.math.HUE);
this.setOutput(!0,"Number");a=new Blockly.FieldDropdown(a,function(a){b.updateType_(a)});this.appendValueInput("LIST").setCheck("Array").appendField(a,"OP");this.setTooltip(function(){var a=b.getFieldValue("OP");return{SUM:Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM,MIN:Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN,MAX:Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX,AVERAGE:Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE,MEDIAN:Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN,MODE:Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE,STD_DEV:Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV,
RANDOM:Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM}[a]})},updateType_:function(a){"MODE"==a?this.outputConnection.setCheck("Array"):this.outputConnection.setCheck("Number")},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("op",this.getFieldValue("OP"));return a},domToMutation:function(a){this.updateType_(a.getAttribute("op"))}};
Blockly.Blocks.math_modulo={init:function(){this.jsonInit({message0:Blockly.Msg.MATH_MODULO_TITLE,args0:[{type:"input_value",name:"DIVIDEND",check:"Number"},{type:"input_value",name:"DIVISOR",check:"Number"}],inputsInline:!0,output:"Number",colour:Blockly.Blocks.math.HUE,tooltip:Blockly.Msg.MATH_MODULO_TOOLTIP,helpUrl:Blockly.Msg.MATH_MODULO_HELPURL})}};
Blockly.Blocks.math_constrain={init:function(){this.jsonInit({message0:Blockly.Msg.MATH_CONSTRAIN_TITLE,args0:[{type:"input_value",name:"VALUE",check:"Number"},{type:"input_value",name:"LOW",check:"Number"},{type:"input_value",name:"HIGH",check:"Number"}],inputsInline:!0,output:"Number",colour:Blockly.Blocks.math.HUE,tooltip:Blockly.Msg.MATH_CONSTRAIN_TOOLTIP,helpUrl:Blockly.Msg.MATH_CONSTRAIN_HELPURL})}};
Blockly.Blocks.math_random_int={init:function(){this.jsonInit({message0:Blockly.Msg.MATH_RANDOM_INT_TITLE,args0:[{type:"input_value",name:"FROM",check:"Number"},{type:"input_value",name:"TO",check:"Number"}],inputsInline:!0,output:"Number",colour:Blockly.Blocks.math.HUE,tooltip:Blockly.Msg.MATH_RANDOM_INT_TOOLTIP,helpUrl:Blockly.Msg.MATH_RANDOM_INT_HELPURL})}};
Blockly.Blocks.math_random_float={init:function(){this.jsonInit({message0:Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM,output:"Number",colour:Blockly.Blocks.math.HUE,tooltip:Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP,helpUrl:Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL})}};Blockly.Blocks.procedures={};Blockly.Blocks.procedures.HUE=290;
Blockly.Blocks.procedures_defnoreturn={init:function(){var a=new Blockly.FieldTextInput(Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE,Blockly.Procedures.rename);a.setSpellcheck(!1);this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE).appendField(a,"NAME").appendField("","PARAMS");this.setMutator(new Blockly.Mutator(["procedures_mutatorarg"]));Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT&&this.setCommentText(Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT);this.setColour(Blockly.Blocks.procedures.HUE);
this.setTooltip(Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP);this.setHelpUrl(Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL);this.arguments_=[];this.setStatements_(!0);this.statementConnection_=null},setStatements_:function(a){this.hasStatements_!==a&&(a?(this.appendStatementInput("STACK").appendField(Blockly.Msg.PROCEDURES_DEFNORETURN_DO),this.getInput("RETURN")&&this.moveInputBefore("STACK","RETURN")):this.removeInput("STACK",!0),this.hasStatements_=a)},updateParams_:function(){for(var a=!1,b={},c=0;c<
this.arguments_.length;c++){if(b["arg_"+this.arguments_[c].toLowerCase()]){a=!0;break}b["arg_"+this.arguments_[c].toLowerCase()]=!0}a?this.setWarningText(Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING):this.setWarningText(null);a="";this.arguments_.length&&(a=Blockly.Msg.PROCEDURES_BEFORE_PARAMS+" "+this.arguments_.join(", "));Blockly.Events.disable();try{this.setFieldValue(a,"PARAMS")}finally{Blockly.Events.enable()}},mutationToDom:function(a){var b=document.createElement("mutation");a&&b.setAttribute("name",
this.getFieldValue("NAME"));for(var c=0;c<this.arguments_.length;c++){var e=document.createElement("arg");e.setAttribute("name",this.arguments_[c]);a&&this.paramIds_&&e.setAttribute("paramId",this.paramIds_[c]);b.appendChild(e)}this.hasStatements_||b.setAttribute("statements","false");return b},domToMutation:function(a){this.arguments_=[];for(var b=0,c;c=a.childNodes[b];b++)"arg"==c.nodeName.toLowerCase()&&this.arguments_.push(c.getAttribute("name"));this.updateParams_();Blockly.Procedures.mutateCallers(this);
this.setStatements_("false"!==a.getAttribute("statements"))},decompose:function(a){var b=a.newBlock("procedures_mutatorcontainer");b.initSvg();this.getInput("RETURN")?b.setFieldValue(this.hasStatements_?"TRUE":"FALSE","STATEMENTS"):b.getInput("STATEMENT_INPUT").setVisible(!1);for(var c=b.getInput("STACK").connection,e=0;e<this.arguments_.length;e++){var d=a.newBlock("procedures_mutatorarg");d.initSvg();d.setFieldValue(this.arguments_[e],"NAME");d.oldLocation=e;c.connect(d.previousConnection);c=d.nextConnection}Blockly.Procedures.mutateCallers(this);
return b},compose:function(a){this.arguments_=[];this.paramIds_=[];for(var b=a.getInputTargetBlock("STACK");b;)this.arguments_.push(b.getFieldValue("NAME")),this.paramIds_.push(b.id),b=b.nextConnection&&b.nextConnection.targetBlock();this.updateParams_();Blockly.Procedures.mutateCallers(this);a=a.getFieldValue("STATEMENTS");if(null!==a&&(a="TRUE"==a,this.hasStatements_!=a))if(a)this.setStatements_(!0),Blockly.Mutator.reconnect(this.statementConnection_,this,"STACK"),this.statementConnection_=null;
else{a=this.getInput("STACK").connection;if(this.statementConnection_=a.targetConnection)a=a.targetBlock(),a.unplug(),a.bumpNeighbours_();this.setStatements_(!1)}},getProcedureDef:function(){return[this.getFieldValue("NAME"),this.arguments_,!1]},getVars:function(){return this.arguments_},renameVar:function(a,b){for(var c=!1,e=0;e<this.arguments_.length;e++)Blockly.Names.equals(a,this.arguments_[e])&&(this.arguments_[e]=b,c=!0);if(c&&(this.updateParams_(),this.mutator.isVisible()))for(var c=this.mutator.workspace_.getAllBlocks(),
e=0,d;d=c[e];e++)"procedures_mutatorarg"==d.type&&Blockly.Names.equals(a,d.getFieldValue("NAME"))&&d.setFieldValue(b,"NAME")},customContextMenu:function(a){var b={enabled:!0},c=this.getFieldValue("NAME");b.text=Blockly.Msg.PROCEDURES_CREATE_DO.replace("%1",c);var e=goog.dom.createDom("mutation");e.setAttribute("name",c);for(var d=0;d<this.arguments_.length;d++)c=goog.dom.createDom("arg"),c.setAttribute("name",this.arguments_[d]),e.appendChild(c);e=goog.dom.createDom("block",null,e);e.setAttribute("type",
this.callType_);b.callback=Blockly.ContextMenu.callbackFactory(this,e);a.push(b);if(!this.isCollapsed())for(d=0;d<this.arguments_.length;d++)b={enabled:!0},c=this.arguments_[d],b.text=Blockly.Msg.VARIABLES_SET_CREATE_GET.replace("%1",c),e=goog.dom.createDom("field",null,c),e.setAttribute("name","VAR"),e=goog.dom.createDom("block",null,e),e.setAttribute("type","variables_get"),b.callback=Blockly.ContextMenu.callbackFactory(this,e),a.push(b)},callType_:"procedures_callnoreturn"};
Blockly.Blocks.procedures_defreturn={init:function(){var a=new Blockly.FieldTextInput(Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE,Blockly.Procedures.rename);a.setSpellcheck(!1);this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_DEFRETURN_TITLE).appendField(a,"NAME").appendField("","PARAMS");this.appendValueInput("RETURN").setAlign(Blockly.ALIGN_RIGHT).appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN);this.setMutator(new Blockly.Mutator(["procedures_mutatorarg"]));Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT&&
this.setCommentText(Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT);this.setColour(Blockly.Blocks.procedures.HUE);this.setTooltip(Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP);this.setHelpUrl(Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL);this.arguments_=[];this.setStatements_(!0);this.statementConnection_=null},setStatements_:Blockly.Blocks.procedures_defnoreturn.setStatements_,updateParams_:Blockly.Blocks.procedures_defnoreturn.updateParams_,mutationToDom:Blockly.Blocks.procedures_defnoreturn.mutationToDom,domToMutation:Blockly.Blocks.procedures_defnoreturn.domToMutation,
decompose:Blockly.Blocks.procedures_defnoreturn.decompose,compose:Blockly.Blocks.procedures_defnoreturn.compose,getProcedureDef:function(){return[this.getFieldValue("NAME"),this.arguments_,!0]},getVars:Blockly.Blocks.procedures_defnoreturn.getVars,renameVar:Blockly.Blocks.procedures_defnoreturn.renameVar,customContextMenu:Blockly.Blocks.procedures_defnoreturn.customContextMenu,callType_:"procedures_callreturn"};
Blockly.Blocks.procedures_mutatorcontainer={init:function(){this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE);this.appendStatementInput("STACK");this.appendDummyInput("STATEMENT_INPUT").appendField(Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS).appendField(new Blockly.FieldCheckbox("TRUE"),"STATEMENTS");this.setColour(Blockly.Blocks.procedures.HUE);this.setTooltip(Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.procedures_mutatorarg={init:function(){var a=new Blockly.FieldTextInput("x",this.validator_);this.appendDummyInput().appendField(Blockly.Msg.PROCEDURES_MUTATORARG_TITLE).appendField(a,"NAME");this.setPreviousStatement(!0);this.setNextStatement(!0);this.setColour(Blockly.Blocks.procedures.HUE);this.setTooltip(Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP);this.contextMenu=!1;a.onFinishEditing_=this.createNewVar_;a.onFinishEditing_("x")},validator_:function(a){return(a=a.replace(/[\s\xa0]+/g,
" ").replace(/^ | $/g,""))||null},createNewVar_:function(a){var b=this.sourceBlock_;b&&b.workspace&&b.workspace.options&&b.workspace.options.parentWorkspace&&b.workspace.options.parentWorkspace.createVariable(a)}};
Blockly.Blocks.procedures_callnoreturn={init:function(){this.appendDummyInput("TOPROW").appendField(this.id,"NAME");this.setPreviousStatement(!0);this.setNextStatement(!0);this.setColour(Blockly.Blocks.procedures.HUE);this.setHelpUrl(Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL);this.arguments_=[];this.quarkConnections_={};this.quarkIds_=null},getProcedureCall:function(){return this.getFieldValue("NAME")},renameProcedure:function(a,b){Blockly.Names.equals(a,this.getProcedureCall())&&(this.setFieldValue(b,
"NAME"),this.setTooltip((this.outputConnection?Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP:Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP).replace("%1",b)))},setProcedureParameters_:function(a,b){var c=Blockly.Procedures.getDefinition(this.getProcedureCall(),this.workspace),e=c&&c.mutator&&c.mutator.isVisible();e||(this.quarkConnections_={},this.quarkIds_=null);if(b)if(goog.array.equals(this.arguments_,a))this.quarkIds_=b;else{if(b.length!=a.length)throw"Error: paramNames and paramIds must be the same length.";
this.setCollapsed(!1);this.quarkIds_||(this.quarkConnections_={},a.join("\n")==this.arguments_.join("\n")?this.quarkIds_=b:this.quarkIds_=[]);c=this.rendered;this.rendered=!1;for(var d=0;d<this.arguments_.length;d++){var f=this.getInput("ARG"+d);f&&(f=f.connection.targetConnection,this.quarkConnections_[this.quarkIds_[d]]=f,e&&f&&-1==b.indexOf(this.quarkIds_[d])&&(f.disconnect(),f.getSourceBlock().bumpNeighbours_()))}this.arguments_=[].concat(a);this.updateShape_();if(this.quarkIds_=b)for(d=0;d<this.arguments_.length;d++)e=
this.quarkIds_[d],e in this.quarkConnections_&&(f=this.quarkConnections_[e],Blockly.Mutator.reconnect(f,this,"ARG"+d)||delete this.quarkConnections_[e]);(this.rendered=c)&&this.render()}},updateShape_:function(){for(var a=0;a<this.arguments_.length;a++){var b=this.getField("ARGNAME"+a);if(b){Blockly.Events.disable();try{b.setValue(this.arguments_[a])}finally{Blockly.Events.enable()}}else b=new Blockly.FieldLabel(this.arguments_[a]),this.appendValueInput("ARG"+a).setAlign(Blockly.ALIGN_RIGHT).appendField(b,
"ARGNAME"+a).init()}for(;this.getInput("ARG"+a);)this.removeInput("ARG"+a),a++;if(a=this.getInput("TOPROW"))this.arguments_.length?this.getField("WITH")||(a.appendField(Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS,"WITH"),a.init()):this.getField("WITH")&&a.removeField("WITH")},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("name",this.getProcedureCall());for(var b=0;b<this.arguments_.length;b++){var c=document.createElement("arg");c.setAttribute("name",this.arguments_[b]);
a.appendChild(c)}return a},domToMutation:function(a){var b=a.getAttribute("name");this.renameProcedure(this.getProcedureCall(),b);for(var b=[],c=[],e=0,d;d=a.childNodes[e];e++)"arg"==d.nodeName.toLowerCase()&&(b.push(d.getAttribute("name")),c.push(d.getAttribute("paramId")));this.setProcedureParameters_(b,c)},renameVar:function(a,b){for(var c=0;c<this.arguments_.length;c++)Blockly.Names.equals(a,this.arguments_[c])&&(this.arguments_[c]=b,this.getField("ARGNAME"+c).setValue(b))},onchange:function(a){if(this.workspace&&
!this.workspace.isFlyout)if(a.type==Blockly.Events.CREATE&&-1!=a.ids.indexOf(this.id)){var b=this.getProcedureCall(),b=Blockly.Procedures.getDefinition(b,this.workspace);!b||b.type==this.defType_&&JSON.stringify(b.arguments_)==JSON.stringify(this.arguments_)||(b=null);if(!b){Blockly.Events.setGroup(a.group);a=goog.dom.createDom("xml");b=goog.dom.createDom("block");b.setAttribute("type",this.defType_);var c=this.getRelativeToSurfaceXY(),e=c.y+2*Blockly.SNAP_RADIUS;b.setAttribute("x",c.x+Blockly.SNAP_RADIUS*
(this.RTL?-1:1));b.setAttribute("y",e);c=this.mutationToDom();b.appendChild(c);c=goog.dom.createDom("field");c.setAttribute("name","NAME");c.appendChild(document.createTextNode(this.getProcedureCall()));b.appendChild(c);a.appendChild(b);Blockly.Xml.domToWorkspace(a,this.workspace);Blockly.Events.setGroup(!1)}}else a.type==Blockly.Events.DELETE&&(b=this.getProcedureCall(),b=Blockly.Procedures.getDefinition(b,this.workspace),b||(Blockly.Events.setGroup(a.group),this.dispose(!0,!1),Blockly.Events.setGroup(!1)))},
customContextMenu:function(a){var b={enabled:!0};b.text=Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF;var c=this.getProcedureCall(),e=this.workspace;b.callback=function(){var a=Blockly.Procedures.getDefinition(c,e);a&&a.select()};a.push(b)},defType_:"procedures_defnoreturn"};
Blockly.Blocks.procedures_callreturn={init:function(){this.appendDummyInput("TOPROW").appendField("","NAME");this.setOutput(!0);this.setColour(Blockly.Blocks.procedures.HUE);this.setHelpUrl(Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL);this.arguments_=[];this.quarkConnections_={};this.quarkIds_=null},getProcedureCall:Blockly.Blocks.procedures_callnoreturn.getProcedureCall,renameProcedure:Blockly.Blocks.procedures_callnoreturn.renameProcedure,setProcedureParameters_:Blockly.Blocks.procedures_callnoreturn.setProcedureParameters_,
updateShape_:Blockly.Blocks.procedures_callnoreturn.updateShape_,mutationToDom:Blockly.Blocks.procedures_callnoreturn.mutationToDom,domToMutation:Blockly.Blocks.procedures_callnoreturn.domToMutation,renameVar:Blockly.Blocks.procedures_callnoreturn.renameVar,onchange:Blockly.Blocks.procedures_callnoreturn.onchange,customContextMenu:Blockly.Blocks.procedures_callnoreturn.customContextMenu,defType_:"procedures_defreturn"};
Blockly.Blocks.procedures_ifreturn={init:function(){this.appendValueInput("CONDITION").setCheck("Boolean").appendField(Blockly.Msg.CONTROLS_IF_MSG_IF);this.appendValueInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN);this.setInputsInline(!0);this.setPreviousStatement(!0);this.setNextStatement(!0);this.setColour(Blockly.Blocks.procedures.HUE);this.setTooltip(Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP);this.setHelpUrl(Blockly.Msg.PROCEDURES_IFRETURN_HELPURL);this.hasReturnValue_=!0},
mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("value",Number(this.hasReturnValue_));return a},domToMutation:function(a){this.hasReturnValue_=1==a.getAttribute("value");this.hasReturnValue_||(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN))},onchange:function(a){a=!1;var b=this;do{if(-1!=this.FUNCTION_TYPES.indexOf(b.type)){a=!0;break}b=b.getSurroundParent()}while(b);a?("procedures_defnoreturn"==b.type&&
this.hasReturnValue_?(this.removeInput("VALUE"),this.appendDummyInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!1):"procedures_defreturn"!=b.type||this.hasReturnValue_||(this.removeInput("VALUE"),this.appendValueInput("VALUE").appendField(Blockly.Msg.PROCEDURES_DEFRETURN_RETURN),this.hasReturnValue_=!0),this.setWarningText(null)):this.setWarningText(Blockly.Msg.PROCEDURES_IFRETURN_WARNING)},FUNCTION_TYPES:["procedures_defnoreturn","procedures_defreturn"]};Blockly.Blocks.texts={};Blockly.Blocks.texts.HUE=160;
Blockly.Blocks.text={init:function(){this.setHelpUrl(Blockly.Msg.TEXT_TEXT_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);this.appendDummyInput().appendField(this.newQuote_(!0)).appendField(new Blockly.FieldTextInput(""),"TEXT").appendField(this.newQuote_(!1));this.setOutput(!0,"String");var a=this;this.setTooltip(function(){var b=a.getParent();return b&&b.getInputsInline()&&b.tooltip||Blockly.Msg.TEXT_TEXT_TOOLTIP})},newQuote_:function(a){return new Blockly.FieldImage(a==this.RTL?"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAqUlEQVQI1z3KvUpCcRiA8ef9E4JNHhI0aFEacm1o0BsI0Slx8wa8gLauoDnoBhq7DcfWhggONDmJJgqCPA7neJ7p934EOOKOnM8Q7PDElo/4x4lFb2DmuUjcUzS3URnGib9qaPNbuXvBO3sGPHJDRG6fGVdMSeWDP2q99FQdFrz26Gu5Tq7dFMzUvbXy8KXeAj57cOklgA+u1B5AoslLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg==":
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAAn0lEQVQI1z3OMa5BURSF4f/cQhAKjUQhuQmFNwGJEUi0RKN5rU7FHKhpjEH3TEMtkdBSCY1EIv8r7nFX9e29V7EBAOvu7RPjwmWGH/VuF8CyN9/OAdvqIXYLvtRaNjx9mMTDyo+NjAN1HNcl9ZQ5oQMM3dgDUqDo1l8DzvwmtZN7mnD+PkmLa+4mhrxVA9fRowBWmVBhFy5gYEjKMfz9AylsaRRgGzvZAAAAAElFTkSuQmCC",12,12,'"')}};
Blockly.Blocks.text_join={init:function(){this.setHelpUrl(Blockly.Msg.TEXT_JOIN_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);this.itemCount_=2;this.updateShape_();this.setOutput(!0,"String");this.setMutator(new Blockly.Mutator(["text_create_join_item"]));this.setTooltip(Blockly.Msg.TEXT_JOIN_TOOLTIP)},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("items",this.itemCount_);return a},domToMutation:function(a){this.itemCount_=parseInt(a.getAttribute("items"),10);
this.updateShape_()},decompose:function(a){var b=a.newBlock("text_create_join_container");b.initSvg();for(var c=b.getInput("STACK").connection,e=0;e<this.itemCount_;e++){var d=a.newBlock("text_create_join_item");d.initSvg();c.connect(d.previousConnection);c=d.nextConnection}return b},compose:function(a){var b=a.getInputTargetBlock("STACK");for(a=[];b;)a.push(b.valueConnection_),b=b.nextConnection&&b.nextConnection.targetBlock();for(b=0;b<this.itemCount_;b++){var c=this.getInput("ADD"+b).connection.targetConnection;
c&&-1==a.indexOf(c)&&c.disconnect()}this.itemCount_=a.length;this.updateShape_();for(b=0;b<this.itemCount_;b++)Blockly.Mutator.reconnect(a[b],this,"ADD"+b)},saveConnections:function(a){a=a.getInputTargetBlock("STACK");for(var b=0;a;){var c=this.getInput("ADD"+b);a.valueConnection_=c&&c.connection.targetConnection;b++;a=a.nextConnection&&a.nextConnection.targetBlock()}},updateShape_:function(){this.itemCount_&&this.getInput("EMPTY")?this.removeInput("EMPTY"):this.itemCount_||this.getInput("EMPTY")||
this.appendDummyInput("EMPTY").appendField(this.newQuote_(!0)).appendField(this.newQuote_(!1));for(var a=0;a<this.itemCount_;a++)if(!this.getInput("ADD"+a)){var b=this.appendValueInput("ADD"+a);0==a&&b.appendField(Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH)}for(;this.getInput("ADD"+a);)this.removeInput("ADD"+a),a++},newQuote_:Blockly.Blocks.text.newQuote_};
Blockly.Blocks.text_create_join_container={init:function(){this.setColour(Blockly.Blocks.texts.HUE);this.appendDummyInput().appendField(Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN);this.appendStatementInput("STACK");this.setTooltip(Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.text_create_join_item={init:function(){this.setColour(Blockly.Blocks.texts.HUE);this.appendDummyInput().appendField(Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM);this.setPreviousStatement(!0);this.setNextStatement(!0);this.setTooltip(Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP);this.contextMenu=!1}};
Blockly.Blocks.text_append={init:function(){this.setHelpUrl(Blockly.Msg.TEXT_APPEND_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);this.appendValueInput("TEXT").appendField(Blockly.Msg.TEXT_APPEND_TO).appendField(new Blockly.FieldVariable(Blockly.Msg.TEXT_APPEND_VARIABLE),"VAR").appendField(Blockly.Msg.TEXT_APPEND_APPENDTEXT);this.setPreviousStatement(!0);this.setNextStatement(!0);var a=this;this.setTooltip(function(){return Blockly.Msg.TEXT_APPEND_TOOLTIP.replace("%1",a.getFieldValue("VAR"))})}};
Blockly.Blocks.text_length={init:function(){this.jsonInit({message0:Blockly.Msg.TEXT_LENGTH_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Number",colour:Blockly.Blocks.texts.HUE,tooltip:Blockly.Msg.TEXT_LENGTH_TOOLTIP,helpUrl:Blockly.Msg.TEXT_LENGTH_HELPURL})}};
Blockly.Blocks.text_isEmpty={init:function(){this.jsonInit({message0:Blockly.Msg.TEXT_ISEMPTY_TITLE,args0:[{type:"input_value",name:"VALUE",check:["String","Array"]}],output:"Boolean",colour:Blockly.Blocks.texts.HUE,tooltip:Blockly.Msg.TEXT_ISEMPTY_TOOLTIP,helpUrl:Blockly.Msg.TEXT_ISEMPTY_HELPURL})}};
Blockly.Blocks.text_indexOf={init:function(){var a=[[Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST,"FIRST"],[Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST,"LAST"]];this.setHelpUrl(Blockly.Msg.TEXT_INDEXOF_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);this.setOutput(!0,"Number");this.appendValueInput("VALUE").setCheck("String").appendField(Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT);this.appendValueInput("FIND").setCheck("String").appendField(new Blockly.FieldDropdown(a),"END");Blockly.Msg.TEXT_INDEXOF_TAIL&&this.appendDummyInput().appendField(Blockly.Msg.TEXT_INDEXOF_TAIL);
this.setInputsInline(!0);a=Blockly.Msg.TEXT_INDEXOF_TOOLTIP.replace("%1",Blockly.Blocks.ONE_BASED_INDEXING?"0":"-1");this.setTooltip(a)}};
Blockly.Blocks.text_charAt={init:function(){this.WHERE_OPTIONS=[[Blockly.Msg.TEXT_CHARAT_FROM_START,"FROM_START"],[Blockly.Msg.TEXT_CHARAT_FROM_END,"FROM_END"],[Blockly.Msg.TEXT_CHARAT_FIRST,"FIRST"],[Blockly.Msg.TEXT_CHARAT_LAST,"LAST"],[Blockly.Msg.TEXT_CHARAT_RANDOM,"RANDOM"]];this.setHelpUrl(Blockly.Msg.TEXT_CHARAT_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);this.setOutput(!0,"String");this.appendValueInput("VALUE").setCheck("String").appendField(Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT);this.appendDummyInput("AT");
this.setInputsInline(!0);this.updateAt_(!0);var a=this;this.setTooltip(function(){var b=a.getFieldValue("WHERE"),c=Blockly.Msg.TEXT_CHARAT_TOOLTIP;if("FROM_START"==b||"FROM_END"==b)c+=" "+Blockly.Msg.LISTS_INDEX_FROM_END_TOOLTIP.replace("%1",Blockly.Blocks.ONE_BASED_INDEXING?"#1":"#0");return c})},mutationToDom:function(){var a=document.createElement("mutation"),b=this.getInput("AT").type==Blockly.INPUT_VALUE;a.setAttribute("at",b);return a},domToMutation:function(a){a="false"!=a.getAttribute("at");
this.updateAt_(a)},updateAt_:function(a){this.removeInput("AT");this.removeInput("ORDINAL",!0);a?(this.appendValueInput("AT").setCheck("Number"),Blockly.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL").appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX)):this.appendDummyInput("AT");Blockly.Msg.TEXT_CHARAT_TAIL&&(this.removeInput("TAIL",!0),this.appendDummyInput("TAIL").appendField(Blockly.Msg.TEXT_CHARAT_TAIL));var b=new Blockly.FieldDropdown(this.WHERE_OPTIONS,function(b){var c="FROM_START"==
b||"FROM_END"==b;if(c!=a){var d=this.sourceBlock_;d.updateAt_(c);d.setFieldValue(b,"WHERE");return null}});this.getInput("AT").appendField(b,"WHERE")}};
Blockly.Blocks.text_getSubstring={init:function(){this.WHERE_OPTIONS_1=[[Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START,"FROM_START"],[Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END,"FROM_END"],[Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST,"FIRST"]];this.WHERE_OPTIONS_2=[[Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START,"FROM_START"],[Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END,"FROM_END"],[Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST,"LAST"]];this.setHelpUrl(Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);
this.appendValueInput("STRING").setCheck("String").appendField(Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT);this.appendDummyInput("AT1");this.appendDummyInput("AT2");Blockly.Msg.TEXT_GET_SUBSTRING_TAIL&&this.appendDummyInput("TAIL").appendField(Blockly.Msg.TEXT_GET_SUBSTRING_TAIL);this.setInputsInline(!0);this.setOutput(!0,"String");this.updateAt_(1,!0);this.updateAt_(2,!0);this.setTooltip(Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP)},mutationToDom:function(){var a=document.createElement("mutation"),
b=this.getInput("AT1").type==Blockly.INPUT_VALUE;a.setAttribute("at1",b);b=this.getInput("AT2").type==Blockly.INPUT_VALUE;a.setAttribute("at2",b);return a},domToMutation:function(a){var b="true"==a.getAttribute("at1");a="true"==a.getAttribute("at2");this.updateAt_(1,b);this.updateAt_(2,a)},updateAt_:function(a,b){this.removeInput("AT"+a);this.removeInput("ORDINAL"+a,!0);b?(this.appendValueInput("AT"+a).setCheck("Number"),Blockly.Msg.ORDINAL_NUMBER_SUFFIX&&this.appendDummyInput("ORDINAL"+a).appendField(Blockly.Msg.ORDINAL_NUMBER_SUFFIX)):
this.appendDummyInput("AT"+a);2==a&&Blockly.Msg.TEXT_GET_SUBSTRING_TAIL&&(this.removeInput("TAIL",!0),this.appendDummyInput("TAIL").appendField(Blockly.Msg.TEXT_GET_SUBSTRING_TAIL));var c=new Blockly.FieldDropdown(this["WHERE_OPTIONS_"+a],function(c){var d="FROM_START"==c||"FROM_END"==c;if(d!=b){var e=this.sourceBlock_;e.updateAt_(a,d);e.setFieldValue(c,"WHERE"+a);return null}});this.getInput("AT"+a).appendField(c,"WHERE"+a);1==a&&this.moveInputBefore("AT1","AT2")}};
Blockly.Blocks.text_changeCase={init:function(){var a=[[Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE,"UPPERCASE"],[Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE,"LOWERCASE"],[Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE,"TITLECASE"]];this.setHelpUrl(Blockly.Msg.TEXT_CHANGECASE_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);this.appendValueInput("TEXT").setCheck("String").appendField(new Blockly.FieldDropdown(a),"CASE");this.setOutput(!0,"String");this.setTooltip(Blockly.Msg.TEXT_CHANGECASE_TOOLTIP)}};
Blockly.Blocks.text_trim={init:function(){var a=[[Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH,"BOTH"],[Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT,"LEFT"],[Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT,"RIGHT"]];this.setHelpUrl(Blockly.Msg.TEXT_TRIM_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);this.appendValueInput("TEXT").setCheck("String").appendField(new Blockly.FieldDropdown(a),"MODE");this.setOutput(!0,"String");this.setTooltip(Blockly.Msg.TEXT_TRIM_TOOLTIP)}};
Blockly.Blocks.text_print={init:function(){this.jsonInit({message0:Blockly.Msg.TEXT_PRINT_TITLE,args0:[{type:"input_value",name:"TEXT"}],previousStatement:null,nextStatement:null,colour:Blockly.Blocks.texts.HUE,tooltip:Blockly.Msg.TEXT_PRINT_TOOLTIP,helpUrl:Blockly.Msg.TEXT_PRINT_HELPURL})}};
Blockly.Blocks.text_prompt_ext={init:function(){var a=[[Blockly.Msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]];this.setHelpUrl(Blockly.Msg.TEXT_PROMPT_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);var b=this,a=new Blockly.FieldDropdown(a,function(a){b.updateType_(a)});this.appendValueInput("TEXT").appendField(a,"TYPE");this.setOutput(!0,"String");this.setTooltip(function(){return"TEXT"==b.getFieldValue("TYPE")?Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT:Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER})},
updateType_:function(a){this.outputConnection.setCheck("NUMBER"==a?"Number":"String")},mutationToDom:function(){var a=document.createElement("mutation");a.setAttribute("type",this.getFieldValue("TYPE"));return a},domToMutation:function(a){this.updateType_(a.getAttribute("type"))}};
Blockly.Blocks.text_prompt={init:function(){var a=[[Blockly.Msg.TEXT_PROMPT_TYPE_TEXT,"TEXT"],[Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER,"NUMBER"]],b=this;this.setHelpUrl(Blockly.Msg.TEXT_PROMPT_HELPURL);this.setColour(Blockly.Blocks.texts.HUE);a=new Blockly.FieldDropdown(a,function(a){b.updateType_(a)});this.appendDummyInput().appendField(a,"TYPE").appendField(this.newQuote_(!0)).appendField(new Blockly.FieldTextInput(""),"TEXT").appendField(this.newQuote_(!1));this.setOutput(!0,"String");this.setTooltip(function(){return"TEXT"==
b.getFieldValue("TYPE")?Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT:Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER})},newQuote_:Blockly.Blocks.text.newQuote_,updateType_:Blockly.Blocks.text_prompt_ext.updateType_,mutationToDom:Blockly.Blocks.text_prompt_ext.mutationToDom,domToMutation:Blockly.Blocks.text_prompt_ext.domToMutation};Blockly.Blocks.variables={};Blockly.Blocks.variables.HUE=330;
Blockly.Blocks.variables_get={init:function(){this.setHelpUrl(Blockly.Msg.VARIABLES_GET_HELPURL);this.setColour(Blockly.Blocks.variables.HUE);this.appendDummyInput().appendField(new Blockly.FieldVariable(Blockly.Msg.VARIABLES_DEFAULT_NAME),"VAR");this.setOutput(!0);this.setTooltip(Blockly.Msg.VARIABLES_GET_TOOLTIP);this.contextMenuMsg_=Blockly.Msg.VARIABLES_GET_CREATE_SET},contextMenuType_:"variables_set",customContextMenu:function(a){var b={enabled:!0},c=this.getFieldValue("VAR");b.text=this.contextMenuMsg_.replace("%1",
c);c=goog.dom.createDom("field",null,c);c.setAttribute("name","VAR");c=goog.dom.createDom("block",null,c);c.setAttribute("type",this.contextMenuType_);b.callback=Blockly.ContextMenu.callbackFactory(this,c);a.push(b)}};
Blockly.Blocks.variables_set={init:function(){this.jsonInit({message0:Blockly.Msg.VARIABLES_SET,args0:[{type:"field_variable",name:"VAR",variable:Blockly.Msg.VARIABLES_DEFAULT_NAME},{type:"input_value",name:"VALUE"}],previousStatement:null,nextStatement:null,colour:Blockly.Blocks.variables.HUE,tooltip:Blockly.Msg.VARIABLES_SET_TOOLTIP,helpUrl:Blockly.Msg.VARIABLES_SET_HELPURL});this.contextMenuMsg_=Blockly.Msg.VARIABLES_SET_CREATE_GET},contextMenuType_:"variables_get",customContextMenu:Blockly.Blocks.variables_get.customContextMenu};
|
#!/usr/bin/env node
'use strict';
let client = require('../init-client');
console.log('Retrieving user...');
client.users.get()
.then(user => {
if (user === undefined) {
return console.log(' Not found.');
}
console.log(` Username: ${user.username}`);
console.log(` Device type: ${user.deviceType}`);
console.log(` Create date: ${user.created}`);
console.log(` Last use date: ${user.lastUsed}`);
})
.catch(error => {
console.log(error.stack);
});
|
var RepositoryController = Ember.Controller.extend({
needs: ['dashboard'],
path: Ember.computed.alias('controllers.dashboard.id')
});
export default RepositoryController;
|
var Map = function(filename) {
this.x = 0;
this.y = 0;
this.mapData = load('res/maps/' + filename);
this.tileset = load('res/tilesets/' + this.mapData.tileset.path);
this.data = this.mapData.layers[0].data;
this.draw = function(ctx) {
ctx.fillStyle = 'white';
var width = Math.floor(ctx.canvas.width / 16);
var height = Math.floor(ctx.canvas.height / 16);
for (var x = 0; x < width; ++x) {
for (var y = 0; y < height; ++y) {
var spritePos = this.data[x + y * this.mapData.width] - 1;
if (spritePos != undefined && x < this.mapData.width) {
ctx.drawImage(
this.tileset, // tileset
(spritePos % this.mapData.tileset.width) * 16, // tile x offset
Math.floor(spritePos / this.mapData.tileset.width) * 16, // tile y offset
16, // tile width in tileset
16, // tile height in tileset
x * 16 + ctx.canvas.width / 2 - 8 - this.x, // pos x
y * 16 + ctx.canvas.height / 2 - 8 - this.y, // pos y
16, // tile width on screen
16 // tile height on screen
);
}
}
}
// player rect
ctx.strokeStyle = '#FF0000';
ctx.rect(ctx.canvas.width / 2 - 8, ctx.canvas.height / 2 - 8, 16, 16);
ctx.stroke();
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:5788f7718a6d40a47e10cb78b0bf45912d2dcd1a1a40a249cddc1e645001f5a0
size 799
|
/**
* [Event descripticon]
*/
window.$MR.Event = {};
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[6],{304:function(t,n,e){"use strict";e.r(n);var r=e(38),s=Object(r.a)({},(function(){var t=this.$createElement,n=this._self._c||t;return n("ContentSlotsDistributor",{attrs:{"slot-key":this.$parent.slotKey}},[n("p",[n("a",{attrs:{href:"https://auth0.com/blog/securing-spring-boot-apis-and-spas-with-oauth2/",target:"_blank",rel:"noopener noreferrer"}},[this._v("Securing Spring Boot APIs and SPAs with OAuth 2.0"),n("OutboundLink")],1)])])}),[],!1,null,null,null);n.default=s.exports}}]);
|
'use strict';
angular.module('biyblApp')
.service('bcvParser', function () {
// AngularJS will instantiate a singleton by calling "new" on this function
});
|
import Nav from './Nav'
export {default as NavTree} from './NavTree'
export default Nav
export {navTable, navHorizontal, navVertical, navDynamic} from './NavFunctions'
|
const config = require('./../../config/config');
const debug = require('debug')('service:auth');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
class AuthService {
constructor() {
this.tokenMiddleware = this.tokenMiddleware.bind(this);
this.generateTempToken = this.generateTempToken.bind(this);
}
tokenMiddleware(guestRoutes) {
return (req, res, next) => {
if (req.method === 'OPTIONS' || req.url.indexOf('/api/') === -1) {
return next();
}
var token = req.headers['authorization'];
if (guestRoutes.reduce((isMatched, current) => {
if (req.url.indexOf(current) !== -1) {
return true;
}
return isMatched;
}, false)
) {
return next();
}
jwt.verify(token, config.server.jwt.secret, (err, user) => {
if (err) {
debug('got wrong token', token);
const error = new Error('Invalid credentials, please authorize');
error.status = 401;
next(error);
} else {
debug('success token for user', user);
if (!user._id || !user.email) {
debug('token user data mismatch', user);
const error = new Error('Invalid credentials, please authorize');
error.status = 401;
next(error);
}
req.user = user;
next();
}
});
};
}
generateTempToken(done) {
crypto.randomBytes(15, (err, buf) => {
const token = !err ? buf.toString('hex') : '';
done(err, token);
});
}
}
module.exports = new AuthService();
|
'use strict';
const execBuffer = require('exec-buffer');
const isPng = require('is-png');
const optipng = require('optipng-bin');
module.exports = options => async buffer => {
options = {
optimizationLevel: 3,
bitDepthReduction: true,
colorTypeReduction: true,
paletteReduction: true,
interlaced: false,
errorRecovery: true,
...options
};
if (!Buffer.isBuffer(buffer)) {
throw new TypeError('Expected a buffer');
}
if (!isPng(buffer)) {
return buffer;
}
const arguments_ = [
'-strip',
'all',
'-clobber',
'-o',
options.optimizationLevel,
'-out',
execBuffer.output
];
if (options.errorRecovery) {
arguments_.push('-fix');
}
if (!options.bitDepthReduction) {
arguments_.push('-nb');
}
if (typeof options.interlaced === 'boolean') {
arguments_.push('-i', options.interlaced ? '1' : '0');
}
if (!options.colorTypeReduction) {
arguments_.push('-nc');
}
if (!options.paletteReduction) {
arguments_.push('-np');
}
arguments_.push(execBuffer.input);
return execBuffer({
input: buffer,
bin: optipng,
args: arguments_
});
};
|
import {
createStore,
applyMiddleware,
compose,
combineReducers
} from 'redux';
import createSagaMiddleware from 'redux-saga';
import { initializeCurrentLocation } from 'redux-little-router';
import allReducers from '../redux';
import rootSaga from '../sagas';
import routerObj from './routes.js';
const getCompose = () => {
if (process.env.NODE_ENV !== 'production' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) {
return window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
}
return compose;
}
const sageMiddleware = createSagaMiddleware();
const composeEnhancers = getCompose();
const store = createStore(
combineReducers({
localAppData: allReducers,
router: routerObj.reducer
}),
composeEnhancers(
routerObj.enhancer,
applyMiddleware(
sageMiddleware,
routerObj.middleware
)
)
)
sageMiddleware.run(rootSaga);
const initialLocation = store.getState().router;
if (initialLocation) {
store.dispatch(initializeCurrentLocation(initialLocation));
};
export default store
|
'use strict';
var aws = require('aws-sdk');
var s3 = new aws.S3();
const fs = require('fs');
const util = require('util');
const exec = require('child_process').execSync;
var sync = require('child_process').spawnSync;
exports.handler = (event, context, callback) => {
process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];
// var bucketName = 'rubixcube';
// var imagefileName = 'test.png';
var bucketName = event.bucketName;
var imagefileName = event.imagefileName;
console.log( bucketName + " " + imagefileName);
// var params = {Bucket: 'pronovosrubixcube123', Key: 'example-abstract.pdf'};
var params = {Bucket: bucketName, Key: imagefileName};
var ocrText = 'ne docekuva';
s3.getObject(params).promise().then( data => {
// console.log("snimam na tmp");
fs.writeFileSync("/tmp/"+imagefileName, data.Body, 'utf8');
var vvv = exec('LD_LIBRARY_PATH=./lib TESSDATA_PREFIX=./ ./tesseract /tmp/'+imagefileName+' stdout -l eng', (error, stdout, stderr) => {
if (error) {
console.log(`exec error: ${error}`);
callback('error', JSON.stringify(error));
}
else{
console.log(JSON.stringify(stdout));
callback('stdout', JSON.stringify(stdout));
}
});
// });
// console.log(vvv);
callback(null, JSON.stringify(vvv.toString('utf8')));
});
};
|
var searchData=
[
['utils_5fh',['UTILS_H',['../utils_8h.html#a4f4a6641716bd0f4b9fe38c4f18e6550',1,'utils.h']]]
];
|
'use strict';
/* Directives */
angular.module('myApp.directives',['ngSanitize','myApp.services']).
directive('lorem', function(imageBuilder) {
return {
restrict: 'EA',
scope:{
text:'@',
count:'@',
width:'@',
height:'@',
category:'@'
},
templateUrl:'partials/lorem-image.html',
controller: function($scope) {
$scope.images = imageBuilder.build($scope.width,
$scope.height,
$scope.category,
$scope.count,
$scope.text)
}
}
});
|
var test = require('tape');
var sync = require('../ampersand-sync');
var Model = require('ampersand-model');
test('should get a response for read', function (t) {
t.plan(2);
var Me = Model.extend({
url: 'http://www.mocky.io/v2/54f1d2b932d8370a036e5b21',
ajaxConfig: {
useXDR: true
},
props: {
foo: 'string'
},
sync: sync //override with this sync, so fetch doesn't use the stable one from dependencies
});
var m = new Me();
m.on('change', function () {
//TODO: assert more arguments
t.equal(m.foo, "bar");
});
m.fetch({
success: function (data) {
//TODO: assert more arguments
t.equal(data.foo, "bar");
t.end();
},
error: function () {
t.fail('error while fetching (are you offline?)');
t.end();
}
});
});
test('should call error when read results in 404', function (t) {
t.plan(1);
var Me = Model.extend({
url: '/nothing',
sync: sync
});
var m = new Me();
m.fetch({
success: function () {
t.fail('unexpected success call');
t.end();
},
error: function () {
t.pass('received an expected error');
t.end();
}
});
});
|
"use strict";
if (typeof (JSIL) === "undefined")
throw new Error("JSIL.Core is required");
if (!$jsilcore)
throw new Error("JSIL.Core is required");
JSIL.DeclareNamespace("JSIL.PInvoke");
// Used to access shared heap
var warnedAboutMultiModule = false;
JSIL.PInvoke.CurrentCallContext = null;
JSIL.PInvoke.GetGlobalModule = function () {
var module = JSIL.GlobalNamespace.Module || JSIL.__NativeModules__["__global__"];
if (!module)
JSIL.RuntimeError("No emscripten modules loaded");
if (Object.keys(JSIL.__NativeModules__).length > 2) {
if (!warnedAboutMultiModule) {
warnedAboutMultiModule = true;
JSIL.Host.warning("More than one Emscripten module is loaded, so operations that need a global heap will fail. This is due to a limitation of Emscripten.");
}
}
return module;
};
// Used in operations like AllocHGlobal to try and ensure we pick the best possible
// heap during marshaling operations (when we have a good guess) instead of just choking
JSIL.PInvoke.GetDefaultModule = function () {
if (JSIL.PInvoke.CurrentCallContext)
return JSIL.PInvoke.CurrentCallContext.module;
else
return JSIL.PInvoke.GetGlobalModule();
};
// Used to access specific entry points
JSIL.PInvoke.GetModule = function (name, throwOnFail) {
var modules = JSIL.__NativeModules__;
// HACK
var key = name.toLowerCase().replace(".so", ".dll");
var module = modules[key];
if (!module && (throwOnFail !== false))
JSIL.RuntimeError("No module named '" + name + "' loaded.");
return module;
};
// Locates the emscripten module that owns a given heap
JSIL.PInvoke.GetModuleForHeap = function (heap, throwOnFail) {
var buffer;
if (!heap)
JSIL.RuntimeError("No heap provided");
else if (heap && heap.buffer)
buffer = heap.buffer;
else
buffer = heap;
var nm = JSIL.__NativeModules__;
for (var k in nm) {
if (!nm.hasOwnProperty(k))
continue;
var m = nm[k];
var mBuffer = m.HEAPU8.buffer;
if (mBuffer === buffer)
return m;
}
if (throwOnFail !== false)
JSIL.RuntimeError("No module owns the specified heap");
return null;
};
JSIL.PInvoke.PickModuleForPointer = function (pointer, enableFallback) {
var result = null;
if (pointer.pointer) {
result = JSIL.PInvoke.GetModuleForHeap(pointer.pointer.memoryRange.buffer, !enableFallback);
}
if (result === null) {
if (enableFallback) {
result = JSIL.PInvoke.GetDefaultModule();
} else {
JSIL.RuntimeError("No appropriate module available");
}
}
return result;
};
JSIL.PInvoke.CreateBytePointerForModule = function (module, address) {
var memoryRange = JSIL.GetMemoryRangeForBuffer(module.HEAPU8.buffer);
var emscriptenMemoryView = memoryRange.getView(System.Byte.__Type__);
var emscriptenPointer = new JSIL.BytePointer(System.Byte.__Type__, memoryRange, emscriptenMemoryView, address);
return emscriptenPointer;
};
JSIL.PInvoke.CreateIntPtrForModule = function (module, address) {
var emscriptenPointer = JSIL.PInvoke.CreateBytePointerForModule(module, address);
var intPtr = JSIL.CreateInstanceOfType(
System.IntPtr.__Type__,
"$fromPointer",
[emscriptenPointer]
);
return intPtr;
};
JSIL.PInvoke.DestroyFunctionPointer = function (fp) {
var nm = JSIL.__NativeModules__;
for (var k in nm) {
if (!nm.hasOwnProperty(k))
continue;
if (k === "__global__")
continue;
var module = nm[k];
module.Runtime.removeFunction(fp);
}
return result;
};
JSIL.MakeClass("System.Object", "JSIL.Runtime.NativePackedArray`1", true, ["T"], function ($) {
var T = new JSIL.GenericParameter("T", "JSIL.Runtime.NativePackedArray`1");
var TArray = System.Array.Of(T);
$.Field({Public: false, Static: false, ReadOnly: true}, "_Array", TArray);
$.Field({Public: true , Static: false, ReadOnly: true}, "Length", $.Int32);
$.Field({Public: false, Static: false}, "IsNotDisposed", $.Boolean);
$.RawMethod(false, "$innerCtor", function innerCtor (module, size) {
this.Length = size;
this.IsNotDisposed = true;
this.ElementSize = JSIL.GetNativeSizeOf(this.T, false);
var sizeBytes = this.ElementSize * this.Length;
this.Module = module;
this.EmscriptenOffset = module._malloc(sizeBytes);
var tByte = $jsilcore.System.Byte.__Type__;
this.MemoryRange = new JSIL.MemoryRange(module.HEAPU8.buffer, this.EmscriptenOffset, sizeBytes);
if (this.T.__IsNativeType__) {
this._Array = this.MemoryRange.getView(this.T);
} else {
var buffer = this.MemoryRange.getView(tByte);
var arrayType = JSIL.PackedStructArray.Of(elementTypeObject);
this._Array = new arrayType(buffer, this.MemoryRange);
}
});
$.Method({Static: false, Public: true }, ".ctor",
new JSIL.MethodSignature(null, [$.Int32], []),
function (size) {
this.$innerCtor(JSIL.PInvoke.GetDefaultModule(), size);
}
);
$.Method({Static: false, Public: true }, ".ctor",
new JSIL.MethodSignature(null, [$.String, $.Int32], []),
function (dllName, size) {
this.$innerCtor(JSIL.PInvoke.GetModule(dllName), size);
}
);
$.Method({Static: true, Public: true }, "op_Implicit",
new JSIL.MethodSignature(TArray, [T], []),
function (self) {
return self._Array;
}
);
$.Method(
{Public: true , Static: false}, "get_Array",
new JSIL.MethodSignature(TArray, [], []),
function get_Array () {
return this._Array;
}
);
$.Method(
{Public: true , Static: false}, "Dispose",
JSIL.MethodSignature.Void,
function Dispose () {
if (!this.IsNotDisposed)
// FIXME: Throw
return;
this.IsNotDisposed = false;
this.Module._free(this.EmscriptenOffset);
}
);
$.Property({}, "Array");
$.ImplementInterfaces(
/* 0 */ System.IDisposable
);
});
JSIL.PInvoke.CallContext = function (module) {
// HACK: Save and restore the current call context value.
// This is important so operations like AllocHGlobal can choose the right module.
this.prior = JSIL.PInvoke.CurrentCallContext;
JSIL.PInvoke.CurrentCallContext = this;
this.module = module;
this.allocations = [];
this.cleanups = [];
};
JSIL.PInvoke.CallContext.prototype.Allocate = function (sizeBytes) {
var offset = this.module._malloc(sizeBytes);
this.allocations.push(offset);
return offset;
};
JSIL.PInvoke.CallContext.prototype.Dispose = function () {
JSIL.PInvoke.CurrentCallContext = this.prior;
for (var i = 0, l = this.cleanups.length; i < l; i++) {
var c = this.cleanups[i];
c();
}
this.cleanups.length = 0;
for (var i = 0, l = this.allocations.length; i < l; i++) {
var a = this.allocations[i];
this.module._free(a);
}
this.allocations.length = 0;
};
// FIXME: Kill this
JSIL.PInvoke.CallContext.prototype.QueueCleanup = function (callback) {
this.cleanups.push(callback);
}
// JavaScript is garbage
JSIL.PInvoke.SetupMarshallerPrototype = function (t) {
t.prototype = Object.create(JSIL.PInvoke.BaseMarshallerPrototype);
t.prototype.constructor = t;
};
JSIL.PInvoke.BaseMarshallerPrototype = Object.create(Object.prototype);
JSIL.PInvoke.BaseMarshallerPrototype.GetSignatureToken = function (type) {
JSIL.RuntimeError("Marshaller of type '" + this.constructor.name + "' has no signature token implementation");
};
JSIL.PInvoke.ByValueMarshaller = function ByValueMarshaller (type) {
this.type = type;
};
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.ByValueMarshaller);
JSIL.PInvoke.ByValueMarshaller.prototype.GetSignatureToken = function () {
var storageType = this.type.__IsEnum__ ? this.type.__StorageType__ : this.type;
switch (storageType.__FullName__) {
case "System.Int32":
case "System.UInt32":
case "System.Boolean":
return "i";
case "System.Single":
case "System.Double":
return "d";
}
JSIL.RuntimeError("No signature token for type '" + this.type.__FullName__ + "'");
};
JSIL.PInvoke.ByValueMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
return managedValue;
};
JSIL.PInvoke.ByValueMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
return nativeValue;
};
JSIL.PInvoke.BoxedValueMarshaller = function BoxedValueMarshaller (type) {
this.type = type;
this.sizeInBytes = JSIL.GetNativeSizeOf(type, false);
this.namedReturnValue = true;
};
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.BoxedValueMarshaller);
JSIL.PInvoke.BoxedValueMarshaller.prototype.AllocateZero = function (callContext) {
return callContext.Allocate(this.sizeInBytes);
};
JSIL.PInvoke.BoxedValueMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
var module = callContext.module;
var offset = callContext.Allocate(this.sizeInBytes);
var tByte = $jsilcore.System.Byte.__Type__;
var memoryRange = JSIL.GetMemoryRangeForBuffer(module.HEAPU8.buffer);
var emscriptenMemoryView = memoryRange.getView(tByte);
var emscriptenPointer = JSIL.NewPointer(
this.type, memoryRange, emscriptenMemoryView, offset
);
emscriptenPointer.set(managedValue);
return offset;
};
JSIL.PInvoke.BoxedValueMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
var module = callContext.module;
var tByte = $jsilcore.System.Byte.__Type__;
var memoryRange = JSIL.GetMemoryRangeForBuffer(module.HEAPU8.buffer);
var emscriptenMemoryView = memoryRange.getView(tByte);
var emscriptenPointer = JSIL.NewPointer(
this.type, memoryRange, emscriptenMemoryView, nativeValue
);
return emscriptenPointer.get();
};
JSIL.PInvoke.ByValueStructMarshaller = function ByValueStructMarshaller (type) {
this.type = type;
this.sizeInBytes = JSIL.GetNativeSizeOf(type, true);
this.marshaller = JSIL.$GetStructMarshaller(type);
this.unmarshalConstructor = JSIL.$GetStructUnmarshalConstructor(type);
// clang/emscripten optimization for single-member structs as return values
if (JSIL.GetFieldList(type).length === 1) {
this.unpackedReturnValue = true;
this.namedReturnValue = false;
} else {
this.unpackedReturnValue = false;
this.namedReturnValue = true;
}
};
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.ByValueStructMarshaller);
JSIL.PInvoke.ByValueStructMarshaller.prototype.GetSignatureToken = function () {
return "i";
};
JSIL.PInvoke.ByValueStructMarshaller.prototype.AllocateZero = function (callContext) {
return callContext.Allocate(this.sizeInBytes);
};
JSIL.PInvoke.ByValueStructMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
var module = callContext.module;
var offset = callContext.Allocate(this.sizeInBytes);
this.marshaller(managedValue, module.HEAPU8, offset);
return offset;
};
JSIL.PInvoke.ByValueStructMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
var module = callContext.module;
if (this.unpackedReturnValue) {
// FIXME: Is this always an int32?
var scratchBytes = $jsilcore.BytesFromInt32(nativeValue);
return new (this.unmarshalConstructor)(scratchBytes, 0);
} else {
return new (this.unmarshalConstructor)(module.HEAPU8, nativeValue);
}
};
JSIL.PInvoke.IntPtrMarshaller = function IntPtrMarshaller () {
};
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.IntPtrMarshaller);
JSIL.PInvoke.IntPtrMarshaller.prototype.GetSignatureToken = function () {
return "i";
};
JSIL.PInvoke.IntPtrMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
if (managedValue.pointer) {
if (callContext.module.HEAPU8.buffer !== managedValue.pointer.memoryRange.buffer)
JSIL.RuntimeError("The pointer does not point into the module's heap");
return managedValue.pointer.offsetInBytes | 0;
} else {
// HACK: We have no way to know this address is in the correct heap.
// FIXME: Preserve 53 bits?
return managedValue.value.ToInt32() | 0;
}
};
JSIL.PInvoke.IntPtrMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
return JSIL.PInvoke.CreateIntPtrForModule(callContext.module, nativeValue);
};
JSIL.PInvoke.PointerMarshaller = function PointerMarshaller (type) {
this.type = type;
};
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.PointerMarshaller);
JSIL.PInvoke.PointerMarshaller.prototype.GetSignatureToken = function () {
return "i";
};
JSIL.PInvoke.PointerMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
var module = callContext.module;
if (managedValue.memoryRange.buffer !== module.HEAPU8.buffer)
JSIL.RuntimeError("Pointer is not pinned inside the emscripten heap");
return managedValue.offsetInBytes;
};
JSIL.PInvoke.PointerMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
JSIL.RuntimeError("Not implemented");
};
JSIL.PInvoke.ByRefMarshaller = function ByRefMarshaller (type) {
this.type = type;
// XXX (Mispy): should this be necessary? the first is null for ref System.String
this.innerType = type.__ReferentType__.__Type__ || type.__ReferentType__;
this.innerMarshaller = JSIL.PInvoke.GetMarshallerForType(this.innerType, true);
};
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.ByRefMarshaller);
JSIL.PInvoke.ByRefMarshaller.prototype.GetSignatureToken = function () {
return "i";
};
JSIL.PInvoke.ByRefMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
var emscriptenOffset = this.innerMarshaller.ManagedToNative(managedValue.get(), callContext);
var innerMarshaller = this.innerMarshaller;
callContext.QueueCleanup(function () {
managedValue.set(innerMarshaller.NativeToManaged(emscriptenOffset, callContext));
});
return emscriptenOffset;
};
JSIL.PInvoke.ByRefMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
JSIL.RuntimeError("Not valid for byref arguments");
};
JSIL.PInvoke.ArrayMarshaller = function ArrayMarshaller (type, isOut) {
this.type = type;
this.elementType = type.__ElementType__;
this.isOut = isOut;
};
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.ArrayMarshaller);
JSIL.PInvoke.ArrayMarshaller.prototype.GetSignatureToken = function () {
return "i";
};
JSIL.PInvoke.ArrayMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
var module = callContext.module;
var pointer = JSIL.PinAndGetPointer(managedValue, 0, false);
if (pointer === null) {
// Array can't be pinned, so copy to temporary storage one item at a time, then back
// FIXME: Generate a one-time performance warning if this array is big
var arrayLength = managedValue.length;
var itemSizeBytes = JSIL.GetNativeSizeOf(this.elementType);
var sizeBytes = arrayLength * itemSizeBytes;
var emscriptenOffset = callContext.Allocate(sizeBytes);
var destPointer = JSIL.PInvoke.CreateBytePointerForModule(module, emscriptenOffset).cast(this.elementType);
for (var i = 0; i < arrayLength; i++)
destPointer.setElement(i, managedValue[i]);
if (this.isOut) {
callContext.QueueCleanup(function () {
for (var i = 0; i < arrayLength; i++)
managedValue[i] = destPointer.getElement(i);
});
}
return emscriptenOffset;
} else if (pointer.memoryRange.buffer === module.HEAPU8.buffer) {
return pointer.offsetInBytes | 0;
} else {
// Copy to temporary storage on the emscripten heap, then copy back after the call
var sizeBytes = managedValue.byteLength;
var emscriptenOffset = callContext.Allocate(sizeBytes);
var sourceView = pointer.asView($jsilcore.System.Byte, sizeBytes);
var destView = new Uint8Array(module.HEAPU8.buffer, emscriptenOffset, sizeBytes);
if (this.isOut) {
destView.set(sourceView, 0);
callContext.QueueCleanup(function () {
sourceView.set(destView, 0);
});
}
return emscriptenOffset;
}
};
JSIL.PInvoke.ArrayMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
JSIL.RuntimeError("Not valid for array arguments");
};
JSIL.PInvoke.StringBuilderMarshaller = function StringBuilderMarshaller (charSet) {
if (charSet)
JSIL.RuntimeError("Not implemented");
};
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.StringBuilderMarshaller);
JSIL.PInvoke.StringBuilderMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
var sizeInBytes = managedValue.get_Capacity();
var emscriptenOffset = callContext.Allocate(sizeInBytes + 1);
var module = callContext.module;
var tByte = $jsilcore.System.Byte.__Type__;
var memoryRange = JSIL.GetMemoryRangeForBuffer(module.HEAPU8.buffer);
var emscriptenMemoryView = memoryRange.getView(tByte);
for (var i = 0, l = sizeInBytes + 1; i < l; i++)
module.HEAPU8[(i + emscriptenOffset) | 0] = 0;
System.Text.Encoding.ASCII.GetBytes(
managedValue._str, 0, managedValue._str.length, module.HEAPU8, emscriptenOffset
);
callContext.QueueCleanup(function () {
managedValue._str = JSIL.StringFromNullTerminatedByteArray(
module.HEAPU8, emscriptenOffset, managedValue._capacity
);
});
return emscriptenOffset;
};
JSIL.PInvoke.StringBuilderMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
JSIL.RuntimeError("Not valid");
};
JSIL.PInvoke.StringMarshaller = function StringMarshaller (charSet) {
if (charSet)
JSIL.RuntimeError("Not implemented");
this.allocates = true;
};
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.StringMarshaller);
JSIL.PInvoke.StringMarshaller.prototype.GetSignatureToken = function() {
return "i";
}
JSIL.PInvoke.StringMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
var sizeInBytes = managedValue.length;
var emscriptenOffset = callContext.Allocate(sizeInBytes + 1);
var module = callContext.module;
var tByte = $jsilcore.System.Byte.__Type__;
var memoryRange = JSIL.GetMemoryRangeForBuffer(module.HEAPU8.buffer);
var emscriptenMemoryView = memoryRange.getView(tByte);
for (var i = 0, l = sizeInBytes + 1; i < l; i++)
module.HEAPU8[(i + emscriptenOffset) | 0] = 0;
System.Text.Encoding.ASCII.GetBytes(
managedValue, 0, managedValue.length, module.HEAPU8, emscriptenOffset
);
return emscriptenOffset;
};
JSIL.PInvoke.StringMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
JSIL.RuntimeError("Not implemented");
};
JSIL.PInvoke.DelegateMarshaller = function DelegateMarshaller (type) {
this.type = type;
};
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.DelegateMarshaller);
JSIL.PInvoke.DelegateMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
var module = callContext.module;
var wrapper = JSIL.PInvoke.CreateNativeToManagedWrapper(
module, managedValue, this.type.__Signature__
);
var functionPointer = module.Runtime.addFunction(wrapper);
callContext.QueueCleanup(function () {
module.Runtime.removeFunction(functionPointer);
});
return functionPointer;
};
JSIL.PInvoke.DelegateMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
var module = callContext.module;
var wrapper = System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer$b1(
this.type
)(
JSIL.PInvoke.CreateIntPtrForModule(callContext.module, nativeValue)
);
return wrapper;
};
// Fallback UnimplementedMarshaller delays error until the actual point of attempted marshalling
JSIL.PInvoke.UnimplementedMarshaller = function UnimplementedMarshaller (type, errorMsg) {
this.type = type;
}
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.UnimplementedMarshaller);
JSIL.PInvoke.UnimplementedMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
JSIL.RuntimeErrorFormat("Type '{0}' has no marshalling implementation", [this.type.__FullName__]);
}
JSIL.PInvoke.UnimplementedMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
JSIL.RuntimeErrorFormat("Type '{0}' has no marshalling implementation", [this.type.__FullName__]);
}
JSIL.PInvoke.ManagedMarshaller = function ManagedMarshaller (type, customMarshalerType, cookie) {
this.type = type;
this.customMarshalerPublicInterface = JSIL.ResolveTypeReference(customMarshalerType)[0];
if (typeof (cookie) === "string")
this.cookie = cookie;
else
this.cookie = null;
this.cachedInstance = null;
}
JSIL.PInvoke.SetupMarshallerPrototype(JSIL.PInvoke.ManagedMarshaller);
JSIL.PInvoke.ManagedMarshaller.prototype.GetInstance = function () {
if (!this.cachedInstance)
this.cachedInstance = this.customMarshalerPublicInterface.GetInstance(this.cookie);
return this.cachedInstance;
};
JSIL.PInvoke.ManagedMarshaller.prototype.GetSignatureToken = function () {
return "i";
};
JSIL.PInvoke.ManagedMarshaller.prototype.ManagedToNative = function (managedValue, callContext) {
var instance = this.GetInstance();
var ptr = instance.MarshalManagedToNative(managedValue);
callContext.QueueCleanup(function () {
instance.CleanUpNativeData(ptr);
});
var emscriptenOffset = ptr.ToInt32();
return emscriptenOffset;
}
JSIL.PInvoke.ManagedMarshaller.prototype.NativeToManaged = function (nativeValue, callContext) {
var instance = this.GetInstance();
var ptr = JSIL.PInvoke.CreateIntPtrForModule(callContext.module, nativeValue);
var managedValue = instance.MarshalNativeToManaged(ptr);
callContext.QueueCleanup(function () {
instance.CleanUpManagedData(managedValue);
});
return managedValue;
}
JSIL.PInvoke.WrapManagedCustomMarshaler = function (type, customMarshaler, cookie) {
return new JSIL.PInvoke.ManagedMarshaller(type, customMarshaler, cookie);
};
JSIL.PInvoke.GetMarshallerForType = function (type, box, isOut) {
// FIXME: Caching
if (type.__IsByRef__)
return new JSIL.PInvoke.ByRefMarshaller(type);
var typeName = type.__FullNameWithoutArguments__ || type.__FullName__;
switch (typeName) {
case "System.IntPtr":
case "System.UIntPtr":
return new JSIL.PInvoke.IntPtrMarshaller();
case "JSIL.Pointer":
return new JSIL.PInvoke.PointerMarshaller(type);
case "System.Text.StringBuilder":
return new JSIL.PInvoke.StringBuilderMarshaller();
case "System.String":
return new JSIL.PInvoke.StringMarshaller();
}
if (type.__IsDelegate__) {
return new JSIL.PInvoke.DelegateMarshaller(type);
} else if (type.__IsNativeType__) {
if (box)
return new JSIL.PInvoke.BoxedValueMarshaller(type);
else
return new JSIL.PInvoke.ByValueMarshaller(type);
} else if (type.__IsStruct__) {
return new JSIL.PInvoke.ByValueStructMarshaller(type);
} else if (type.__IsEnum__) {
return new JSIL.PInvoke.ByValueMarshaller(type);
} else if (type.__IsArray__) {
return new JSIL.PInvoke.ArrayMarshaller(type, isOut);
} else {
return new JSIL.PInvoke.UnimplementedMarshaller(type);
}
};
JSIL.PInvoke.FindNativeMethod = function (module, methodName) {
var key = "_" + methodName;
return module[key];
};
JSIL.PInvoke.GetMarshallersForSignature = function (methodSignature, pInvokeInfo) {
var argumentMarshallers = new Array(methodSignature.argumentTypes.length);
for (var i = 0, l = argumentMarshallers.length; i < l; i++) {
var argumentType = methodSignature.argumentTypes[i];
var resolvedArgumentType = JSIL.ResolveTypeReference(argumentType)[1];
var marshalInfo = null;
if (pInvokeInfo && pInvokeInfo.Parameters)
marshalInfo = pInvokeInfo.Parameters[i];
if (marshalInfo && marshalInfo.CustomMarshaler) {
argumentMarshallers[i] = JSIL.PInvoke.WrapManagedCustomMarshaler(resolvedArgumentType, marshalInfo.CustomMarshaler, marshalInfo.Cookie);
} else {
var isOut = false;
if (marshalInfo)
isOut = marshalInfo.Out || false;
argumentMarshallers[i] = JSIL.PInvoke.GetMarshallerForType(resolvedArgumentType, false, isOut);
}
}
var resolvedReturnType = null, resultMarshaller = null;
if (methodSignature.returnType) {
resolvedReturnType = JSIL.ResolveTypeReference(methodSignature.returnType)[1];
if (pInvokeInfo && pInvokeInfo.Result && pInvokeInfo.Result.CustomMarshaler) {
resultMarshaller = JSIL.PInvoke.WrapManagedCustomMarshaler(resolvedReturnType, pInvokeInfo.Result.CustomMarshaler, pInvokeInfo.Result.Cookie);
} else {
resultMarshaller = JSIL.PInvoke.GetMarshallerForType(resolvedReturnType);
}
}
return {
arguments: argumentMarshallers,
result: resultMarshaller
};
};
JSIL.PInvoke.CreateManagedToNativeWrapper = function (module, nativeMethod, methodName, methodSignature, pInvokeInfo, marshallers) {
if (!marshallers)
marshallers = JSIL.PInvoke.GetMarshallersForSignature(methodSignature, pInvokeInfo);
var structResult = marshallers.result && marshallers.result.namedReturnValue;
var wrapper = function SimplePInvokeWrapper () {
var context = new JSIL.PInvoke.CallContext(module);
var argc = arguments.length | 0;
var convertOffset = structResult ? 1 : 0;
var convertedArguments = new Array(argc + convertOffset);
for (var i = 0; i < argc; i++)
convertedArguments[i + convertOffset] = marshallers.arguments[i].ManagedToNative(arguments[i], context);
if (structResult) {
convertedArguments[0] = marshallers.result.AllocateZero(context);
}
try {
var nativeResult;
nativeResult = nativeMethod.apply(this, convertedArguments);
if (structResult)
return marshallers.result.NativeToManaged(convertedArguments[0], context);
else if (marshallers.result)
return marshallers.result.NativeToManaged(nativeResult, context);
else
return nativeResult;
} finally {
context.Dispose();
}
};
return wrapper;
};
JSIL.PInvoke.CreateNativeToManagedWrapper = function (module, managedFunction, methodSignature, pInvokeInfo) {
var marshallers = JSIL.PInvoke.GetMarshallersForSignature(methodSignature, pInvokeInfo);
if (marshallers.result && marshallers.result.allocates)
JSIL.RuntimeError("Return type '" + methodSignature.returnType + "' is not valid because it allocates on the native heap");
var structResult = marshallers.result && marshallers.result.namedReturnValue;
var wrapper = function SimplePInvokeWrapper () {
var context = new JSIL.PInvoke.CallContext(module);
var argc = arguments.length | 0;
var convertOffset = structResult ? 1 : 0;
var convertedArguments = new Array(argc);
for (var i = 0, l = argc - convertOffset; i < l; i++)
convertedArguments[i] = marshallers.arguments[i].NativeToManaged(arguments[i + convertOffset], context);
try {
var managedResult;
managedResult = managedFunction.apply(this, convertedArguments);
if (structResult) {
// HACK: FIXME: Oh god
var structMarshaller = marshallers.result.marshaller;
structMarshaller(managedResult, module.HEAPU8, arguments[0]);
return;
} else if (marshallers.result) {
// FIXME: What happens if the return value has to get pinned into the emscripten heap?
return marshallers.result.ManagedToNative(managedResult, context);
} else {
return managedResult;
}
} finally {
context.Dispose();
}
};
return wrapper;
};
JSIL.PInvoke.CreateUniversalFunctionPointerForDelegate = function (delegate, signature) {
var result = null;
var nm = JSIL.__NativeModules__;
for (var k in nm) {
if (!nm.hasOwnProperty(k))
continue;
if (k === "__global__")
continue;
var module = nm[k];
var wrappedFunction = JSIL.PInvoke.CreateNativeToManagedWrapper(module, delegate, signature);
var localFp = module.Runtime.addFunction(wrappedFunction);
if (result === null)
result = localFp;
else if (result !== localFp)
JSIL.RuntimeError("Emscripten function pointer tables are desynchronized between modules");
}
return result;
};
JSIL.ImplementExternals("System.Runtime.InteropServices.Marshal", function ($) {
var warnedAboutFunctionTable = false;
$.Method({Static: true , Public: true }, "GetFunctionPointerForDelegate",
(new JSIL.MethodSignature($.IntPtr, ["!!0"], ["T"])),
function GetFunctionPointerForDelegate (T, delegate) {
if (!T.__IsDelegate__)
JSIL.RuntimeError("Type argument must be a delegate");
var signature = T.__Signature__;
if (!signature)
JSIL.RuntimeError("Delegate type must have a signature");
var functionPointer = JSIL.PInvoke.CreateUniversalFunctionPointerForDelegate(delegate, signature);
// FIXME
var result = new System.IntPtr(functionPointer);
return result;
}
);
function _GetDelegateForFunctionPointer(T, ptr) {
if (!T.__IsDelegate__) {
JSIL.WarningFormat("Cannot get delegate of type {0}: Not a delegate type", [T.__FullName__]);
return null;
}
var signature = T.__Signature__;
if (!signature) {
JSIL.WarningFormat("Cannot get delegate of type {0}: Delegate type must have a signature", [T.__FullName__]);
return null;
}
var pInvokeInfo = T.__PInvokeInfo__;
if (!pInvokeInfo)
pInvokeInfo = null;
var methodIndex = ptr.ToInt32();
var module = JSIL.PInvoke.PickModuleForPointer(ptr, false);
if (methodIndex === 0) {
JSIL.WarningFormat("Cannot get delegate of type {0}: Null function pointer", [T.__FullName__]);
return null;
}
var marshallers = JSIL.PInvoke.GetMarshallersForSignature(signature, pInvokeInfo);
var invokeImplementation = null;
// Build signature
var dynCallSignature = "";
var rm = marshallers.result;
if (rm) {
if (rm.namedReturnValue)
dynCallSignature += "v";
dynCallSignature += rm.GetSignatureToken(signature.returnType);
} else {
dynCallSignature += "v";
}
for (var i = 0, l = signature.argumentTypes.length; i < l; i++) {
var m = marshallers.arguments[i];
dynCallSignature += m.GetSignatureToken(signature.argumentTypes[i]);
}
var functionTable = module["FUNCTION_TABLE_" + dynCallSignature];
if (functionTable) {
invokeImplementation = functionTable[methodIndex];
} else {
var dynCallImplementation = module["dynCall_" + dynCallSignature];
if (!dynCallImplementation) {
JSIL.WarningFormat("Cannot get delegate of type {0}: No dynCall implementation or function table for signature '{1}'", [T.__FullName__, dynCallSignature]);
return null;
}
if (!warnedAboutFunctionTable) {
warnedAboutFunctionTable = true;
JSIL.Host.warning("This emscripten module was compiled without '-s EXPORT_FUNCTION_TABLES=1'. Performance will be compromised.");
}
var boundDynCall = function (/* arguments... */) {
var argc = arguments.length | 0;
var argumentsList = new Array(argc + 1);
argumentsList[0] = methodIndex;
for (var i = 0; i < argc; i++)
argumentsList[i + 1] = arguments[i];
return dynCallImplementation.apply(this, argumentsList);
};
invokeImplementation = boundDynCall;
}
var wrappedMethod = JSIL.PInvoke.CreateManagedToNativeWrapper(
module, invokeImplementation, "GetDelegateForFunctionPointer_Result",
signature, pInvokeInfo, marshallers
);
return wrappedMethod;
}
$.Method({Static: true , Public: true }, "GetDelegateForFunctionPointer",
(new JSIL.MethodSignature($jsilcore.TypeRef("System.Delegate"), [$.IntPtr, $jsilcore.TypeRef("System.Type")])),
function GetDelegateForFunctionPointer (ptr, T) {
return _GetDelegateForFunctionPointer(T, ptr);
}
);
$.Method({Static: true , Public: true }, "GetDelegateForFunctionPointer",
(new JSIL.MethodSignature("!!0", [$.IntPtr], ["T"])),
function GetDelegateForFunctionPointer (T, ptr) {
return _GetDelegateForFunctionPointer(T, ptr);
}
);
});
|
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Query } from '@apollo/client/react/components'
import styled from 'styled-components'
import InfiniteScroll from 'react-infinite-scroller'
import { map, flatten } from 'underscore'
import feedQuery from 'v2/components/Feed/queries/feed'
import ErrorAlert from 'v2/components/UI/ErrorAlert'
import LoadingIndicator from 'v2/components/UI/LoadingIndicator'
import BlocksLoadingIndicator from 'v2/components/UI/BlocksLoadingIndicator'
import FeedGroups from 'v2/components/FeedGroups'
import CenteringBox from 'v2/components/UI/CenteringBox'
const LoadingContainer = styled(CenteringBox)`
margin-top: -250px; // Hack for now
`
export default class Feed extends PureComponent {
static propTypes = {
onCompleted: PropTypes.func,
type: PropTypes.string,
}
static defaultProps = {
onCompleted: () => {},
type: 'User',
}
state = {
offset: 0,
limit: 20,
hasMore: true,
}
getContext = data => {
if (!data) return []
const {
me: {
feed: { groups },
},
} = data
return flatten(map(groups, group => group.objects))
}
render() {
const { onCompleted, type } = this.props
const { limit, hasMore, offset } = this.state
return (
<Query
query={feedQuery}
variables={{ limit, type }}
onCompleted={onCompleted}
ssr={false}
>
{({ loading, error, data, fetchMore }) => {
if (loading) {
return (
<LoadingContainer>
<LoadingIndicator p={6} />
</LoadingContainer>
)
}
if (error) {
return <ErrorAlert m={6}>{error.message}</ErrorAlert>
}
const {
me: {
feed: { groups },
},
} = data
return (
<InfiniteScroll
pageStart={1}
threshhold={1000}
loader={<BlocksLoadingIndicator key="loading" />}
hasMore={hasMore}
loadMore={() => {
fetchMore({
variables: { limit, offset: offset + limit },
updateQuery: (prevResult, { fetchMoreResult }) => {
if (!fetchMoreResult) return prevResult
const mergedResults = {
...prevResult,
me: {
...prevResult.me,
feed: {
...prevResult.me.feed,
groups: [
...prevResult.me.feed.groups,
...fetchMoreResult.me.feed.groups,
],
},
},
}
return mergedResults
},
}).then(res => {
this.setState({
offset: offset + limit,
hasMore: !res.errors && res.data.me.feed.groups.length > 0,
})
})
}}
>
<FeedGroups groups={groups} context={this.getContext(data)} />
</InfiniteScroll>
)
}}
</Query>
)
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:b901edf7fc1fbfe2e206ce3b0cae56bf129a0b9f775a7f1d032710b5633f2e4b
size 453760
|
/*
Copyright JS Foundation and other contributors, https://js.foundation/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var esprima = require('../');
function readEverythingJsProgram(type) {
return require('fs').readFileSync(require.resolve('everything.js/' + type), 'utf-8');
}
try {
esprima.parse(readEverythingJsProgram('es2015-script'));
esprima.parse(readEverythingJsProgram('es2015-module'), { sourceType: 'module' });
} catch (e) {
console.error('Error:', e.toString());
process.exit(1);
}
|
var userLocation,userLocationLat, userLocationLng, autocomplete;
function search() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')));
google.maps.event.addListener(autocomplete, 'place_changed', function () {
userLocation = autocomplete.getPlace();
userLocationLat = userLocation.geometry.location.lat();
userLocationLng = userLocation.geometry.location.lng();
$('.closest-signs').empty();
$('.sign-info').empty();
getClosestSigns();
});
}
$('.closest-signs').html();
function getClosestSigns() {
$.ajax({
method: "GET",
url: "signs/?variable=" + userLocationLat + "," + userLocationLng}).done(function(data) {
console.log(data);
$('.closest-signs').append(data);
}).fail(function(err) {
console.log(err)
})
}
$("a").on("click", function(event) {
$('.sign-info').empty();
event.preventDefault();
var parkLat = parseFloat($(this).attr('lat'));
var parkLng = parseFloat($(this).attr('lng'));
$.ajax({
method: "GET",
data: {id: this.id},
dataType: "json",
url: "/parks/" + this.id
}).done(function(data) {
if (data == false) {
$('.sign-info').append("<p>No data available.</p>");
}
for (i = 0; i < data.length; i++) {
$('.sign-info').append("<div class='sign'><h3>" +data[i].name + "</h3><h4>" + data[i].borough + "</h4>" + data [i].content + "</div>");
}
loadParkMap(parkLat,parkLng);
}).fail(function(err) {
console.log(err);
})
})
loadMap();
|
import path from 'path';
import { spawn } from 'child_process';
import webpack from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import merge from 'webpack-merge';
import baseConfig from './webpack.config.base';
const port = process.env.SERVER_PORT || 8080;
const publicPath = "http://127.0.0.1:" + port + "/dist";
export default merge.smart(baseConfig, {
devtool: 'inline-source-map',
entry: [
"react-hot-loader/patch",
"webpack-dev-server/client?" + "http://127.0.0.1:" + port,
"webpack/hot/only-dev-server",
"./src/js/app.js"
],
output: {
path: path.resolve(__dirname, "app/dist"),
publicPath: publicPath,
filename: "app-bundle.js"
},
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
sourceMap: true,
},
}
]
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin({}),
new webpack.NamedModulesPlugin(),
new ExtractTextPlugin({
filename: '[file].css'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
})
],
devServer: {
hot: true,
port: port,
inline: true,
compress: true,
headers: {'Access-Control-Allow-Origin': '*'},
contentBase: path.resolve(__dirname, "dist"),
setup() {
if (process.env.START_APP === 'yes') {
spawn(
'npm',
['run', 'dev-app'],
{shell: true, env: process.env, stdio: 'inherit'}
)
.on('close', code => process.exit(code))
.on('error', spawnError => console.error(spawnError));
}
}
}
});
|
import React from "react";
import BezierComponent from "./BezierComponent";
function range(from, to, step) {
const t = [];
for (let i = from; i < to; i += step)
t.push(i);
return t;
}
function sameShadowObject(a, b) {
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) return false;
for (let i in a) {
if (a[i] !== b[i]) return false;
}
return true;
}
export default class Grid extends BezierComponent {
gridX(div) {
var step = 1 / div;
return range(0, 1, step).map(this.x);
}
gridY(div) {
var step = 1 / div;
return range(0, 1, step).map(this.y);
}
shouldComponentUpdate(nextProps) {
if (super.shouldComponentUpdate(nextProps)) return true;
const { background, gridColor, textStyle } = this.props;
return (
nextProps.background !== background ||
nextProps.gridColor !== gridColor ||
!sameShadowObject(nextProps.textStyle, textStyle)
);
}
render() {
const { x, y } = this;
const { background, gridColor, textStyle } = this.props;
const sx = x(0);
const sy = y(0);
const ex = x(1);
const ey = y(1);
const xhalf = this.gridX(2);
const yhalf = this.gridY(2);
const xtenth = this.gridX(10);
const ytenth = this.gridY(10);
const gridbg = `M${sx},${sy} L${sx},${ey} L${ex},${ey} L${ex},${sy} Z`;
const tenth = xtenth
.map(xp => `M${xp},${sy} L${xp},${ey}`)
.concat(ytenth.map(yp => `M${sx},${yp} L${ex},${yp}`))
.join(" ");
const half = xhalf
.map(xp => `M${xp},${sy} L${xp},${ey}`)
.concat(yhalf.map(yp => `M${sx},${yp} L${ex},${yp}`))
.concat([`M${sx},${sy} L${ex},${ey}`])
.join(" ");
const ticksLeft = ytenth
.map((yp, i) => {
const w = 3 + (i % 5 === 0 ? 2 : 0);
return `M${sx},${yp} L${sx - w},${yp}`;
})
.join(" ");
const ticksBottom = xtenth
.map((xp, i) => {
const h = 3 + (i % 5 === 0 ? 2 : 0);
return `M${xp},${sy} L${xp},${sy + h}`;
})
.join(" ");
return (
<g>
<path fill={background} d={gridbg} />
<path strokeWidth="1px" stroke={gridColor} d={tenth} />
<path strokeWidth="2px" stroke={gridColor} d={half} />
<path strokeWidth="1px" stroke={gridColor} d={ticksLeft} />
<text
style={{ textAnchor: "end", ...textStyle }}
transform="rotate(-90)"
x={-this.y(1)}
y={this.x(0) - 8}
>
Progress Percentage
</text>
<path strokeWidth="1px" stroke={gridColor} d={ticksBottom} />
<text
style={{ dominantBaseline: "text-before-edge", ...textStyle }}
textAnchor="end"
x={this.x(1)}
y={this.y(0) + 5}
>
Time Percentage
</text>
</g>
);
}
}
|
var WO = WO || {};
WO.Metronome = {
metronome: null,
notes: {
"Gb4": "soundfont/Click-16-44b.wav",
// "G4": "soundfont/MetroBar.mp3",
// "A4": "soundfont/MetroBeat.mp3",
// "D4" : "soundfont/acoustic-kit/snare.wav",
// "A4" : "soundfont/acoustic-kit/tom1.wav",
// "G4" : "soundfont/acoustic-kit/tom2.wav",
"F4" : "soundfont/Click-16-44.wav",
// "C4" : "soundfont/acoustic-kit/kick.wav"
},
playMetronome: function(){
var metronomePreset = [
[true,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false],
// [true,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false],
// [false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false],
// [false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false],
// [false,false,false,false,true,false,false,false,true,false,false,false,true,false,false,false],
[false,false,false,false,true,false,false,false,true,false,false,false,true,false,false,false]
// [false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false]
];
var stepNumber = 0;
var noteName = Object.keys(this.notes);
Tone.Transport.setInterval(function(time){
stepNumber = stepNumber % 16;
for (var i = 0; i < metronomePreset.length; i++){
if (metronomePreset[i][stepNumber]){
this.metronome.triggerAttack(noteName[i], time);
}
}
stepNumber++;
}.bind(this), "16n");
}
};
WO.Metronome.metronome = new Tone.MultiSampler(WO.Metronome.notes, function(){
});
WO.Metronome.metronome.setVolume(-5);
WO.Metronome.metronome.toMaster();
|
/*!
* Socialcontrol
*
* Copyright 2013 Enrico Berti and other contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
$(document).ready(function () {
// Handler when the "add Member" button is clicked
$(document).on('click', '#btnAddMember', function () {
var members = [];
members.push({ 'name': $('#newModal .txtName').val(), 'screen_name': $('#newModal .txtScreenName').val() });
var shortCode = $('#newModal .ddlGroup').val();
// Save it!
saveMember(shortCode, members, function (err, response) {
if (err) {
//TODO: Handle this.
} else {
window.location.href = '/admin/members';
}
});
});
// Handler to populate "edit member" form
$(document).on('click', '.editMember', function () {
// Populate the edit modal with group details.
$('#editModal .txtTwitterName').val($(this).data('screen_name'));
$('#editModal .txtName').val($(this).data('name'));
$('#editModal .ddlGroup').val($(this).data('shortcode'));
$('#editModal .hidOldGroup').val($(this).data('shortcode'));
});
// Handler when the "Update Member" button is clicked
$(document).on('click', '#btnEditMember', function () {
var screen_name = $('#editModal .txtTwitterName').val();
var name = $('#editModal .txtName').val();
var shortCode = $('#editModal .ddlGroup').val();
var oldShortCode = $('#editModal .hidOldGroup').val();
// First, delete from existing group
$.ajax({
url: '/api/group/' + oldShortCode + '/members/' + screen_name,
method: 'DELETE',
dataType: 'json',
success: function (response) {
// Second, Re-add the member
var members = [];
members.push({ 'name': name, 'screen_name': screen_name});
saveMember(shortCode, members, function (err, response) {
if (err) {
// TODO: Handle this.
} else {
window.location.href = '/admin/members';
}
});
},
error: function (ex) {
console.log(ex);
},
complete: function () {
}
});
});
// Handler to populate the "delete group" form
$(document).on('click', '.deleteMember', function () {
$('#deleteModal #deleteMemberName').text($(this).data('name') + ' (' + $(this).data('screen_name') + ')');
$('#deleteModal #hidScreenName').val($(this).data('screen_name'));
$('#deleteModal #hidGroupShortCode').val($(this).data('shortcode'));
});
// Handler when the "Delete Group" button is clicked
$(document).on('click', '#btnDeleteMember', function () {
var screen_name = $('#deleteModal #hidScreenName').val();
var shortCode = $('#deleteModal #hidGroupShortCode').val();
$.ajax({
url: '/api/group/' + shortCode + '/members/' + screen_name,
method: 'DELETE',
dataType: 'json',
success: function (response) {
window.location.href = '/admin/members';
},
error: function (ex) {
// TODO: What to do here?
console.log(ex);
},
complete: function () {
}
});
});
$('#tweetsModal').on('show', function () {
$('#tweetsModal #tweetsContainer').html('<i class="icon-fire"></i> Loading...');
});
// Handler when the "view tweets" button is clicked
$(document).on('click', '.viewTweets', function () {
var screen_name = $(this).data('screen_name');
$('#tweetsModal #memberName').text($(this).data('name'));
$('#tweetsModal #memberScreenName').text('@' + screen_name);
// Retrieve the tweets for this member
$.ajax({
url: '/api/tweets/member/' + screen_name,
method: 'GET',
dataType: 'json',
success: function (response) {
// Render the tweets using a Handlebars template
var template = Handlebars.compile($('#adminTweetTemplate').html());
var html = template(response.data);
$('#tweetsModal #tweetsContainer').html(html);
},
error: function (ex) {
// TODO: What to do here?
console.log(ex);
},
complete: function () {
}
});
});
// Handler when the "delete tweet" button is clicked
$(document).on('click', '.deleteTweet', function () {
var tweetId = $(this).data('tweetid');
// Delete this tweet.
$.ajax({
url: '/api/tweets/' + tweetId,
method: 'DELETE',
dataType: 'json',
success: function (response) {
// Remove this tweet from the DOM
$('#' + tweetId).remove();
},
error: function (ex) {
// TODO: What to do here?
console.log(ex);
},
complete: function () {
}
});
});
// Add member filtering
$('#txtSearchQuery').on('change keyup', function () {
var query = $('#txtSearchQuery').val().toLowerCase();
$('#memberTable > tbody > tr').each(function () {
if ($(this).data('name').toLowerCase().indexOf(query.toLowerCase()) != -1 || $(this).data('screen_name').toLowerCase().indexOf(query.toLowerCase()) != -1) {
$(this).show();
} else {
$(this).hide();
}
});
});
});
// Generic function to add/edit a member.
function saveMember(shortCode, members, callback) {
var postData = {
'members': members
};
console.log(postData);
$.ajax({
url: '/api/group/' + shortCode + '/members',
method: 'POST',
dataType: 'json',
data: postData,
success: function (response) {
callback(null, response);
},
error: function (ex) {
callback(ex);
},
complete: function () {
}
});
}
// Add functionality for "starts with".
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str) {
return this.slice(0, str.length) == str;
};
}
|
'use strict';
/**
* Update handler for transition database version 3 -> 4
*
* In database version 4, we need to add a "provider" flag to the
* indexeddb. only gmail was allowed as a mail service provider before,
* so let's add this...
*/
export default function(options) {
const VERSION_DB_TYPE = 'dbVersion',
EMAIL_ADDR_DB_KEY = 'emailaddress',
USERNAME_DB_KEY = 'username',
PROVIDER_DB_KEY = 'provider',
IMAP_DB_KEY = 'imap',
SMTP_DB_KEY = 'smtp',
REALNAME_DB_KEY = 'realname',
POST_UPDATE_DB_VERSION = 4;
const imap = {
host: 'imap.gmail.com',
port: 993,
secure: true
},
smtp = {
host: 'smtp.gmail.com',
port: 465,
secure: true
};
// load the email address (if existing)
let emailAddress;
return loadFromDB(EMAIL_ADDR_DB_KEY).then(address => {
emailAddress = address;
// load the provider (if existing)
return loadFromDB(PROVIDER_DB_KEY);
}).then(provider => {
// if there is an email address without a provider, we need to add the missing provider entry
// for any other situation, we're good.
if (!(emailAddress && !provider)) {
// update the database version to POST_UPDATE_DB_VERSION
return options.appConfigStorage.storeList([POST_UPDATE_DB_VERSION], VERSION_DB_TYPE);
}
// add the missing provider key
const storeProvider = options.appConfigStorage.storeList(['gmail'], PROVIDER_DB_KEY);
// add the missing user name key
const storeAdress = options.appConfigStorage.storeList([emailAddress], USERNAME_DB_KEY);
// add the missing imap host info key
const storeImap = options.appConfigStorage.storeList([imap], IMAP_DB_KEY);
// add the missing empty real name
const storeEmptyName = options.appConfigStorage.storeList([''], REALNAME_DB_KEY);
// add the missing smtp host info key
const storeSmtp = options.appConfigStorage.storeList([smtp], SMTP_DB_KEY);
return Promise.all([storeProvider, storeAdress, storeImap, storeEmptyName, storeSmtp]).then(() => {
// reload the credentials
options.auth.initialized = false;
return options.auth._loadCredentials();
}).then(() => options.appConfigStorage.storeList([POST_UPDATE_DB_VERSION], VERSION_DB_TYPE)); // update the db version
});
function loadFromDB(key) {
return options.appConfigStorage.listItems(key).then(cachedItems => cachedItems && cachedItems[0]);
}
}
|
var specificAnswer = require('./answers').specific;
//specific answercomment has this path fragment.
exports.specific = specificAnswer + '/comment/:comment_id';
var specific = exports.specific;
exports.route = function (app, controllers, doc) {
var route = require('../route')(app, controllers, doc, __filename);
route('post', specificAnswer + '/comments', 'create', 'Create;Add new comment to answer');
route('get', specificAnswer + '/comments', 'all', 'Get All; Get all comments of answer');
route('get', specific, 'get', 'Get;Get answer comment with specific ID');
route('put', specific, 'update', 'Update;Update comment of answer');
route('delete', specific, 'remove', 'Delete; Delete comment of answer');
route('head', specific, 'head', 'Head; Get headers for testing validity, accessibility, and recent modification');
};
|
const find = require('./find')
module.exports = function last (tree, selector) {
const nodes = find(tree, selector)
return nodes[nodes.length - 1]
}
|
/*global Plyfe */
describe('Api', function() {
'use strict';
it('should send card and user data with cardStart', function(done) {
Plyfe.onCardStart = function(card, user) {
expect(card).to.not.be(null);
expect(user).to.not.be(null);
expect(card.id).to.be(1);
expect(card.type).to.be('poll_challenge');
expect(user.id).to.be(1);
done();
};
var data = {
card: {id: 1, type: 'poll_challenge'},
user: {id: 1}
};
window.postMessage('plyfe:card:start' + '\n' + JSON.stringify(data), '*');
});
it('should send default data with cardStart', function(done) {
Plyfe.onCardStart = function(card, user) {
expect(card).to.not.be(null);
expect(user).to.not.be(null);
expect(card.id).to.be(0);
expect(card.type).to.be('no_type');
expect(user.id).to.be(0);
done();
};
window.postMessage('plyfe:card:start' + '\n' + JSON.stringify({}), '*');
});
it('should send card and user data with cardComplete', function(done) {
Plyfe.onCardComplete = function(card, user) {
expect(card).to.not.be(null);
expect(user).to.not.be(null);
expect(card.id).to.be(1);
expect(card.type).to.be('poll_challenge');
expect(user.id).to.be(1);
done();
};
var data = {
card: {id: 1, type: 'poll_challenge'},
user: {id: 1}
};
window.postMessage('plyfe:card:complete' + '\n' + JSON.stringify(data), '*');
});
it('should send default data with cardComplete', function(done) {
Plyfe.onCardComplete = function(card, user) {
expect(card).to.not.be(null);
expect(user).to.not.be(null);
expect(card.id).to.be(0);
expect(card.type).to.be('no_type');
expect(user.id).to.be(0);
done();
};
window.postMessage('plyfe:card:complete' + '\n' + JSON.stringify({}), '*');
});
it('should send card, user and choice data with choiceSelection', function(done) {
Plyfe.onChoiceSelection = function(card, user, choice) {
expect(card.id).to.be(1);
expect(card.type).to.be('trivia_challenge');
expect(user.id).to.be(1);
expect(choice.id).to.be(1);
expect(choice.name).to.be('Choice 1');
expect(choice.correct).to.be(true);
done();
};
var data = {
card: { id: 1, type: 'trivia_challenge' },
user: { id: 1 },
choice: { id: 1, name: 'Choice 1', correct: true }
};
window.postMessage('plyfe:choice:selection' + '\n' + JSON.stringify(data), '*');
});
it('should send default data with choiceSelection', function(done) {
Plyfe.onChoiceSelection = function(card, user, choice) {
expect(card.id).to.be(0);
expect(card.type).to.be('no_type');
expect(user.id).to.be(0);
expect(choice.id).to.be(0);
expect(choice.name).to.be('no_name');
expect(choice.correct).to.be(null);
done();
};
window.postMessage('plyfe:choice:selection' + '\n' + JSON.stringify({}), '*');
});
});
|
const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')
let win
app.on('ready', function(){
win = new BrowserWindow ({width: 1280, height: 800, icon: path.join(__dirname, 'icon.png')})
win.setMenu(null);
win.loadURL(url.format ({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file',
slashes: true
}));
});
|
module.exports = function(
gulp, confFileMap, confPlugins, pathFiles, notify
) {
return function() {
var protractor = require("gulp-protractor").protractor;
var path = confFileMap.env.dev;
var base = path.base,
ref = confFileMap.sourceFiles.tests.e2e;
gulp.src(pathFiles(base, ref))
.pipe(protractor({
confGlobalFile: '.' + confPlugins.protractor.configFile,
args: ['--baseUrl', 'http://127.0.0.1:8000']
}))
.on('error', function(err) {
this.emit('end');
});
notify('Starting end to end tests. Note that this starts up a browser and could take a while, press Ctrl+C to quit.', 'title');
};
};
|
vows = require('vows');
assert = require('assert');
_ = require('lodash');
r = require('../');
vows.describe('Rhythmically duration').addBatch({
"sequence duration": function() {
assert.equal(r.duration(r.sequence('a b c d')), 1);
}
}).export(module);
|
'use strict';
require('jquery');
require('bootstrap3');
require('featherlight');
const SmoothScroll = require('smooth-scroll');
const angular = require('angular');
require('./main');
angular.module('TunaTechApp', [])
.controller('HomeController', HomeController)
.directive('lightboxDirective', lightboxDirective);
HomeController.$inject = ['$http'];
function HomeController($http) {
var vm = this;
vm.showSpeakerLightBox = false;
vm.activateSpeakerLightBox = activateSpeakerLightBox;
_init();
function _init() {
const baseDir = './data/2018';
if(event === 'tunatech-2017') {
const baseDir = './data/2017';
}
$http.get(baseDir + '/speakers.json?rand=' + Math.random() )
.then(function (res) {
vm.speakers = [];
let row = [];
res.data.forEach(function(speaker) {
row.push(speaker);
if(row.length === 4){
vm.speakers.push(row);
row = [];
}
});
if(row.length > 0){
vm.speakers.push(row);
}
});
$http.get(baseDir + '/schedule.json?rand=' + Math.random())
.then(function (res) {
vm.schedule = res.data;
});
}
function activateSpeakerLightBox(speaker) {
vm.currentSpeaker = speaker;
vm.showSpeakerLightBox = true;
}
}
function lightboxDirective() {
return {
restrict: 'E', // applied on 'element'
transclude: true, // re-use the inner HTML of the directive
template: '<section ng-transclude></section>', // need this so that inner HTML will be used
}
}
/*
* SmoothScroll
*/
var scroll = new SmoothScroll('a[href*="#"]', {
ignore: '[data-scroll-ignore]', // Selector for links to ignore (must be a valid CSS selector)
header: null, // Selector for fixed headers (must be a valid CSS selector)
topOnEmptyHash: true, // Scroll to the top of the page for links with href="#"
speed: 500, // Integer. How fast to complete the scroll in milliseconds
clip: true, // If true, adjust scroll distance to prevent abrupt stops near the bottom of the page
easing: 'easeInOutCubic', // Easing pattern to use
updateURL: true, // Update the URL on scroll
popstate: true, // Animate scrolling with the forward/backward browser buttons (requires updateURL to be true)
emitEvents: true // Emit custom events
});
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M7.71 9.29l3.88 3.88 3.88-3.88c.39-.39 1.02-.39 1.41 0 .39.39.39 1.02 0 1.41l-4.59 4.59c-.39.39-1.02.39-1.41 0L6.29 10.7a.9959.9959 0 0 1 0-1.41c.39-.38 1.03-.39 1.42 0z" />
, 'KeyboardArrowDownRounded');
|
var test = require('tape')
, mixly = require('../')
;
/**
* Test object zero
*/
var o0 = {
zoo: 'boo'
};
/**
* Test object one
*/
var o1 = Object.create(o0, {
O1: {writable: true, enumerable: true, configurable: true, value: true},
commonThing: {writable: true, enumerable: true, configurable: true, value: 'o1'}
});
/**
* Test object one
*/
var o2 = Object.create(null, {
O2: {writable: true, enumerable: true, configurable: true, value: true},
commonThing: {writable: true, enumerable: true, configurable: true, value: 'o2'}
});
/**
* Test object one
*/
var o3 = Object.create(o0, {
O3: {writable: true, enumerable: true, configurable: true, value: true},
commonThing: {writable: true, enumerable: true, configurable: true, value: 'o3'}
});
test('copy', function(t)
{
t.plan(16);
// o1 + o2
mixly.copy(o1, o2);
t.equal(Object.getPrototypeOf(o1), o0);
t.equal(Object.getPrototypeOf(o2), null);
t.true(o1.O1);
t.true(o1.O2);
t.equal(o1.commonThing, 'o2');
t.true(o1.hasOwnProperty('commonThing'));
t.true(o1.hasOwnProperty('O1'));
t.true(o1.hasOwnProperty('O2'));
// o2 + o3
mixly.copy(o2, o3);
t.equal(Object.getPrototypeOf(o2), null);
t.equal(Object.getPrototypeOf(o3), o0);
t.true(o2.O2);
t.true(o2.O3);
t.equal(o2.commonThing, 'o3');
t.true(Object.prototype.hasOwnProperty.call(o2, 'commonThing'));
t.true(Object.prototype.hasOwnProperty.call(o2, 'O2'));
t.true(Object.prototype.hasOwnProperty.call(o2, 'O3'));
});
|
module.exports = {
db: {
host: 'localhost',
collection: 'test'
},
development: false,
port: 3000
};
|
var $mod$122 = core.VW.Ecma2015.Utils.module(require('./get-set'));
var $mod$123 = core.VW.Ecma2015.Utils.module(require('../units/month'));
var $mod$124 = core.VW.Ecma2015.Utils.module(require('../duration/create'));
var $mod$125 = core.VW.Ecma2015.Utils.module(require('../utils/deprecate'));
var $mod$126 = core.VW.Ecma2015.Utils.module(require('../utils/hooks'));
var $mod$127 = core.VW.Ecma2015.Utils.module(require('../utils/abs-round'));
function createAdder(direction, name) {
return function (val, period) {
var dur, tmp;
if (period !== null && !isNaN(+period)) {
$mod$125.deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).');
tmp = val;
val = period;
period = tmp;
}
val = typeof val === 'string' ? +val : val;
dur = $mod$124.createDuration(val, period);
addSubtract(this, dur, direction);
return this;
};
}
function addSubtract(mom, duration, isAdding, updateOffset) {
var milliseconds = duration._milliseconds, days = $mod$127.default(duration._days), months = $mod$127.default(duration._months);
if (!mom.isValid()) {
return;
}
updateOffset = updateOffset == null ? true : updateOffset;
if (milliseconds) {
mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
}
if (days) {
$mod$122.set(mom, 'Date', $mod$122.get(mom, 'Date') + days * isAdding);
}
if (months) {
$mod$123.setMonth(mom, $mod$122.get(mom, 'Month') + months * isAdding);
}
if (updateOffset) {
$mod$126.hooks.updateOffset(mom, days || months);
}
}
exports.addSubtract = addSubtract;
var add = createAdder(1, 'add');
exports.add = add;
var subtract = createAdder(-1, 'subtract');
exports.subtract = subtract;
|
/**
* @file ttf读取和写入支持的表
* @author mengke01(kekee000@gmail.com)
*/
define(
function (require) {
var support = {
'head': require('./head'),
'maxp': require('./maxp'),
'loca': require('./loca'),
'cmap': require('./cmap'),
'glyf': require('./glyf'),
'name': require('./name'),
'hhea': require('./hhea'),
'hmtx': require('./hmtx'),
'post': require('./post'),
'OS/2': require('./OS2'),
'fpgm': require('./fpgm'),
'cvt': require('./cvt'),
'prep': require('./prep'),
'gasp': require('./gasp'),
'CFF': require('./CFF'),
'COLR': require('./COLR'),
'CPAL': require('./CPAL'),
'SVG': require('./SVG')
};
return support;
}
);
|
var request = require('superagent');
var config = require('../config');
var routing = {
route(latLngs, profile, idx, callback) {
var lonLats = latLngs.map(function(latLng) {
return latLng[1] + ',' + latLng[0];
});
var req = request.post(config.brouterHost + '/brouter');
req.query({
nogos: '',
alternativeidx: idx,
format: 'geojson'
});
req._query.push('lonlats=' + lonLats.join('|'));
req.type('text/plain');
req.send(profile);
req.end((err, response) => {
if (!err && response.ok && response.type === 'application/vnd.geo+json') {
callback(null, JSON.parse(response.text));
} else {
callback(response && response.text ? response.text : '');
}
});
}
};
module.exports = routing;
|
// Saves options to localStorage.
function save_options() {
/*
var select = document.getElementById("color");
var color = select.children[select.selectedIndex].value;
localStorage["favorite_color"] = color;
*/
localStorage["enable_popup"] = $('#enable_popup').is(':checked');
//alert($('#enable_popup').is(':checked'));
// Update status to let user know options were saved.
var status = document.getElementById("status");
status.innerHTML = "options saved";
setTimeout(function() {
status.innerHTML = "";
}, 750);
update_debug();
}
// Restores select box state to saved value from localStorage.
function restore_options() {
var favorite = localStorage["favorite_color"];
if (favorite) {
var select = document.getElementById("color");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
if (child.value == favorite) {
child.selected = "true";
break;
}
}
}
if (localStorage["enable_popup"] == 'true') {
$('#enable_popup').attr('checked', 'on');
}
update_debug();
}
function update_debug() {/*
for (var i = 0; i < localStorage.length; i++){
$('#debug').append('<dt>' + localStorage.key(i) + '</dt><dd>' + localStorage.getItem(localStorage.key(i)) + '</dd>');
}
*/}
function updateTTX() {
var ttx = Math.round((new Date(new Date().getFullYear(), 12-1, 25) - new Date()) / (1000 * 60 * 60 * 24) + 0.5);
//document.querySelector('#ttx').innerHTML = ttx;
$('#ttx').append(ttx);
}
$(document).ready(function() {
restore_options();
updateTTX();
});
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('input[type=button]').addEventListener('click', save_options);
});
|
var path = require('path');
var nodeEnv = process.env.NODE_ENV || 'development';
var isDev = (nodeEnv !== 'production');
var config = {
entry: {
dist: './src/entries/dist.ts'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader'
},
{
test: /\.css$/,
include: path.resolve(__dirname, 'src'),
use: ['style-loader', 'css-loader', 'postcss-loader']
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.ractive.html$/,
use: {
loader: 'html-loader',
options: {
minimize: false
}
}
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js", ".ractive.html"]
}
};
if (isDev) {
config.devtool = 'inline-source-map';
}
module.exports = config;
|
/**
* Creates an utility to manage sprites.
*
* @param Image The image data of the sprite
*/
var Sprite = function(img) {
this.img = img;
this.parts = {};
};
Sprite.prototype = {
registerIds: function(array) {
for(var i = array.length - 1; i >= 0; i--) {
this.registerId(
array[i].id,
array[i].position,
array[i].width,
array[i].height
);
}
return this;
},
registerId: function(id, position, width, height) {
this.parts[id] = new SpritePart(this, position, width, height);
return this;
},
draw: function(ctx, part, position) {
if(!(part instanceof SpritePart)) {
part = this.get(part);
}
if(part === null) {
// TODO Error?
return this;
}
return this.drawPart(ctx, part, position);
},
// Use this if you don't want the lookup time
drawPart: function(ctx, part, position) {
ctx.drawImage(
this.img,
part.position.x,
part.position.y,
part.width,
part.height,
position.x,
position.y,
part.width,
part.height
);
if(Game.debug) {
ctx.save();
// Id lookup
var id;
for(var i in this.parts) {
if(this.parts[i].position.equals(part.position)) {
id = i;
break;
}
}
var w = ctx.measureText(id).width;
ctx
.beginPath()
// Text shadow
.beginPath()
.rect(position.x, position.y + part.width, w + 10, 20)
.set('fillStyle', 'rgba(0, 0, 0, 0.4)')
.fill()
.set('strokeStyle', '#111')
.stroke()
// Name
.set('fillStyle', '#fff')
.set('textAlign', 'center')
.set('font', '15px')
.fillText(id, position.x + w / 2 + 5, position.y + part.width + 15)
;
ctx.restore();
}
return this;
},
get: function(id) {
return this.parts[id];
},
};
var SpritePart = function(sprite, pos, width, height) {
this.sprite = sprite;
this.position = pos;
this.width = width;
this.height = height;
};
SpritePart.prototype = {
draw: function(ctx, position) {
this.sprite.drawPart(ctx, this, position);
return this;
}
};
|
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// concat 설정.
concat: {
basic: {
src: [
"src/L2.js",
"src/event/EventDispatcher.js",
"src/display/Container.js",
"src/**/*.js"
],
dest: "build/<%= pkg.name %>.js"
}
},
// uglify 설정.
uglify: {
options: {
banner: '/*! <%= pkg.name %> [<%= pkg.version %>] <%= grunt.template.today("yyyy-mm-dd, hh:MM:ss TT") %> */\n'
},
build: {
src: 'build/<%= pkg.name %>.js',
dest: 'js/<%= pkg.name %>.min.js'
}
},
shell:
{
options: {
stdout: true,
stderr: true
},
target: {
command: [
'git add .',
'git commit -m "commited by grunt watch at <%= grunt.template.today("yyyy-mm-dd, hh:MM:ss TT") %>"',
'git push origin gh-pages'
].join( '&' )
}
},
// Project configuration.
qunit: {
all: ['qunit/QunitTest.html']
},
watch: {
scripts: {
files: ['src/**/*.js'],
tasks: ['concat', 'uglify', 'qunit']
},
},
// connect: {
// server: {
// options: {
// port:9001,
// base: 'www-root'
// },
// },
// },
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
// Load the plugin that provides the "concat" task.
grunt.loadNpmTasks( 'grunt-contrib-concat' );
// load watch
grunt.loadNpmTasks( 'grunt-contrib-watch' );
// load shell command plugins
grunt.loadNpmTasks( 'grunt-shell' );
// load shell command plugins
grunt.loadNpmTasks( 'grunt-contrib-qunit' );
// load connect plugins: simple http server
// grunt.loadNpmTasks('grunt-contrib-connect');
// Default task(s)
grunt.registerTask('default', ['concat', 'uglify', 'shell' ]);
};
|
/**
* Plural rules for the ce (Chechen, нохчийн мотт) language
*
* This plural file is generated from CLDR-DATA
* (http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html)
* using js-simple-plurals and universal-i18n
*
* @param {number} p
* @return {number} 0 - one, 1 - other
*
* @example
* function pluralize_en(number, one, many) {
* var rules = [one, many];
* var position = plural.en(number)
* return rules[position];
* }
*
* console.log('2 ' + pluralize_en(2, 'day', 'days')); // prints '2 days'
*/
plural = window.plural || {};
plural.ce = function (p) { var n = Math.abs(p)||0; return n === 1 ? 0 : 1; };
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Restaurant = mongoose.model('Restaurant'),
_ = require('lodash');
/**
* Create a Restaurant
*/
exports.create = function(req, res) {
var restaurant = new Restaurant(req.body);
restaurant.user = req.user;
restaurant.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(restaurant);
}
});
};
/**
* Show the current Restaurant
*/
exports.read = function(req, res) {
res.jsonp(req.restaurant);
};
/**
* Update a Restaurant
*/
exports.update = function(req, res) {
var restaurant = req.restaurant ;
restaurant = _.extend(restaurant , req.body);
restaurant.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(restaurant);
}
});
};
/**
* Delete an Restaurant
*/
exports.delete = function(req, res) {
var restaurant = req.restaurant ;
restaurant.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(restaurant);
}
});
};
/**
* List of Restaurants
*/
exports.list = function(req, res) {
Restaurant.find().sort('-created').populate('user', 'displayName').exec(function(err, restaurants) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(restaurants);
}
});
};
/**
* Restaurant middleware
*/
exports.restaurantByID = function(req, res, next, id) {
Restaurant.findById(id).populate('user', 'displayName').exec(function(err, restaurant) {
if (err) return next(err);
if (! restaurant) return next(new Error('Failed to load Restaurant ' + id));
req.restaurant = restaurant ;
next();
});
};
/**
* Restaurant authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.restaurant.user.id !== req.user.id) {
return res.status(403).send('User is not authorized');
}
next();
};
|
var inquirer
var keyManager
(function init() { // ask for password until user gets is right or terminates
inquirer = require('inquirer')
keyManager = require('./key_manager')
inquirer.prompt([
{
type: 'password',
message: 'Enter key file password',
name: 'password'
}
]).then(function (answers) {
//check that pass makes sense
try {
if (answers.password === '') throw new SyntaxError("Password cannot be an empty string!")
keyManager = keyManager(answers.password) //it would be nice if we could cache password for future runs
keyManager.getKeys() // will throw error is password is incorrect
mainLoop()
} catch(err) {
console.log(err + "\n")
init()
}
})
}())
function mainLoop() {
inquirer.prompt([
{
type: 'list',
name: 'what',
message: 'What would you like to do? (ctrl+c to exit)',
choices: [
{name: '1. See info stored in keyFile', value: 1},
{name: '2. Add person to keyFile', value: 2},
{name: '3. Remove someone from keyFile', value: 3},
{name: '4. Change password of keyFile', value: 4},
{name: '5. Make report of someone', value: 5},
]
}
]).then(function (answers) {
switch(answers.what){
case 1:
console.log('\nKeys File Info:\n-------------------------------------------')
for (let prsn of keyManager.getKeys()){
console.log(`${prsn.name}\t${prsn.api_key}`)
console.log('-------------------------------------------')
}
console.log('\n')
mainLoop()
break
case 2:
addPersonWrapper()
break
case 3:
removeSomeoneWrapper()
break
case 4:
changePassWrapper()
break
case 5:
makeReport()
break
//default option is not needed since user cannot give us invalid input
}
})
}
function addPersonWrapper() {
inquirer.prompt([
{
type: 'input',
name: 'name',
message: 'Name of the person you want to add:',
},
{
type: 'input',
name: 'api_key',
message: 'Api key of this person:',
}
]).then(function (answers) {
keyManager.addKeys(answers.name, answers.api_key)
mainLoop()
})
}
function changePassWrapper() {
inquirer.prompt([
{
type: 'input',
name: 'newPass',
message: 'What is the new password you would like to use?',
}
]).then(function (answers) {
keyManager.changePassowrd(answers.newPass)
mainLoop()
})
}
function makeReport() {
let dt = new Date()
inquirer.prompt([
{
type: 'checkbox',
name: 'who',
message: 'For who do you want to get the reports?',
choices: keyManager.getKeys().map(el => {return {name: el.name, value: el.api_key, checked: true}})
},
{
type: 'input',
name: 'year',
message: 'For what year would you like to generate the report?',
default: (new Date()).getUTCFullYear() // By Default is this year
},
{
type: 'input',
name: 'month',
message: 'For what month would you like to generate the report?',
default: dt.getUTCMonth() === 0 ? 12 : dt.getUTCMonth() // By default is last month
}
]).then(function (answers) {
answers.month = answers.month < 10 ? "0" + answers.month : answers.month //add padding if needed
let asanaFlow = require('./asanaFlow')
try {
(require("fs")).unlinkSync("Monthly Report.csv")
} catch(err){
console.log(err)
}
let promises = []
for (let us of answers.who) {
promises.push(asanaFlow(
us, // Access key
`${answers.year}-${answers.month}-01T01:01:01.001Z`,mainLoop) // Date from which to get tasks
)
}
Promise.all(promises).then(()=>{
console.log(`Please find the report file in the root folder of the Asana Exporter project.`)
mainLoop()
})
})
}
function removeSomeoneWrapper(){
inquirer.prompt([
{
type: 'list',
name: 'name',
message: 'For who do you want to get the reports?',
choices: keyManager.getKeys().map(el => {return {name: el.name, value: el.name}})
}
]).then(function (answers) {
keyManager.removeSomeone(answers.name)
mainLoop()
})
}
|
import React, { Component } from 'react';
import styled from 'styled-components';
import { connect } from 'react-redux';
import SideNav from './SideNav';
import MainContent from '../components/MainContent';
const Wrapper = styled.div`
box-sizing: border-box;
width: 80vw;
height: 80vh;
border: 2px solid black;
margin: 0 auto;
display: flex;
`
class Dashboard extends Component {
render () {
console.log(this.props);
return (
<Wrapper>
<SideNav />
<MainContent feedData={this.props.currentFeed}/>
</Wrapper>
);
}
};
export default connect(state => ({
currentFeed: state.rssFeeds.currentFeed,
}),{})(Dashboard);
|
import React, { Component } from 'react';
import Gift from './Gift';
class Gifts extends Component {
componentDidMount() {
this.props.getGifts();
}
render() {
let mainContent;
if (this.props.gifts.length) {
mainContent = this.props.gifts.map(gift => {
return (
<Gift key={gift.id} giver={gift.giver} recipient={gift.recipient}/>
)
});
} else {
mainContent = <p>Nadie. Sacá alguno.</p>;
}
return (
<div className='Gifts'>
<h3>Regalos</h3>
<p>Le tenés que dar regalos a:</p>
{mainContent}
<hr />
<button type="button" onClick={this.props.drawGift.bind(this)}>Sacar regalo</button>
<hr />
<button type="button" onClick={this.props.logout.bind(this)}>Salir</button>
</div>
)
}
}
export default Gifts;
|
var Promise = require('bluebird');
var request = require('../connection/request.js');
var config = require('../config.js');
var parser = require('../parser.js');
var _ = require('lodash');
//Messages
exports.methods = function(params) {
return {
getList: function(userID) {
var path = '/'+config.protocol+'/people/'+userID+'/messages';
var method = 'GET';
request(path, method, null);
},
getDetails: function(userID) {
var path = '/'+config.protocol+'/messages/'+userID;
var method = 'GET';
request(path, method, null);
},
addItem: function(userID) {
var path = '/'+config.protocol+'/messages/'+userID;
var method = 'GET';
request(path, method, null);
},
}
};
|
/* @flow */
import { createEpicMiddleware } from "redux-observable";
import configureMockStore from "redux-mock-store";
import FileWriters from "../../lib/file-writers";
import makeFileWritesEpic from "../../lib/epics/file-writes";
import * as A from "../../lib/action-creators";
describe("epics/file-writes", () => {
let state: State;
let store;
let filenameFileWriter: FileWriter;
let tagsFileWriter: FileWriter;
let writeSpy;
beforeEach(() => {
const fileWriters = new FileWriters();
writeSpy = jasmine.createSpy("write");
tagsFileWriter = {
editCellName: "nvtags",
write: (path: string, str: string, callback: NodeCallback) => {
callback(new Error("this should never have been called!"));
}
};
fileWriters.add(tagsFileWriter);
filenameFileWriter = {
editCellName: "filename",
write: function(path: string, str: string, callback: NodeCallback) {
writeSpy(...arguments);
}
};
fileWriters.add(filenameFileWriter);
const fileWritesEpic = makeFileWritesEpic(fileWriters);
const epicMiddleware = createEpicMiddleware(fileWritesEpic);
const mockStore = configureMockStore([epicMiddleware]);
state = {
columnHeaders: [],
dir: "/notes",
editCellName: null,
initialScan: {
done: true,
rawFiles: []
},
listHeight: 50,
notes: {},
queryOriginal: "",
rowHeight: 25,
scrollTop: 0,
selectedNote: null,
sifterResult: {
items: [],
options: {
fields: ["name", "ext"],
sort: [
{ field: "name", direction: "asc" },
{ field: "$score", direction: "desc" }
]
},
query: "",
tokens: [],
total: 0
}
};
store = mockStore(state);
});
afterEach(function() {
store.dispatch(A.dispose()); // tests dispose logic working
store.clearActions();
const finalAction = A.editCellSave(
"filename",
"should not be picked up anymore"
);
store.dispatch(finalAction);
expect(store.getActions()).toEqual(
[finalAction],
"should not have any other actions dispatched anymore"
);
});
describe("when saving edited cell", function() {
beforeEach(function() {
spyOn(atom.notifications, "addError").andCallThrough();
state.selectedNote = {
filename: "foobar.txt",
index: 1
};
store.dispatch(A.editCellSave("filename", "value to save"));
});
it("should try to write value to selected note", function() {
expect(writeSpy).toHaveBeenCalled();
expect(writeSpy.calls[0].args[0]).toEqual("/notes/foobar.txt");
expect(writeSpy.calls[0].args[1]).toEqual("value to save");
});
describe("when save write succeed", function() {
beforeEach(function() {
writeSpy.calls[0].args[2](null, "value to save");
});
it("should not add any error", function() {
expect(atom.notifications.addError).not.toHaveBeenCalled();
});
});
describe("when save write fails", function() {
beforeEach(function() {
writeSpy.calls[0].args[2](
new Error("oh dear, something went wrong…"),
null
);
});
it("should add an error explaining the situation", function() {
expect(atom.notifications.addError).toHaveBeenCalled();
});
});
});
});
|
export { default } from 'ember-polymer-paper/components/paper-slider';
|
import Ember from 'ember';
import { executeTest } from 'dummy/tests/acceptance/components/flexberry-objectlistview/execute-folv-test';
import { filterCollumn, refreshListByFunction } from 'dummy/tests/acceptance/components/flexberry-objectlistview/folv-tests-functions';
import { Query } from 'ember-flexberry-data';
executeTest('check like filter', (store, assert, app) => {
assert.expect(3);
let path = 'components-acceptance-tests/flexberry-objectlistview/folv-filter';
let modelName = 'ember-flexberry-dummy-suggestion';
let filtreInsertOperation = 'like';
let filtreInsertParametr;
visit(path);
andThen(function() {
assert.equal(currentPath(), path);
let builder2 = new Query.Builder(store).from(modelName).selectByProjection('SuggestionL').where('address', Query.FilterOperator.Neq, '').top(1);
store.query(modelName, builder2.build()).then((result) => {
let arr = result.toArray();
filtreInsertParametr = arr.objectAt(0).get('address');
filtreInsertParametr = filtreInsertParametr.slice(1, filtreInsertParametr.length);
if (!filtreInsertParametr) {
assert.ok(false, 'Empty data');
}
}).then(function() {
let $filterButtonDiv = Ember.$('.buttons.filter-active');
let $filterButton = $filterButtonDiv.children('button');
let $objectListView = Ember.$('.object-list-view');
// Activate filtre row.
$filterButton.click();
filterCollumn($objectListView, 0, filtreInsertOperation, filtreInsertParametr).then(function() {
// Apply filter function.
let refreshFunction = function() {
let refreshButton = Ember.$('.refresh-button')[0];
refreshButton.click();
};
// Apply filter.
let controller = app.__container__.lookup('controller:' + currentRouteName());
let done1 = assert.async();
refreshListByFunction(refreshFunction, controller).then(() => {
let filtherResult = controller.model.content;
let successful = true;
for (let i = 0; i < filtherResult.length; i++) {
let address = filtherResult[i]._data.address;
if (address.lastIndexOf(filtreInsertParametr) === -1) {
successful = false;
}
}
assert.equal(filtherResult.length >= 1, true, 'Filtered list is empty');
assert.equal(successful, true, 'Filter successfully worked');
done1();
});
});
});
});
});
|
var foo = new Object();
var bar = new Object({
baz: 'baz'
});
|
// 04. Write a function to count the number of divs on the web page
function getDivsCount() {
var count = document.getElementsByTagName('div').length;;
console.log("The number of divs is " + count);
}
getDivsCount();
|
const fs = require('fs');
const parse = require('csv-parse');
const stringify = require('csv-stringify');
const transform = require('stream-transform');
var input = fs.createReadStream('../workshop/long-cadence.csv');
var output = fs.createWriteStream('brightness.csv');
var parser = parse();
var stringifier = stringify();
var transformer = transform(function(data){
const time = data[0];
const brightness = data.slice(1);
const sum = brightness
.map(function(value){ return parseFloat(value); })
.reduce(function(partial_sum, value){
return partial_sum + value;
}, 0);
const average = sum / brightness.length;
const filtered_sum = brightness
.filter(function(value){
return value >= average;
})
.reduce(function(partial_sum, value){
return partial_sum + value;
}, 0);
return [time, filtered_sum];
});
input
.pipe(parser)
.pipe(transformer)
.pipe(stringifier)
.pipe(output);
|
'use strict';
const gulp = require('gulp');
const plugin = require('../../lib/index');
const del = require('del');
gulp.task('clean', cb => del('build', cb));
gulp.task('default', ['clean'], () => {
return gulp.src('src/**/*')
// ...
.pipe(plugin({
// options here
}))
// ...
.pipe(gulp.dest('build'));
});
|
(function() {
var CoffeeScript, error, helpers, readline, repl, run, stdin, stdout;
CoffeeScript = require('./coffee-script');
helpers = require('./helpers');
readline = require('readline');
stdin = process.openStdin();
stdout = process.stdout;
error = function(err) {
return stdout.write((err.stack || err.toString()) + '\n\n');
};
helpers.extend(global, {
quit: function() {
return process.exit(0);
}
});
run = function(buffer) {
var val;
try {
val = CoffeeScript.eval(buffer.toString(), {
bare: true,
globals: true,
filename: 'repl'
});
if (val !== void 0) {
process.stdout.write(val + '\n');
}
} catch (err) {
error(err);
}
return repl.prompt();
};
process.on('uncaughtException', error);
if (readline.createInterface.length < 3) {
repl = readline.createInterface(stdin);
stdin.on('data', function(buffer) {
return repl.write(buffer);
});
} else {
repl = readline.createInterface(stdin, stdout);
}
repl.setPrompt('coffee> ');
repl.on('close', function() {
return stdin.destroy();
});
repl.on('line', run);
repl.prompt();
}).call(this);
|
// Search script generated by doxygen
// Copyright (C) 2009 by Dimitri van Heesch.
// The code in this file is loosly based on main.js, part of Natural Docs,
// which is Copyright (C) 2003-2008 Greg Valure
// Natural Docs is licensed under the GPL.
var indexSectionsWithContent =
{
0: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010001110101010011101111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
1: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
2: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
3: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010001110101010010101111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
4: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000001000001100010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "namespaces",
3: "functions",
4: "variables"
};
function convertToId(search)
{
var result = '';
for (i=0;i<search.length;i++)
{
var c = search.charAt(i);
var cn = c.charCodeAt(0);
if (c.match(/[a-z0-9]/))
{
result+=c;
}
else if (cn<16)
{
result+="_0"+cn.toString(16);
}
else
{
result+="_"+cn.toString(16);
}
}
return result;
}
function getXPos(item)
{
var x = 0;
if (item.offsetWidth)
{
while (item && item!=document.body)
{
x += item.offsetLeft;
item = item.offsetParent;
}
}
return x;
}
function getYPos(item)
{
var y = 0;
if (item.offsetWidth)
{
while (item && item!=document.body)
{
y += item.offsetTop;
item = item.offsetParent;
}
}
return y;
}
/* A class handling everything associated with the search panel.
Parameters:
name - The name of the global variable that will be
storing this instance. Is needed to be able to set timeouts.
resultPath - path to use for external files
*/
function SearchBox(name, resultsPath, inFrame, label)
{
if (!name || !resultsPath) { alert("Missing parameters to SearchBox."); }
// ---------- Instance variables
this.name = name;
this.resultsPath = resultsPath;
this.keyTimeout = 0;
this.keyTimeoutLength = 500;
this.closeSelectionTimeout = 300;
this.lastSearchValue = "";
this.lastResultsPage = "";
this.hideTimeout = 0;
this.searchIndex = 0;
this.searchActive = false;
this.insideFrame = inFrame;
this.searchLabel = label;
// ----------- DOM Elements
this.DOMSearchField = function()
{ return document.getElementById("MSearchField"); }
this.DOMSearchSelect = function()
{ return document.getElementById("MSearchSelect"); }
this.DOMSearchSelectWindow = function()
{ return document.getElementById("MSearchSelectWindow"); }
this.DOMPopupSearchResults = function()
{ return document.getElementById("MSearchResults"); }
this.DOMPopupSearchResultsWindow = function()
{ return document.getElementById("MSearchResultsWindow"); }
this.DOMSearchClose = function()
{ return document.getElementById("MSearchClose"); }
this.DOMSearchBox = function()
{ return document.getElementById("MSearchBox"); }
// ------------ Event Handlers
// Called when focus is added or removed from the search field.
this.OnSearchFieldFocus = function(isActive)
{
this.Activate(isActive);
}
this.OnSearchSelectShow = function()
{
var searchSelectWindow = this.DOMSearchSelectWindow();
var searchField = this.DOMSearchSelect();
if (this.insideFrame)
{
var left = getXPos(searchField);
var top = getYPos(searchField);
left += searchField.offsetWidth + 6;
top += searchField.offsetHeight;
// show search selection popup
searchSelectWindow.style.display='block';
left -= searchSelectWindow.offsetWidth;
searchSelectWindow.style.left = left + 'px';
searchSelectWindow.style.top = top + 'px';
}
else
{
var left = getXPos(searchField);
var top = getYPos(searchField);
top += searchField.offsetHeight;
// show search selection popup
searchSelectWindow.style.display='block';
searchSelectWindow.style.left = left + 'px';
searchSelectWindow.style.top = top + 'px';
}
// stop selection hide timer
if (this.hideTimeout)
{
clearTimeout(this.hideTimeout);
this.hideTimeout=0;
}
return false; // to avoid "image drag" default event
}
this.OnSearchSelectHide = function()
{
this.hideTimeout = setTimeout(this.name +".CloseSelectionWindow()",
this.closeSelectionTimeout);
}
// Called when the content of the search field is changed.
this.OnSearchFieldChange = function(evt)
{
if (this.keyTimeout) // kill running timer
{
clearTimeout(this.keyTimeout);
this.keyTimeout = 0;
}
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==40 || e.keyCode==13)
{
if (e.shiftKey==1)
{
this.OnSearchSelectShow();
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
child.focus();
return;
}
}
return;
}
else if (window.frames.MSearchResults.searchResults)
{
var elem = window.frames.MSearchResults.searchResults.NavNext(0);
if (elem) elem.focus();
}
}
else if (e.keyCode==27) // Escape out of the search field
{
this.DOMSearchField().blur();
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.lastSearchValue = '';
this.Activate(false);
return;
}
// strip whitespaces
var searchValue = this.DOMSearchField().value.replace(/ +/g, "");
if (searchValue != this.lastSearchValue) // search value has changed
{
if (searchValue != "") // non-empty search
{
// set timer for search update
this.keyTimeout = setTimeout(this.name + '.Search()',
this.keyTimeoutLength);
}
else // empty search field
{
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.lastSearchValue = '';
}
}
}
this.SelectItemCount = function(id)
{
var count=0;
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
count++;
}
}
return count;
}
this.SelectItemSet = function(id)
{
var i,j=0;
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
var node = child.firstChild;
if (j==id)
{
node.innerHTML='•';
}
else
{
node.innerHTML=' ';
}
j++;
}
}
}
// Called when an search filter selection is made.
// set item with index id as the active item
this.OnSelectItem = function(id)
{
this.searchIndex = id;
this.SelectItemSet(id);
var searchValue = this.DOMSearchField().value.replace(/ +/g, "");
if (searchValue!="" && this.searchActive) // something was found -> do a search
{
this.Search();
}
}
this.OnSearchSelectKey = function(evt)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==40 && this.searchIndex<this.SelectItemCount()) // Down
{
this.searchIndex++;
this.OnSelectItem(this.searchIndex);
}
else if (e.keyCode==38 && this.searchIndex>0) // Up
{
this.searchIndex--;
this.OnSelectItem(this.searchIndex);
}
else if (e.keyCode==13 || e.keyCode==27)
{
this.OnSelectItem(this.searchIndex);
this.CloseSelectionWindow();
this.DOMSearchField().focus();
}
return false;
}
// --------- Actions
// Closes the results window.
this.CloseResultsWindow = function()
{
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.Activate(false);
}
this.CloseSelectionWindow = function()
{
this.DOMSearchSelectWindow().style.display = 'none';
}
// Performs a search.
this.Search = function()
{
this.keyTimeout = 0;
// strip leading whitespace
var searchValue = this.DOMSearchField().value.replace(/^ +/, "");
var code = searchValue.toLowerCase().charCodeAt(0);
var hexCode;
if (code<16)
{
hexCode="0"+code.toString(16);
}
else
{
hexCode=code.toString(16);
}
var resultsPage;
var resultsPageWithSearch;
var hasResultsPage;
if (indexSectionsWithContent[this.searchIndex].charAt(code) == '1')
{
resultsPage = this.resultsPath + '/' + indexSectionNames[this.searchIndex] + '_' + hexCode + '.html';
resultsPageWithSearch = resultsPage+'?'+escape(searchValue);
hasResultsPage = true;
}
else // nothing available for this search term
{
resultsPage = this.resultsPath + '/nomatches.html';
resultsPageWithSearch = resultsPage;
hasResultsPage = false;
}
window.frames.MSearchResults.location.href = resultsPageWithSearch;
var domPopupSearchResultsWindow = this.DOMPopupSearchResultsWindow();
if (domPopupSearchResultsWindow.style.display!='block')
{
var domSearchBox = this.DOMSearchBox();
this.DOMSearchClose().style.display = 'inline';
if (this.insideFrame)
{
var domPopupSearchResults = this.DOMPopupSearchResults();
domPopupSearchResultsWindow.style.position = 'relative';
domPopupSearchResultsWindow.style.display = 'block';
var width = document.body.clientWidth - 8; // the -8 is for IE :-(
domPopupSearchResultsWindow.style.width = width + 'px';
domPopupSearchResults.style.width = width + 'px';
}
else
{
var domPopupSearchResults = this.DOMPopupSearchResults();
var left = getXPos(domSearchBox) + 150; // domSearchBox.offsetWidth;
var top = getYPos(domSearchBox) + 20; // domSearchBox.offsetHeight + 1;
domPopupSearchResultsWindow.style.display = 'block';
left -= domPopupSearchResults.offsetWidth;
domPopupSearchResultsWindow.style.top = top + 'px';
domPopupSearchResultsWindow.style.left = left + 'px';
}
}
this.lastSearchValue = searchValue;
this.lastResultsPage = resultsPage;
}
// -------- Activation Functions
// Activates or deactivates the search panel, resetting things to
// their default values if necessary.
this.Activate = function(isActive)
{
if (isActive || // open it
this.DOMPopupSearchResultsWindow().style.display == 'block'
)
{
this.DOMSearchBox().className = 'MSearchBoxActive';
var searchField = this.DOMSearchField();
if (searchField.value == this.searchLabel) // clear "Search" term upon entry
{
searchField.value = '';
this.searchActive = true;
}
}
else if (!isActive) // directly remove the panel
{
this.DOMSearchBox().className = 'MSearchBoxInactive';
this.DOMSearchField().value = this.searchLabel;
this.searchActive = false;
this.lastSearchValue = ''
this.lastResultsPage = '';
}
}
}
// -----------------------------------------------------------------------
// The class that handles everything on the search results page.
function SearchResults(name)
{
// The number of matches from the last run of <Search()>.
this.lastMatchCount = 0;
this.lastKey = 0;
this.repeatOn = false;
// Toggles the visibility of the passed element ID.
this.FindChildElement = function(id)
{
var parentElement = document.getElementById(id);
var element = parentElement.firstChild;
while (element && element!=parentElement)
{
if (element.nodeName == 'DIV' && element.className == 'SRChildren')
{
return element;
}
if (element.nodeName == 'DIV' && element.hasChildNodes())
{
element = element.firstChild;
}
else if (element.nextSibling)
{
element = element.nextSibling;
}
else
{
do
{
element = element.parentNode;
}
while (element && element!=parentElement && !element.nextSibling);
if (element && element!=parentElement)
{
element = element.nextSibling;
}
}
}
}
this.Toggle = function(id)
{
var element = this.FindChildElement(id);
if (element)
{
if (element.style.display == 'block')
{
element.style.display = 'none';
}
else
{
element.style.display = 'block';
}
}
}
// Searches for the passed string. If there is no parameter,
// it takes it from the URL query.
//
// Always returns true, since other documents may try to call it
// and that may or may not be possible.
this.Search = function(search)
{
if (!search) // get search word from URL
{
search = window.location.search;
search = search.substring(1); // Remove the leading '?'
search = unescape(search);
}
search = search.replace(/^ +/, ""); // strip leading spaces
search = search.replace(/ +$/, ""); // strip trailing spaces
search = search.toLowerCase();
search = convertToId(search);
var resultRows = document.getElementsByTagName("div");
var matches = 0;
var i = 0;
while (i < resultRows.length)
{
var row = resultRows.item(i);
if (row.className == "SRResult")
{
var rowMatchName = row.id.toLowerCase();
rowMatchName = rowMatchName.replace(/^sr\d*_/, ''); // strip 'sr123_'
if (search.length<=rowMatchName.length &&
rowMatchName.substr(0, search.length)==search)
{
row.style.display = 'block';
matches++;
}
else
{
row.style.display = 'none';
}
}
i++;
}
document.getElementById("Searching").style.display='none';
if (matches == 0) // no results
{
document.getElementById("NoMatches").style.display='block';
}
else // at least one result
{
document.getElementById("NoMatches").style.display='none';
}
this.lastMatchCount = matches;
return true;
}
// return the first item with index index or higher that is visible
this.NavNext = function(index)
{
var focusItem;
while (1)
{
var focusName = 'Item'+index;
focusItem = document.getElementById(focusName);
if (focusItem && focusItem.parentNode.parentNode.style.display=='block')
{
break;
}
else if (!focusItem) // last element
{
break;
}
focusItem=null;
index++;
}
return focusItem;
}
this.NavPrev = function(index)
{
var focusItem;
while (1)
{
var focusName = 'Item'+index;
focusItem = document.getElementById(focusName);
if (focusItem && focusItem.parentNode.parentNode.style.display=='block')
{
break;
}
else if (!focusItem) // last element
{
break;
}
focusItem=null;
index--;
}
return focusItem;
}
this.ProcessKeys = function(e)
{
if (e.type == "keydown")
{
this.repeatOn = false;
this.lastKey = e.keyCode;
}
else if (e.type == "keypress")
{
if (!this.repeatOn)
{
if (this.lastKey) this.repeatOn = true;
return false; // ignore first keypress after keydown
}
}
else if (e.type == "keyup")
{
this.lastKey = 0;
this.repeatOn = false;
}
return this.lastKey!=0;
}
this.Nav = function(evt,itemIndex)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==13) return true;
if (!this.ProcessKeys(e)) return false;
if (this.lastKey==38) // Up
{
var newIndex = itemIndex-1;
var focusItem = this.NavPrev(newIndex);
if (focusItem)
{
var child = this.FindChildElement(focusItem.parentNode.parentNode.id);
if (child && child.style.display == 'block') // children visible
{
var n=0;
var tmpElem;
while (1) // search for last child
{
tmpElem = document.getElementById('Item'+newIndex+'_c'+n);
if (tmpElem)
{
focusItem = tmpElem;
}
else // found it!
{
break;
}
n++;
}
}
}
if (focusItem)
{
focusItem.focus();
}
else // return focus to search field
{
parent.document.getElementById("MSearchField").focus();
}
}
else if (this.lastKey==40) // Down
{
var newIndex = itemIndex+1;
var focusItem;
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem && elem.style.display == 'block') // children visible
{
focusItem = document.getElementById('Item'+itemIndex+'_c0');
}
if (!focusItem) focusItem = this.NavNext(newIndex);
if (focusItem) focusItem.focus();
}
else if (this.lastKey==39) // Right
{
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem) elem.style.display = 'block';
}
else if (this.lastKey==37) // Left
{
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem) elem.style.display = 'none';
}
else if (this.lastKey==27) // Escape
{
parent.searchBox.CloseResultsWindow();
parent.document.getElementById("MSearchField").focus();
}
else if (this.lastKey==13) // Enter
{
return true;
}
return false;
}
this.NavChild = function(evt,itemIndex,childIndex)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==13) return true;
if (!this.ProcessKeys(e)) return false;
if (this.lastKey==38) // Up
{
if (childIndex>0)
{
var newIndex = childIndex-1;
document.getElementById('Item'+itemIndex+'_c'+newIndex).focus();
}
else // already at first child, jump to parent
{
document.getElementById('Item'+itemIndex).focus();
}
}
else if (this.lastKey==40) // Down
{
var newIndex = childIndex+1;
var elem = document.getElementById('Item'+itemIndex+'_c'+newIndex);
if (!elem) // last child, jump to parent next parent
{
elem = this.NavNext(itemIndex+1);
}
if (elem)
{
elem.focus();
}
}
else if (this.lastKey==27) // Escape
{
parent.searchBox.CloseResultsWindow();
parent.document.getElementById("MSearchField").focus();
}
else if (this.lastKey==13) // Enter
{
return true;
}
return false;
}
}
|
import $ from 'jquery';
import debounce from 'lodash.debounce';
import getViewportDimensions from './getViewportDimensions';
const $window = $(window);
const $doc = $(document);
const $body = $(document.body);
const modalDataAttr = 'umodal-id';
const triggerDataAttr = `[data-${modalDataAttr}]`;
const modalContentClassName = '.unfoldModal-content';
const modalFooterClassName = '.unfoldModal-actionBar';
const modalHeaderClassName = '.unfoldModal-header';
const overlayClassName = '.unfoldModal-overlay';
const scrollClassName = 'unfoldModal-content--scroll';
const showClassName = 'is-visible';
const bodyActiveClassName = 'is-modalActive';
const closeModalClassName = '.close-modal';
let $overlay;
const noop = () => undefined;
const isFunction = fn => typeof fn === 'function';
function positionModal ($modal) {
const $modalContent = $modal.find(modalContentClassName).first();
$body.removeClass(bodyActiveClassName);
$body.css('top', 'auto');
$modalContent.css('max-height', 'none');
$modalContent.removeClass(scrollClassName);
$modal.css('top', 0);
$modal.css('left', 0);
const vPort = getViewportDimensions()();
const modalHeight = $modal.outerHeight(true);
const modalWidth = $modal.outerWidth(true);
// For desktop and tablet, center the modal both horizontally and vertically
if (window.matchMedia('(min-width: 768px)').matches) {
const top = (modalHeight <= vPort.innerHeight)
? (((vPort.innerHeight - modalHeight) / 2) + $doc.scrollTop()) + 'px'
: $window.scrollTop();
const left = (((vPort.innerWidth - modalWidth) / 2) - $modal.offset().left) + 'px';
$modal.css({ top, left });
// For mobile screens, center the modal horizontally and align to the top of the viewport
} else {
const footerHeight = (window.matchMedia('(min-height: 321px)').matches)
? 0
: $modal.find(modalFooterClassName).outerHeight(true) || 0;
const headerHeight = $modal.find(modalHeaderClassName).outerHeight(true) || 0;
$modalContent
.css('max-height', (vPort.innerHeight - footerHeight - headerHeight) + 'px')
.addClass(scrollClassName);
$body.css('top', ($modal.scrollPosition * -1));
}
$body.addClass(bodyActiveClassName);
if (/Android/.test(window.navigator.appVersion)) {
document.activeElement.scrollIntoViewIfNeeded();
}
}
function ensureOverlay () {
// Already created by unfold
if ($overlay) return $overlay;
// Exists for some other reason
const o = $(overlayClassName);
if (o.length) return ($overlay = o);
// Doesn't exist; add it
const cls = overlayClassName.replace('.', '');
$overlay = $(`<div class="${cls}"></div>`);
$body.append($overlay);
return $overlay;
}
class Unfold {
constructor (elementId) {
this.$modal = $(elementId);
this.$modal.scrollPosition = 0;
this.identifier = elementId;
this.eventIdentifier = 'unfold_' + elementId;
this._handleOpen = noop;
this._handleClose = noop;
this.reset();
}
reset () {
this.$modal.find(closeModalClassName)
.on(`click.${this.eventIdentifier}`, e => this.close(e));
}
close (e) {
if (!this.isOpen()) return;
ensureOverlay().off(`click.${this.eventIdentifier}`);
ensureOverlay().removeClass(showClassName);
this.$modal.removeClass(showClassName);
$body.removeClass(bodyActiveClassName).css('top', 'auto');
$('body, html').animate({
scrollTop: this.$modal.scrollPosition
}, 0);
$window.off(`resize.${this.eventIdentifier}`);
this._handleClose(e);
}
open () {
unfoldFactory.closeAll(m => m !== this);
this.$modal.scrollPosition = $doc.scrollTop();
ensureOverlay().addClass(showClassName);
this.$modal.addClass(showClassName);
$window.on(
`resize.${this.eventIdentifier}`,
debounce(() => positionModal(this.$modal), 200)
);
positionModal(this.$modal);
this._handleOpen(this.$modal[0]);
setTimeout(() => {
$doc.on(`keyup.${this.eventIdentifier}`, e => this.closeOnEscapeKey(e));
ensureOverlay().on(`click.${this.eventIdentifier}`, e => this.close(e));
}, 1);
}
onOpen (callback) {
if (!isFunction(callback)) return;
this._handleOpen = callback;
}
onClose (callback) {
if (!isFunction(callback)) return;
this._handleClose = callback;
}
isOpen () {
return this.$modal.hasClass(showClassName);
}
closeOnEscapeKey (e) {
const escapeKeyCode = 27;
if (e.keyCode !== escapeKeyCode) return;
this.close(e);
}
destroy () {
this.close();
$window.off(this.eventIdentifier);
ensureOverlay().off(this.eventIdentifier);
}
}
const unfoldFactory = {
modals: [],
_triggerModalMap: {},
get (elemId) {
return this.modals.filter(m => m.identifier === elemId)[0];
},
create (elemId, ...triggers) {
let modal = this.get(elemId);
if (!this._triggerModalMap[elemId]) this._triggerModalMap[elemId] = [];
if (!modal) {
modal = new Unfold(elemId);
this.modals.push(modal);
}
triggers && triggers.filter(t => this._triggerModalMap[elemId].indexOf(t) === -1)
.forEach((trigger) => {
$(trigger).on(`click.${modal.eventIdentifier}`, () => modal.open());
this._triggerModalMap[elemId].push(trigger);
});
return modal;
},
init () {
//make sure this event is added to the loop.
setTimeout(() => {
const triggers = [].slice.apply($(triggerDataAttr));
triggers.forEach((trigger) => {
this.create('#' + $(trigger).data(modalDataAttr), trigger);
});
}, 1);
},
destroy () {
this.modals.forEach(modal => {
this._triggerModalMap[modal.identifier]
.forEach(trigger => $(trigger).off(`click.${modal.eventIdentifier}`));
modal.destroy();
});
ensureOverlay().removeClass(showClassName);
this.modals = [];
this._triggerModalMap = {};
},
closeAll (except) {
const exceptFn = isFunction(except) ? except : () => true;
this.modals.filter(exceptFn).forEach(modal => modal.close());
}
};
export default unfoldFactory;
|
var GHClient = require('../..');
var assert = require('assert');
describe('gitCommit', function() {
describe('non mocked', function() {
var ghClient;
before(function() {
assert(process.env.GITHUB_ACCESS_TOKEN, 'Please set GITHUB_ACCESS_TOKEN');
ghClient = new GHClient({ accessToken: process.env.GITHUB_ACCESS_TOKEN });
});
it('get', function(done) {
ghClient.gitCommit.get('gitterHQ/tentacles', '23ba77b441de50d61f4fa2b219fcad5859480c74')
.then(function(commit) {
assert.strictEqual(commit.sha, '23ba77b441de50d61f4fa2b219fcad5859480c74');
})
.nodeify(done);
});
});
describe('mocked', function() {
var mockRequest, requestCalls, requestOptions;
beforeEach(function() {
requestCalls = 0;
requestOptions = null;
mockRequest = function(options, callback) {
requestCalls++;
requestOptions = options;
callback(null, { statusCode: 200 }, { });
};
ghClient = new GHClient({ accessToken: process.env.GITHUB_ACCESS_TOKEN, request: mockRequest });
});
it('create', function(done) {
var body = {
"message": "my commit message",
"author": {
"name": "Andrew Newdigate",
"email": "andrew@gitter.im",
"date": "2008-07-09T16:13:30+12:00"
},
"parents": [
"7d1b31e74ee336d15cbd21741bc88a537ed063a0"
],
"tree": "827efc6d56897b048c772eb4087f854f46256132"
};
ghClient.gitCommit.create('suprememoocow/playground', body)
.then(function() {
assert.strictEqual(requestCalls, 1);
assert.strictEqual(requestOptions.uri, 'https://api.github.com/repos/suprememoocow/playground/git/commits');
assert.strictEqual(requestOptions.method, 'POST');
assert.deepEqual(requestOptions.body, body);
})
.nodeify(done);
});
});
});
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var URL_GetUsers = 'http://introtoapps.com/datastore.php?action=load&appid=214098128&objectid=users';
var URL_GetQuizzes = 'http://introtoapps.com/quizzes_sample.json';
var app = {
// Application Constructor
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
// deviceready Event Handler
onDeviceReady: function() {
this.receivedEvent('deviceready');
LoadQuizzes();
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
app.initialize();
GetQuizzes();
var UserObject = {
username : String,
password : String,
quizzes : []
};
//const URL_GetQuizzes;
var tempScore;
var onsItem;
function GetQuizzes(){
//Check if the user has already attempted/completed this quiz
$.getJSON(URL_GetUsers,function(data)
{
UserObject = data.Users[localStorage.getItem("userNum")];
LoadQuizzes();
})
}
//Load all the quizzes from the json file
function LoadQuizzes()
{
//ERROR cannot get access to resource.
$.getJSON("json/quizzes_sample.json",function(data)
{
$.each(data.Quizzes,function(i,emp){
onsItem = document.createElement('ons-list-item');
onsItem.setAttribute('id', "item("+i+")");
onsItem.setAttribute('onclick', "goToMain("+i+")");
for(i = 0; i < UserObject.quizzes.length; i++)
{
if(UserObject.quizzes[i].quizName == emp.title)
{
tempScore = UserObject.quizzes[i].score;
}
}
//If the quiz is not scored do not show anything for the right side of the list item.
if(emp.score == null)
{
onsItem.innerHTML = "<div class='left'>" + emp.title +" </div>";
}
else {
onsItem.innerHTML = "<div class='left'>" + emp.title +" </div>" + "<div class='right'>" + tempScore + "/" + emp.score +" </div>";
}
document.getElementById('quizList').appendChild(onsItem);
});
console.log('Loaded quizzes for user: ' + localStorage.getItem("userNum"));
}).fail(function(){
document.getElementById("question").innerHTML = "error";
console.log('error');
});
}
//Move to main.html and save the quiz number to be used when accessing it later
function goToMain(pos)
{
window.location = "main.html";
localStorage.setItem("_quizNum",pos);
}
|
/**
* Author: Jeff Whelpley
* Date: 10/25/2014
*
* This is a wrapper for all libs needed for testing
*/
var _ = require('lodash');
var Q = require('q');
var sinon = require('sinon');
var chai = require('chai');
var sinonChai = require('sinon-chai');
var chaiAsPromised = require('chai-as-promised');
var path = require('path');
var argv = require('yargs').argv;
var targetDir;
Q.longStackSupport = true;
chai.use(sinonChai);
chai.use(chaiAsPromised);
//chai.config.truncateThreshold = 0;
/**
* Initialize taste with the input params
* @param dir
*/
function firstBite(dir) {
targetDir = dir || path.join(__dirname, '../../..');
if (targetDir.substring(targetDir.length - 1) === '/') {
targetDir = targetDir.substring(0, targetDir.length - 1);
}
}
/**
* Used to wrap all promises
* @param promises
* @param done Optional param if it exists, will do notify at end
* @returns {*|Promise.<Array.<Object>>}
*/
function all(promises, done) {
Q.all(promises).should.notify(done);
}
/**
* Shorthand for just making sure a promise eventually equals a value
* @param promise
* @param expected
* @param done
*/
function eventuallyEqual(promise, expected, done) {
all([
promise.should.be.fulfilled,
promise.should.eventually.deep.equal(expected)
], done);
}
/**
* Shorthand for making sure promise eventually fulfilled
* @param promise
* @param done
*/
function eventuallyFulfilled(promise, done) {
all([
promise.should.be.fulfilled
], done);
}
/**
* Shorthand for making sure the promise will eventually be rejected
* @param promise
* @param done
*/
function eventuallyRejected(promise, done) {
all([
promise.should.be.rejected
], done);
}
/**
* Shorthand for making sure the promise will eventually be rejected
* @param promise
* @param expected
* @param done
*/
function eventuallyRejectedWith(promise, expected, done) {
all([
promise.should.be.rejectedWith(expected)
], done);
}
/**
* Create copy of an object
* @param obj
* @returns {*}
*/
function copy(obj) {
return JSON.parse(JSON.stringify(obj));
}
/**
* Convienice method for getting a module
* @param relativePath
*/
function target(relativePath) {
return require(targetDir + '/' + relativePath);
}
/**
* Add command line arguments to a given object
* @param obj
*/
function addCommandLineArgs(obj) {
_.extend(obj, argv);
delete obj.$0;
delete obj._;
}
module.exports = {
delim: path.normalize('/'),
firstBite: firstBite,
all: all,
eventuallyEqual: eventuallyEqual,
eventuallyFulfilled: eventuallyFulfilled,
eventuallyRejected: eventuallyRejected,
eventuallyRejectedWith: eventuallyRejectedWith,
copy: copy,
target: target,
addCommandLineArgs: addCommandLineArgs,
spy: sinon.spy,
stub: sinon.stub,
expect: chai.expect,
should: chai.should()
};
|
{
res.end = function() {
originalEnd.apply(this, arguments);
done(null, 0);
};
doIt(req, res, () => done(null, 1));
}
|
'use strict';
var React = require('react');
var CtrApp = require('./Controler_App.js');
var CtrAPI = require('./Controller_QuestetraAPI.js');
var DateView = require('./DateView.js');
module.exports = React.createClass({
displayName: 'exports',
getInitialState: function getInitialState() {
if (this.props.workitem) {
return {
workitem: this.props.workitem,
dateProcessInstanceStart: CtrAPI.Util.ISO8601ToUnix(this.props.workitem.processInstanceStartDatetime),
dateAllocateDatetime: CtrAPI.Util.ISO8601ToUnix(this.props.workitem.allocateDatetime),
dateStartDatetime: CtrAPI.Util.ISO8601ToUnix(this.props.workitem.startDatetime),
dateOfferDatetime: CtrAPI.Util.ISO8601ToUnix(this.props.workitem.offerDatetime),
dateEndDatetime: CtrAPI.Util.ISO8601ToUnix(this.props.workitem.endDatetime),
processInstanceInitQuser: {
name: this.props.workitem.processInstanceInitQgroupName,
id: this.props.workitem.processInstanceInitQuserId
}
};
}
},
onClickTask: function onClickTask(e) {
console.log("onClickTask:" + CtrApp.Views.TASK_FORM);
CtrApp.Action.setView(CtrApp.Views.TASK_FORM, this.state.workitem);
},
render: function render() {
return React.createElement(
'div',
{ className: 'media', onClick: this.onClickTask },
React.createElement('img', { className: 'd-flex mr-3', src: 'http://placehold.it/64x64' }),
React.createElement(
'div',
{ className: 'media-body' },
React.createElement(
'h5',
{ className: 'mt-0' },
this.state.workitem.nodeName,
':',
this.state.workitem.processModelInfoName
),
React.createElement(DateView, { date: this.state.dateProcessInstanceStart }),
React.createElement(DateView, { date: this.state.dateAllocateDatetime }),
React.createElement(DateView, { date: this.state.dateEndDatetime })
)
);
}
});
|
const on = require('@clubajax/on');
class BaseComponent extends HTMLElement {
constructor () {
super();
this._uid = uid(this.localName);
privates[this._uid] = { DOMSTATE: 'created' };
privates[this._uid].handleList = [];
plugin('init', this);
}
connectedCallback () {
privates[this._uid].DOMSTATE = privates[this._uid].domReadyFired ? 'domready' : 'connected';
plugin('preConnected', this);
nextTick(onCheckDomReady.bind(this));
if (this.connected) {
this.connected();
}
this.fire('connected');
plugin('postConnected', this);
}
onConnected (callback) {
if (this.DOMSTATE === 'connected' || this.DOMSTATE === 'domready') {
callback(this);
return;
}
this.once('connected', () => {
callback(this);
});
}
onDomReady (callback) {
if (this.DOMSTATE === 'domready') {
callback(this);
return;
}
this.once('domready', () => {
callback(this);
});
}
disconnectedCallback () {
privates[this._uid].DOMSTATE = 'disconnected';
plugin('preDisconnected', this);
if (this.disconnected) {
this.disconnected();
}
this.fire('disconnected');
let time
const dod = this.destroyOnDisconnect !== undefined ? this.destroyOnDisconnect : BaseComponent.destroyOnDisconnect;
if (dod) {
time = typeof dod === 'number' ? dod : 300;
setTimeout(() => {
if (this.DOMSTATE === 'disconnected') {
this.destroy();
}
}, time);
}
}
attributeChangedCallback(attrName, oldVal, newVal) {
if (this.isSettingAttribute !== attrName) {
newVal = BaseComponent.normalize(newVal);
plugin('preAttributeChanged', this, attrName, newVal, oldVal);
if (this.attributeChanged && BaseComponent.normalize(oldVal) !== newVal) {
this.attributeChanged(attrName, newVal, oldVal);
}
}
}
destroy () {
this.fire('destroy');
privates[this._uid].handleList.forEach(function (handle) {
handle.remove();
});
destroy(this);
}
fire (eventName, eventDetail, bubbles) {
return on.fire(this, eventName, eventDetail, bubbles);
}
emit (eventName, value) {
return on.emit(this, eventName, value);
}
on (node, eventName, selector, callback) {
return this.registerHandle(
typeof node !== 'string' ? // no node is supplied
on(node, eventName, selector, callback) :
on(this, node, eventName, selector));
}
once (node, eventName, selector, callback) {
return this.registerHandle(
typeof node !== 'string' ? // no node is supplied
on.once(node, eventName, selector, callback) :
on.once(this, node, eventName, selector, callback));
}
attr(key, value, toggle) {
this.isSettingAttribute = key;
const add = toggle === undefined ? true : !!toggle;
if (add) {
this.setAttribute(key, value);
} else {
this.removeAttribute(key);
}
this.isSettingAttribute = false;
}
registerHandle (handle) {
privates[this._uid].handleList.push(handle);
return handle;
}
get DOMSTATE () {
return privates[this._uid].DOMSTATE;
}
static set destroyOnDisconnect (value) {
privates['destroyOnDisconnect'] = value;
}
static get destroyOnDisconnect () {
return privates['destroyOnDisconnect'];
}
static clone (template) {
if (template.content && template.content.children) {
return document.importNode(template.content, true);
}
const frag = document.createDocumentFragment();
const cloneNode = document.createElement('div');
cloneNode.innerHTML = template.innerHTML;
while (cloneNode.children.length) {
frag.appendChild(cloneNode.children[0]);
}
return frag;
}
static addPlugin (plug) {
let i, order = plug.order || 100;
if (!plugins.length) {
plugins.push(plug);
}
else if (plugins.length === 1) {
if (plugins[0].order <= order) {
plugins.push(plug);
}
else {
plugins.unshift(plug);
}
}
else if (plugins[0].order > order) {
plugins.unshift(plug);
}
else {
for (i = 1; i < plugins.length; i++) {
if (order === plugins[i - 1].order || (order > plugins[i - 1].order && order < plugins[i].order)) {
plugins.splice(i, 0, plug);
return;
}
}
// was not inserted...
plugins.push(plug);
}
}
}
let
privates = {},
plugins = [];
function plugin (method, node, a, b, c) {
plugins.forEach(function (plug) {
if (plug[method]) {
plug[method](node, a, b, c);
}
});
}
function onCheckDomReady () {
if (this.DOMSTATE !== 'connected' || privates[this._uid].domReadyFired) {
return;
}
let
count = 0,
children = getChildCustomNodes(this),
ourDomReady = onSelfDomReady.bind(this);
function addReady () {
count++;
if (count === children.length) {
ourDomReady();
}
}
// If no children, we're good - leaf node. Commence with onDomReady
//
if (!children.length) {
ourDomReady();
}
else {
// else, wait for all children to fire their `ready` events
//
children.forEach(function (child) {
// check if child is already ready
// also check for connected - this handles moving a node from another node
// NOPE, that failed. removed for now child.DOMSTATE === 'connected'
if (child.DOMSTATE === 'domready') {
addReady();
}
// if not, wait for event
child.on('domready', addReady);
});
}
}
function onSelfDomReady () {
privates[this._uid].DOMSTATE = 'domready';
// domReady should only ever fire once
privates[this._uid].domReadyFired = true;
plugin('preDomReady', this);
// call this.domReady first, so that the component
// can finish initializing before firing any
// subsequent events
if (this.domReady) {
this.domReady();
this.domReady = function () {};
}
// allow component to fire this event
// domReady() will still be called
if (!this.fireOwnDomready) {
this.fire('domready');
}
plugin('postDomReady', this);
}
function getChildCustomNodes (node) {
// collect any children that are custom nodes
// used to check if their dom is ready before
// determining if this is ready
let i, nodes = [];
for (i = 0; i < node.children.length; i++) {
if (node.children[i].nodeName.indexOf('-') > -1) {
nodes.push(node.children[i]);
}
}
return nodes;
}
function nextTick (cb) {
requestAnimationFrame(cb);
}
const uids = {};
function uid (type = 'uid') {
if (uids[type] === undefined) {
uids[type] = 0;
}
const id = type + '-' + (uids[type] + 1);
uids[type]++;
return id;
}
const destroyer = document.createElement('div');
function destroy (node) {
if (node) {
destroyer.appendChild(node);
destroyer.innerHTML = '';
}
}
function makeGlobalListeners (name, eventName) {
window[name] = function (nodeOrNodes, callback) {
function handleDomReady (node, cb) {
function onReady () {
cb(node);
node.removeEventListener(eventName, onReady);
}
if (node.DOMSTATE === eventName || node.DOMSTATE === 'domready') {
cb(node);
}
else {
node.addEventListener(eventName, onReady);
}
}
if (!Array.isArray(nodeOrNodes)) {
handleDomReady(nodeOrNodes, callback);
return;
}
let count = 0;
function onArrayNodeReady () {
count++;
if (count === nodeOrNodes.length) {
callback(nodeOrNodes);
}
}
for (let i = 0; i < nodeOrNodes.length; i++) {
handleDomReady(nodeOrNodes[i], onArrayNodeReady);
}
};
}
makeGlobalListeners('onDomReady', 'domready');
makeGlobalListeners('onConnected', 'connected');
function testOptions(options) {
const tests = {
'prop': 'props',
'bool': 'bools',
'attr': 'attrs',
'properties': 'props',
'booleans': 'bools',
'property': 'props',
'boolean': 'bools'
}
Object.keys(tests).forEach((key) => {
if (options[key]) {
console.error(`BaseComponent.define found "${key}"; Did you mean: "${tests[key]}"?` );
}
})
}
BaseComponent.injectProps = function (Constructor, { props = [], bools = [], attrs = [] }) {
Constructor.bools = [...(Constructor.bools || []), ...bools];
Constructor.props = [...(Constructor.props || []), ...props];
Constructor.attrs = [...(Constructor.attrs || []), ...attrs];
Constructor.observedAttributes = [...Constructor.bools, ...Constructor.props, ...Constructor.attrs];
};
BaseComponent.define = function (tagName, Constructor, options = {}) {
testOptions(options);
BaseComponent.injectProps(Constructor, options);
customElements.define(tagName, Constructor);
return Constructor;
};
module.exports = BaseComponent;
|
import React from 'react';
import PropTypes from 'prop-types';
import { themr } from 'react-css-themr';
import classnames from 'classnames';
import { CARD } from '../identifiers';
const CardText = ({
children, className, theme, ...other
}) => (
<div className={classnames(theme.cardText, className)} {...other}>
{typeof children === 'string' ? <p>{children}</p> : children}
</div>
);
CardText.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
theme: PropTypes.shape({
cardText: PropTypes.string,
}),
};
export default themr(CARD)(CardText);
export { CardText };
|
this.VideoRecorder = new class {
constructor() {
this.started = false;
this.cameraStarted = new ReactiveVar(false);
this.recording = new ReactiveVar(false);
this.recordingAvailable = new ReactiveVar(false);
}
start(videoel, cb) {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
window.URL = window.URL || window.webkitURL;
this.videoel = videoel;
const ok = (stream) => {
this.startUserMedia(stream);
return (cb != null ? cb.call(this) : undefined);
};
if (navigator.getUserMedia == null) {
return cb(false);
}
return navigator.getUserMedia({ audio: true, video: true }, ok, (e) => console.log(`No live video input: ${ e }`));
}
record() {
this.chunks = [];
if (this.stream == null) {
return;
}
this.mediaRecorder = new MediaRecorder(this.stream);
this.mediaRecorder.stream = this.stream;
this.mediaRecorder.mimeType = 'video/webm';
this.mediaRecorder.ondataavailable = (blobev) => {
this.chunks.push(blobev.data);
if (!this.recordingAvailable.get()) {
return this.recordingAvailable.set(true);
}
};
this.mediaRecorder.start();
return this.recording.set(true);
}
startUserMedia(stream) {
this.stream = stream;
this.videoel.src = URL.createObjectURL(stream);
this.videoel.onloadedmetadata = () => this.videoel.play();
this.started = true;
return this.cameraStarted.set(true);
}
stop(cb) {
if (this.started) {
this.stopRecording();
if (this.stream) {
const vtracks = this.stream.getVideoTracks();
for (const vtrack of Array.from(vtracks)) {
vtrack.stop();
}
const atracks = this.stream.getAudioTracks();
for (const atrack of Array.from(atracks)) {
atrack.stop();
}
}
if (this.videoel) {
this.videoel.pause;
this.videoel.src = '';
}
this.started = false;
this.cameraStarted.set(false);
this.recordingAvailable.set(false);
if (cb && this.chunks) {
const blob = new Blob(this.chunks, { type : 'video/webm' });
cb(blob);
}
delete this.recorder;
delete this.stream;
return delete this.videoel;
}
}
stopRecording() {
if (this.started && this.recording && this.mediaRecorder) {
this.mediaRecorder.stop();
this.recording.set(false);
return delete this.mediaRecorder;
}
}
};
|
import {Validator} from './utilities'
var formChangePassword = document.querySelector('#changePassword'),
validator = new Validator(formChangePassword)
validator.config([
{
fn : 'equals',
params : 'newPassword confirmNewPassword',
messageError : 'Las contraseñas no **coinciden**.'
}
])
formChangePassword.onsubmit = function (event){
var validation = validator.isValid()
if(!validation.isValid){
event.preventDefault()
validator.showErrors('.errors')
}else{
if(!confirm('¿Esta seguro de cambiar su contraseña actual?')) return event.preventDefault()
}
}
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2017 GochoMugo <mugo@forfuture.co.ke>
* Copyright (c) 2017 Forfuture LLC <we@forfuture.co.ke>
*/
// built-in modules
const assert = require("assert");
const EventEmitter = require("events");
// installed modules
const Debug = require("debug");
// own modules
const QueryController = require("./query-controller");
// module variables
const debug = Debug("mau:form");
/**
* @class Form
* @private
*/
class Form extends EventEmitter {
/**
* @constructor
* @param {String} name Name of the form
* @param {Array} queries Array of queries
* @param {Object} [options] Options
* @param {Function} [options.cb] Callback invoked on form completion
* @param {Function} [options.i18n] Invoked to return internationalized text.
* @todo Ensure the queries are valid!
*/
constructor(name, queries, options={}) {
debug("constructing new form: %s", name);
assert.ok(name, "Name of form must be provided.");
assert.ok(queries, "Queries must be provided.");
super();
this.name = name;
this.queries = queries;
this.options = options;
}
/**
* Invoke form callback, if any.
* @private
* @param {FormSet} formset Associated formset
* @param {Object} answers Current answers
* @param {Object} ref Reference
* @param {Function} done
*/
_invokeCb(formset, answers, ref, done) {
const event = "done";
if (this.listenerCount(event)) {
debug("emitting done event");
return this.emit(event, formset, answers, ref, done);
}
if (this.options.cb) {
debug("firing form callback");
this.options.cb(answers, ref);
}
return done();
}
/**
* Process a message.
* @param {FormSet} formset Associated formset
* @param {Session} session Session to be used in this context
* @param {String|Number|Null} text Text of the message
* @param {Object} ref Reference
* @param {Function} done callback(error, question, updatedSession)
*/
process(formset, session, text, ref, done) {
debug("processing message '%s' in session '%j'", text, session);
assert.ok(formset, "FormSet must be provided.");
assert.ok(session, "Session must be provided.");
assert.ok(typeof text === "string" || typeof text === "number" || text === null, "Message text must be provided, or `null` for first query.");
assert.ok(ref, "Reference must be provided.");
assert.ok(done, "Callback must be provided.");
let controller;
try {
controller = new QueryController(formset, this, session, ref);
} catch (ex) {
return done(ex);
}
return controller.advance(text, (error, question, updatedSession) => {
if (error) {
return done(error);
}
return done(null, question, updatedSession);
});
}
}
exports = module.exports = Form;
|
/*
* Copyright (c) 2016-present, Parse, LLC
* All rights reserved.
*
* This source code is licensed under the license found in the LICENSE file in
* the root directory of this source tree.
*/
import ParseApp from 'lib/ParseApp';
import React from 'react';
export default class JobsData extends React.Component {
constructor() {
super();
this.state = {
jobs: undefined,
inUse: undefined,
release: undefined
};
}
fetchRelease(app) {
app.getLatestRelease().then(
({ release }) => this.setState({ release }),
() => this.setState({ release: null })
);
}
fetchJobs(app) {
app.getAvailableJobs().then(
({ jobs, in_use }) => {
let available = [];
for (let i = 0; i < jobs.length; i++) {
if (in_use.indexOf(jobs[i]) < 0) {
available.push(jobs[i]);
}
}
this.setState({ jobs: available, inUse: in_use })
}, () => this.setState({ jobs: [], inUse: [] })
);
}
componentDidMount() {
this.fetchJobs(this.context.currentApp);
this.fetchRelease(this.context.currentApp);
}
componentWillReceiveProps(props, context) {
if (this.context !== context) {
this.setState({ release: undefined, jobs: undefined, inUse: undefined });
this.fetchJobs(context.currentApp);
this.fetchRelease(context.currentApp);
}
}
render() {
let child = React.Children.only(this.props.children);
return React.cloneElement(
child,
{
...child.props,
availableJobs: this.state.jobs,
jobsInUse: this.state.inUse,
release: this.state.release
}
);
}
}
JobsData.contextTypes = {
currentApp: React.PropTypes.instanceOf(ParseApp)
};
|
define([
'jQuery-2.1.4.min',
'underscore_1.3.3',
'backbone_0.9.2',
], function ($, _, Backbone) {
//Create local Model to represent the Post model I'll retrieve from the server.
var UserModel = Backbone.Model.extend({
idAttribute: "_id", //Map the Model 'id' to the '_id' assigned by the server.
//When initialized this.id is undefined. This url gets fixed in the initialize() function.
//url: 'http://'+global.serverIp+':'+global.serverPort+'/api/post/'+this.id+'/update',
url: '',
//Initialize is called upon the instantiation of this model. This function is executed once
//per model retrieved from the server.
initialize: function() {
//This function is often used for debugging, so leave it here.
//this.on('change', function() {
//debugger;
// this.save();
//});
//debugger;
this.url = '/api/user/'+this.id+'/update';
},
defaults: {
'_id': '',
'name': '',
'email': '',
'password': '',
'isAdmin': false
},
//Override the default Backbone save() function with one that our API understands.
save: function() {
debugger;
$.getJSON(this.url, this.attributes, function(data) {
//Regardless of success or failure, the API returns the JSON data of the model that was just updated.
//debugger;
log.push('UserModel.save() executed.');
}).error( function(err) {
//This is the error handler.
//debugger;
log.push('Error while trying UserModel.save(). Most likely due to communication issue with the server.');
sendLog();
console.error('Communication error with server while execute UserModel.save()');
});
}
});
return UserModel;
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
Parentheses of the form ( Disjunction ) serve both to group the components of the Disjunction pattern together and to save the result of the match.
The result can be used either in a backreference (\ followed by a nonzero decimal number),
referenced in a replace string,
or returned as part of an array from the regular expression matching function
es5id: 15.10.2.8_A3_T14
description: Execute /a(.?)b\1c\1d\1/.exec("abcd") and check results
---*/
__executed = /a(.?)b\1c\1d\1/.exec("abcd");
__expected = ["abcd",""];
__expected.index = 0;
__expected.input = "abcd";
//CHECK#1
if (__executed.length !== __expected.length) {
$ERROR('#1: __executed = /a(.?)b\\1c\\1d\\1/.exec("abcd"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}
//CHECK#2
if (__executed.index !== __expected.index) {
$ERROR('#2: __executed = /a(.?)b\\1c\\1d\\1/.exec("abcd"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}
//CHECK#3
if (__executed.input !== __expected.input) {
$ERROR('#3: __executed = /a(.?)b\\1c\\1d\\1/.exec("abcd"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}
//CHECK#4
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
$ERROR('#4: __executed = /a(.?)b\\1c\\1d\\1/.exec("abcd"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
}
}
|
"use strict";
var validation_parser_1 = require('./validation-parser');
/**
* Dictionary of validation messages. [messageKey]: messageExpression
*/
exports.validationMessages = {
/**
* The default validation message. Used with rules that have no standard message.
*/
default: "${$displayName} is invalid.",
required: "${$displayName} is required.",
matches: "${$displayName} is not correctly formatted.",
email: "${$displayName} is not a valid email.",
minLength: "${$displayName} must be at least ${$config.length} character${$config.length === 1 ? '' : 's'}.",
maxLength: "${$displayName} cannot be longer than ${$config.length} character${$config.length === 1 ? '' : 's'}.",
minItems: "${$displayName} must contain at least ${$config.count} item${$config.count === 1 ? '' : 's'}.",
maxItems: "${$displayName} cannot contain more than ${$config.count} item${$config.count === 1 ? '' : 's'}.",
equals: "${$displayName} must be ${$config.expectedValue}.",
};
/**
* Retrieves validation messages and property display names.
*/
var ValidationMessageProvider = (function () {
function ValidationMessageProvider(parser) {
this.parser = parser;
}
/**
* Returns a message binding expression that corresponds to the key.
* @param key The message key.
*/
ValidationMessageProvider.prototype.getMessage = function (key) {
var message;
if (key in exports.validationMessages) {
message = exports.validationMessages[key];
}
else {
message = exports.validationMessages['default'];
}
return this.parser.parseMessage(message);
};
/**
* When a display name is not provided, this method is used to formulate
* a display name using the property name.
* Override this with your own custom logic.
* @param propertyName The property name.
*/
ValidationMessageProvider.prototype.getDisplayName = function (propertyName) {
// split on upper-case letters.
var words = propertyName.split(/(?=[A-Z])/).join(' ');
// capitalize first letter.
return words.charAt(0).toUpperCase() + words.slice(1);
};
ValidationMessageProvider.inject = [validation_parser_1.ValidationParser];
return ValidationMessageProvider;
}());
exports.ValidationMessageProvider = ValidationMessageProvider;
|
import { ProxyProvider } from './proxyProvider.js';
import { Addresses } from './addresses.js';
import { isChrome, isFirefox, isMajorUpdate, isMinorUpdate } from './helpers.js';
import { Connector } from './connector.js';
import { Address } from './address.js';
import { detectConflicts } from './conflict.js';
(function setup() {
let proxyListSession = new Addresses();
let proxyProvider = new ProxyProvider();
let connector = new Connector();
let blacklistSession = [];
let pendingRequests = [];
let isBlacklistEnabled = false;
let authenticationEvents = false;
let appState = {
filters: {
countryFilter: [],
protocolFilter: [],
protocols: [],
favorites: true
}
};
if (!isChrome() && browser.proxy.register) {
browser.proxy.register('addon/pac/firefox.js');
}
connector
.addObserver(
newConnector => {
const isConnected = newConnector
.connected instanceof Address;
browser
.browserAction
.setIcon({
path: {
16: isConnected
? 'data/icons/action/icon-16-active.png'
: 'data/icons/action/icon-16.png',
32: isConnected
? 'data/icons/action/icon-32-active.png'
: 'data/icons/action/icon-32.png',
48: isConnected
? 'data/icons/action/icon-48-active.png'
: 'data/icons/action/icon-48.png',
64: isConnected
? 'data/icons/action/icon-64-active.png'
: 'data/icons/action/icon-64.png',
128: isConnected
? 'data/icons/action/icon-128-active.png'
: 'data/icons/action/icon-128.png',
}
});
}
);
// Disable all proxies on browser start
connector.disconnect();
const pacMessageConfiguration = { toProxyScript: true };
browser.storage.local.get()
.then(
storage => {
let favorites = (storage.favorites || [])
.map(element => Object.assign(new Address(), element));
proxyListSession = Addresses
.create(favorites)
.unique()
.union(proxyListSession);
blacklistSession = storage.patterns || [];
isBlacklistEnabled = storage.isBlacklistEnabled || false;
if (!isChrome()) {
browser.runtime.sendMessage({
blacklist: blacklistSession,
isBlacklistEnabled: isBlacklistEnabled
}, pacMessageConfiguration);
}
}
);
browser.storage.onChanged.addListener(
storage => {
if (storage.isBlacklistEnabled || storage.patterns) {
isBlacklistEnabled = storage.isBlacklistEnabled ? storage.isBlacklistEnabled.newValue : isBlacklistEnabled;
blacklistSession = storage.patterns ? storage.patterns.newValue : blacklistSession ;
if (!isChrome()) {
browser.runtime.sendMessage({
blacklist: blacklistSession,
isBlacklistEnabled: isBlacklistEnabled
}, pacMessageConfiguration);
} else {
let proxies = proxyListSession.filterEnabled();
if (!proxies.isEmpty()) {
connector.connect(proxies.one(), blacklistSession, isBlacklistEnabled);
}
}
}
}
);
browser.runtime.onInstalled.addListener(details => {
const { reason, previousVersion } = details;
if (reason === 'update') {
const currentVersion = browser.runtime.getManifest().version;
if (isMajorUpdate(previousVersion, currentVersion) || isMinorUpdate(previousVersion, currentVersion)) {
browser.tabs.create({
url: '../welcome/index.html'
});
}
}
});
function setupAuthentication() {
if (authenticationEvents) {
return;
}
const permissions = {
origins: ['<all_urls>'],
permissions: ['webRequest', 'webRequestBlocking']
};
const onAuthHandlerAsync = ({ isProxy, requestId }, asyncCallback) => {
if (!isProxy) {
return asyncCallback();
}
if (pendingRequests.indexOf(requestId) > -1) {
return asyncCallback({
cancel: true
});
}
pendingRequests.push(requestId);
try {
const proxy = proxyListSession.filterEnabled().one();
if (proxy.getUsername() && proxy.getPassword()) {
asyncCallback({
authCredentials: {
username: proxy.getUsername(),
password: proxy.getPassword()
}
});
}
} catch (e) {
asyncCallback({
cancel: true
});
}
};
const onAuthHandler = ({ isProxy, requestId }) => {
if (!isProxy) {
return {};
}
if (pendingRequests.indexOf(requestId) > -1) {
return { cancel: true };
}
pendingRequests.push(requestId);
try {
const proxy = proxyListSession.filterEnabled().one();
if (proxy.getUsername() && proxy.getPassword()) {
return new Promise(resolve => resolve({
authCredentials: {
username: proxy.getUsername(),
password: proxy.getPassword()
}
}));
}
} catch (e) {
return { cancel: true };
}
};
const onRequestFinished = ({ requestId }) => {
const index = pendingRequests.indexOf(requestId);
if (index > -1) {
pendingRequests.splice(index, 1);
}
};
browser.permissions.contains(permissions).then(yes => {
if (!yes) {
return;
}
if (isFirefox()) {
browser.webRequest.onAuthRequired.addListener(onAuthHandler, { urls: ["<all_urls>"] }, ["blocking"]);
} else {
browser.webRequest.onAuthRequired.addListener(onAuthHandlerAsync, { urls: ["<all_urls>"] }, ["asyncBlocking"]);
}
browser.webRequest.onCompleted.addListener(onRequestFinished, { urls: ["<all_urls>"] });
browser.webRequest.onErrorOccurred.addListener(onRequestFinished, { urls: ["<all_urls>"] });
authenticationEvents = true;
})
}
setupAuthentication();
// Chrome on macOS closes the extension popup when permissions are accepted by user
// so message does not accepted by onMessage event
if (browser.permissions.onAdded) {
browser.permissions.onAdded.addListener(setupAuthentication);
}
browser.runtime.onMessage.addListener(
(request, sender, sendResponse) => {
const { name, message } = request;
switch (name) {
case 'resolve-conflicts': {
if (isChrome()) {
detectConflicts()
.then(conflicts => {
conflicts.forEach(extension => {
browser.management.setEnabled(extension.id, false);
});
});
}
break;
}
case 'get-conflicts': {
detectConflicts().then(conflicts => sendResponse(conflicts));
break;
}
case 'get-proxies': {
const { force } = message;
if (!proxyListSession.byExcludeFavorites().isEmpty() && !force) {
sendResponse(proxyListSession.unique());
} else {
let favoriteProxies = proxyListSession.byFavorite();
proxyProvider
.getProxies()
.then(response => {
let result = response
.map(proxy => {
return (new Address())
.setIPAddress(proxy.server)
.setPort(proxy.port)
.setCountry(proxy.country)
.setProtocol(proxy.protocol)
.setPingTimeMs(proxy.pingTimeMs)
.setIsoCode(proxy.isoCode);
});
proxyListSession = proxyListSession
.filterEnabled()
.concat(favoriteProxies)
.concat(result);
sendResponse(proxyListSession.unique());
});
}
break;
}
case 'connect': {
const { ipAddress, port } = message;
connector.connect(
proxyListSession
.disableAll()
.byIpAddress(ipAddress)
.byPort(port)
.one()
.enable(),
blacklistSession,
isBlacklistEnabled
);
break;
}
case 'disconnect': {
connector.disconnect().then(() => proxyListSession.disableAll());
break;
}
case 'toggle-favorite': {
const { ipAddress, port } = message;
proxyListSession
.byIpAddress(ipAddress)
.byPort(port)
.one()
.toggleFavorite();
browser.storage.local.set({
favorites: [...proxyListSession.byFavorite()]
});
break;
}
case 'update-state': {
appState = Object.assign(appState, message);
break;
}
case 'poll-state': {
sendResponse(appState);
break;
}
case 'add-proxy': {
const { protocol, ipAddress, username, password, port } = message;
const newAddress = new Address()
.setProtocol(protocol)
.setIPAddress(ipAddress)
.setPort(port)
.setFavorite(true)
.setUsername(username)
.setPassword(password);
proxyListSession.unshift(newAddress);
browser.storage.local.set({
favorites: [...proxyListSession.byFavorite()]
});
sendResponse(newAddress);
break;
}
case 'register-authentication': {
// browser.permissions.onAdded is not supported by Firefox
setupAuthentication();
break;
}
}
return true;
}
);
})();
|
const Promise = require('./promise');
const testDriver = require('promises-aplus-tests');
function fulfilled(value) {
return new Promise({
value: value,
state: 'fulfilled'
});
}
function rejected(reason) {
return new Promise({
reason: reason,
state: 'rejected'
});
}
function pending() {
var p = new Promise();
return {
promise: p,
fulfill: p.fulfill,
reject: p.reject
};
}
const adapter = {
fulfilled: fulfilled,
rejected: rejected,
pending: pending
};
testDriver(adapter, {reporter: 'spec'}, function (err) {
console.log(err);
});
|
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {Link} from 'react-router';
import StarRatingComponent from 'react-star-rating-component';
import {toDateString} from '../utils/TimeUtils';
class MovieDetailContent extends Component {
constructor() {
super();
this.state = {
rating: 1
};
}
starClick() {
//
}
renderCategory() {
return this.props.movie.categories.map( (category, index) => {
return <Link key={index} to={'/views/category/' + category.id}>{category.name}</Link> ;
} );
}
render() {
const {rating} = this.state;
const {movie} = this.props;
return (
<div className="movie-detail-content">
<div className="sheader">
<div className="poster">
<img src={movie.poster} alt={movie.name} />
</div>
<div className="data">
<h1>{movie.name}</h1>
<div className="extra">
<span className="tagline">{movie.short_desc}</span>
<span className="date">发行自: {movie.from_year}年 收录于: {toDateString(movie.created ? movie.created: 0)} 最后更新: {toDateString(movie.last_updated ? movie.last_updated: 0)}</span>
<span className="country">({movie.company.name})</span>
<span className="runtime">{movie.status_desc}</span>
<span className="CN/A rated">热度: {movie.hot_number}</span>
</div>
<div className="starstruck-ptype">
<div className="starstruck-wrap">
<div className="dt_rating_data">
<StarRatingComponent name="movieStar" startCount="8" value={rating} onStarClick={this.starClick.bind(this)}/>
</div>
</div>
</div>
<div className="sgeneros">
{this.renderCategory()}
</div>
</div>
</div>
</div>
);
}
}
const propTypes = {
movie: PropTypes.object.isRequired
};
MovieDetailContent.propTypes = propTypes;
export default MovieDetailContent;
|
module.exports = {
css: {
extract: false
}
}
|
(function() {
'use strict';
angular
.module('gulpAngularAbtest')
.directive('acmeMalarkey', acmeMalarkey);
/** @ngInject */
function acmeMalarkey(malarkey) {
var directive = {
restrict: 'E',
scope: {
extraValues: '='
},
template: ' ',
link: linkFunc,
controller: MalarkeyController,
controllerAs: 'vm'
};
return directive;
function linkFunc(scope, el, attr, vm) {
var watcher;
var typist = malarkey(el[0], {
typeSpeed: 40,
deleteSpeed: 40,
pauseDelay: 800,
loop: true,
postfix: ' '
});
el.addClass('acme-malarkey');
angular.forEach(scope.extraValues, function(value) {
typist.type(value).pause().delete();
});
watcher = scope.$watch('vm.contributors', function() {
angular.forEach(vm.contributors, function(contributor) {
typist.type(contributor.login).pause().delete();
});
});
scope.$on('$destroy', function () {
watcher();
});
}
/** @ngInject */
function MalarkeyController($log, githubContributor) {
var vm = this;
vm.contributors = [];
activate();
function activate() {
return getContributors().then(function() {
$log.info('Activated Contributors View');
});
}
function getContributors() {
return githubContributor.getContributors(10).then(function(data) {
vm.contributors = ['Sai','Kats'];
return vm.contributors;
});
}
}
}
})();
|
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'magicline', 'pt-br', {
title: 'Insera um parágrafo aqui'
} );
|
// BerryJS 0.10.5
// (c) 2011-2016 Adam Smallcomb
// Licensed under the MIT license.
// For all details and documentation:
// https://github.com/Cloverstone/Berry
//
//
Berry = function(options, target) {
/**
* Destroys the global reference to this form instance, empties the fieldsets that
* were used and calls the destroy function on each field.
*/
this.destroy = function() {
this.trigger('destroy');
//Trigger the destroy methods for each field
this.each(function() {if(typeof this.destroy === 'function') {this.destroy();}});
//Clean up affected containers
this.$el.empty();
for(var i = this.fieldsets.length-1;i >=0; i--) { $(this.fieldsets[i]).empty(); }
//Dispatch the destroy method of the renderer we used
if(typeof this.renderer.destroy === 'function') { this.renderer.destroy(); }
//Remove the global reference to our form
delete Berry.instances[this.options.name];
this.trigger('destroyed');
};
/**
* Gets the values for all of the fields and structures them according to the
* configuration of the option 'flatten' and 'toArray'. If field name is requested
* then just the value of that field is returned.
*
* @param {string} s Name of the field to return the value of.
* @param {booleon} validate Indicates whether or not to validate
* the values befor returning the results.
*/
this.toJSON = function(s, validate) {
// validate if desired this.valid will hold the result
// if a search string return the valu of the field with that name
if(typeof s === 'string' && s.length > 0){
this.attributes = this.find(s).getValue();
} else {
this.attributes = processMultiples.call(this, this.parsefields(this.options));
}
if(validate || (typeof valid == 'undefined' && this.options.validate) || !this.valid) { this.validate(true); }
return this.attributes;
};
var cloneMultiples = function(attributes, fields){
this.each(function(attributes) {
if(this.multiple) {
var min = this.multiple.min || 1;
if(typeof attributes !== 'undefined'){
var items = Berry.search(attributes, this.getPath());
var attcount = 0;
if(items !== null){
attcount = items.length;
}
if(min < attcount){min = attcount;}
}
var status = true;
var root = this.fields;
if(this.parent){root = this.parent.children;}
if(root[this.name]){
while(this.owner.find(this.getPath()).length < min && status){
status = this.clone();
}
}
}
}, [attributes], fields);
this.each(function(attributes) {
if(this.multiple) {
var min = this.multiple.min || 1;
if(typeof attributes !== 'undefined'){
var items = Berry.search(attributes, this.getPath());
var attcount = 0;
if(items !== null){
attcount = items.length;
}
if(min < attcount){min = attcount;}
}
var status = true;
var root = this.fields;
if(this.parent){root = this.parent.children;}
if(root[this.name]){
while(this.owner.find(this.getPath()).length < min && status){
status = this.clone();
}
}
}
}, [attributes], fields);
return attributes;
};
/**
* Gets the values for all of the fields and structures them according to the
* configuration of the option 'flatten' and 'toArray'
*
* @param {object} attributes The values for the fields to be populated
* @param {?array} fields These are the fields that the attributes will be applied to
* the values befor returning the results.
*/
this.populate = function(attributes, fields) {
this.each(function(attributes) {
if(!this.isContainer) {
var temp = Berry.search(attributes, this.getPath());
//if(typeof temp !== 'undefined' && typeof temp !== 'object') {
// if(typeof temp !== 'object') {
this.setValue(temp);
this.trigger('change');
this.toJSON();
// }
}
}, [attributes], fields);
};
/**
*
*
* @param {function} toCall
* @param {?array} args
* @param {?array} fields
*/
this.each = function(toCall, args, fields) {
fields = (fields || this.fields);
var c = true;
for(var i in fields) {
if(c !== false){
var field = fields[i];
if(field.item && field.isActive()) {
c = toCall.apply(field, args);
} else if(!$.isEmptyObject(field.instances)) {
c = this.each(toCall, args, field.instances);
}
if(!$.isEmptyObject(field.children)) {
c = this.each(toCall, args, field.children);
}
} else { break; }
}
if(c && (typeof args !== 'undefined')) {
return args;
} else {
return c;
}
};
/**
*
*
* @param {string} s This is the path or name of the field you are looking for
* @param {?array} fields These are the fields to be searched
*/
this.find = function(s, fields){
var items = [];
this.each(function(s, items) {
if(this.getPath() == s || this.name == s){
items.push(this);
}
}, [s, items], fields);
if(items.length == 0){
return false;
}
if(items.length > 1 || items[0].multiple){
return items;
}
return items[0];
};
/**
*
*
* @param {string} id This is the id you are looking for
* @param {?array} fields These are the fields to be searched
*/
this.findByID = function(id, fields){
var items = [];
this.each(function(id, items) {
if(this.id == id){
items.push(this);
}
}, [id, items], fields);
return items[0];
};
/**
* Iterates over an array of fields and normalizes the field before passing it on to be
* processed
*
* @param {?array} fields These are the fields we are going to process
* @param {element} target Target is the default element where new fields should be added
* @param {Berry.field} parent This is the parent field
*/
this.processfields = function(fields, target, parent) {
for(var i in fields) {
var state = this.createField(Berry.normalizeItem(fields[i], i, this.options.default), target, parent);
}
};
/**
*
*
* @param {object} item This is the field descriptor to be processed
* @param {element} target Target is the default element where new fields should be added
* @param {Berry.field} parent This is the parent field
* @param {string} insert Location relative to target to place the new field
*/
this.createField = function(item, target, parent, insert) {
if(target[0] !== undefined){target = target[0];}
var field = addField.call(this, item, parent, target, insert);
// this.initializing[field.id] = true;
if(typeof field.fieldset === 'undefined') { field.fieldset = target; }
if(insert == 'before') {
$(target).before(field.render());
} else if(insert == 'after') {
$(target).after(field.render());
} else {
if(field.type !== 'fieldset' || field.isChild() || !this.sectionsEnabled) {
var cRow;
if(typeof $(field.fieldset).children('.row').last().attr('id') !== 'undefined') {
cRow = rows[$(field.fieldset).children('.row').last().attr('id')];
}
if(typeof cRow === 'undefined' || (cRow.used + parseInt(field.columns,10) + parseInt(field.offset,10)) > this.options.columns){
var temp = Berry.getUID();
cRow = {};
cRow.used = 0;
cRow.ref = $(Berry.render('berry_row', {id: temp}));
rows[temp] = cRow;
$(field.fieldset).append(cRow.ref);
}
cRow.used += parseInt(field.columns, 10);
cRow.used += parseInt(field.offset, 10);
cRow.ref.append( $('<div/>').addClass('col-md-' + field.columns).addClass('col-md-offset-' + field.offset).append(field.render()) );
}else{
$(field.fieldset).append(field.render() );
}
}
field.initialize();
return field;
};
var addField = function(item , parent, target, insert) {
var field = new Berry.types[item.type](item, this);
field.parent = parent;
var root = this.fields;
if(parent !== null && parent !== undefined) {
root = parent.children;
}
var exists = (root[field.name] !== undefined);
if(field.isContainer) {
if(!exists) {
root[field.name] = { isContainer: true , multiple: field.multiple , hasChildren: !$.isEmptyObject(item.fields) /*, toArray: (field.item.toArray || field.owner.options.flatten)*/, instances:[] };
}
var insertAt = root[field.name].instances.length;
var targetId = $(target).attr('id');
for(var j in root[field.name].instances){
if(root[field.name].instances[j].id == targetId){
insertAt = parseInt(j, 10) + 1;
break;
}
}
root[field.name].instances.splice(insertAt, 0, field);
var index = 0;
for(var k in root[field.name].instances){
root[field.name].instances[k].instance_id = index++;
}
}else{
if(exists || field.multiple){
if(root[field.name].isContainer){
var temp = [];
temp.push(root[field.name]);
temp = root[field.name];
root[field.name] = {multiple: field.multiple, hasChildren:!$.isEmptyObject(item.fields), instances:[]};
root[field.name].instances.push(temp);
}else if(root[field.name] instanceof Berry.field){
var temp = [];
temp.push(root[field.name]);
temp = root[field.name];
root[field.name] = {instances: []};
root[field.name].instances.push(temp);
}
root[field.name].instances.push(field);
} else {
root[field.name] = field;
}
}
return field;
};
this.parsefields = function(options) {
var newAttributes = {};//$.extend(true, {}, attributes);
// var newAttributes = JSON.parse(JSON.stringify(attributes))
this.each(function(newAttributes, options) {
if(this.isParsable) {
var root;
if(this.isChild() && (!options.flatten || typeof this.parent.multiple !== 'undefined')/*|| (this.instance_id !== null)*/){
root = Berry.search(newAttributes, this.parent.getPath());
} else {
//if(typeof root === 'undefined'){
root = newAttributes;
}
if(!this.isContainer) {
var value = this.getValue();
if(value === null){
value = '';
}
if($.isArray(root)){
if(!root[this.parent.instance_id]) { root[this.parent.instance_id] = {}; }
root[this.parent.instance_id][this.name] = value;
}else{
root[this.name] = value;
}
}else{
if(this.multiple){
// root[this.name] = root[this.name]||[];
if(this.isChild() && this.parent.multiple && $.isArray(root) ){
if(typeof root[this.parent.instance_id] == 'undefined'){root[this.parent.instance_id] = {}}
root[this.parent.instance_id][this.name] = root[this.parent.instance_id][this.name]||[];
}else{
// root[this.name] = {};
root[this.name] = root[this.name]||[];
}
}else if(!options.flatten){
if(this.isChild() && this.parent.multiple && $.isArray(root) ){
if(typeof root[this.parent.instance_id] == 'undefined'){root[this.parent.instance_id] = {}}
root[this.parent.instance_id][this.name] = {};
}else{
root[this.name] = {};
}
}
}
}
}, [newAttributes, options]);
return newAttributes;
};
this.setActions = function(actions) {
if(!this.options.actionTarget) {
this.options.actionTarget = $('<div class="berry-actions" style="overflow:hidden;padding-bottom:10px"></div>');
this.target.append(this.options.actionTarget);
}
this.options.actionTarget.empty();
if(actions) {
actions = containsKey(Berry.btn, actions);
for(var action in actions) {
actions[action].form = this.options.name;
var temp = $(Berry.render('berry__action', actions[action]));
if(typeof actions[action].click === 'function'){
temp.click($.proxy(actions[action].click, this));
}
this.options.actionTarget.append(temp);
}
}
};
var inflate = function(atts) {
var altered = {};
this.each(function(atts, altered) {
var val;
if(this.isContainer){
if(this.multiple){
val = atts[this.name] || [];
}else{
val = {};
}
}else{
val = atts[this.name];
}
if(this.isChild()){
if(!this.parent.multiple){
Berry.search(altered, this.parent.getPath())[this.name] = val;
}
} else {
altered[this.name] = val;
}
}, [atts, altered]);
return altered;
};
var processMultiples = function(attributes) {
var altered = $.extend(true, {}, attributes);
this.each(function(attributes, altered) {
if(this.multiple && this.toArray){
var root = attributes;
var temp = Berry.search(root, this.getPath());
if(this.isChild()){
root = Berry.search(altered, this.parent.getPath());
}
root[this.name] = {};
for(var i in this.children) {
root[this.name][i] = $.pluck(temp,i);
}
}
}, [attributes, altered]);
return altered;
};
var importArrays = function(attributes) {
var altered = $.extend(true, {}, attributes);
this.each(function(attributes, altered) {
if(this.isContainer && this.multiple && this.toArray){
var target = Berry.search(altered, this.parent.getPath());
var localAtts = target[this.name];
var newAtts = [];
var i = 0;
while(i >= 0 && i< 20){
for(var j in localAtts){
if(localAtts[j].length > i){
newAtts[i] = newAtts[i] || {};
newAtts[i][j] = localAtts[j][i];
}else{i = -2;break;}
}
i++;
}
target[this.name] = newAtts;
}
}, [attributes, altered]);
return altered;
};
this.load = function(options){
if(typeof options.attributes !== 'undefined') {
if(typeof options.attributes === 'string') {
$.ajax({
url: this.options.attributes,
method: 'GET',
success: $.proxy(function(data){
this.options.attributes = data;
options = this.options;
if(options.flatten) {
options.attributes = inflate.call(this, options.attributes);
}
this.populate(cloneMultiples.call(this, importArrays.call(this, options.attributes)));
}, this)
});
}else{
if(options.flatten) {
options.attributes = inflate.call(this, options.attributes);
}
this.populate(cloneMultiples.call(this, importArrays.call(this, options.attributes)));
}
}else{
cloneMultiples.call(this);
}
//Sets the initial state of conditionals
this.each(function() {
if(!this.isContainer){
this.trigger('change');
}
});
if(options.autoFocus) {
this.each(function() {
if(!this.isContainer){
this.focus();
return false;
}
});
}
this.trigger('loaded');
};
this.$el = target;
// Track sections for tabs, pages, wizard etc.
this.section_count = 0;
this.sectionsEnabled = false;
this.sections = [];
this.sectionList = [];
// this.initializing = {};
// flags for progress
// this.fieldsinitialized = false;
this.initialized = false;
// Initialize objects/arrays
var rows = {};
this.fieldsets = [];
this.fields = {};
this.options = $.extend({name: Berry.getUID()}, Berry.options, options);
this.events = $.extend(true, {}, Berry.prototype.events);
this.trigger('initialize');
// Give renderers and other plugins a chance to default this
if(typeof this.$el === 'undefined') { this.$el = $('<div/>'); }
// Now the we have an element to work with instantiate the renderer
this.renderer = new Berry.renderers[this.options.renderer](this);
// Render and get the target returned from the renderer
this.target = this.renderer.render();
// Create the legend if not disabled
if(this.options.legend && this.options.legendTarget) { this.options.legendTarget.append(this.options.legend); }
// Process the fields we were given and apply them to the target
// we got from the renderer
this.processfields(this.options.fields, this.target, null);
this.setActions(this.options.actions);
if(typeof this.renderer.initialize === 'function') {
this.renderer.initialize();
}
this.$el.find('form').on('submit', $.proxy(function(){this.trigger('save')}, this) );
if(typeof Berry.instances[this.options.name] !== 'undefined') {
Berry.instances[this.options.name].on('destroyed', $.proxy(function(){
Berry.instances[this.options.name] = this;
this.initialized = true;
this.load(this.options);
this.trigger('initialized');
},this));
Berry.instances[this.options.name].destroy();
}else{
Berry.instances[this.options.name] = this;
this.initialized = true;
this.load(this.options);
this.trigger('initialized');
}
};
/**
* Takes the item descriptor passed in and makes sure the required attributes
* are set and if they are not tries to apply sensible defaults
*
* @param {object} item This is the raw field descriptor to be normalized
* @param {string or int} i The key index of the item
*/
Berry.normalizeItem = function(item, i, defaultItem){
if(typeof item === 'string') {
item = { type : item, label : i };
}
if($.isArray(item)) {
item = { options : item, label : i };
}
item = $.extend({}, defaultItem, item);
//if no name given and a name is needed, check for a given id else use the key
if((typeof item.name === 'undefined' || item.name.length === 0) && !item.isContainer){
if(typeof item.label !== 'undefined' && !isNaN(parseFloat(i))){
item.name = item.label.toLowerCase().split(' ').join('_');
}else if(typeof item.id !== 'undefined') {
item.name = item.id;
} else {
item.name = i.toLowerCase().split(' ').join('_');
}
}
if(typeof item.label === 'undefined' && item.label !== false) {
item.label = i;
}
// Sync the validation with the 'required' shorthand
if(item.required){
$.extend(item, {validate: {required: true}});
} else if(typeof item.validate !== 'undefined'){
item.required = item.validate.required;
}
// Set a sensible type default if type is not defined or not found
if(typeof Berry.types[item.type] === 'undefined') {
// if(typeof item.choices === 'undefined' && typeof item.options === 'undefined'){
// }else{
var length = 0;
if(typeof item.choices !== 'undefined'){length = item.choices.length;}
if(typeof item.options !== 'undefined'){length = item.options.length;}
// if(item.options)
switch(length){
case 0:
if(typeof item.fields === 'undefined'){
item.type = 'text';
}else{
item.type = 'fieldset';
}
break;
case 2:
item.falsestate = item.options[1].toLowerCase().split(' ').join('_');
case 1:
item.type = 'checkbox';
item.truestate = item.options[0].toLowerCase().split(' ').join('_');
break;
case 3:
case 4:
item.type = 'radio';
break;
default:
item.type = 'select';
}
// if(item.options.length == 1){
// item.type = 'checkbox';
// item.truestate = item.options[0].toLowerCase().split(' ').join('_');
// }else
// if(item.options.length <= 4){
// item.type = 'radio';
// }else{
// item.type = 'select';
// }
}
// }
return item;
};
Berry.field = function(item, owner) {
this.children = {};
this.owner = owner;
this.hidden = false;
this.item = $.extend(true, {}, this.defaults, item);
this.owner.trigger('initializeField', {field: this});
$.extend(this, this.owner.options, this.item);
if(this.item.value !== 0){
if(typeof item.value === 'function') {
this.valueFunc = item.value;
this.liveValue = function() {
return this.valueFunc.call(this.owner.toJSON());
};
item.value = this.item.value = this.liveValue();
this.owner.on('change', $.proxy(function(){
this.set(this.liveValue());
},this));
} else if(typeof this.item.value === 'string' && this.item.value.indexOf('=') === 0 && typeof math !== 'undefined') {
this.formula = this.item.value.substr(1);
this.enabled = false;
this.liveValue = function() {
try {
var temp = math.eval(this.formula, this.owner.toJSON());
if($.isNumeric(temp)){
return temp.toFixed((this.item.precision || 0));
}
return temp;
}catch(e){
return this.formula;
}
};
item.value = this.item.value = this.liveValue();
this.owner.on('change', $.proxy(function() {
this.set(this.liveValue());
}, this));
} else {
this.value = (item.value || this.value || item.default || '');
}
} else {
this.value = 0;
}
this.lastSaved = this.liveValue();
this.id = (item.id || Berry.getUID());
this.self = undefined;
this.fieldset = undefined;
if(typeof this.item.fieldset !== 'object'){
if(this.item.fieldset !== undefined && $('.' + this.item.fieldset).length > 0) {
this.fieldset = $('.' + this.item.fieldset)[0];
this.owner.fieldsets.push(this.fieldset);
}else{
if(this.item.fieldset !== undefined && $('[name=' + this.item.fieldset + ']').length > 0) {
this.fieldset = $('[name=' + this.item.fieldset + ']')[0];
this.owner.fieldsets.push(this.fieldset);
}
}
}else{
if(this.item.fieldset.length){
this.fieldset = this.item.fieldset;
}
}
this.val = function(value) {
if(typeof value !== 'undefined') {
this.set(value);
}
return this.getValue();
};
this.columns = (this.columns || this.owner.options.columns);
if(this.columns > this.owner.options.columns) { this.columns = this.owner.options.columns; }
};
$.extend(Berry.field.prototype, {
type: 'text',
offset: 0,
version: '1.0',
isContainer: false,
isParsable: true,
isVisible: true,
isEnabled: true,
instance_id: null,
path: '',
defaults: {},
parent: null,
getPath: function(force) {
var path = '';
if(this.parent !== null && this.parent !== undefined) {
path = this.parent.getPath(force) + '.';
if(this.parent.multiple || force){
path += this.parent.instance_id + '.';
}
}
return path + this.name;
},
isActive: function() {
return this.parent === null || this.parent.isEnabled !== false;
},
isChild: function(){
return this.parent !== null;
},
set: function(value){
if(this.value != value) {
//this.value = value;
this.setValue(value);
this.trigger('change');
}
},
revert: function(){
this.item.value = this.lastSaved;
this.setValue(this.lastSaved);
return this;
},
hasChildren: function() {return !$.isEmptyObject(this.children);},
create: function() {return Berry.render('berry_' + (this.elType || this.type), this);},
render: function() {
if(typeof this.self === 'undefined') {
this.self = $(this.create()).attr('data-Berry', this.owner.options.name);
} else {
this.self.html($(this.create()).html());
}
this.display = this.getDisplay();
return this.self;
},
getValue: function() { return this.$el.val(); },
toJSON: function() {
this.value = this.getValue();
this.lastSaved = this.value;
this.display = this.getDisplay();
return this.lastSaved;
},
liveValue: function() {
return this.value;
},
setup: function() {
this.$el = this.self.find('input');
this.$el.off();
if(this.onchange !== undefined){ this.$el.on('input', this.onchange);}
this.$el.on('input', $.proxy(function() {
this.trigger('change');
}, this));
if(this.item.mask && $.fn.mask) {
this.$el.mask(this.item.mask);
}
},
initialize: function() {
this.setup();
if(typeof this.show !== 'undefined') {
this.isVisible = (typeof this.show == 'undefined' || $.isEmptyObject(this.show));
this.self.toggle(this.isVisible);
// this.update({}, true);
this.showConditions = Berry.processConditions.call(this, this.show,
function(bool, token) {
if(typeof bool == 'boolean') {
// var temp = this.isVisible;
this.showConditions[token] = bool;
// this.self.show();
this.isVisible = true;
for(var c in this.showConditions) {
if(!this.showConditions[c]) {
this.isVisible = false;
// this.self.hide();
break;
}
}
this.self.toggle(this.isVisible);
}
}
);
if(typeof this.showConditions === 'boolean') {
this.self.toggle(this.showConditions);
this.isVisible = this.showConditions;
this.update({}, true);
}
}
if(typeof this.enabled !== 'undefined') {
this.enabledConditions = Berry.processConditions.call(this, this.enabled,
function(bool, token) {
if(typeof bool == 'boolean') {
this.enabledConditions[token] = bool;
this.isEnabled = true;
this.enable();
for(var c in this.enabledConditions) {
if(!this.enabledConditions[c]) {
this.isEnabled = false;
this.disable();
break;
}
}
}
}
);
if(typeof this.enabledConditions == 'boolean'){
this.isEnabled = this.enabledConditions;
this.update({}, true);
}
}
if(typeof this.parsable !== 'undefined') {
this.parsableConditions = Berry.processConditions.call(this, this.parsable,
function(bool, token) {
if(typeof bool == 'boolean') {
var temp = this.isParsable;
this.parsableConditions[token] = bool;
this.isParsable = true;
for(var c in this.parsableConditions) {
if(!this.parsableConditions[c]) {
this.isParsable = false;
break;
}
}
if(temp !== this.isParsable){
this.trigger('change');
}
}
}
);
if(typeof this.parsableConditions == 'boolean'){this.isParsable = this.parsableConditions;}
}
this.owner.trigger('initializedField', {field: this});
},
on: function(topic, func) {
this.owner.on(topic + ':' + this.name, func);
},
delay: function(topic, func) {
this.owner.delay(topic + ':' + this.name, func);
},
trigger: function(topic) {
this.value = this.getValue();
this.owner.trigger(topic + ':' + this.name, {
// type: this.type,
// name: this.name,
id: this.id,
value: this.value,
// path: this.getPath()
});
//this.owner.trigger(topic);
},
setValue: function(value) {
if(typeof value !== 'object'){
if(typeof this.lastSaved === 'undefined'){
this.lastSaved = value;
}
this.value = value;
return this.$el.val(value);
}
return this.value;
},
update: function(item, silent) {
if(typeof item === 'object') {
$.extend(this.item, item);
}
$.extend(this, this.item);
this.setValue(this.value);
this.render();
this.setup();
if(!silent) {
this.trigger('change');
}
},
blur: function() {
this.$el.blur();
},
focus: function() {
this.$el.focus().val('').val(this.value);
},
disable: function() {
this.$el.prop('disabled', true);
},
enable: function() {
this.$el.prop('disabled', false);
},
satisfied: function(){
return (typeof this.value !== 'undefined' && this.value !== null && this.value !== '');
},
displayAs: function() {
return this.lastSaved;
},
getDisplay: function() {
if(this.displayAs !== undefined) {
if(this.item.template !== undefined) {
this.display = this.displayAs();
return Berry.render(this.item.template, this);
} else {
return this.displayAs() || this.item.default || this.item.value || 'Empty';
}
}else{
if(this.item.template !== undefined) {
return Berry.render(this.item.template, this);
} else {
return this.lastSaved || this.item.default || this.item.value || 'Empty';
}
}
},
destroy: function() {
if(this.$el){
this.$el.off();
}
},
});
Berry.field.extend = function(protoProps) {
var parent = this;
var child = function() { return parent.apply(this, arguments); };
var Surrogate = function() { this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
if (protoProps) $.extend(child.prototype, protoProps);
return child;
};
/*********************************/
/* Events */
/*********************************/
Berry.prototype.events = {initialize:[]};
Berry.prototype.addSub = function(topic, func){
if (!this.events[topic]) {
this.events[topic] = [];
}
var token = Berry.getUID();
this.events[topic].push({
token: token,
func: func
});
return token;
};
Berry.prototype.on = function(topic, func, context, execute) {
var eventSplitter = /\s+/;
if(eventSplitter.test(topic)){
var list = topic.split(eventSplitter);
for (var t in list) {
if(typeof context !== 'undefined'){
this.addSub(list[t], $.proxy(func, context));
}else{
this.addSub(list[t], func);
}
}
}else{
if(typeof context !== 'undefined'){
this.lastToken = this.addSub(topic, $.proxy(func, context));
}else{
this.lastToken = this.addSub(topic, func);
}
}
if(execute){
func.call(this, null, topic);
}
return this;
};
//add code to handle parameters and cancelation of events for objects/forms that are deleted
Berry.prototype.delay = function(topic, func, context, execute, delay) {
var temp = function(args, topic, token){
clearTimeout(this.events[token].timer);
this.events[token].timer = setTimeout($.proxy(function(){
this.events[token].func.call(this);
}, context || this) , (delay || 250));
};
var eventSplitter = /\s+/;
if(eventSplitter.test(topic)){
var list = topic.split(eventSplitter);
for (var t in list) {
this.lastToken = this.addSub(list[t], temp);
this.events[this.lastToken] = {func: func, timer: null};
}
}else{
this.lastToken = this.addSub(topic, temp);
this.events[this.lastToken] = {func: func, timer: null};
}
if(execute){
func.call(context || this, null, topic);
}
return this;
};
Berry.prototype.off = function(token) {
for (var m in this.events) {
if (this.events[m]) {
for (var i = 0, j = this.events[m].length; i < j; i++) {
if (this.events[m][i].token === token) {
this.events[m].splice(i, 1);
return token;
}
}
}
}
return this;
};
Berry.prototype.trigger = function(topic, args) {
if (this.events[topic]) {
var t = this.events[topic],
len = t ? t.length : 0;
while (len--) {
t[len].func.call(this, args, topic, t[len].token);
}
}
//this.processTopic(topic, args);
newtopic = topic.split(':')[0];
if(newtopic !== topic){
topic = newtopic;
if (this.events[topic]) {
var t = this.events[topic],
len = t ? t.length : 0;
while (len--) {
t[len].func.call(this, args, topic, t[len].token);
}
}
}
return this;
};
/*********************************/
/* End Events */
/*********************************/Berries = Berry.instances = {};
Berry.counter = 0;
Berry.types = {};
Berry.options = {
errorClass: 'has-error',
errorTextClass: 'font-xs.text-danger',
inline: false,
modifiers: '',
renderer: 'base',
flatten: true,
columns: 12,
autoDestroy: true,
autoFocus: true,
validate: false,
actions: ['cancel', 'save']
};
Berry.register = function(elem) {
if(elem.extends && typeof Berry.types[elem.extends] !== 'undefined'){
Berry.types[elem.type] = Berry.types[elem.extends].extend(elem);
}else{
Berry.types[elem.type] = Berry.field.extend(elem);
}
}
/**
*
*
* @param {array} o The array of fields to be searched
* @param {string} s The path
* @internal
*/
Berry.search = function(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
var a = s.split('.');
while (a.length) {
var n = a.shift();
if (typeof o !== 'undefined' && o !== null && typeof o !== 'string' && n in o) {
o = o[n];
}
}
return o;
}
Berry.collection = function(Berry){
var collections = {};
this.events = {initialize: []};
this.addSub = Berry.prototype.addSub;
this.on = Berry.prototype.on;
this.off = Berry.prototype.off;
this.trigger = Berry.prototype.trigger;
return {
add: function(name, data){
collections[name] = data;
},
get: function(name){
return collections[name];
},
update: function(name, data){
collections[name] = data;
this.trigger(name);
}.bind(this),
on: this.on.bind(this),
off: this.off.bind(this)
}
}(Berry)
Berry.processOpts = function(item, object) {
// If max is set on the item, assume a number set is desired.
// min defaults to 0 and the step defaults to 1.
if(typeof item.max !== 'undefined') {
item.min = (item.min || 0);
item.choices = (item.choices || []);
if(item.step != 0){
if(item.min <= item.max) {
for (var i = item.min; i <= item.max; i=i+(item.step || 1) ) {
item.choices.push(i.toString());
}
}
}
}
// If a function is defined for choices use that.
if(typeof item.choices === 'function') {
item.options = item.choices.call(this, item);
}
if(typeof item.choices !== 'undefined' && item.choices.length > 0) {
if(typeof item.choices === 'string' ) {
item.optionPath = item.choices;
// if(typeof Berry.collections[item.choices] === 'undefined') {
if(typeof Berry.collection.get(item.optionPath) === 'undefined'){// && Berry.collection.get(item.choices) !== 'pending') {
// Berry.collections[item.choices] = [];
Berry.collection.add(item.optionPath, []);
//var getAttributes =
(function(object) {
$.ajax({
url: item.optionPath,
type: 'get',
success: function(data) {
Berry.collection.on(item.optionPath,function(item){
item.waiting = false;
this.update({choices: Berry.collection.get(item.optionPath),options: Berry.collection.get(item.optionPath)});//,value: Berry.search(object.owner.options.attributes, object.getPath())});
if(this.parent && this.parent.multiple){
if(typeof this.owner !== 'undefined') {
this.update({value: Berry.search(this.owner.options.attributes, this.getPath())});
}
}
}.bind(object, item))
Berry.collection.update(item.optionPath, data);
}
});
}(object))
//getAttributes(object);
item.waiting = true;
item.options = [];
return item;
} else {
Berry.collection.on(item.optionPath,function(item, path){
this.item.waiting = false;
this.update({choices: Berry.collection.get(path),options: Berry.collection.get(path)});
if(this.parent && this.parent.multiple){
if(typeof this.owner !== 'undefined') {
this.update({value: Berry.search(this.owner.options.attributes, this.getPath())});
}
}
}.bind(object))
if(Berry.collection.get(item.optionPath).length){
item.choices = Berry.collection.get(item.optionPath);
}
}
}
if(typeof item.choices === 'object' && !$.isArray(item.choices)) {
// item.choices = item.choices.toJSON();
for(var c in conditions) {
Berry.conditions[c].call(this, this.owner, conditions[c], function(bool, token) {
// conditions[c].callBack
});
}
}
// Insert the default value at the beginning
// if(typeof item.default !== 'undefined') {
// item.choices.unshift(item.default);
// }
if(typeof item.choices === 'object'){
item.options = $.map(item.choices, function(value, index) {
return [value];
});
}
}
// else{
// // Insert the default value at the beginning
// if(typeof item.default !== 'undefined' && typeof item.options !== 'undefined') {
// item.options.unshift(item.default);
// }
// }
if(typeof item.default !== 'undefined' && typeof item.options !== 'undefined' && item.options[0] !== item.default) {
item.options.unshift(item.default);
}
if(typeof item.options !== 'undefined' && item.options.length > 0) {
var set = false;
for ( var o in item.options ) {
var cOpt = item.options[o];
if(typeof cOpt === 'string' || typeof cOpt === 'number') {
cOpt = {label: cOpt};
if(item.value_key !== 'index'){
cOpt.value = cOpt.label;
}
}
if(typeof item.value_key !== 'undefined' && item.value_key !== ''){
if(item.value_key === 'index'){
cOpt.value = o;
}else{
cOpt.value = cOpt[item.value_key];
}
}
if(typeof cOpt.value === 'undefined'){
cOpt.value = cOpt.id;
}
if(typeof item.label_key !== 'undefined' && item.label_key !== ''){
cOpt.label = cOpt[item.label_key];
}
if(typeof cOpt.label === 'undefined'){
cOpt.label = cOpt.label || cOpt.name || cOpt.title;
}
item.options[o] = cOpt;//$.extend({label: cOpt.name, value: o}, {label: cOpt[(item.label_key || 'title')], value: cOpt[(item.value_key || 'id')]}, cOpt);
//if(!set) {
if(typeof item.value !== 'undefined' && item.value !== '') {
if(!$.isArray(item.value)) {
item.options[o].selected = (cOpt.value == item.value);
} else {
item.options[o].selected = ($.inArray(cOpt.value, item.value) > -1);
}
}
// else {
// item.options[o].selected = true;
// item.value = item.options[o].value;
// }
// set = item.options[o].selected;
// } else {
// item.options[o].selected = false;
// }
}
}
return item;
}
Berry.getUID = function() {
return 'b' + (Berry.counter++);
};
Berry.render = function(name , data) {
return (templates[name] || templates['berry_text']).render(data, templates);
};
Berry.register({
type: 'fieldset',
getValue: function() { return null;},
create: function() {
this.name = this.name || Berry.getUID();
if(typeof this.multiple !== 'undefined'){
this.multiple.min = this.multiple.min || 1;
if(typeof this.multiple.max !== 'undefined'){
if(this.multiple.max > this.multiple.min){
this.multiple.duplicate = true;
}else if(this.multiple.min > this.multiple.max){
this.multiple.min = this.multiple.max;
}
}//else{this.multiple.duplicate = true;}
}
if(!this.isChild()){
++this.owner.section_count;
this.owner.sections.push(this);
this.owner.sectionList.push({'index': this.owner.section_count, 'text': this.item.legend || this.item.label, state: 'disabled', completed: false, active: false, error: false});
}
this.owner.fieldsets.push( $('[name="' + this.name + '"]')[0]);
return this.owner.renderer.fieldset(this);
},
focus: function(){
this.owner.each(function(){
this.focus();
return false;
}, {}, this.children);
return false;
},
setValue: function(value) {return true;},
setup: function() {
if(this.fields !== undefined) {
return this.owner.processfields(this.fields, this.self, this);
}
},
isContainer: true
});
Berry.renderers = {
base: function(owner) {
this.owner = owner;
this.initialize = function() {
$(this.owner.$el).keydown($.proxy(function(event) {
switch(event.keyCode) {
case 27://escape
$('#close').click();
break;
case 13://enter
if (event.ctrlKey) {
this.owner.$el.find('[data-id=berry-submit]').click();
}
break;
}
}, this));
};
this.fieldset = function(data) {
return Berry.render('berry_' + this.owner.options.renderer + '_fieldset',data);
};
this.destroy = function() {
$(this.owner.$el).off();
this.owner.$el.empty();
};
this.render = function() {
this.owner.$el.html(Berry.render('berry_' + this.owner.options.renderer + '_form' , this.owner.options));
return this.owner.$el.find('form');
};
}
};
Berry.btn = {
save: {
label: 'Save',
icon:'check',
id: 'berry-submit',
modifier: 'success pull-right',
click: function() {
if(this.options.autoDestroy) {
this.on('saved', this.destroy);
}
this.trigger('save');
}
},
cancel: {
label: 'Cancel',
icon: 'times',
id: 'berry-close',
modifier:'default pull-left',
click: function() {
if(this.options.autoDestroy) {this.destroy();}
this.trigger('cancel');
}
}
};
Berry.prototype.events.save = [{
token: Berry.getUID(),
func: function() {
if(typeof this.options.action === 'string') {
if(this.validate()){
this.trigger('saveing');
$.ajax({
url: this.options.action,
data: this.toJSON(),
method: this.options.method || 'POST',
success: $.proxy(function(data){this.trigger('saved', data)}, this)
});
}
}
}
}];
function containsKey(l,k){var r={};for(var j in k){if(typeof l[k[j]]!=='undefined'){r[k[j]]=l[k[j]];}}return r;}
Berry.prototype.sum = function(search) {
var inputs = this.toJSON(search);
var val = 0;
if(typeof inputs === 'object') {
for(var i in inputs) {
val += (parseInt(inputs[i] , 10) || 0);
}
return val;
}
return inputs;
};
$((function($){
$.fn.berry = function(options) {
return new Berry(options, this);
}
})(jQuery));
$.pluck = function(arr, key) {
return $.map(arr, function(e) { return e[key]; });
};Berry.prototype.events.initialize.push({
token: Berry.getUID(),
func: function() {
Berry.field.prototype.clone = function(options) {
// var target = this.self;
var max = this.multiple.max;
if(typeof max === 'undefined' || max > this.parent.children[this.name].instances.length){
var item = $.extend({}, this.owner.options.default, this.item, {id: Berry.getUID(), name: this.name});
this.owner.createField(
$.extend({}, this.owner.options.default, this.item, {id: Berry.getUID(), name: this.name}),
$(this.self), this.parent, 'after');
this.trigger('change');
return true;
}
return false;
}
Berry.field.prototype.remove = function() {
// if((this.multiple.min || 1) < this.parent.children[this.name].instances.length){
if((this.multiple.min || 1) < this.owner.find(this.getPath()).length){
$(this.self).empty().remove();
this.trigger('dropped');
var fields = this.owner.fields;
if(this.isChild()){
fields = this.parent.children;
}
fields[this.name].instances.splice(this.instance_id, 1);
var index=0;
var instances = this.owner.find(this.getPath());
for(var j in instances){
instances[j].instance_id = index++;
}
this.trigger('change');
return true;
}
return false;
}
// this.on('dropped', function(info){
// var temp = this.findByID(info.id);
// var target = this.fields;
// if(temp.isChild()){
// target = temp.parent.children;
// }
// target[temp.name].instances.splice(temp.instance_id, 1);
// }, this);
this.on('initializedField', function(opts){
if(opts.field.multiple && opts.field.multiple.duplicate) {
opts.field.self.find('.duplicate').on('click', $.proxy(opts.field.clone, opts.field) );
opts.field.self.find('.remove').on('click', $.proxy(opts.field.remove, opts.field) );
}
});
}
});Berry.processConditions = function(conditions, func) {
if (typeof conditions === 'string') {
if(conditions === 'show' || conditions === 'enabled' || conditions === 'parsable') {
conditions = this.item[conditions];
}else if(conditions === 'enable') {
conditions = this.item.enable;
}
}
if (typeof conditions === 'boolean') {
return conditions;
}
if (typeof conditions === 'object') {
var keys = [];
for(var c in conditions){
keys.push(Berry.conditions[c].call(this, this.owner, conditions[c], (func || conditions[c].callBack)));
}
return keys;
}
return true;
};
Berry.conditions = {
requires: function(Berry, args, func) {
return Berry.on('change:' + args.name, $.proxy(function(args, local, topic, token) {
func.call(this, (local.value !== null && local.value !== ''), token);
}, this, args)
).lastToken;
},
// valid_previous: function(Berry, args) {},
not_matches: function(Berry , args, func) {
return Berry.on('change:' + args.name, $.proxy(function(args, local, topic, token) {
func.call(this, (args.value !== local.value), token);
}, this, args)
).lastToken;
},
matches: function(Berry, args, func) {
return Berry.on('change:' + args.name, $.proxy(function(args, local, topic, token) {
func.call(this, (args.value === local.value), token);
}, this, args)
).lastToken;
},
test: function(Berry, args, func) {
return Berry.on('change:' + this.name, $.proxy(function(args, local, topic, token) {
func.call(this, args(), token);
}, this, args)
).lastToken;
},
multiMatch: function(Berry, args, func) {
berry.on('change:' + _.pluck(args, 'name').join(' change:'), $.proxy(function(args, local, topic) {
func.call(this, function(args,form){
var status = false;
for(var i in args) {
var val = args[i].value;
var localval = form.toJSON()[args[i].name];
if(typeof val == 'object' && localval !== null){
status = (val.indexOf(localval) !== -1);
}else{
status = (val == localval);
}
if(!status)break;
}
return status;
}(args, berry), 'mm');
}, this, args))
return 'mm';
}
};
Berry.prototype.valid = true;
Berry.prototype.validate = function(processed){
if(!processed) {
this.toJSON();
}
//this.parsefields(this.options);
this.clearErrors();
this.each(this.validateItem);
return this.valid;
};
Berry.prototype.validateItem = function(){
this.owner.performValidate(this);
this.owner.errors[this.item.name] = this.errors;
this.owner.valid = this.valid && this.owner.valid;
};
Berry.prototype.performValidate = function(target, pValue){
var item = target.item;
var value = target.value;
if(typeof pValue !== 'undefined'){value = pValue;}
target.valid = true;
target.errors = '';
if(typeof item.validate !== 'undefined' && typeof item.validate === 'object'){
for(var r in item.validate){
if(!Berry.validations[r].method.call(target, value, item.validate[r])){
if((typeof item.show === 'undefined') || target.isVisible){
target.valid = false;
var estring = Berry.validations[r].message;
if(typeof item.validate[r] == 'string') {
estring = item.validate[r];
}
target.errors = estring.replace('{{label}}', item.label);
}
}
target.self.toggleClass(target.owner.options.errorClass, !target.valid);
target.self.find('.' + target.owner.options.errorTextClass).html(target.errors);
}
}
};
Berry.prototype.errors = {};
Berry.prototype.clearErrors = function() {
this.valid = true;
this.errors = {};
this.$el.find("." + this.options.errorClass).removeClass(this.options.errorClass).find("." + this.options.errorTextClass).html("");
};
//var ruleRegex = /^(.+)\[(.+)\]$/,
Berry.regex = {};
Berry.regex.numeric = /^[0-9]+$/;
Berry.regex.integer = /^\-?[0-9]+$/;
Berry.regex.decimal = /^\-?[0-9]*\.?[0-9]+$/;
Berry.regex.email = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i;
Berry.regex.alpha = /^[a-z]+$/i;
Berry.regex.alphaNumeric = /^[a-z0-9]+$/i;
Berry.regex.alphaDash = /^[a-z0-9_-]+$/i;
Berry.regex.natural = /^[0-9]+$/i;
Berry.regex.naturalNoZero = /^[1-9][0-9]*$/i;
Berry.regex.ip = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/i;
Berry.regex.base64 = /[^a-zA-Z0-9\/\+=]/i;
Berry.regex.url = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
Berry.regex.date = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
Berry.validations = {
required:{
method: function(value, args) {
// var value = field.value;
// if (field.type === 'checkbox') {
// return (field.checked === true);
// }
return this.satisfied();
// return (value !== null && value !== '');
},
message: 'The {{label}} field is required.'
},
matches:{
method: function(value, matchName) {
if (el == this.Berry[matchName]) {
return value === el.value;
}
return false;
},
message: 'The {{label}} field does not match the %s field.'
},
valid_email:{
method: function(value) {
return (Berry.regex.email.test(value) || value === '');
},
message: 'The {{label}} field must contain a valid email address.'
},
valid_emails:{
method: function(value) {
var result = value.split(",");
for (var i = 0; i < result.length; i++) {
if (!Berry.regex.email.test(result[i])) {
return false;
}
}
return true;
},
message: 'The {{label}} field must contain all valid email addresses.'
},
min_length:{
method: function(value, length) {
if (!Berry.regex.numeric.test(length)) {
return false;
}
return (value.length >= parseInt(length, 10));
},
message: 'The {{label}} field must be at least %s characters in length.'
},
max_length:{
method: function(value, length) {
if (!Berry.regex.numeric.test(length)) {
return false;
}
return (value.length <= parseInt(length, 10));
},
message: 'The {{label}} field must not exceed %s characters in length.'
},
exact_length:{
method: function(value, length) {
if (!Berry.regex.numeric.test(length)) {
return false;
}
return (value.length === parseInt(length, 10));
},
message: 'The {{label}} field must be exactly %s characters in length.'
},
greater_than:{
method: function(value, param) {
if (!Berry.regex.decimal.test(value)) {
return false;
}
return (parseFloat(value) > parseFloat(param));
},
message: 'The {{label}} field must contain a number greater than %s.'
},
less_than:{
method: function(value, param) {
if (!Berry.regex.decimal.test(value)) {
return false;
}
return (parseFloat(value) < parseFloat(param));
},
message: 'The {{label}} field must contain a number less than %s.'
},
alpha:{
method: function(value) {
return (Berry.regex.alpha.test(value) || value === '');
},
message: 'The {{label}} field must only contain alphabetical characters.'
},
alpha_numeric:{
method: function(value) {
return (Berry.regex.alphaNumeric.test(value) || value === '');
},
message: 'The {{label}} field must only contain alpha-numeric characters.'
},
alpha_dash:{
method: function(value) {
return (Berry.regex.alphaDash.test(value) || value === '');
},
message: 'The {{label}} field must only contain alpha-numeric characters, underscores, and dashes.'
},
numeric:{
method: function(value) {
return (Berry.regex.decimal.test(value) || value === '');
},
message: 'The {{label}} field must contain only numbers.'
},
integer:{
method: function(value) {
return (Berry.regex.integer.test(value) || value === '');
},
message: 'The {{label}} field must contain an integer.'
},
decimal:{
method: function(value) {
return (Berry.regex.decimal.test(value) || value === '');
},
message: 'The {{label}} field must contain a decimal number.'
},
is_natural:{
method: function(value) {
return (Berry.regex.natural.test(value) || value === '');
},
message: 'The {{label}} field must contain only positive numbers.'
},
is_natural_no_zero:{
method: function(value) {
return (Berry.regex.naturalNoZero.test(value) || value === '');
},
message: 'The {{label}} field must contain a number greater than zero.'
},
valid_ip:{
method: function(value) {
return (Berry.regex.ip.test(value) || value === '');
},
message: 'The {{label}} field must contain a valid IP.'
},
valid_url:{
method: function(value) {
return (Berry.regex.url.test(value) || value === '');
},
message: 'The {{label}} field must contain a valid Url.'
},
valid_base64:{
method: function(value) {
return (Berry.regex.base64.test(value) || value === '');
},
message: 'The {{label}} field must contain a base64 string.'
},
date:{
method: function(value, args) {
return (Berry.regex.date.test(value) || value === '');
},
message: 'The {{label}} field should be in the format MM/DD/YYYY.'
}
};(function(b, $){
b.register({ type: 'checkbox',
defaults: {container: 'span'},
create: function() {
this.checkStatus(this.value);
return b.render('berry_checkbox', this);
},
checkStatus: function(value){
if(value === true || value === "true" || value === 1 || value === "1" || value === "on" || value == this.truestate){
this.value = true;
}else{
this.value = false;
}
},
setup: function() {
this.$el = this.self.find('[type=checkbox]');
this.$el.off();
if(this.onchange !== undefined) {
this.on('change', this.onchange);
}
this.$el.change($.proxy(function(){this.trigger('change');},this));
},
getValue: function() {
if(this.$el.is(':checked')){
return this.truestate || true
}else{
if(typeof this.falsestate !== 'undefined') return this.falsestate;
return false;
};
},
setValue: function(value) {
this.checkStatus(value);
this.$el.prop('checked', this.value);
this.value = value;
},
displayAs: function() {
for(var i in this.item.options) {
if(this.item.options[i].value == this.lastSaved) {
return this.item.options[i].name;
}
}
},
focus: function(){
this.$el.focus();
},
satisfied: function(){
return this.$el.is(':checked');
},
});
})(Berry, jQuery);(function(b, $){
b.register({ type: 'radio',
create: function() {
this.options = b.processOpts.call(this.owner, this.item, this).options;
return b.render('berry_' + (this.elType || this.type), this);
},
setup: function() {
this.$el = this.self.find('[type=radio]');
this.$el.off();
if(this.onchange !== undefined) {
this.on('change', this.onchange);
}
this.$el.change($.proxy(function(){this.trigger('change');}, this));
},
getValue: function() {
if(this.item.waiting){
return this.value;
}
var selected = this.self.find('[type="radio"]:checked').data('label');
for(var i in this.item.options) {
if(this.item.options[i].label == selected) {
return this.item.options[i].value;
}
}
},
setValue: function(value) {
if(typeof value !== 'object' && this.item.waiting || (typeof _.findWhere(this.options, {value: value}) !== 'undefined' || typeof _.findWhere(this.options, {value: value+=''}) !== 'undefined' || typeof _.findWhere(this.options, {value: parseInt(value, 10)}) !== 'undefined') ){
if(typeof this.lastSaved === 'undefined'){
this.lastSaved = value;
}
//if(typeof _.findWhere(this.options, {value: value}) !== 'undefined'){
this.value = value;
this.self.find('[value="' + this.value + '"]').prop('checked', true);
}
},
displayAs: function() {
for(var i in this.item.options) {
if(this.item.options[i].value == this.lastSaved) {
return this.item.options[i].label;
}
}
},
focus: function(){
this.self.find('[type="radio"]:checked').focus();
}
});
})(Berry, jQuery);(function(b, $){
b.register({ type: 'select',
// value: '',
create: function() {
this.options = b.processOpts.call(this.owner, this.item, this).options;
return b.render('berry_' + (this.elType || this.type), this);
},
setup: function() {
this.$el = this.self.find('select');
this.$el.off();
this.setValue(this.value);
if(this.onchange !== undefined){
this.on('change', this.onchange);
}
this.$el.change($.proxy(function(){this.trigger('change');}, this));
},
displayAs: function() {
var o = this.options;
for(var i in o) {
if(o[i].value == this.lastSaved) {
return o[i].label;
}
}
},
getValue: function() {
if(this.item.waiting){
return this.value;
}
return this.$el.val();
},
setValue: function(value){
if(typeof value !== 'object' && this.item.waiting || (typeof _.findWhere(this.options, {value: value}) !== 'undefined' || typeof _.findWhere(this.options, {value: value+=''}) !== 'undefined' || typeof _.findWhere(this.options, {value: parseInt(value, 10)}) !== 'undefined') ){
if(typeof this.lastSaved === 'undefined'){
this.lastSaved = value;
}
this.value = value;
this.$el.val(value);
}
return this.value;
}
});
})(Berry, jQuery);(function(b, $){
b.register({type: 'text' });
b.register({type: 'raw' });
b.register({type: 'password' });
b.register({type: 'date' ,
setValue: function(value) {
if(typeof value !== 'object'){
if(typeof moment !== 'undefined'){value = moment.utc(value).format('YYYY-MM-DD');}
if(typeof this.lastSaved === 'undefined'){
this.lastSaved = value;
}
this.value = value;
return this.$el.val(value);
}
return this.value;
}
});
b.register({type: 'range' });
b.register({type: 'hidden',
create: function() {
return '<div><input type="hidden" name="'+this.name+'" value="'+this.value+'" /></div>';}
});
b.register({ type: 'url',
defaults: {
post: '<i class="fa fa-link"></i>',
validate: {'valid_url': true }
}
});
b.register({ type: 'phone',
defaults: {
mask: '(999) 999-9999',
post: '<i class="fa fa-phone"></i>' ,
placeholder: '+1'
}
});
b.register({ type: 'color',
defaults: {
pre: '<i></i>' ,
type: 'text'
},
setValue: function(value) {
if(typeof value !== 'object'){
if(typeof this.lastSaved === 'undefined'){
this.lastSaved = value;
}
this.value = value;
this.$el.parent().colorpicker('setValue', this.value)
return this.$el.val(value);
}
return this.value;
},
setup: function() {
this.$el = this.self.find('input');
this.$el.off();
if(this.onchange !== undefined){ this.$el.on('input', this.onchange);}
this.$el.on('input', $.proxy(function() {this.trigger('change');}, this));
this.$el.attr('type','text');
this.$el.parent().colorpicker({format: 'hex'}).on('changeColor', $.proxy(function(ev){
this.trigger('change');
}, this));
}
});
b.register({ type: 'email',
defaults: {
post: '<i class="fa fa-envelope"></i>' ,
validate: { 'valid_email': true }
}
});
b.register({ type: 'number',
defaults: { elType: 'text' },
value: 0,
getValue: function() {
var temp = this.$el.val();
if(temp === '') {
return 0;
}else{
if( $.isNumeric( temp ) ){
return parseFloat(temp, 10);
}
}
// if( $.isNumeric( temp ) ){
// return parseFloat(temp, 10);
// }else{
// if(temp === '') {
// return temp;
// }
// this.revert();
// return 0;
// }
},
satisfied: function(){
return (typeof this.value !== 'undefined' && this.value !== null && this.value !== '' && this.value !== 0);
}
});
b.register({ type: 'tags',
defaults: { elType: 'text' },
setup: function() {
this.$el = this.self.find('input');
this.$el.off();
if(this.onchange !== undefined){ this.$el.on('input',this.onchange);}
this.$el.on('input', $.proxy(function(){this.trigger('change');}, this));
if($.fn.tagsInput){
this.$el.tagsInput();
}
},
setValue: function(value) {
if(typeof this.lastSaved === 'undefined'){
this.lastSaved = value;
}
this.value = value;
this.$el.importTags(value);
return this.$el.val(value);
}
});
})(Berry,jQuery);(function(b, $){
b.register({
type: 'textarea',
default: {autosize: true, advanced: false},
setup: function() {
this.$el = this.self.find('textarea');
this.$el.off();
if(this.onchange !== undefined) {
this.$el.on('input', this.onchange);
}
this.$el.on('input', $.proxy(function(){this.trigger('change');},this));
if(this.item.advanced && $.fn.htmlarea){
this.$el.css({height: '300px'}).htmlarea({
toolbar: (this.item.toolbar || [
//['html'],
['bold', 'italic', 'underline'],
['superscript', 'subscript'],
['justifyleft', 'justifycenter', 'justifyright'],
['indent', 'outdent'],
['orderedList', 'unorderedList'],
['link', 'unlink'],
['horizontalrule']
])
});
this.$el.on('change', $.proxy(function(){this.trigger('change');},this));
}
if((this.autosize !== false) && $.fn.autosize){
this.$el.autosize();
}
},
setValue: function(value){
if(typeof value !== 'object'){
if(typeof this.lastSaved === 'undefined'){
this.lastSaved = value;
}
this.value = value;
this.$el.val(value)
if((this.autosize !== false) && $.fn.autosize){
this.$el.trigger('autosize.resize');
}
if(this.item.advanced && $.fn.htmlarea){
this.$el.htmlarea('updateHtmlArea', value);
}
}
return this.$el;
},
focus: function(){
this.$el.focus().val('').val(this.value);
this.self.find('iframe').focus();
}
});
})(Berry,jQuery);Berry.backbone = true;
Berry.prototype.events.initialize.push({
token: Berry.getUID(),
func: function() {
if(typeof this.options.model !== 'undefined'){
this.on('save', function() {
if(this.validate()){
// this.options.model.save(this.toJSON() , {wait: true, patch: true, success: $.proxy(function(){
// this.trigger('saved');
// }, this)});
this.trigger('saveing');
this.options.model.set(this.toJSON());
this.trigger('saved');
}
return this.valid;
});
//may be more universal way to do thisd
var list = this.options.model.schema;
var returnArray = {};
var keys = this.options.fields;
if(keys === 'all' || typeof this.options.fields === 'undefined'){
this.options.fields = list;
}else{
for (var key in keys) {
if(typeof keys[key] === 'string'){
if(typeof list[keys[key]] !== 'undefined'){
returnArray[keys[key]] = list[keys[key]];
}
}else{
returnArray["key_"+key] = keys[key];
}
}
this.options.fields = returnArray;
}
if(typeof this.options.attributes === 'undefined' || $.isEmptyObject(this.options.attributes)) {
this.options.attributes = this.options.model.toJSON();
this.options.model.on('change', function(){
for(var i in this.options.model.changed){
var temp = this.find(i);
if(temp && !$.isArray(temp)) {
temp.set(this.options.model.changed[i]);
}
}
}, this);
this.on('destroy',function(){
this.options.model.off('change', null, this);
});
}
}
}
});
Berry.register({
type: 'fieldset',
getValue: function() { return null;},
create: function() {
this.name = this.name || Berry.getUID();
this.owner.fieldsets.push(this.name);
if(!this.isChild()){
++this.owner.section_count;
this.owner.sections.push(this);
this.owner.sectionList.push({'index': this.owner.section_count, 'text': this.item.legend, state: 'disabled', completed: false, active: false, error: false});
}
return this.owner.renderer.fieldset(this);
},
focus: function(){
this.owner.each(function(){
this.focus();
return false;
}, {}, this.children);
return false;
},
setValue: function(value){return true;},
setup: function() {
if(typeof this.fields !== 'undefined') {
// if(typeof this.owner.options.model !== 'undefined') {
// var list = this.owner.options.model.schema;
// var returnArray = {};
// var keys = this.fields;
// for (var key in keys) {
// if(typeof keys[key] === 'string'){
// if(typeof list[keys[key]] !== 'undefined'){
// returnArray[keys[key]] = list[keys[key]];
// }
// }else{
// returnArray["key_"+key] = keys[key];
// }
// }
// this.fields = returnArray;
// }
this.owner.processfields(this.fields, this.self, this);
}
},
isContainer: true
});Berry.extract = true;
Berry.prototype.events.initialize.push({
token: Berry.getUID(),
func: function() {
if(typeof this.options.template !== 'undefined'){
var myRegexp = /\{\{\{?(.[\s\S]*?)\}\}\}?/g;
text = this.options.template;
var tempdiv = text;
var match = myRegexp.exec(text);
this.options.fields = this.options.fields || {};
while (match != null) {
//split into the constituent parts
var splits = match[1].split(':{');
var pre = '{{';
//if this is a comment we still want to process it and return it to its status as a comment
if(splits[0].substr(0,1) == '!'){splits[0] = splits[0].substr(1);pre += '!';}
//ignore advanced types in the mustache
if($.inArray( splits[0].substr(0,1) , [ "^", "#", "/", ">" ] ) < 0 ){
var cobj = {};
//identify if there is more info about this field, if so map it to an object
if(splits.length>1){cobj = JSON.parse('{'+splits[1] )}
//update the fields array with the the values
this.options.fields[splits[0]] = $.extend(this.options.fields[splits[0]], cobj);
//replace with the mustache equivilent with the key
tempdiv = tempdiv.replace(match[0], pre+(this.options.fields[splits[0]].name || splits[0].toLowerCase().split(' ').join('_'))+"}}");
}
//check if there is more
match = myRegexp.exec(text);
}
this.options.template = Hogan.compile(tempdiv);
}
}
});Berry.prototype.events.initialize.push({
token: Berry.getUID(),
func: function() {
if((typeof this.$el == 'undefined') || !this.$el.length) {
this.autoDestroy = false;
this.$el = $('<div/>');
this.options.modal = (this.options.modal || {});
this.options.modal.header_class = this.options.modal.header_class || 'bg-success';
this.ref = $(Berry.render('modal', this.options));
$(this.ref).appendTo('body');
this.options.legendTarget = this.ref.find('.modal-title');
this.options.actionTarget = this.ref.find('.modal-footer');
this.$el = this.ref.find('.modal-body');
this.ref.modal(this.options.modal);
this.ref.on('shown.bs.modal', $.proxy(function () {
if(this.options.autoFocus){
this.$el.find('.form-control:first').focus();
}
},this));
//Add two more ways to hide the modal (escape and X)
this.on('cancel', $.proxy(function(){
this.ref.modal('hide');
},this));
this.on('saved, close', $.proxy(function(){
this.ref.modal('hide');
this.closeAction = 'save';
},this));
//After the modal is hidden destroy the form that it contained
this.ref.on('hidden.bs.modal', $.proxy(function () {
this.closeAction = (this.closeAction || 'cancel');
this.destroy();
},this));
//After the form has been destroyed remove it from the dom
this.on('destroyed', $.proxy(function(){
// this.ref.remove();
this.ref.modal('hide');
this.trigger('completed');
},this));
}
}
});
(function(b, $){
b.register({
type: 'cselect',
create: function() {
this.options = b.processOpts.call(this.owner, this.item, this).options;
if(this.reference){
for(var i in this.options){
this.options[i].image = this.options[i][this.reference];
}
}
return b.render('berry_' + (this.elType || this.type), this);
},
setup: function() {
this.$el = this.self.find('.dropdown');
this.$el.find('li > a').off();
this.$el.find('li > a').on('click', $.proxy(function(e){
this.$el.find('a').removeClass('list-group-item-success');
$(e.target).closest('a').addClass('list-group-item-success');
this.$el.find('button').html(_.findWhere(this.options,{value:$(e.target).closest('a').attr('data-value')}).label+' <span class="caret"></span>')
if(typeof this.onchange === 'function'){
this.onchange();
}
this.trigger('change');
}, this));
},
getValue: function() {
if(this.$el.find('.list-group-item-success').length){
return this.$el.find('.list-group-item-success').attr('data-value');
}else{
return this.value;
}
},
setValue: function(val) {
if(this.$el.find('[data-value="'+val+'"]').length){
this.value = val;
return this.$el.find('[data-value="'+val+'"]').click();
}else if(typeof val !== 'object' && val && val.length){
this.$el.find('a').removeClass('list-group-item-success');
this.value = val;
this.$el.find('button').html(val+' <span class="caret"></span>')
}
}
});
})(Berry,jQuery);(function(b, $){
b.register({
type: 'ace',
create: function() {
return b.render('berry_ace', this);
},
setup: function() {
this.$el = this.self.find('.formcontrol > div');
this.$el.off();
if(this.onchange !== undefined) {
this.$el.on('input', this.onchange);
}
this.$el.on('input', $.proxy(function(){this.trigger('change');},this));
this.editor = ace.edit(this.id+"container");
this.editor.setTheme(this.item.theme || "ace/theme/chrome");
this.editor.getSession().setMode(this.item.mode || "ace/mode/handlebars");
},
setValue: function(value){
if(typeof this.lastSaved === 'undefined'){
this.lastSaved = value;
}
this.value = value;
this.editor.session.setValue(value);
return this.$el;
},
getValue: function(){
return this.editor.getValue()
},
// destroy: function(){
// this.editor.destroy();
// }
focus: function(){
this.editor.focus();
}
});
})(Berry,jQuery);(function(b, $){
b.register({
type: 'base64',
defaults: { elType: 'file' },
create: function() {
return b.render('berry_text', this);
},
// defaults: {autosize: true, advanced: false},
setup: function() {
this.$el = this.self.find('input');
this.$el.off();
this.$el.on('change', _.partial(function (field, e) {
var files = this.files
// Check for the various File API support.
if (window.FileReader) {
// FileReader are supported.
(function (fileToRead, field) {
var reader = new FileReader();
// Read file into memory as UTF-8
reader.readAsDataURL(fileToRead);
reader.onload = function (event) {
// event.target.result;
this.set(event.target.result);//.split(',').pop());
}.bind(field)
reader.onerror = function (evt) {
if(evt.target.error.name == "NotReadableError") {
alert("Canno't read file !");
}
}
})(files[0],field);
e.currentTarget.value = '';
} else {
alert('FileReader is not supported in this browser.');
}
}, this));
},
setValue: function(value) {
if(typeof value !== 'object'){
if(typeof this.lastSaved === 'undefined'){
this.lastSaved = value;
}
this.value = value;
return this.value;
}
return this.value;
},
getValue: function() { return this.value; }
});
})(Berry,jQuery);
(function(b, $){
// var oldEditor = $.summernote.options.modules.editor;
// $.summernote.options.modules.editor = function() {
// oldEditor.apply(this, arguments);
// var oldCreateRange = this.createRange;
// var oldFocus = this.focus;
// this.createRange = function () {
// this.focus = function() {};
// var result = oldCreateRange.apply(this, arguments);
// this.focus = oldFocus;
// return result;
// };
// };
b.register({
type: 'contenteditable',
create: function() {
return b.render('berry_contenteditable', this);
},
setup: function() {
this.$el = this.self.find('.formcontrol > div');
this.$el.off();
if(this.onchange !== undefined) {
this.$el.on('input', this.onchange);
}
// this.$el.on('input', $.proxy(function(){this.trigger('change');},this));
this.$el.summernote({
// disableDragAndDrop: true,
// dialogsInBody: true,
toolbar: [
// [groupName, [list of button]]
['style', ['bold', 'italic', 'underline', 'clear']],
['link', ['linkDialogShow', 'unlink']],
['font', ['strikethrough', 'superscript', 'subscript']],
['fontsize', ['fontsize']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['height', ['height']],
['view', ['fullscreen']]
]
});
this.$el.on('summernote.change', $.proxy(function(){this.trigger('change');},this));
// this.$el.on('summernote.blur', $.proxy(function() {
// this.$el.summernote('saveRange');
// },this));
// this.$el.on('summernote.focus', $.proxy(function() {
// this.$el.summernote('restoreRange');
// },this));
// this.editor = new Pen({
// editor: this.$el[0], // {DOM Element} [required]
// //textarea: '<textarea name="content"></textarea>', // fallback for old browsers
// //list: ['bold', 'italic', 'underline'] // editor menu list
// });
// tinymce.init({
// selector: '.formcontrol > div', // change this value according to your HTML
// plugins: ['autolink link code image'],
// inline: true,
// toolbar1: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
// });
// this.editor = tinyMCE.editors[tinyMCE.editors.length-1];
},
setValue: function(value){
if(typeof this.lastSaved === 'undefined'){
this.lastSaved = value;
}
// this.editor.setContent(value)
this.$el.summernote('code', value)
this.value = value;
// this.$el.html(value)
return this.$el;
},
getValue: function(){
return this.$el.summernote('code')
// return this.editor.getContent()
// return this.$el.html();
},satisfied: function(){
this.value = this.getValue()
return (typeof this.value !== 'undefined' && this.value !== null && this.value !== '');
}, destroy: function() {
this.$el.summernote('destroy');
if(this.$el){
this.$el.off();
}
}
// destroy: function(){
// this.editor.destroy();
// }
// focus: function(){
// this.$el.focus().val('').val(this.value);
// this.self.find('iframe').focus();
// }
});
})(Berry,jQuery);
$(document).on('focusin', function(e) {
if ($(e.target).closest(".note-editable").length) {
e.stopImmediatePropagation();
}
});
$(document).on('click', function(e) {
if ($(e.target).hasClass(".note-editor")) {
e.stopImmediatePropagation();
$(e.target).find('.open').removeClass('open')
}
});
(function(b, $){
b.register({
type: 'custom_radio',
create: function() {
this.options = b.processOpts.call(this.owner, this.item, this).options;
return b.render('berry_' + (this.elType || this.type), this);
},
defaults: {
selectedClass: 'btn-success',
defaultClass: 'btn-default',
},
setup: function() {
this.$el = this.self.find('.custom-group');
this.$el.children('.btn').off();
this.$el.children('.btn').on('click', $.proxy(function(e){
this.$el.children('.' + this.selectedClass).toggleClass(this.selectedClass + ' ' + this.defaultClass);
$(e.target).closest('.btn').toggleClass(this.selectedClass + ' ' + this.defaultClass);
if(typeof this.onchange === 'function'){
this.onchange();
}
this.trigger('change');
}, this));
},
getValue: function() {
return this.$el.children('.' + this.selectedClass).attr('data-value');
},
setValue: function(val) {
return this.$el.children('[data-value="'+val+'"]').click();
}
});
})(Berry,jQuery);(function(b, $){
b.register({
type: 'custom_select',
create: function() {
this.options = b.processOpts.call(this.owner, this.item, this).options;
if(this.reference){
for(var i in this.options){
this.options[i].image = this.options[i][this.reference];
}
}
return b.render('berry_' + (this.elType || this.type), this);
},
setup: function() {
this.$el = this.self.find('.list-group');
this.$el.children('.list-group-item').off();
this.$el.children('.list-group-item').on('click', $.proxy(function(e){
this.$el.children('.list-group-item-success').removeClass('list-group-item-success');
$(e.target).closest('.list-group-item').addClass('list-group-item-success');
if(typeof this.onchange === 'function'){
this.onchange();
}
this.trigger('change');
}, this));
},
getValue: function() {
return this.$el.children('.list-group-item-success').attr('data-value');
},
setValue: function(val) {
return this.$el.children('[data-value="'+val+'"]').click();
}
});
})(Berry,jQuery);(function(b, $){
b.register({
type: 'dropdown',
create: function() {
// return f.render('berry_dropdown', f.processOpts(this.item));
this.options = b.processOpts.call(this.owner, this.item, this).options;
return b.render('berry_' + (this.elType || this.type), this);
},
setup: function() {
this.$el = this.self.find('.btn-group');
this.$el.find('a').on('click',$.proxy(function(e){
e.preventDefault();
this.setValue($(e.target).data('value'));
this.trigger('change');
if(this.onchange !== undefined){
this.onchange();
}
}, this));
},
setValue: function(value) {
this.$el.find('ul').attr('data-value',value);
return this.$el.find('button').html(this.displayAs(value) + ' <span class="caret"></span>');
},
getValue: function() {
return this.$el.find('ul').attr('data-value');
},
displayAs: function(value) {
for(var i in this.options) {
if(this.options[i].value == (value || this.value)) {
return this.options[i].label;
}
}
}
});
})(Berry,jQuery);(function(b, $){
b.register({ type: 'grid_select',
defaults: {select_class: "text-info",},
create: function() {
//return f.render('berry_grid_select', f.processOpts(this.item));
this.options = b.processOpts.call(this.owner, this.item, this).options;
// if(this.value_key){
for(var i in this.options){
this.options[i].image = this.options[i][(this.value_key || 'value')];
// }
}
return b.render('berry_' + (this.elType || this.type), this);
},
setup: function() {
this.$el = this.self.find('.list');
this.$el.children('.col-md-3').off();
this.$el.children('.col-md-3').on('click', $.proxy(function(e){
this.$el.children('.'+this.select_class).removeClass(this.select_class);
$(e.target).closest('.col-md-3').addClass(this.select_class);
if(typeof this.onchange === 'function'){
this.onchange();
}
this.trigger('change');
}, this));
},
getValue: function() {
return this.$el.children('.'+this.select_class).attr('data-value');
},
setValue: function(val) {
return this.$el.children('[data-value="'+val+'"]').click();
}
});
})(Berry,jQuery);(function(b, $){
b.register({
type: 'image_picker',
default: {autosize: true, advanced: false},
setup: function() {
this.$el = this.self.find('input');
this.$el.off();
if(this.onchange !== undefined){ this.$el.on('input', this.onchange);}
this.$el.on('input', $.proxy(function() {
this.trigger('change');
}, this));
this.self.find('button,img').on('click', $.proxy(function(){
this.modal = $().berry({legend:(this.label || "Choose One"), fields:{
Image:{
label: false,
value: this.value,
options: this.options,
choices: this.choices,
value_key: this.value_key,
label_key: this.label_key,
root: this.path,
type:'grid_select'
}
} }).on('save', function(){
this.update({value:this.modal.fields.image.toJSON()})
this.modal.trigger('close');
}, this)
},this));
},
setValue: function(value){
if(this.value != value) {
this.update({value:value})
}
}
});
})(Berry,jQuery);(function(b, $){
b.register({ type: 'rateit',
create: function() {
return b.render('berry_rateit', this);
},
setup: function() {
this.render();
this.$el = this.self.find('.rateit');
this.$el.rateit();
this.$el.rateit('value', this.value);
this.$el.bind('rated reset', $.proxy(function (e) {
this.$el.focus();
this.trigger('change');
if(this.onchange !== undefined){
this.onchange();
}
},this));
},
setValue: function(value) {
this.value = value;
return this.$el.rateit('value', value);
},
getValue: function() {
return this.$el.rateit('value');
},
getDisplay: function() {
for(var i in this.options) {
if(this.options[i].value == this.lastSaved) {
return this.options[i].label;
}
}
var rstring = "";
for(var i = 1; i<= this.value; i++){
rstring += '<i class="fa fa-star"></i>';
}
var temp = Math.floor(this.value);
if(this.value - temp >= 0.5){
rstring += '<i class="fa fa-star-half-full"></i>';
}
for(var i = Math.round(this.value); i< 5; i++){
rstring += '<i class="fa fa-star-o"></i>';
}
return rstring;
}
});
})(Berry,jQuery);(function(b, $){
b.register({
type: 'upload',
defaults: {autosize: true, advanced: false},
setup: function() {
this.$el = this.self.find('form input');
this.$el.off();
if(this.onchange !== undefined) {
this.$el.on('input', this.onchange);
}
this.$el.on('input', $.proxy(function(){this.trigger('change');},this));
this.myDropzone = new Dropzone('#' + this.name, { method: 'post', paramName: this.name, success: $.proxy(function(message,response){
//contentManager.currentView.model.set(this.name, response[this.name]);
//myDropzone.removeAllFiles();
//this.setValue(response[this.name]);
this.setValue(response);
this.trigger('uploaded');
}, this)});
// myDropzone.on("complete", function(file) {
// myDropzone.removeFile(file);
// });
},
getValue: function() {
return this.value;
},
setValue: function(value){
if(typeof this.lastSaved === 'undefined'){
this.lastSaved = value;
}
this.value = value;
return this.$el;
},
update: function(item, silent) {
if(typeof item === 'object') {
$.extend(this.item, item);
}
$.extend(this, this.item);
this.setValue(this.value);
this.myDropzone.destroy();
this.render();
this.setup();
if(!silent) {
this.trigger('change');
}
},
render: function() {
if(typeof this.self === 'undefined') {
this.self = $(this.create()).attr('data-Berry', this.owner.options.name);
} else {
this.self.find('div:first').replaceWith($(this.create()).html())
}
this.display = this.getDisplay();
return this.self;
}
});
})(Berry,jQuery);Berry.renderers['inline'] = function(owner) {
this.owner = owner;
// this.selector =
this.fieldset = function(data) {
Berry.render('berry_base_fieldset', data);
};
this.render = function() {
return $('<div/>');
};
};
Berry.prototype.events.initialize.push({
token: Berry.getUID(),
func: function(){
if(this.options.renderer == 'inline'){
this.options.inline = true;
this.options.autoFocus = false;
this.options.default = {hideLabel: true,};
this.on('initializeField', function(opts){
opts.field.item.fieldset = this.$el.find('[data-inline="'+opts.field.item.name+'"]');
if(opts.field.item.fieldset.length > 1){
var test = this.$el.find('[data-inline="'+opts.field.item.name+'"][id='+opts.field.item.id+']');
if(test.length > 0){
opts.field.item.fieldset = test;
}
}
if(opts.field.item.fieldset){$.extend(opts.field.item, opts.field.item.fieldset.data());}
// return temp;
});
// fieldset: function(){
// // debugger;
// var temp = this.owner.$el.find('[data-inline='+this.item.name+']');
// if(temp){$.extend(this.item, temp.data());}
// return temp;
// }
// };
}
}
});
Berry.renderers['popins'] = function(owner) {
this.owner = owner;
// this.selector =
this.fieldset = function(data) {
Berry.render('berry_base_fieldset', data);
};
this.render = function() {
return $('<div/>');
};
this.initialize = function() {
this.owner.on('destroy', function(){
$('.row.form-group[data-berry='+this.options.name+']').closest('.popover').remove();
})
if(typeof this.owner.options.popins_template === 'string'){
this.owner.$el.html(Berry.render(this.owner.options.popins_template , {fields: _.toArray(this.owner.fields)}));
}
this.owner.each(function(_this) {
_this.create(this);
}, [this]);
$('body').off('click', '.popoverCancel');
$('body').on('click', '.popoverCancel', function(){
$('[data-popins]').popover('hide');
var fl = Berry.instances[$(this).data('berry')];
var field = fl.find($(this).data('name'));
field.revert();
//fl.$el.find('[name="' + field.name + '"].popins').popover('destroy').siblings('.popover').remove();
//Berry.renderers.popins.prototype.create(field);
$('[data-popins="' + $(this).data('name') + '"]').focus();
});
$('body').off('click', '.popoverSave');
$('body').on('click', '.popoverSave', function() {
var fl = Berry.instances[$(this).data('berry')];
var name = $(this).data('name');
var field = fl.find(name);
$(field.self).find('.form-control').blur();
fl.performValidate(field, field.getValue());
if(field.valid) {
field.toJSON();
fl.$el.find('[data-popins="' + name + '"]').focus().html(field.display).popover('hide');
// fl.$el.find('[name="' + name + '"].popins')
fl.trigger('updated');
fl.trigger('save');
}else{
field.focus();
}
});
$('body').keydown(function(event) {
switch(event.keyCode) {
case 27://escape
$('.popover.in .popoverCancel').click();
break;
case 13://enter
$('.popover.in .popoverSave').click();
break;
}
});
this.owner.on('loaded', $.proxy(function(){
this.owner.each(function() {
this.owner.$el.find('[data-popins="' + this.name + '"]').html(this.display);
});
},this))
};
};
Berry.renderers.popins.prototype.create = function(field){
var target = field.owner.$el.find('[data-popins="' + field.name + '"]');
var pOpts = $.extend(/*{trigger: "manual" , html: true, animation:false},*/{container: '#'+field.owner.$el.attr('id'), viewport:{ selector: '#content', padding: 20 }}, { title:'<div style="padding-left:0"><div class="btn-group pull-right"><div style="margin-left:2px;" class="btn-xs popoverCancel fa fa-times btn btn-danger" data-name="'+field.name+'" data-berry="'+field.owner.options.name+'"></div><div class="btn-xs fa fa-check btn btn-success popoverSave" data-name="'+field.name+'" data-berry="'+field.owner.options.name+'"></div></div></div>'+(field.prompt || field.label), content: field.self, html: true, placement: 'left auto', template: '<div class="popover berry"><div class="arrow"></div><h3 class="popover-title"></h3><div style="min-width:270px" class="popover-content"></div></div>'}, field.owner.options.popins, field.popins);
target.popover(pOpts);
target.on('hidden.bs.popover', function () {
$('.berry.popover').css({display:"none"});
});
target.on('show.bs.popover', function () {
$('.popover.in .popoverCancel').click();
});
target.on('shown.bs.popover', function () {
var field = Berry.instances[$('.berry.popover').find('.row').data('berry')].find($('.berry.popover').find('.row').attr('name'));
field.initialize(); //maybe not needed
field.focus();
});
};
Berry.prototype.events.initialize.push({
token: Berry.getUID(),
func: function(){
if(this.options.renderer == 'popins'){
this.options.default = {hideLabel: true};
this.options.inline = true;
$.extend(this.options.default,{hideLabel: true});
}
}
});Berry.renderers['tabs'] = function(owner) {
this.owner = owner;
this.fieldset = function(data){
if(data.parent === null){
return Berry.render('berry_tabs_fieldset', data);
}
return Berry.render('berry_base_fieldset', data);
};
this.render = function(){
this.owner.$el.html(Berry.render('berry_base_form', this.owner.options));
return this.owner.$el.find('form');
};
this.initialize = function() {
if(this.owner.options.tabsTarget){
this.owner.on('destroy', function(){
this.options.tabsTarget.empty();
});
}else{
this.owner.options.tabsTarget = this.owner.$el;
}
this.owner.options.tabsTarget.prepend(Berry.render('berry_tabs', this.owner)).find('a:first').tab('show');
};
};
Berry.prototype.events.initialize.push({
token: Berry.getUID(),
func: function() {
if(this.options.renderer == 'tabs') {
this.sectionsEnabled = true;
this.options.modifiers += " tab-content";
}
}
});
Berry.renderers['wizard'] = function(owner) {
this.owner = owner;
this.fieldset = function(data){
return Berry.render('berry_' + this.owner.options.renderer + '_fieldset', data);
};
this.render = function(){
this.owner.$el.html(Berry.render('berry_' + this.owner.options.renderer + '_form', this.owner.options));
return this.owner.$el.find('form');
};
this.$element = null;
this.update = function(){
this.$element.find('ul').html(Berry.render('berry_wizard_steps',this.owner));
$('[data-id=berry-submit],[data-id=wizard-next]').hide();
$('.step-pane').removeClass('active');
$('#step' + (this.owner.currentSection + 1)).addClass('active');
if((this.owner.currentSection + 1) != this.owner.section_count){
$('[data-id=wizard-next]').show();
}else{
$('[data-id=berry-submit]').show();
}
if(this.owner.currentSection === 0){
$('[data-id=wizard-previous]').hide();
}else{
$('[data-id=wizard-previous]').show();
}
// reset the wizard position to the left
this.$element.find('ul').first().attr('style','margin-left: 0');
// check if the steps are wider than the container div
var totalWidth = 0;
this.$element.find('ul > li').each(function () {
totalWidth += $(this).outerWidth();
});
var containerWidth = 0;
if (this.$element.find('.actions').length) {
containerWidth = this.$element.width() - this.$element.find('.actions').first().outerWidth();
} else {
containerWidth = this.$element.width();
}
if (totalWidth > containerWidth) {
// set the position so that the last step is on the right
var newMargin = totalWidth - containerWidth;
this.$element.find('ul').first().attr('style','margin-left: -' + newMargin + 'px');
// set the position so that the active step is in a good
// position if it has been moved out of view
if (this.$element.find('li.' + this.owner.sectionList[this.owner.currentSection].state ).first().position().left < 200) {
newMargin += this.$element.find('li.' + this.owner.sectionList[this.owner.currentSection].state ).first().position().left - 200;
if (newMargin < 1) {
this.$element.find('ul').first().attr('style','margin-left: 0');
} else {
this.$element.find('ul').first().attr( 'style' , 'margin-left: -' + newMargin + 'px');
}
}
}
};
this.next = function(){
this.owner.valid = true;
this.owner.toJSON();
this.owner.each(this.owner.validateItem, null, this.owner.sections[this.owner.currentSection].children);
if(this.owner.valid){
if(this.owner.currentSection < (this.owner.section_count - 1)){
this.owner.sectionList[this.owner.currentSection].state = 'complete';
this.owner.currentSection++;
this.owner.clearErrors();
this.owner.sectionList[this.owner.currentSection].state = 'active';
}
}else{
this.owner.sectionList[this.owner.currentSection].state = 'error';
}
this.update();
};
this.previous = function(){
if(this.owner.currentSection > 0){
this.owner.sectionList[this.owner.currentSection].state = 'disabled';
this.owner.currentSection--;
this.owner.sectionList[this.owner.currentSection].state = 'active';
}
this.update();
};
this.sectionClick = function(e){
var clickedSection = parseInt($(e.currentTarget).data('target').replace('#step', ''), 10) - 1;
if(clickedSection < this.owner.currentSection) {
for(var i = clickedSection; i <= this.owner.currentSection; i++){
this.owner.sectionList[i].state = 'disabled';
}
this.owner.currentSection = clickedSection;
this.owner.sectionList[this.owner.currentSection].state = 'active';
}
this.update();
};
this.initialize = function() {
this.owner.sectionList[0].state = 'active';
this.owner.currentSection = 0;
if((this.owner.currentSection + 1) == this.owner.section_count){
$('[data-id=wizard-next]').hide();
}else{
$('[data-id=berry-submit]').hide();
}
if(this.owner.currentSection === 0){
$('[data-id=wizard-previous]').hide();
}else{
$('[data-id=wizard-previous]').show();
}
this.$element = this.owner.$el.find('.wizard');
this.$element.find('ul').html(Berry.render('berry_wizard_steps',this.owner));
$('#step1').addClass('active');
$('body').on('click','.wizard li',$.proxy(this.sectionClick,this));
$('body').on('click','[data-id=wizard-next]',$.proxy(this.next,this));
$('body').on('click','[data-id=wizard-previous]',$.proxy(this.previous,this));
};
};
Berry.btn['previous'] = {
'label': "Previous",
'icon':'arrow-left',
'id': 'wizard-previous',
'modifier': 'danger pull-left'
};
Berry.btn['next'] = {
'label': "Next",
'icon':'arrow-right',
'id': 'wizard-next',
'modifier': 'success pull-right'
};
Berry.btn['finish'] = $.extend({}, Berry.btn['save'], {label: 'Finish'});
Berry.prototype.events.initialize.push({
token: Berry.getUID(),
func: function(){
if(this.options.renderer == 'wizard') {
this.sectionsEnabled = true;
this.options.actions = ['finish', 'next', 'previous'];
}
}
});
|
// gamelib.mathあたりに移動する?
export default class Utils {
static clamp(value, min, max) {
if (value < min) {
return min;
}
if (value > max) {
return max;
}
return value;
}
}
/*
gamelib.radian = function (degree) {
return degree * Math.PI * 2 / 360;
}
gamelib.inRange = function (value, min, max) {
return (value >= min && value <= max);
}
gamelib.random = function (min, max) {
return min + Math.random() * (max - min);
}
gamelib.randomInt = function (min, max) {
return Math.floor(gamelib.random(min, max + 1));
}
gamelib.map = function (value, s0, s1, d0, d1) {
return d0 + (value - s0) * (d1 - d0) / (s1 - s0);
}
gamelib.vectorLength = function (x, y) {
return Math.sqrt(x * x + y * y);
}
// normalize angle to [-PI, PI]
gamelib.wrapAngle = function (angle) {
var t = angle - Math.floor((angle + Math.PI) / (Math.PI * 2)) * Math.PI * 2;
return t;
}
gamelib.rotatePoint = function (px, py, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
var qx = px * c + py * -s;
var qy = px * s + py * c;
return {
x : qx,
y : qy
};
}
gamelib.debug = function (message) {
document.getElementById("debug").innerHTML += message + "<br>";
}
*/
|
/*------------------------------------*\
debounced events
\*------------------------------------*/
/**
* Requesting animation frames on scroll/resize updates
* rather than running these functions a billion times...
* http://www.html5rocks.com/en/tutorials/speed/animations/
*/
vital.debouncedEvents = (function(){
/**
*
* $scrollUpdate - functions to run on scroll
* picturefill loading
* scroll to top
*
* $resizeUpdate - functions to run on resize
*
* $pageUpdateTick - called by requestAnimationFrame, calls appropriate event functions
*
* $sortByPriority - sorts an array of items on the priority value...
*
* $requestAnimationTick - using requestAnimationFrame to debounce event handlers
*
* $addFunctionOn
*
* $removeFunctionOn
*
*/
/**
* PRIVATE
*/
var _scrollFunctionArray = [];
var _resizeFunctionArray = [];
/*----------------------------------------*\
$scrollupdate
\*----------------------------------------*/
function _scrollUpdate(){
/**
* This function loops through any/all functions added to the _scrollFunctionArray in order
*/
//console.log('doing a scroll update. Here\'s the _scrollFunctionArray: ');
//console.log(_scrollFunctionArray);
var i, l;
l = _scrollFunctionArray.length;
i = 0;
//console.log(_scrollFunctionArray);
for (i; i < l; i++) {
//console.log('_scrollUpdate '+i+': '+_scrollFunctionArray[i].func.toString());
//console.log('\n---\n');
_scrollFunctionArray[i].func( _scrollFunctionArray[i].args );
}
}
/*----------------------------------------*\
$resizeUpdate
\*----------------------------------------*/
function _resizeUpdate(){
/**
* This function loops through any/all functions added to the _resizeFunctionArray in order
*/
//console.log('doing a resize update. Here\'s the _resizeFunctionArray: ');
//console.log(_resizeFunctionArray);
var i, l;
l = _resizeFunctionArray.length;
i = 0;
for (i; i < l; i++) {
//console.log('_resizeUpdate '+i+': '+_resizeFunctionArray[i].func.toString());
_resizeFunctionArray[i].func( _resizeFunctionArray[i].args );
}
}
/*------------------------------------*\
$pageUpdateTick
\*------------------------------------*/
var _animationTicking = false;
var _animateResize = false;
var _animateScroll = false;
//called by requestAnimationTick on pages with deferred images
function _pageUpdateTick(){
if(_animateScroll){
_scrollUpdate();
_animateScroll = false;
}
if(_animateResize){
_resizeUpdate();
_animateResize = false;
}
_animationTicking = false;
}//pageUpdateTick
/*------------------------------------*\
$sortByPriority
\*------------------------------------*/
function _sortByPriority(a, b){
if (a.priority > b.priority) {
return 1;
}
if (a.priority < b.priority) {
return -1;
}
// a must be equal to b
return 0;
}
/**
* PUBLIC
*/
/*------------------------------------*\
$requestAnimationTick
\*------------------------------------*/
function requestAnimationTick(type){
//console.log(type);
if(type === 'scroll'){
_animateScroll = true;
}else if(type === 'resize'){
_animateResize = true;
}
if(!_animationTicking){
requestAnimationFrame(_pageUpdateTick);
}
_animationTicking = true;
}
/*------------------------------------*\
$addFunctionOn
\*------------------------------------*/
/**
* Function to add a function to an array which is looped through on scroll events
* _priority is optional but defaults to 10 (with lower priorities happening earlier)
* _args is an optional object of options passed to the function when called
*/
function addFunctionOn(type, funk, _priority, _args){
var funkArray = type === 'scroll' ? _scrollFunctionArray : (type === 'resize' ? _resizeFunctionArray : false);
if(funkArray !== false){
if( (_priority < 0) || (typeof _priority !== 'number') ){
//if priority is < 0, missing, or not a number we set it's priority to 10 which is the default
_priority = 10;
}
funkArray.push( {func: funk, priority: _priority, args: _args} );
//sort the array we just pushed to by priority
funkArray.sort(_sortByPriority);
}
}
/*------------------------------------*\
$removeFunctionOn
\*------------------------------------*/
/**
* Remove a function from an array!
* returns true if function was removed.
*/
function removeFunctionOn(type, funk, _priority){
var funkArray = type === 'scroll' ? _scrollFunctionArray : (type === 'resize' ? _resizeFunctionArray : false);
var i = funkArray.length - 1;
for (i; i >= 0; i--) {
if( funkArray[i].func === funk && funkArray[i].priority === _priority ){
//we found an exact match for priority and function so let's remove it
funkArray.splice(i, 1);
return true;
}
}
return false;
}
//revealing public methods
return {
requestAnimationTick : requestAnimationTick,
addFunctionOn : addFunctionOn,
removeFunctionOn : removeFunctionOn
};
}()); //vital.debouncedEvents
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require foundation/app
//= require onloadfunc
|
'use strict';
/**
* Module dependencies.
*/
var Sequelize = require('sequelize');
var db = require('../../config/sequelize');
var sequelize = db.sequelize;
var schema = db.schema;
// var mongoose = require('mongoose'),
// Schema = mongoose.Schema;
var Item = sequelize.define('item', {
name: Sequelize.STRING,
description: Sequelize.STRING,
location: Sequelize.STRING,
stock: Sequelize.INTEGER,
price: Sequelize.FLOAT,
creator: Sequelize.STRING,
category: Sequelize.STRING,
image: Sequelize.STRING
});
Item.sync({force: false}).then(function() {
// return Item.create({
// name: "Male Enhancement Drugs",
// description: "Five inches in Five Days",
// location: "Your mom's house",
// stock: 10,
// price: 69.69,
// creator: "asdf",
// image: "http://www.genericviagra123.com/wp-content/uploads/2013/02/generic-viagra.jpg"
// });
});
schema['Item'] = Item;
// /**
// * Item Schema
// */
// var ItemSchema = new Schema({
// name: {
// type: String,
// default: '',
// required: 'Please fill Item name',
// trim: true
// },
// created: {
// type: Date,
// default: Date.now
// },
// user: {
// type: Schema.ObjectId,
// ref: 'User'
// }
// });
// mongoose.model('Item', ItemSchema);
|
const util = require('util');
const hasFunction = (obj, attr) => (
(typeof obj === 'object') &&
(typeof obj[attr] === 'function'));
const inspect = (val) => util.inspect(val, { depth: 2 });
const validate = (obj, attr, { missing, invalid }) => {
if (!hasFunction(obj, attr)) {
throw new Error(obj === undefined
? missing
: `${invalid}: ${inspect(obj)}`);
}
};
module.exports = validate;
module.exports.inspect = inspect;
|
import { Criteria } from '../criteria.js';
export class CriteriaPath extends Criteria {
constructor(options, valueMap) {
super();
this.options = options;
this.valueMap = valueMap;
this.checkVar = 'aka_request_path';
}
process() {
let usePattern = true;
let valueSuffix = '*'; // path is a special case as it matches as a prefix always
return super.process(usePattern, valueSuffix);
}
}
Criteria.register('path', CriteriaPath);
|
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/column', function(req, res, next) {
res.render('column', { title: 'Express' });
});
router.get('/door', function(req, res, next) {
res.render('door', { title: 'Express' });
});
router.get('/grid', function(req, res, next) {
res.render('grid', { title: 'Express' });
});
router.get('/window', function(req, res, next) {
res.render('window', { title: 'Express' });
});
router.get('/login', function(req, res, next) {
res.render('login', { title: 'Express' });
});
router.get('/submit', function(req, res, next) {
res.render('submit', { title: 'Express' });
});
router.get('/level', function(req, res, next) {
res.render('level', { title: '编辑标高' });
});
router.get('/createSheets', function(req, res, next) {
res.render('createSheets', { title: '创建图纸' });
});
router.get('/case', function(req, res, next) {
res.render('case', { title: '我的项目' });
});
router.get('/fileUpdate', function(req, res, next) {
res.render('fileUpdate', { title: '文件更新提醒' });
});
router.get('/review', function(req, res, next) {
res.render('review', { title: '校审' });
});
router.get('/editReview', function(req, res, next) {
res.render('editReview', { title: '校审意见' });
});
router.get('/submitReview', function(req, res, next) {
res.render('submitReview', { title: '提交校审' });
});
router.get('/submitData', function(req, res, next) {
res.render('submitData', { title: '提资' });
});
router.get('/family', function(req, res, next) {
res.render('family', { title: '族库' });
});
router.get('/cabinet', function(req, res, next) {
res.render('cabinet', { title: '插入电气柜' });
});
router.get('/support', function(req, res, next) {
res.render('support', { title: '布置支吊架' });
});
router.get('/triangleBeam', function(req, res, next) {
res.render('triangleBeam', { title: '三角梁布置' });
});
router.get('/exportDWG', function(req, res, next) {
res.render('exportDWG', { title: '导出DWG' });
});
router.get('/cable', function(req, res, next) {
res.render('cable', { title: '电缆沟' });
});
router.get('/shortCircuit', function(req, res, next) {
res.render('shortCircuit', { title: '短路计算' });
});
router.get('/shortCalc', function(req, res, next) {
res.render('shortCalc', { title: '短路计算' });
});
router.get('/calcResult', function(req, res, next) {
res.render('calcResult', { title: '计算结果' });
});
router.get('/calclightning', function(req, res, next) {
res.render('calclightning', { title: '计算结果' });
});
router.get('/groundCalc', function(req, res, next) {
res.render('groundCalc', { title: '接地计算' });
});
router.get('/groundGrid', function(req, res, next) {
res.render('groundGrid', { title: '接地网布置' });
});
router.get('/doorWindow', function(req, res, next) {
res.render('doorWindow', { title: '布置门窗' });
});
router.get('/pdzz', function(req, res, next) {
res.render('pdzz', { title: '配电装置-安全净距' });
});
router.get('/checkGrid', function(req, res, next) {
res.render('checkGrid', { title: '碰撞检查' });
});
router.get('/conflictExport', function(req, res, next) {
res.render('conflictExport', { title: '碰撞检查' });
});
router.get('/traverseCalc', function(req, res, next) {
res.render('traverseCalc', { title: '导线计算' });
});
router.get('/addrow', function(req, res, next) {
res.render('addrow', { title: '增加数据行' });
});
router.get('/showCrossSection', function(req, res, next) {
res.render('showCrossSection', { title: '截面轮廓' });
});
router.get('/pier', function(req, res, next) {
res.render('pier', { title: '闸墩参数' });
});
router.get('/RoadSet', function(req, res, next) {
res.render('RoadSet', { title: '道路绘制' });
});
router.get('/ErectionWall', function(req, res, next) {
res.render('ErectionWall', { title: '装配式围墙' });
});
router.get('/CableInstallation', function(req, res, next) {
res.render('CableInstallation', { title: '电缆敷设' });
});
router.get('/tab', function(req, res, next) {
res.render('tab', { title: 'tab' });
});
router.get('/exportIn', function(req, res, next) {
res.render('exportIn', { title: '导入文件' });
});
router.get('/tableCell', function(req, res, next) {
res.render('tableCell', { title: '' });
});
module.exports = router;
|
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import axios from 'axios';
import createReducer from './createReducer';
export function configureStore(initialState) {
const store = createStore(
createReducer(),
initialState,
compose(
applyMiddleware(thunk.withExtraArgument({ axios })),
process.env.NODE_ENV === 'development' &&
typeof window === 'object' &&
typeof window.devToolsExtension !== 'undefined'
? window.devToolsExtension()
: f => f
),
);
store.asyncReducers = {};
if (process.env.NODE_ENV === 'development') {
if (module.hot) {
module.hot.accept('./createReducer', () => store.replaceReducer(require('./createReducer').default));
}
}
return store;
}
export function injectAsyncReducer(store, name, asyncReducer) {
store.asyncReducers[name] = asyncReducer;
store.replaceReducer(createReducer(store.asyncReducers));
}
|
module.exports = {
bundle: {
src: 'tmp/ractive-decorators-helpers.js',
dest: 'tmp/ractive-decorators-helpers.min.js'
}
};
|
module.exports = {
"extends": "airbnb",
"env": {
"mocha": true,
"mongo": true,
},
"settings": {
"ecmascript": 6,
"jsx": true,
},
"plugins": [
"react",
],
"rules": {
"no-underscore-dangle": ["error", { "allow": ["_id"] }],
"no-console": 0,
"func-names": ["error", "never"],
"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
}
};
|
/******/ (function(modules) { // webpackBootstrap
/******/ // install a JSONP callback for chunk loading
/******/ var parentJsonpFunction = window["webpackJsonp"];
/******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules) {
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0, callbacks = [];
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(installedChunks[chunkId])
/******/ callbacks.push.apply(callbacks, installedChunks[chunkId]);
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/ for(moduleId in moreModules) {
/******/ modules[moduleId] = moreModules[moduleId];
/******/ }
/******/ if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules);
/******/ while(callbacks.length)
/******/ callbacks.shift().call(null, __webpack_require__);
/******/ };
/******/ // The module cache
/******/ var installedModules = {};
/******/ // object to store loaded and loading chunks
/******/ // "0" means "already loaded"
/******/ // Array means "loading", array contains callbacks
/******/ var installedChunks = {
/******/ 0:0
/******/ };
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = function requireEnsure(chunkId, callback) {
/******/ // "0" is the signal for "already loaded"
/******/ if(installedChunks[chunkId] === 0)
/******/ return callback.call(null, __webpack_require__);
/******/ // an array means "currently loading".
/******/ if(installedChunks[chunkId] !== undefined) {
/******/ installedChunks[chunkId].push(callback);
/******/ } else {
/******/ // start chunk loading
/******/ installedChunks[chunkId] = [callback];
/******/ var head = document.getElementsByTagName('head')[0];
/******/ var script = document.createElement('script');
/******/ script.type = 'text/javascript';
/******/ script.charset = 'utf-8';
/******/ script.async = true;
/******/ script.src = __webpack_require__.p + "" + chunkId + ".chunk.js";
/******/ head.appendChild(script);
/******/ }
/******/ };
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "js/";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
console.log(__webpack_require__(1));
// require("./style.css");
__webpack_require__.e/* nsure */(1, function(require) {
console.log(__webpack_require__(4));
console.log(__webpack_require__(5));
});
console.log(__webpack_require__(2));
console.log(__webpack_require__(2));
console.log(__webpack_require__(2));
console.log(__webpack_require__(3));
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = "It works from content.js.";
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = {
"content": "It works from json file."
};
/***/ },
/* 3 */
/***/ function(module, exports) {
exports.question = 'the answer';
exports.answer = 42;
/***/ }
/******/ ]);
|
import _ from 'lodash';
import React from 'react';
import TodosListHeader from './todos-list-header';
import TodosListItem from './todos-list-item';//Had problems with page loading looked in all files and finally realized with help that it was in import page. We had misspelling line 8.
export default class TodosList extends React.Component { //this is what were calling our component
renderItems() {
return _.map(this.props.todos, (todo, index) => <TodosListItem key={index
} {...todo} />);
///the triple dot is the spread syntax in es6.
}
render () {
return ( //keeps code organzed, putting divs in there
<table>
<TodosListHeader />
<tbody>
{this.renderItems()}
</tbody>
</table>
);
}
}
|
export default (value, [other] = []) => {
return value !== other;
};
|
Template.home.helpers({
});
Template.home.events({
});
|
/**
* Created by Usuario on 28/09/2015.
*/
console.log( __filename );
|
'use strict';
var loginApi = {
baseUrl: baseConfig.apiUrl,
userLogin: 'login/login',
userLogout: 'user/logout',
};
/* Controllers */
// signin controller
app.controller('SigninFormController', ['$scope', '$http', '$state', 'initData','commonService', function($scope, $http, $state ,initData , commonService) {
$scope.user = {};
$scope.authError = null;
$scope.login = function() {
$scope.authError = null;
// Try to login
commonService.httpPost(loginApi.userLogin, {email: $scope.user.email, password: $scope.user.password})
.then(function(response) {
if ( !response.status ) {
$scope.authError = response.msg ? response.msg : 'Email or Password not is wrong!';
}else{
angular.copy(response.user_data, commonService.sync.user_data);
$state.go('app.dashboard');
}
}/*, function(x) {
$scope.authError = 'Server Error';
}*/);
};
}])
;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.