code
stringlengths 2
1.05M
|
|---|
/*
* Copyright (C) 2014 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration. All Rights Reserved.
*/
/**
* @exports LevelRowColumnUrlBuilder
* @version $Id: LevelRowColumnUrlBuilder.js 2643 2015-01-09 20:37:58Z tgaskins $
*/
define([
'../error/ArgumentError',
'../util/Logger',
'../util/WWUtil'
],
function (ArgumentError,
Logger,
WWUtil) {
"use strict";
/**
* Constructs a URL builder for level/row/column tiles.
* @alias LevelRowColumnUrlBuilder
* @constructor
* @classdesc Provides a factory to create URLs for level/row/column tile REST requests.
* <p>
* URLs are formed by appending the specified server address with the specified path and appending
* a path of the form <em>/level/row/row_column.image-format</em>, where image-format is the corresponding
* suffix to the image mime type specified when a URL is requested. For example, if the specified server
* address is <em>http://worldwindserver.net/webworldwind</em> and the specified path-to-data is
* <em>../data/Earth/BMNG256</em>, and the requested tile's level, row and column are 0, 5 and 9 respectively,
* and the image format is <em>image/jpeg</em>, the composed URL is
* <em>http://worldwindserver.net/webworldwind/../data/Earth/BMNG256/0/5/5_9.jpg.
*
* @param {String} serverAddress The server address. May be null, in which case the address is assumed to be
* the current location (see <code>window.location</code>) minus the last path component.
* @param {String} pathToData The path to the dataset on the server. May be null or empty to indicate that
* the data is directly relative to the specified server address.
*
*/
var LevelRowColumnUrlBuilder = function (serverAddress, pathToData) {
/**
* The server address.
* @type {String}
*/
this.serverAddress = serverAddress;
if (!serverAddress || serverAddress.length === 0) {
this.serverAddress = WWUtil.currentUrlSansFilePart();
}
/**
* The server-side path to the dataset.
* @type {String}
*/
this.pathToData = pathToData;
};
/**
* Creates the URL string for a WMS Get Map request.
* @param {Tile} tile The tile for which to create the URL.
* @param {String} imageFormat The image format to request.
* @throws {ArgumentError} If the specified tile or image format are null or undefined.
*/
LevelRowColumnUrlBuilder.prototype.urlForTile = function (tile, imageFormat) {
if (!tile) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "WmsUrlBuilder", "urlForTile", "missingTile"));
}
if (!imageFormat) {
throw new ArgumentError(
Logger.logMessage(Logger.LEVEL_SEVERE, "WmsUrlBuilder", "urlForTile",
"The image format is null or undefined."));
}
var sb = this.serverAddress;
if (this.pathToData) {
sb = sb + "/" + this.pathToData;
}
sb = sb + "/" + tile.level.levelNumber.toString();
sb = sb + "/" + tile.row.toString();
sb = sb + "/" + tile.row.toString() + "_" + tile.column.toString();
sb = sb + "." + WWUtil.suffixForMimeType(imageFormat);
sb = sb.replace(" ", "%20");
return sb;
};
return LevelRowColumnUrlBuilder;
});
|
module.exports = {
entry: './test/unit/specs/index.js',
output: {
path: './test/unit',
filename: 'specs.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /test|node_modules\/dist/,
loader: 'babel-loader'
}
]
}
}
|
define(function(require, exports, module){
'use strict';
var layers = require('cqwrap/layers');
var BaseLayer = layers.BaseLayer, BgLayer = layers.BgLayer;
var BaseScene = cc.Scene.extend({
ctor:function() {
this._super();
this.init.apply(this, arguments);
cc.associateWithNative( this, cc.Scene );
}
});
function loadFrames(cache, frames, callback){
callback(frames);
if(frames.length <= 0){
return;
}
cache.addSpriteFrames(frames[0][0], frames[0][1]);
setTimeout(function(){
loadFrames(cache, frames.slice(1), callback);
}, 100);
}
var LoadingLayer = BaseLayer.extend({
init: function(frameCaches){
this._super();
var self = this;
setTimeout(function(){
var cache = cc.SpriteFrameCache.getInstance();
loadFrames(cache, frameCaches, function(frames){
self.getParent().onProgressChange(1 - frames.length / frameCaches.length);
if(frames.length <= 0){
setTimeout(function(){
self.getParent().onLoaded();
}, 200);
}
});
}, 100);
if(this.setKeypadEnabled){
this.setKeypadEnabled(true);
}
},
backClicked: function(){
this.getParent().backClicked();
}
});
var LoadingScene = BaseScene.extend({
init: function(resFrames){
this._super();
var loadingLayer = new LoadingLayer(resFrames);
this.addChild(loadingLayer);
},
onProgressChange: function(){
//Overload by subclass
},
onLoaded: function(){
//Overload by subclass
},
backClicked: function(){
director.end();
}
});
module.exports = {
BaseScene: BaseScene,
LoadingScene: LoadingScene
};
});
|
'use strict';
var React = require('React');
var createReactClass = require('create-react-class');
var Component = createReactClass({
displayName: 'Component',
render() {
return <div />;
},
});
|
import Ember from 'ember';
import layout from '../templates/container';
import UnlessDestroyedMixin from '../mixins/unless-destroyed';
const { RSVP, Component, Logger:logger } = Ember;
const AsyncActionContainer = Component.extend(UnlessDestroyedMixin, {
layout,
inFlight: false,
result: null,
actions: {
invoke() {
if (!this.attrs.hasOwnProperty('asyncAction')) {
logger.warn('No async-container attribute found for action');
return;
}
this.set('inFlight', true);
this.set('result', null);
return RSVP
.cast(this.attrs.asyncAction(...arguments))
.then(this.unlessDestroyed(function(result) {
this.set('result', result);
return result;
}))
.finally(this.unlessDestroyed(function() {
this.set('inFlight', false);
}));
}
}
});
AsyncActionContainer.reopenClass({
positionalParams: ['asyncAction']
});
export default AsyncActionContainer;
|
/*jslint nomen:true*/
/*global define*/
define([
'backgrid',
'orodatagrid/js/datagrid/formatter/cell-formatter'
], function (Backgrid, CellFormatter) {
'use strict';
var StringCell;
/**
* String column cell. Added missing behaviour.
*
* @export oro/datagrid/cell/string-cell
* @class oro.datagrid.cell.StringCell
* @extends Backgrid.StringCell
*/
StringCell = Backgrid.StringCell.extend({
/**
@property {(Backgrid.CellFormatter|Object|string)}
*/
formatter: new CellFormatter(),
/**
* @inheritDoc
*/
enterEditMode: function (e) {
if (this.column.get("editable")) {
e.stopPropagation();
}
return StringCell.__super__.enterEditMode.apply(this, arguments);
}
});
return StringCell;
});
|
var conectaN_8cpp =
[
[ "main", "conectaN_8cpp.html#ae66f6b31b5ad750f1fe042a706a4e3d4", null ]
];
|
console.log("Hello space !");
|
'use strict';
const
Input = require('./input'),
Level = require('./level'),
StartScreen = require('./start-screen'),
LevelEnding = require('./level-ending'),
GameEnding = require('./game-ending'),
Sound = require('./sound'),
FpsCounter = require('./fps-counter');
const
config = require('./config'),
stats = require('./stats'),
eventBus = require('./event-bus');
Window.meow = () => {
eventBus.fire({ name: 'event.level.end'});
};
class Game {
constructor(stage, renderer) {
this._stage = stage;
this._renderer = renderer;
this._input = new Input();
this._startScreen = new StartScreen(stage, this._input);
this._levelEnding = new LevelEnding(stage, renderer, this._input);
this._gameEnding = new GameEnding(stage);
this._sound = new Sound(this._stage);
this._fpsCounter = new FpsCounter(this._stage, this._input);
this._level = null;
this._levelNumber = 0;
this._mazeOrder = [];
this._lastStep = Date.now();
this._state = 'initialized';
}
start() {
document.body.appendChild(this._renderer.view);
this._input.start();
stats.start();
this._sound.start();
this._fpsCounter.start();
this._fillMazeOrder();
eventBus.register('event.startscreen.end', () => {
this._switchState('level-starting');
});
eventBus.register('event.level.end', () => {
this._switchState('level-ending');
});
eventBus.register('event.level.ending.readyfornext', () => {
this._switchState('level-starting');
});
eventBus.register('event.level.ending.lastlevel', () => {
this._switchState('game-ending');
});
this._switchState('startscreen-active');
}
/**
* Not sure if this will ever be called.
*/
stop() {
this._level.stop();
stats.stop();
this._sound.stop();
this._fpsCounter.stop();
}
draw() {
this._renderer.render(this._stage);
this._fpsCounter.stepRender();
}
step() {
let elapsed = this._calculateElapsed();
switch (this._state) {
case 'initialized':
break;
case 'startscreen-active':
this._startScreen.step(elapsed);
break;
case 'level-starting':
this._level.step(elapsed);
if (this._level.checkForEndLevelCondition()) {
eventBus.fire({ name: 'event.level.end' });
}
break;
case 'level-ending':
this._levelEnding.step(elapsed);
break;
case 'game-ending':
this._gameEnding.step(elapsed);
break;
}
this._sound.step(elapsed);
this._fpsCounter.step(elapsed);
this._resortStageChildren();
}
_fillMazeOrder() {
for (let num = 0; num < config.mazes.length; num++) {
this._mazeOrder.push(num);
}
shuffleArray(this._mazeOrder);
}
_switchState(state) {
this._state = state;
switch (state) {
case 'initialized':
// Do nothing
break;
case 'startscreen-active':
this._startScreen.start();
break;
case 'level-starting':
// TODO: Determine if that was the final level
let currentLevel = this._level;
if (currentLevel !== null && currentLevel !== undefined) {
this._levelNumber = currentLevel.number + 1;
} else {
this._levelNumber = 0;
}
this._level = new Level(
this._levelNumber,
this._input,
this._stage,
this._levelEnding,
this._mazeOrder[this._levelNumber]
);
this._level.start();
break;
case 'level-ending':
this._levelEnding.start(this._levelNumber);
this._level.stop();
break;
case 'game-ending':
this._gameEnding.start();
break;
}
}
_calculateElapsed() {
let elapsed = Date.now() - this._lastStep;
if (elapsed > 1000) {
elapsed = 1000; // enforce speed limit
}
this._lastStep = Date.now();
return elapsed;
}
/**
* Re-sort the stage children to their z-order, if any.
* @private
*/
_resortStageChildren() {
this._stage.children.sort((a, b) => {
if (a.z === undefined || a.z === null) {
return -1;
} else if (b.z === undefined || b.z === null) {
return 1;
} else {
return b.z - a.z;
}
});
}
}
module.exports = Game;
/**
* Fischer-Yates Algorithm
* http://stackoverflow.com/a/6274398/738081
*/
function shuffleArray(arr) {
var counter = arr.length, temp, index;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
temp = arr[counter];
arr[counter] = arr[index];
arr[index] = temp;
}
return arr;
}
|
export { default } from 'ember-fhir/models/encounter-class-history';
|
/*
Generates a deck of cards. You can swap cards between the "main" deck and other decks (which can represent players, dealers etc)
Sebastian Lenton 2013
*/
"use strict";
//globals
var cardValues = [ 'ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king' ];
var suits = [ 'hearts', 'diamonds', 'spades', 'clubs' ];
var deckCardOffset = 2;
function Card( suit, value, index ) {
this.index = index;
this.suit = suit;
this.value = value;
this.flipped = false;
this.getCardString = function( offset ) {
return '<div id="card' + this.index + '" style="top:-' + ( offset * deckCardOffset ) + 'px;" class="card ' + this.suit + '"><p>' + this.value + '</p></div>';
};
this.identify = function() {
return this.suit + ' ' + this.value + ' ' + this.index;
}
}
function Deck( name ) {
this.cards = [];
this.name = name;
this.generate = function() {
var counter = 0;
for( var j = 0; j < suits.length; j++ ) {
for( var i = 0; i < cardValues.length; i++ ) {
this.cards.push( new Card( suits[ j ], cardValues[ i ], counter ) );
//console.log( this.cards[ this.howMany( true ) ].identify() );
}
}
};
this.shuffle = function() {
this.cards = shuffle( this.cards );
};
this.howMany = function( countFromZero ) {
var length = this.cards.length;
if( countFromZero ) {
return length - 1;
} else {
return length;
}
};
this.passCards = function( deck, amount ) { //this could be more efficient
if( !amount ) {
amount = 1;
}
for( var i = 0; i < amount; i++ ) {
var cardToPass = this.cards.pop();
deck.cards.push( cardToPass );
}
}
this.renderAll = function() {
var deckString = '';
for( var j = 0; j < this.cards.length; j++ ) {
deckString += this.cards[ j ].getCardString( j );
}
deckString = '<div id="deck' + this.name + '" class="deck">' + deckString + '</div>';
$( 'body' ).append( deckString );
}
}
var deck = new Deck( 'DefaultDeck' );
var startDeck = new Deck( 'StartDeck' );
var eggDeck = new Deck( 'EggDeck' );
deck.generate();
deck.passCards( eggDeck, 20 );
//deck.passCards( startDeck ); //need to stop too large amounts throwing errors
deck.renderAll();
startDeck.renderAll();
eggDeck.renderAll();
$( '.card' ).click( function() {
console.log( 'clicked;' );
$( this ).toggleClass( 'flipped' );
} )
/*********************
HELPERS
*********************/
function shuffle(array) {
var counter = array.length, temp, index;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
index = (Math.random() * counter--) | 0;
// And swap the last element with it
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
|
/* -----------------------------------------------------------------------------------------------
* BuddyTok Application
* ----------------------------------------------------------------------------------------------*/
/* global jQuery, _, OT, Backbone, log, alert */
/* global LocalUser, BuddyList, InvitationList, UserInfoView, ConnectModalView, BuddyListView */
/* global InvitationListView, ChatView */
// Declare dependencies and prevent leaking into global scope
(function(
exports, doc, // Environment
$, _, OT, Backbone, log, // External libraries
LocalUser, // Application modules
BuddyList,
InvitationList,
UserInfoView,
ConnectModalView,
BuddyListView,
InvitationListView,
ChatView,
undefined
) {
var App = exports.App = {
// Models
presenceSession: null,
me: null,
buddyList: null,
invitationList: null,
// Views
userInfoView: null,
connectModalView: null,
buddyListView: null,
invitationListView: null,
chatView: null,
initialize: function() {
// Presence session initialization
App.once('presenceSessionReady', App.presenceSessionReady, this);
App.retrievePresenceConfig();
// Model initialization
App.me = new LocalUser({}, { dispatcher: App });
App.buddyList = new BuddyList([], { dispatcher: App });
App.invitationList = new InvitationList([], { dispatcher: App });
// View initialization
App.connectModalView = new ConnectModalView({
model: App.me,
el: $('#connect-modal'),
dispatcher: App
});
App.userInfoView = new UserInfoView({ model: App.me });
App.buddyListView = new BuddyListView({
collection: App.buddyList,
dispatcher: App
});
App.invitationListView = new InvitationListView({ collection: App.invitationList });
App.chatView = new ChatView({
dispatcher: App,
localUser: App.me
});
$(doc).ready(App.domReady);
},
retrievePresenceConfig: function() {
$.get('/presence')
.done(function(presenceConfig) {
log.info('App: presenceSessionReady');
App.presenceSession = OT.initSession(presenceConfig.apiKey, presenceConfig.sessionId);
App.trigger('presenceSessionReady', App.presenceSession);
})
.fail(function(jqXHR, responseText, errorThrown) {
log.error('App: presenceSessionReady failed', errorThrown);
alert('Could not retreive the presence configuration. Please try again later');
});
},
domReady: function() {
log.info('App: domReady');
// NOTE: App.connectModalView is already in the DOM and does not need to be rendered
App.connectModalView.show();
App.userInfoView.render().$el.appendTo('.navbar-right');
App.buddyListView.render().$el.appendTo('.sidebar-left');
App.invitationListView.render().$el.appendTo('.row-top');
App.chatView.render().$el.appendTo('.content-right');
},
};
_.extend(App, Backbone.Events);
App.initialize();
}(window, window.document, jQuery, _, OT, Backbone, log, LocalUser, BuddyList, InvitationList,
UserInfoView, ConnectModalView, BuddyListView, InvitationListView, ChatView));
|
'use strict';
/* global angular */
(function() {
var register = angular.module('register');
register.controller('RegisterController', function($rootScope, $scope, $state, sessionFactory) {
$scope.stateName = 'register';
$scope.name = '';
$scope.email = '';
$scope.password = '';
$scope.loading = false;
$scope.registerAndLogin = function() {
if (!$scope.form.$valid) {
return;
}
$scope.loading = false;
var user = { };
user.name = $scope.name;
user.email = $scope.email;
user.password = $scope.password;
sessionFactory.registerAndLogin(user)
.then(function() {
$scope.loading = false;
$state.go('app-root.list');
});
};
});
})();
|
const removeMigratorDir = require('./removeMigratorDir');
module.exports = ({migrator}) => {
return Promise.resolve()
.then(() => migrator.disconnect())
.then(() => removeMigratorDir(migrator))
.then(() => migrator);
};
|
'use strict'
module.exports = function () {
this.When(/^preencher as características do produto$/, {timeout: 60 * 1000}, function (callback) {
})
this.When(/^selecionar alguma categoria$/, {timeout: 60 * 1000}, function (callback) {
})
this.Then(/^devo visualizar o campo de foto do produto$/, {timeout: 60 * 1000}, function (callback) {
})
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:b0478c6949985585d1cbadad447cd75680baa15e4f0fab56943993d2f24afe67
size 4569
|
/*!
Grape JavaScript game engine
(c) 2012-<%= grunt.template.today('yyyy') %> Zoltan Mihalyi.
https://github.com/zoltan-mihalyi/grape/blob/master/MIT-LICENSE.txt
*/
|
/* ==================================================================
AngularJS Datatype Editor - Stock Price
A directive to see and edit a price of a stock in place.
Usage:
<div ade-stock ade-id='1234' adeProvider="yahoo" ade-class="myClass" ng-model="data"></div>
Config:
ade-id:
If this id is set, it will be used in messages broadcast to the app on state changes.
ade-class:
A custom class to give to the input
ade-readonly:
If you don't want the stock ticker to be editable
ade-provider:
By default, stock prices provided by google API. This could be set to yahoo.
Messages:
name: ADE-start
data: id from config
name: ADE-finish
data: {id from config, old value, new value, exit value}
------------------------------------------------------------------*/
angular.module('ADE').directive('adeStock', ['ADE', '$compile', '$filter', '$http',
function(ADE, $compile, $filter, $http) {
return {
require: '?ngModel', //optional dependency for ngModel
restrict: 'A', //Attribute declaration eg: <div ade-url=""></div>
scope: {
adeUrl: "@",
adeId: "@",
adeClass: "@",
adeReadonly: "@",
adeProvider: "@",
adeMovement: "@",
ngModel: "="
},
//The link step (after compile)
link: function(scope, element, attrs) {
var editing = false;
var input = null;
var invisibleInput = null;
var exit = 0; //0=click, 1=tab, -1= shift tab, 2=return, -2=shift return, 3=esc. controls if you exited the field so you can focus the next field if appropriate
var readonly = false;
var inputClass = "";
var stopObserving = null;
var adeId = scope.adeId;
var cache = {};
if(scope.adeClass!==undefined) inputClass = scope.adeClass;
if(scope.adeReadonly!==undefined && scope.adeReadonly=="1") readonly = true;
var makeHTML = function() {
var url, request, html = "";
var value = scope.ngModel;
var cssClasses = "ade-stock-price";
var timestamp = new Date().getTime();
var cache = JSON.parse(localStorage.getItem("adeCache") || "{}");
if (value!==undefined && value!=="") {
if(angular.isArray(value)) value = value[0];
if(value===null || value===undefined) value="";
if(!angular.isString(value)) value = value.toString();
if (scope.adeMovement === "0") {
cssClasses += " ade-stock-price-only";
}
if (scope.adeMovement === "2") {
cssClasses += " ade-stock-popup";
}
element.html("<p class='"+ cssClasses +"'><b>"+ encodeURIComponent(value).toUpperCase() + "</b></p>");
if (cache && cache[value] && cache[value].expires > timestamp) {
handleSuccess(null, cache[value]);
return;
}
if (scope.adeProvider === 'yahoo') {
url = "https://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where " +
"symbol in (\""+ value +"\")&format=json&env=http://datatables.org/alltables.env";
request = $http.get(url);
} else {
url = "http://www.google.com/finance/info?q="+value+"&callback=JSON_CALLBACK";
request = $http.jsonp(url);
}
return( request.then( handleSuccess, handleError ) );
} else {
return element.html("");
}
};
;
var handleError = function(data) {
element.find('.ade-stock-price').append("<span class='ade-stock-no-data'>no price available</span></p>");
};
var handleSuccess = function(resp, cachedPrice) {
var arrowIcon = '<svg xmlns="http://www.w3.org/2000/svg" class="ade-stock-arrow" fill="#000000" ' +
'height="24" viewBox="0 0 24 24" width="24"><path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17' +
'l-5.58-5.59L4 12l8 8 8-8z" class="ade-arrow-down" /><path ' +
'd="M4 12l1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12 l-8-8-8 8z" class="ade-arrow-up"/></svg>';
var adeCache = JSON.parse(localStorage.getItem("adeCache") || "{}");
var $stockEl = element.find(".ade-stock-price"), period = 900000,
change = "", price = "", ticker = "", quote = "";
if (resp) {
if (scope.adeProvider === 'yahoo') {
if (resp.data.query.results === null) {
handleError();
return;
}
quote = resp.data.query.results.quote;
change = quote.Change;
price = quote.LastTradePriceOnly;
ticker = quote.Symbol;
if (price === null) {
handleError();
return;
}
} else {
change = resp.data[0].c;
price = resp.data[0].l_cur;
ticker = resp.data[0].t;
}
//save to localStorage
adeCache[ticker] = {
"expires": new Date().getTime() + period,
"price": price,
"change": change
};
localStorage.setItem("adeCache", JSON.stringify(adeCache));
} else {
//cached data displayed;
price = cachedPrice.price;
change = cachedPrice.change;
}
$stockEl.append(" " + price + '<span class="ade-price-movement">' + arrowIcon +
' <span>$' + change.substring(1) + '</span></span></p>');
if ($stockEl.hasClass("ade-stock-popup")) {
var $movementEl = $stockEl.find(".ade-price-movement");
$movementEl.addClass("ade-popup").addClass("dropdown-menu");
$stockEl.on("mouseenter", function() {
$movementEl.addClass("open");
}).on("mouseleave", function() {
$movementEl.removeClass("open");
});
}
if (change.indexOf("+") !== -1) {
// stock up
element.addClass("ade-stock-up").removeClass("ade-stock-down");
} else if (change.indexOf("-") !== -1) {
element.addClass("ade-stock-down").removeClass("ade-stock-up");
}
};
//called once the edit is done, so we can save the new data and remove edit mode
var saveEdit = function(exited) {
var oldValue = scope.ngModel;
exit = exited;
if (exit !== 3) {
//don't save value on esc
if (input) {
scope.ngModel = input.val();
}
}
element.show();
destroy();
editing = false;
ADE.done(adeId, oldValue, scope.ngModel, exit);
ADE.teardownBlur(input);
ADE.teardownKeys(input);
if(invisibleInput) {
invisibleInput.off('blur.ADE');
ADE.teardownKeys(invisibleInput);
}
};
//place the popup in the proper place on the screen
var place = function() {
ADE.place('.'+ADE.popupClass,element,0,-5);
};
var clickHandler = function(e) {
if (editing) return;
editing = true;
adeId = scope.adeId;
ADE.begin(adeId);
var value = (typeof scope.ngModel === "undefined") ? "" : scope.ngModel;
element.hide();
$compile('<input type="text" class="ade-input '+inputClass+'" value="'+value+'" />')(scope).insertAfter(element);
input = element.next('input');
input.focus();
//put cursor at end
input[0].selectionStart = input[0].selectionEnd = input.val().length;
ADE.setupBlur(input,saveEdit,scope);
ADE.setupKeys(input,saveEdit,false,scope);
};
//setup events
if(!readonly) {
element.on('click.ADE', function(e) {
scope.$apply(function() {
clickHandler(e);
});
});
}
//A callback to observe for changes to the id and save edit
//The model will still be connected, so it is safe, but don't want to cause problems
var observeID = function(value) {
//this gets called even when the value hasn't changed,
//so we need to check for changes ourselves
if(editing && adeId!==value) saveEdit(3);
else if(adeId!==value) ADE.hidePopup(element);
};
//If ID changes during edit, something bad happened. No longer editing the right thing. Cancel
stopObserving = attrs.$observe('adeId', observeID);
var destroy = function() {
ADE.teardownScrollEvents(element);
ADE.hidePopup(element);
ADE.teardownBlur();
if(input) {
input.off();
input.remove();
}
$(document).off('ADE_hidepops.ADE');
};
scope.$on('$destroy', function() { //need to clean up the event watchers when the scope is destroyed
destroy();
if(element) element.off('.ADE');
if(stopObserving && stopObserving!=observeID) { //Angualar <=1.2 returns callback, not deregister fn
stopObserving();
stopObserving = null;
} else {
delete attrs.$$observers['adeId'];
}
});
//need to watch the model for changes
scope.$watch(function(scope) {
return scope.ngModel;
}, function () {
makeHTML();
});
}
};
}]);
|
/*!
* heap.js - example.js
* Author: dead_horse <dead_horse@qq.com>
*/
/**
* Module dependencies.
*/
var heaps = require('./');
var bHeap = heaps.binaryHeap(function (a, b) {
return a.value - b.value;
});
for (var i = 0; i < 10; i++) {
bHeap.push({
value: Math.random()
});
}
var result = [];
while(!bHeap.empty()) {
result.push(bHeap.pop());
}
console.log('%j', result);
|
var pkg = require('../package.json'); //Application Settings
var fs = require('fs');
var db;
var collection; //Twitter Collection
var summaryLength = 2;
var summary = {}; //Tweets by country, total tweets, total smiley face matches
summary.name="World Text";
var countries;
//Heat map coloring
//Provide a range minimum and maximum along with the target value
//Returns a CSS ready RGB value
var rgb = function(heats, value) {
var index = Math.floor(heats.length/9);
var colors = ['rgb(247,244,249)','rgb(231,225,239)','rgb(212,185,218)',
'rgb(201,148,199)','rgb(223,101,176)','rgb(231,41,138)',
'rgb(206,18,86)','rgb(152,0,67)','rgb(103,0,31)'];
if( value < heats[index]){
return colors[0];
}else if ( value <= heats[index*2]){
return colors[1];
}else if ( value <= heats[index*3]){
return colors[2];
}else if ( value <= heats[index*4]){
return colors[3];
}else if ( value <= heats[index*5]){
return colors[4];
}else if ( value <= heats[index*6]){
return colors[5];
}else if ( value <= heats[index*7]){
return colors[6];
}else if ( value <= heats[index*8]){
return colors[7];
}else{
return colors[8];
}
};
var createSummary = function() {
console.log("Starting createSummary");
collection.distinct("properties.country", function(err, docs) {
if (err) {
console.error("Error - distinct countries: " + err.message);
} else {
countries = docs;
summaryLength += (countries.length * 2);
for (var x = 0; x < countries.length; x++) {
countries[x] = countries[x].replace(/\./g,'_');
countrySum(countries[x]);
}
}
wrapIt();
});
};
var countrySum = function(country) {
summary[country] = {};
collection.count({
"properties.country": country
}, {}, function(err, count) {
if (err) {
console.error("Error - summary[" + country + "].total: " + err.message);
} else {
summary[country].total = count;
}
wrapIt();
});
//Regular expression matching for the following smiley faces:
//:) :D :-D ;) :-) :P :p :-P :-p =) ;-) =D =] :] =P :-D ^_^ (^^) (: (8 (;
collection.count({
"properties.country": country,
$or:[
{"properties.text":{$regex:/\:\)/}},
{"properties.text":{$regex:/\:D/}},
{"properties.text":{$regex:/\:\-D/}},
{"properties.text":{$regex:/\(\^\^\)/}},
{"properties.text":{$regex:/\;\)/}},
{"properties.text":{$regex:/\:\-\)/}},
{"properties.text":{$regex:/\:p/}},
{"properties.text":{$regex:/\=\)/}},
{"properties.text":{$regex:/\=D/}},
{"properties.text":{$regex:/\=\]/}},
{"properties.text":{$regex:/\:\]/}},
{"properties.text":{$regex:/\:\-D/}},
{"properties.text":{$regex:/\^\_\^/}},
{"properties.text":{$regex:/\(\:/}},
{"properties.text":{$regex:/\(8/}},
{"properties.text":{$regex:/\(\;/}},
{"properties.text":{$regex:/\:\-P/}},
{"properties.text":{$regex:/\:\-p/}},
{"properties.text":{$regex:/\:p/}},
{'properties.text':/😄|😃|😀|😊|☺|😉|😍|😘|😚|😗|😙|😜|😝|😛|😁|😇|😏|👮|👷|👶|👦|👧|👨|👩|👴|👵|👱|👼|👸|😺|😸|👹|👽|💩/}
]
}, {}, function(err, count) {
if (err) {
console.error("Error - summary[" + country + "].textMatch: " + err.message);
} else {
summary[country].textMatch = count;
}
wrapIt();
});
};
var countryCode = function() {
console.log("Starting countryCode");
var heats = [];
for (var x = 0; x < countries.length; x++) {
summary[countries[x]].percent = summary[countries[x]].textMatch / summary[countries[x]].total;
heats.push(summary[countries[x]].percent);
}
heats.sort(function(a,b){return a-b;});
console.log("Creating HeatMap");
for (var x = 0; x < countries.length; x++) {
if (summary[countries[x]].total) {
summary[countries[x]].heat = rgb(heats, summary[countries[x]].percent);
}
};
wrapIt();
};
var wrapIt = function() {
summaryLength -= 1;
if (summaryLength == 1) {
//DB queries done
countryCode();
} else if (summaryLength == 0) {
console.log('Saving World Text Summary');
db.collection('summary').update({"name": "World Text"}, summary, {upsert: true, w:1, safe:true},function(err) { if(err) { console.error(err.message); } db.close(); });
}
};
var dbLoaded = function(err, database) {
if (err) {
console.error(err.message);
}
db = database;
collection = db.collection('twitter');
console.log("Database Connected");
createSummary();
};
require('mongodb').MongoClient.connect(pkg.config.db_url, dbLoaded);
|
const util = require('../util/httpUtil.js')
function createTask (name, content, creatorId, memberId, progressId, file, ddl) {
return util.httpPost(util.baseURL + 'task', {
name: name,
content: content,
creatorId: creatorId,
memberIds: memberIds,
progressId: progressId,
file: file,
ddl: ddl
})
}
function deleteTask (projectId, taskId, userId) {
return util.httpDel(util.baseURL + 'task', {projectId: projectId, taskId: taskId, userId: userId})
}
function getTaskList (projectId, userId) {
return util.httpGet(util.baseURL + 'task/list?projectId=” + = projectId “&userId=“ + userId')
}
function updateInfo (taskId, executorId, userId) {
return util.httpPut(util.baseURL + 'task/item', {
taskId: taskId,
executorId: executorId,
userId: userId
})
}
function getInfo (projectId, taskId) {
return util.httpGet(util.baseURL + 'task/item?projectId=” + = projectId “&taskId” += taskId')
}
function updateState (taskId, userId) {
return util.httpPut(util.baseURL + 'task/state', {
taskId: taskId,
userId: userId
})
}
function createSubTask (subtaskContent, taskId, userId) {
return util.httpPost(util.baseURL + 'subtask', {
subtaskContent: subtaskContent,
taskId: taskId,
userId: userId
})
}
function deleteSubTask (subtaskId, userId) {
return util.httpDel(util.baseURL + 'subtask', {subtaskId: subtaskId, userId: userId})
}
function getSubtaskList (subtaskId) {
return util.httpGet(util.baseURL + 'subtask/list/?subtaskId=” += subtaskId')
}
function updateSubtaskInfo (subtaskId, subtaskExecutorId) {
return util.httpPut(util.baseURL + 'subtask', {
subtaskId: subtaskId,
subtaskExecutorId: subtaskExecutorId
})
}
function updateSubtaskState (subtaskId, userId) {
return util.httpPut(util.baseURL + 'subtask/state', {
subtaskId: subtaskId,
userId: userId
})
}
function addMember (taskId, participatorIds) {
return util.httpDel(util.baseURL + 'task/participator', {
taskId: taskId,
participatorIds: participatorIds
})
}
function deleteMember (taskId, participatorIds) {
return util.httpDel(util.baseURL + 'task/participator', {
taskId: taskId,
participatorIds: participatorIds
})
}
function getMemberList (taskId) {
return util.httpGet(util.httpGet + 'task/participator/list?taskId=“ + taskId')
}
module.exports = {
createTask,
deleteTask,
getTaskList,
updateInfo,
getInfo,
updateState,
createSubTask,
deleteSubTask,
getSubtaskList,
updateSubtaskInfo,
updateSubtaskState,
addMember,
deleteMember,
getMemberList
}
|
import { h, Component } from 'preact';
import './style.css';
export default class Imprint extends Component {
render() {
return (
<div className="c-imprint b-content">
<h1>Imprint</h1>
<p>
Name
<br />
Address
<br />
Country
<br />
contact@example.com
</p>
</div>
);
}
}
|
var Notify = require('../')
var tape = require('tape')
var pull = require('pull-stream')
tape('simple', function (t) {
var notify = Notify()
var r = Math.random()
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
t.end()
})
)
t.equal(notify(r), r)
notify.end()
})
tape('end', function (t) {
var notify = Notify()
var r = Math.random()
var n = 3
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
if (--n) return
t.end()
})
)
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
if (--n) return
t.end()
})
)
pull(
notify.listen(),
pull.drain(function (data) {
t.equal(data, r)
}, function () {
if (--n) return
t.end()
})
)
t.equal(notify(r), r)
notify.end()
})
|
/*!
* wyre: the new way to do websockets
* Copyright(c) 2015 Jordan S Davidson <thatoneemail@gmail.com>
* MIT Licensed
*/
var port = 22345;
exports = module.exports = function() {
return port++;
}
|
require('es6-promise').polyfill();
var expect = require('expect.js');
var sinon = require('sinon');
var mockery = require('mockery');
describe('Incident controller: GET', function () {
var incident = require('./incidents');
it('has GET handler', function () {
expect(typeof(incident.GET)).equal('function');
});
it('resonds to /', function () {
var req = res = {};
res.send = sinon.spy();
incident.GET(req, res);
expect(res.send.calledOnce).to.equal(true);
});
});
describe('Incident controller: POST', function () {
var incidents;
before(function() {
mockery.registerMock('../models/incident', function () {
var model = function () {};
model.prototype = {
save: function () {
console.warn('Should be overriden with sinon.stub');
throw new Error('Not implemented');
}
};
return model;
}());
// mock the error reporter
mockery.enable({
warnOnReplace: false,
warnOnUnregistered: false,
useCleanCache: true
});
incidents = require('./incidents');
});
afterEach(function () {
// var Incident = require('../models/incident');
// Incident.prototype.save.restore();
});
after(function() {
// disable mock after tests complete
mockery.disable();
});
it('has POST handler', function () {
expect(typeof(incidents.POST)).equal('function');
});
it('creates new incident properly', function (done) {
// Why it's called unittest?
// Because we know all about the internal implementation of the unit.
var Incident = require('../models/incident');
var mockedIncident = {
__v: 0,
_id: 'abc123',
type: 'accident',
location: {
latlng: [1,2],
spec: {
placeid: '123',
administrative_area_level_1: 'Ho Chi Minh City',
country: 'Vietnam'
}
}
};
sinon.stub(Incident.prototype, 'save').returns(Promise.resolve(mockedIncident))
var req = {
body: {
type: 'accident',
location: {
latlng: [1,2],
spec: {
placeid: '123',
administrative_area_level_1: 'Ho Chi Minh City',
country: 'Vietnam'
}
}
}
};
var res = {};
res.send = sinon.spy();
// Perform the tested action
incidents.POST(req, res);
process.nextTick(function() {
expect(Incident.prototype.save.calledOnce).to.equal(true);
// TODO Fix the assertion
expect(res.send.calledOnce).to.equal(true);
Incident.prototype.save.restore();
done();
});
});
it('generates error for improper incident data: No JSON body', function (done) {
// Why it's called unittest?
// Because we know all about the internal implementation of the unit.
var Incident = require('../models/incident');
sinon.stub(Incident.prototype, 'save').returns(Promise.reject({ message: 'Invalid data' }));
var req = {
body: null
};
var send = sinon.spy();
var status = sinon.stub().returns({ send: send }) ;
var res = {
status: status
};
// Perform the tested action
incidents.POST(req, res);
process.nextTick(function() {
expect(Incident.prototype.save.callCount).to.equal(0);
// TODO Fix the assertion
expect(status.calledWith(400)).to.equal(true);
expect(send.calledWith('Invalid data')).to.equal(true);
Incident.prototype.save.restore();
done();
});
});
it('generates error for improper incident data: No type', function (done) {
// Why it's called unittest?
// Because we know all about the internal implementation of the unit.
var Incident = require('../models/incident');
sinon.stub(Incident.prototype, 'save').returns(Promise.reject({ message: 'Invalid data' }));
var req = {
body: {
location: {
latlng: [1,2],
spec: {
placeid: '123',
administrative_area_level_1: 'Ho Chi Minh City',
country: 'Vietnam'
}
}
}
};
var send = sinon.spy();
var status = sinon.stub().returns({ send: send }) ;
var res = {
status: status
};
// Perform the tested action
incidents.POST(req, res);
process.nextTick(function() {
expect(Incident.prototype.save.callCount).to.equal(0);
// TODO Fix the assertion
expect(status.calledWith(400)).to.equal(true);
expect(send.calledWith('Invalid data')).to.equal(true);
Incident.prototype.save.restore();
done();
});
});
it('generates error for improper incident data: No latlng', function (done) {
// Why it's called unittest?
// Because we know all about the internal implementation of the unit.
var Incident = require('../models/incident');
sinon.stub(Incident.prototype, 'save').returns(Promise.reject({ message: 'Invalid data' }));
var req = {
body: {
type: 'accident',
location: {
spec: {
placeid: '123',
administrative_area_level_1: 'Ho Chi Minh City',
country: 'Vietnam'
}
}
}
};
var send = sinon.spy();
var status = sinon.stub().returns({ send: send }) ;
var res = {
status: status
};
// Perform the tested action
incidents.POST(req, res);
process.nextTick(function() {
expect(Incident.prototype.save.callCount).to.equal(0);
// TODO Fix the assertion
expect(status.calledWith(400)).to.equal(true);
expect(send.calledWith('Invalid data')).to.equal(true);
Incident.prototype.save.restore();
done();
});
});
it('generates error for improper incident data: No location', function (done) {
// Why it's called unittest?
// Because we know all about the internal implementation of the unit.
var Incident = require('../models/incident');
sinon.stub(Incident.prototype, 'save').returns(Promise.reject({ message: 'Invalid data' }));
var req = {
body: {
type: 'accident'
}
};
var send = sinon.spy();
var status = sinon.stub().returns({ send: send }) ;
var res = {
status: status
};
// Perform the tested action
incidents.POST(req, res);
process.nextTick(function() {
expect(Incident.prototype.save.callCount).to.equal(0);
// TODO Fix the assertion
expect(status.calledWith(400)).to.equal(true);
expect(send.calledWith('Invalid data')).to.equal(true);
Incident.prototype.save.restore();
done();
});
});
});
|
import { createReducer } from '../utils/misc';
import {
CHAT_MESSAGES_SUCCESS,
CHAT_MESSAGES_FAILURE,
CHAT_MESSAGES_REQUEST,
FRIEND_LIST_SUCCESS,
FRIEND_LIST_FAILURE,
FRIEND_LIST_REQUEST,
FRIEND_HISTORY_REQUEST,
FRIEND_HISTORY_SUCCESS,
FRIEND_HISTORY_FAILURE,
ADD_FRIEND_SUCCESS,
ADD_FRIEND_FAILURE,
ADD_FRIEND_REQUEST,
NEW_CHAT_CHANNEL,
ADD_MESSAGE,
SET_IS_PARTY,
PARTY_LIST_SUCCESS,
PARTY_LIST_FAILURE,
PARTY_LIST_REQUEST,
PARTY_HISTORY_REQUEST,
PARTY_HISTORY_SUCCESS,
PARTY_HISTORY_FAILURE,
ADD_PARTY_SUCCESS,
ADD_PARTY_FAILURE,
ADD_PARTY_REQUEST,
} from '../constants/index';
const initialState = {
party_name: 'Lobby',
party_id: -1,
receiver: null,
friendlist: [],
friendListStatusText: null,
friendHistoryStatusText: null,
messages: [],
allMessages: {},
messagesStatusText: null,
addFriendStatusText: null,
isParty: true,
partylist: [],
partyListStatusText: null,
addPartyStatusText: null,
};
export default createReducer(initialState, {
[CHAT_MESSAGES_REQUEST]: (state) =>
Object.assign({}, state, {
messagesStatusText: null,
}),
[CHAT_MESSAGES_SUCCESS]: (state) => {
console.log('chatmessagesuccess.');
return Object.assign({}, state, {
messagesStatusText: 'messages retreived successfully.',
}); },
[CHAT_MESSAGES_FAILURE]: (state) =>
Object.assign({}, state, {
messagesStatusText: 'error retreiving messages.',
}),
[FRIEND_LIST_REQUEST]: (state) =>
Object.assign({}, state, {
friendListStatusText: null,
}),
[FRIEND_LIST_SUCCESS]: (state, payload) => {
console.log('friendlistsuccess.');
console.dir(payload);
return Object.assign({}, state, {
friendListStatusText: 'friendlist retreived successfully.',
friendlist: payload.data,
}); },
[FRIEND_LIST_FAILURE]: (state) =>
Object.assign({}, state, {
friendListStatusText: 'error retreiving friendlist.',
}),
[FRIEND_HISTORY_REQUEST]: (state) =>
Object.assign({}, state, {
friendHistoryStatusText: null,
}),
[FRIEND_HISTORY_SUCCESS]: (state, payload) => {
if (state.allMessages[payload.party_name].length > 1) { return state; }
console.log('friendhistorysuccess.');
console.dir(payload);
const newstate = Object.assign({}, state, {
allMessages: Object.assign({}, state.allMessages, { [payload.party_name]: state.allMessages[payload.party_name].slice().concat(payload.messages) }),
messages: state.allMessages[payload.party_name].slice().concat(payload.messages),
friendHistoryStatusText: 'friend history retreived successfully.',
});
return newstate;
},
[FRIEND_HISTORY_FAILURE]: (state) =>
Object.assign({}, state, {
friendHistoryStatusText: 'error retreiving friend history.',
}),
[NEW_CHAT_CHANNEL]: (state, payload) => {
console.log('In NEW_CHAT_CHANNEL reducer');
console.dir(payload);
const updatedAllMessages = Object.assign({}, ({ [payload.party_name]: [] }), state.allMessages);
console.log('allmessages: ');
console.dir(updatedAllMessages);
const updatedMessages = updatedAllMessages[payload.party_name].slice();
console.log('messages: ');
console.dir(updatedMessages);
const newstate = Object.assign({}, state, {
party_name: payload.party_name,
party_id: payload.party_id,
allMessages: updatedAllMessages,
messages: updatedMessages,
messagesStatusText: null,
});
// console.log('----__------__');
// console.dir(newstate);
return newstate;
},
[ADD_MESSAGE]: (state, payload) => {
console.log('In ADD_MESSAGE reducer');
console.dir(payload);
return Object.assign({}, state, {
allMessages: Object.assign({}, state.allMessages, { [payload.party_name]: state.allMessages[payload.party_name].slice().concat([payload.message]) }),
messages: state.allMessages[payload.party_name].slice().concat([payload.message]),
messagesStatusText: null,
}); },
[ADD_FRIEND_REQUEST]: (state) =>
Object.assign({}, state, {
addFriendStatusText: null,
}),
[ADD_FRIEND_SUCCESS]: (state) => {
console.log('addfriend success.');
return Object.assign({}, state, {
addFriendStatusText: 'addFriend done successfully.',
}); },
[ADD_FRIEND_FAILURE]: (state) =>
Object.assign({}, state, {
addFriendStatusText: 'error adding a friend.',
}),
[SET_IS_PARTY]: (state, payload) =>
Object.assign({}, state, {
isParty: payload.isParty,
receiver: payload.receiver,
}),
[PARTY_LIST_REQUEST]: (state) =>
Object.assign({}, state, {
partyListStatusText: null,
}),
[PARTY_LIST_SUCCESS]: (state, payload) => {
console.log('partylistsuccess.');
console.dir(payload);
return Object.assign({}, state, {
partyListStatusText: 'partylist retreived successfully.',
partylist: payload.data,
}); },
[PARTY_LIST_FAILURE]: (state) =>
Object.assign({}, state, {
partyListStatusText: 'error retreiving partylist.',
}),
[PARTY_HISTORY_REQUEST]: (state) =>
Object.assign({}, state, {
partyHistoryStatusText: null,
}),
[PARTY_HISTORY_SUCCESS]: (state, payload) => {
if (state.allMessages[payload.party_name].length > 1) { return state; }
console.log('partyhistorysuccess.');
console.dir(payload);
const newstate = Object.assign({}, state, {
allMessages: Object.assign({}, state.allMessages, { [payload.party_name]: state.allMessages[payload.party_name].slice().concat(payload.messages) }),
messages: state.allMessages[payload.party_name].slice().concat(payload.messages),
partyHistoryStatusText: 'party history retreived successfully.',
});
return newstate;
},
[PARTY_HISTORY_FAILURE]: (state) =>
Object.assign({}, state, {
partyHistoryStatusText: 'error retreiving party history.',
}),
[ADD_PARTY_REQUEST]: (state) =>
Object.assign({}, state, {
addPartyStatusText: null,
}),
[ADD_PARTY_SUCCESS]: (state) => {
console.log('addparty success.');
return Object.assign({}, state, {
addPartyStatusText: 'addParty done successfully.',
}); },
[ADD_PARTY_FAILURE]: (state) =>
Object.assign({}, state, {
addPartyStatusText: 'error adding a party.',
}),
});
|
$(document).ready(function () {
$(".courses").each(function () {
var courseClass = ['course-blue', 'course-red', 'course-green', 'course-peach', 'course-darck-green', 'course-darck-blue', 'course-purple', 'course-orange'];
var rand = courseClass[Math.floor(Math.random() * courseClass.length)];
$(this).addClass(rand);
});
});
|
export default _normalizeLink;
/**
This method normalizes a link to an "links object". If the passed link is
already an object it's returned without any modifications.
See http://jsonapi.org/format/#document-links for more information.
@method _normalizeLink
@private
@param {String} link
@return {Object|null}
@for DS
*/
function _normalizeLink(link) {
switch (typeof link) {
case 'object':
return link;
case 'string':
return { href: link };
}
return null;
}
|
var Employee = require('../models/Employee');
var Owner = require('../models/User');
var baby = require('babyparse');
var _ = require('lodash');
var async = require('async');
var nodemailer = require('nodemailer');
var passport = require('passport');
var fs = require('fs');
var validator = require('validator');
var Logger = require('le_node');
var logger = new Logger({
token:'4ed0e98c-c21f-42f0-82ee-0031f09ca161'
});
/**
+ * GET /subdomain login
+ * Employees page.
+ */
exports.postSubdomain = function(req, res){
Owner.findOne({subdomainurl: req.body.subdomain}, function(err, domain) {
if (err) {
// Send logs to logentries
logger.log(4,"Find subDomain Error:" + domain);
console.log("ERROR find subDomain: " + domain);
res.redirect('/subdomain_login');
}
if(domain) {
// Send logs to logentries
logger.log(2,"Find subDomain Success:" + domain);
console.log("success: " + domain);
req.flash('success', { msg: 'Success! You are logged in.' });
res.redirect('/login_employee');
}
else {
res.render('subdomain_login', { msg: 'Cannot Find Your Company' });
}
});
};
/**
* GET /add_employees
* Employees page.
*/
exports.getEmployees = function(req, res){
Employee.find({_admin_id: req.user.id/*, name: "Jane Doe"*/}, function (err, employees) {
//console.log(employee);
// Send logs to logentries
logger.log(2,"Find Employee Success:" + employees);
res.render('add_employees',{title: 'Add Employees', employees: employees, layout: 'navigation_admin'});
});
};
/**
* POST /add_employees
* Add an employee using form.
*/
exports.addEmployee = function(req, res) {
var name = req.body.name;
var number = req.body.number;
var email = req.body.email;
var password = generateRandomString();
var company_id = req.user.id;
var subdomainurl = req.user.subdomainurl;
req.assert('email', 'Email is not valid').isEmail();
//req.assert('number', 'Phone number is invalid').isMobilePhone('en-US'); // not a good validator
Employee.create({
name: name,
phone_number: number,
email: email,
password: password,
subdomainurl: subdomainurl,
_admin_id: company_id
}, function (err, employee) {
if (err) {
// Send logs to logentries
logger.log(4,"Create employee failed: "+err);
console.log("ERROR creating employee: ");
console.log(err);
//TODO - display error message
res.redirect('add_employees');
//res.send("There was a problem adding the employee to the databaase");
} else {
// Send logs to logentries
logger.log(2,"Create employee Success: "+err);
//console.log('Creating new employee: ' + employee);
res.redirect('add_employees');
emailEmployee(employee, req.user, password);
}
});
};
exports.addEmployeesThroughCSV = function(req, res) {
var content = fs.readFileSync(req.file.path, { encoding: 'binary' });
var parsed = baby.parse(content);
var rows = parsed.data;
var admin_id = req.user.id;
for(var i = 0; i < rows.length; i++){
var name = rows[i][0].trim();
var phone = rows[i][1].trim();
var email = rows[i][2].trim();
if (!validator.isEmail(email)) {
console.log("Employee #" + i + " " + name + " does not have a valid email: " + email + ".")
} else {
(function(password) { //anonymous function to enforce password is not outside closure
Employee.create({
name: name,
phone_number: phone,
email: email,
password: password,
_admin_id: admin_id
}, function (err, employee) {
if (err) {
console.log("ERROR creating employee");
console.log(err);
//res.send("There was a problem adding the employee to the database");
} else {
//emailEmployee(employee, req.user, password);
}
}
);
})(generateRandomString());
}
}
res.redirect('/add_employees');
};
exports.selectEmployee = function(req, res) {
Employee.findById(req.id, function(err, employee) {
if (err) {
console.log("ERROR selecting employee: " + employee);
//res.send("There was an error selecting the employee");
} else {
res.render('editEmployee', {title: "Employee: " + employee.name, employee: employee});
}
})
};
exports.editEmployee = function(req, res) {
var name = req.body.name;
var phone = req.body.phone;
var email = req.body.email;
Employee.findById(req.id, function(err, employee) {
if (err) {
console.log("ERROR selecting employee: " + employee);
//res.send("There was an error selecting the employee");
} else {
employee.update({
name: name,
phone_number: phone,
email: email
}, function(err, employee) {
if (err) {
console.log("ERROR updating employee: " + employee);
//res.send("There was an error updating the employee");
} else {
res.redirect("/add_employees");
}
})
}
})
};
exports.emailEmployee = function(req, res) {
var options = {
service: 'gmail',
auth: {
user: 'donotreply.receptional@gmail.com',
pass: 'nightowls1'
}
};
var emailtext = req.body.message;
var transporter = nodemailer.createTransport(options);
// Setup email data
var mailOptions = {
from: req.user.email,
to: req.body.to,
subject: "Receptional",
text: emailtext,
html: emailtext
};
// Send email
transporter.sendMail(mailOptions, function(error, info) {
if(error) {
console.log("Fail sending" + error);
}
else {
console.log('Message sent: ' + info);
console.log(emailtext);
}
});
res.redirect("/add_employees");
};
exports.removeEmployee = function(req, res) {
Employee.findById(req.params.id, function(err, employee) {
if (err) {
console.log("ERROR selecting employee: " + employee);
//res.send("There was an error selecting the employee");
} else {
employee.remove(function (err, employee) {
if (err) {
console.log("ERROR removing employee: " + employee);
//res.send("There was an error removing the employee");
} else {
console.log("Successfully removed " + employee.name);
res.redirect("/add_employees");
}
})
}
})
};
/**
* GET /login
* Login page.
*/
exports.getEmployeeLogin = function(req, res) {
if (req.user) {
return res.redirect('/');
}
var domain = req.headers.host,
subDomain = domain.split('.');
if(subDomain.length > 1) {
subDomain = subDomain[0].split("-").join(" ");
}
res.render('login_employee', {
subdomain: subDomain
});
};
/**
* POST /login
* Sign in using email and password.
*/
exports.postEmployeeLogin = function(req, res, next) {
req.assert('email', 'Email is not valid').isEmail();
req.assert('password', 'Password cannot be blank').notEmpty();
var errors = req.validationErrors();
if (errors) {
console.log(errors);
req.flash('errors', errors);
logger.log(4,"User login Failed:" + errors);
return res.redirect('/login_employee');
}
passport.authenticate('employee', function(err, employee, info) {
console.log(info);
if (err) {
logger.log(4,"User login Failed:" + err);
return next(err);
}
if (!employee) {
console.log(err);
req.flash('errors', { msg: info.message });
logger.log(4,"User login Failed:" + err);
return res.redirect('/login_employee');
}
req.logIn(employee, function(err) {
if (err) {
return next(err);
logger.log(4,"User login Failed:" + err);
}
employee.lastLoginDate = Date.now();
employee.save();
logger.log(2,"User login Success:");
req.flash('success', { msg: 'Success! You are logged in.' });
//res.redirect(req.session.returnTo || '/dashboard_admin');
res.redirect('/dashboard_employee');
});
})(req, res, next);
};
function generateRandomString() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 8; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function emailEmployee(employee, admin, password) {
// Create SMTP transporter object
var options = {
service: 'gmail',
auth: {
user: 'donotreply.receptional@gmail.com',
pass: 'nightowls1'
}
};
var companyname = admin.companyname;
var subdomainurl = admin.subdomainurl;
var emailtext = "Hello " + employee.name + "! Welcome to receptional. You have been added to the company: " + companyname + ". You can access your company receptional website at: " + subdomainurl + ".receptional.xyz. You're password is " + password + ".";
var transporter = nodemailer.createTransport(options);
// Setup email data
var mailOptions = {
from: '"Receptional.xyz" <donotreply.receptional@gmail.com>',
to: employee.email,
subject: "Welcome to Receptional",
text: emailtext,
html: emailtext
};
// Send email
transporter.sendMail(mailOptions, function(error, info) {
if(error) {
console.log(error);
}
else {
console.log('Message sent: ' + info.response);
console.log(emailtext);
}
});
}
/**
* POST /account/password
* Update current password.
*/
exports.postUpdatePassword = function(req, res, next) {
// req.assert('password', 'Password must be at least 4 characters long').len(4);
// req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);
// console.log("get in update password ");
// var errors = req.validationErrors();
// if (errors) {
// console.log("update password failed: " + errors);
// req.flash('errors', errors);
// return res.redirect('/settings');
// }
Employee.findById(req.user.id, function(err, user) {
if (err) {
console.log(" failed: " + err);
return next(err);
}
user.password = req.body.password;
user.save(function(err) {
if (err) {
console.log(" failed: " + err);
return next(err);
}
console.log("success ");
req.flash('success', { msg: 'Password has been changed.' });
res.redirect('/settings');
});
});
};
/**
* POST /account/profile
* Update profile information.
*/
exports.postUpdateProfile = function(req, res, next) {
console.log("update profile");
Employee.findById(req.user.id, function(err, user) {
console.log(req.user.id);
if (err) {
// Send logs to logentries
console.log("Edit profile failed: " + err);
return next(err);
}
user.email = req.body.email || '';
user.name = req.body.name || '';
user.phone_number = req.body.phone || '';
user.picture = req.body.photo || '';
user.save(function(err) {
if (err) {
// Send logs to logentries
console.log("Edit profile failed: " + err);
return next(err);
}
// Send logs to logentries
console.log("Edit profile Success");
req.flash('success', { msg: 'Profile information updated.' });
res.redirect('/settings');
});
});
};
|
import React, { Component, PropTypes } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
export default class Home extends Component {
static propTypes = {
onNavigate: PropTypes.func.isRequired
};
toCounter = () => {
const { onNavigate } = this.props;
onNavigate({
type: 'push',
key: 'counter'
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native Boilerplate!
</Text>
<TouchableOpacity onPress={this.toCounter}>
<Text style={styles.instructions}>Navigate to Counter</Text>
</TouchableOpacity>
</View>
);
}
}
|
// A '.tsx' file enables JSX support in the TypeScript compiler,
// for more information see the following page on the TypeScript wiki:
// https://github.com/Microsoft/TypeScript/wiki/JSX
/// ../typings/es6-promise/es6-promise.d.ts
var Adal = require('./adal.js');
// very important!!! if you put these locally then multiple versions of react get loaded and cause random errors
var React = require('react');
var ReactDOM = require('react-dom');
var Office365_Adal = (function () {
function Office365_Adal() {
}
Office365_Adal.launchWebAuth = function () {
// redirectUri: 'ms-app://S-1-15-2-362237037-3722746685-439561638-2597901564-3613092599-1873846187-518014421'
/* GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
response_type=code&
client_id=32613fc5-e7ac-4894-ac94-fbc39c9f3e4a&
redirect_uri=https:%2f%2foauthplay.azurewebsites.net%2f&
scope=openid+offline_access+https:%2f%2foutlook.office.com%2fmail.read+https:%2f%2foutlook.office.com%2fcalendars.read+https:%2f%2foutlook.office.com%2fcontacts.read&state=f561be3f-e050-4251-bf32-9ae73fc7a6ce&
prompt=login HTTP/1.1
*/
var urlToGo = '';
var displayCallback = function (url) {
urlToGo = url;
};
var config = {
tenant: 'trewin.onmicrosoft.com',
clientId: 'fd79b0e0-38b3-42e7-97fd-2f42d47beb6f',
cacheLocation: 'localStorage',
instance: 'https://login.windows.net/',
resource: 'https://outlook.office365.com',
endpoints: {
'https://outlook.office.com/api/v1.0/me/folders/inbox/messages': 'https://outlook.office.com'
}
};
var authContext = new Adal.inject(config);
// always logout for now
authContext.logOut();
Office365_Adal.getUser(authContext).then(function (token) {
console.log(token);
authContext.acquireToken(config.resource, function (error, token) {
if (error || !token) {
console.log(error);
return;
}
});
});
};
Office365_Adal.getUser = function (authContext) {
var dummyAuthPage = 'default.html';
return new Promise(function (resolve, reject) {
// If the user is cached, resolve the promise immediately.
//var user = authContext.getCachedUser();
//if (user) {
// resolve(user);
// return;
//}
// The user was not cached. Open a popup window which
// performs the OAuth login process, then signals
// the result.
authContext.config.redirectUri = window.location.href;
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
var user = authContext.getCachedUser();
if (user) {
resolve(user);
return;
}
else {
authContext.login();
}
});
};
return Office365_Adal;
})();
module.exports = Office365_Adal;
//// var officeURL = 'https://login.microsoftonline.com/trewin.onmicrosoft.com/oauth2/authorize?response_type=code&client_id=';
////var windowsLoginURL = 'https://login.microsoftonline.com/448cfd31-021b-4a3c-beb9-26d8ba169252/oauth2/v2.0/authorize?response_type=code&client_id=';
//var windowsLoginURL = "https://login.windows.net/Common/oauth2/authorize?response_type=code&client_id=";
//var clientID = 'fd79b0e0-38b3-42e7-97fd-2f42d47beb6f';
//var callbackURL = 'http://localhost:3030/oauth2Callback';
//// var callbackURL = 'ms-app://S-1-15-2-362237037-3722746685-439561638-2597901564-3613092599-1873846187-518014421';
//// var scope = 'https://outlook.office.com/Mail.Read';
//// var resource = "00000002-0000-0000-c000-000000000000";
//var resource = "https://outlook.office365.com";
//# sourceMappingURL=Office365_Adal.js.map
|
export const ic_signal_wifi_0_bar = {"viewBox":"0 0 24 24","children":[{"name":"rect","attribs":{"fill":"none","height":"24","width":"24"},"children":[]},{"name":"path","attribs":{"d":"M12,6L12,6c3.33,0,6.49,1.08,9.08,3.07L12,18.17l-9.08-9.1C5.51,7.08,8.67,6,12,6 M12,4C7.31,4,3.07,5.9,0,8.98L12,21 L24,8.98C20.93,5.9,16.69,4,12,4L12,4z"},"children":[]}]};
|
// API
// ===
module.exports.api = function(server<% if(mongo){ %>, schema<% } %>) {
// Sample Rest Call
server.get('/hello', function(req, res){
res.send('<h1>Hello World!</h1>');
});
}
|
/**
* angular-strap
* @version v2.1.7 - 2015-10-19
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes (olivier@mg-crea.com)
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
"use strict";angular.module("mgcrea.ngStrap.alert").run(["$templateCache",function(t){t.put("alert/alert.tpl.html",'<div class="alert" ng-class="[type ? \'alert-\' + type : null]"><button type="button" class="close" ng-if="dismissable" ng-click="$hide()">×</button> <strong ng-bind="title"></strong> <span ng-bind-html="content"></span></div>')}]);
|
module.exports = {
dir: ""
}
|
const td = require("testdouble");
const proxyquire = require("proxyquire");
const expect = require("chai").expect;
describe("configurationRepository.spec.js", () => {
const cwd = "/home/pawel/workspace/logweb";
const configurationData = {any: "configuration value"};
let configurationRepository;
let fsMock;
let processCwdMock;
let argvSliceMock;
beforeEach(() => {
fsMock = {
readFileSync: td.function(),
writeFile: td.function(),
"@noCallThru": true
};
processCwdMock = td.replace(process, "cwd");
argvSliceMock = td.replace(process.argv, "slice");
td.when(processCwdMock()).thenReturn(cwd);
configurationRepository = proxyquire("./configurationRepository", {fs: fsMock});
});
afterEach(() => {
td.reset();
});
describe("argv configuration", () => {
const configFile = "config/custom-config.json";
beforeEach(() => {
td.when(argvSliceMock(2)).thenReturn([configFile]);
});
it("should load configuration from command argv", () => {
// given
td.when(fsMock.readFileSync(`${cwd}/${configFile}`, "utf8")).thenReturn(JSON.stringify(configurationData));
// expect
expect(configurationRepository.loadConfiguration()).to.eql(configurationData);
});
it("should save configuration file to argv parameter", done => {
// given
td.when(
fsMock.writeFile(
`${cwd}/${configFile}`,
JSON.stringify(configurationData, null, 2),
"utf8"),
{ignoreExtraArgs: true}
).thenCallback(null);
// when
configurationRepository
.saveConfiguration(configurationData)
.then(() => done());
});
});
describe("default configuration location", () => {
beforeEach(() => {
td.when(argvSliceMock(2)).thenReturn([]);
});
it("should load configuration from file named logweb.json in current working directory", () => {
// given
td.when(fsMock.readFileSync(`${cwd}/logweb.json`, "utf8")).thenReturn(JSON.stringify(configurationData));
// expect
expect(configurationRepository.loadConfiguration()).to.eql(configurationData);
});
it("should save configuration to file named logweb.json in current working directory", done => {
// given
td.when(
fsMock.writeFile(
`${cwd}/logweb.json`,
JSON.stringify(configurationData, null, 2),
"utf8"),
{ignoreExtraArgs: true}
).thenCallback(null);
// when
configurationRepository
.saveConfiguration(configurationData)
.then(() => done());
});
});
});
|
/**
* Backbone Application File
* @internal Obviously, I've dumped all the code into one file. This should probably be broken out into multiple
* files and then concatenated and minified but as it's an example, it's all one lumpy file.
* @package $.CpDialog.dialog
*/
/**
* @type {Object} JavaScript namespace for our application.
*/
(function($){
$.CpDialog = {
dialog: {}
};
/**
* Primary Modal Application Class
*/
$.CpDialog.dialog.View = Backbone.View.extend({
id: "cppress_dialog",
events: {
"click .cppress_dialog-close": "close",
"click #btn-cancel": "close",
"click #btn-ok": "save",
"click .navigation-bar a": "doNothing"
},
/**
* Simple object to store any UI elements we need to use over the life of the application.
*/
ui: {
nav: undefined,
content: undefined
},
/**
* Container to store our compiled templates. Not strictly necessary in such a simple example
* but might be useful in a larger one.
*/
coreTemplates: {},
content: null,
button: null,
sidebar: null,
menu: false,
title: 'CpPress dialog',
/**
* Instantiates the Template object and triggers load.
*/
initialize: function () {
"use strict";
_.bindAll( this, 'render', 'close', 'save', 'doNothing' );
this.initialize_templates();
},
/**
* Creates compiled implementations of the templates. These compiled versions are created using
* the wp.template class supplied by WordPress in 'wp-util'. Each template name maps to the ID of a
* script tag ( without the 'tmpl-' namespace ) created in template-data.php.
*/
initialize_templates: function () {
this.coreTemplates.window = wp.template( "cppress-dialog-window" );
this.coreTemplates.backdrop = wp.template( "cppress-dialog-backdrop" );
this.coreTemplates.menuItem = wp.template( "cppress-dialog-menu-item" );
this.coreTemplates.menuItemSeperator = wp.template( "cppress-dialog-menu-item-separator" );
},
/**
* Assembles the UI from loaded templates.
* @internal Obviously, if the templates fail to load, our modal never launches.
*/
render: function () {
"use strict";
// Build the base window and backdrop, attaching them to the $el.
// Setting the tab index allows us to capture focus and redirect it in Application.preserveFocus
},
renderWindow: function(args){
args || (args = {});
// Build the base window and backdrop, attaching them to the $el.
// Setting the tab index allows us to capture focus and redirect it in Application.preserveFocus
this.$el.attr( 'tabindex', '0' );
this.$el.append( this.coreTemplates.backdrop());
this.$el.append( this.coreTemplates.window({
title: this.title,
button: this.button()
})).hide().fadeIn();
this.ui.content = this.$( '.cppress_dialog-main article div.cp-panel-dialog' )
.append( this.content(args) );
this.trigger('content-loaded');
},
getFormValues: function(formSelector){
if(typeof formSelector === "undefined"){
formSelector = '.cp-form';
}
var $form = this.$(formSelector);
var data = {}, parts;
$form.find('[name]').each(function(){
var $$ = $(this);
var name = /([A-Za-z0-9_]+)\[(.*)\]/.exec( $$.attr('name') );
if(name === undefined){
return true;
}
if(name === null){
return true;
}
if($$.is(':disabled')){
return true;
}
// Create an array with the parts of the name
if(typeof name[2] === 'undefined'){
parts = $$.attr('name');
}else{
parts = name[2].split('][');
parts.unshift( name[1] );
}
parts = parts.map(function(e){
if( !isNaN(parseFloat(e)) && isFinite(e) ) {
return parseInt(e);
}else{
return e;
}
});
var sub = data;
var fieldValue = null;
var fieldType = ( typeof $$.attr('type') === 'string' ? $$.attr('type').toLowerCase() : false );
// First we need to get the value from the field
if( fieldType === 'checkbox' ){
if ( $$.is(':checked') ) {
fieldValue = $$.val() !== '' ? $$.val() : true;
} else {
fieldValue = null;
}
} else if( fieldType === 'radio' ){
if ( $$.is(':checked') ) {
fieldValue = $$.val();
} else {
//skip over unchecked radios
return;
}
} else if( $$.prop('tagName') === 'TEXTAREA' && $$.hasClass('wp-editor-area') ){
// This is a TinyMCE editor, so we'll use the tinyMCE object to get the content
var editor = null;
if ( typeof tinyMCE !== 'undefined' ) {
editor = tinyMCE.get( $$.attr('id') );
}
if( editor !== null && typeof( editor.getContent ) === "function" && !editor.isHidden() ) {
fieldValue = editor.getContent();
} else {
fieldValue = $$.val();
}
} else if ( $$.prop('tagName') === 'SELECT' ) {
var selected = $$.find('option:selected');
if( selected.length === 1 ) {
fieldValue = $$.find('option:selected').val();
}else if( selected.length > 1 ) {
// This is a mutli-select field
fieldValue = _.map( $$.find('option:selected'), function(n ,i){
return $(n).val();
});
}
}else{
// This is a fallback that will work for most fields
fieldValue = $$.val();
}
// Now, we need to filter this value if necessary
if( typeof $$.data('filter') !== 'undefined' ) {
switch( $$.data('filter') ) {
case 'json_parse':
// Attempt to parse the JSON value of this field
try {
fieldValue = JSON.parse( fieldValue );
}catch(err) {
fieldValue = '';
}
break;
}
}
// Now convert this into an array
if(fieldValue !== null) {
for (var i = 0; i < parts.length; i++) {
if (i === parts.length - 1) {
if( parts[i] === '' ) {
// This needs to be an array
sub.push(fieldValue);
}else {
sub[parts[i]] = fieldValue;
}
}else {
if (typeof sub[parts[i]] === 'undefined') {
if ( parts[i+1] === '' ) {
sub[parts[i]] = [];
}else {
sub[parts[i]] = {};
}
}
sub = sub[parts[i]];
}
}
}
});
return data;
},
/**
* Closes the modal and cleans up after the instance.
* @param e {object} A jQuery-normalized event object.
*/
close: function ( e ) {
"use strict";
e.preventDefault();
this.undelegateEvents();
$( document ).off( "focusin" );
$( "body" ).css( {"overflow": "auto"} );
this.remove();
this.trigger('dialog-close');
},
/**
* Responds to the btn-ok.click event
* @param e {object} A jQuery-normalized event object.
* @todo You should make this your own.
*/
save: function ( e ) {
"use strict";
this.closeModal( e );
},
/**
* Ensures that events do nothing.
* @param e {object} A jQuery-normalized event object.
* @todo You should probably delete this and add your own handlers.
*/
doNothing: function ( e ) {
"use strict";
e.preventDefault();
}
} );
}(jQuery));
|
EmberApp.ModalDialogComponent = Ember.Component.extend({
actions: {
close: function() {
return this.sendAction('close');
},
save: function(){
return this.sendAction('close', 'save');
}
}
});
|
{
String.fromCodePoint(Infinity);
}
|
'use strict';
function f1(a, b) {
console.log('f1(' + a + ', ' + b + ')');
}
f1(2, 3);
f1.call(null, 2, 3);
f1(...[2, 3]);
f1.apply(null, [2, 3]);
|
var Intersection;
(function (Intersection) {
class Result {
constructor(success, distance, point) {
this.success = success;
this.distance = distance;
this.point = point;
}
}
Result.FAILED = new Result(false, 1000000);
Intersection.Result = Result;
class Point {
constructor(hp, normal, material, object) {
this.hp = hp;
this.normal = normal;
this.material = material;
this.object = object;
}
}
Intersection.Point = Point;
})(Intersection = exports.Intersection || (exports.Intersection = {}));
//# sourceMappingURL=scene-object.js.map
|
var
fs = require("fs"),
path = require("path"),
url = require("url"),
images = require("images"),
ab_getPath = require("./abc-util-getPath").getPath,
ab_extend = require("./abc-util-extend").extend,
ab_checkMime = require("./abc-util-checkMime").checkMime,
ab_getType = require("./abc-util-getType").getType,
ab_model = require("./abc-opt"),
ab_optOptions = ab_model.opt_options,
ab_optTask = ab_model.opt_task,
ab_optPreOpt = ab_model.opt_preOpt;
var
preOpt2IdPreOpt;
/**
* 修改预处理参数("{$now}" -> "{xxx@$now}")修改
* 如果不存在于 ab_optPreOpt 中,则不作处理
*
* @param {string} srcStr : [] 源字符串
* @param {string|number} idname : [] id 名
*
* @return {string} : [] 处理完的字符串
*/
exports.preOpt2IdPreOpt = preOpt2IdPreOpt = function(srcStr, idName) {
return srcStr.replace(/\{\$[^{}]+\}/g, function(str) {
var
__name = str
.replace(/^\{\s*/, '')
.replace(/\s*\}$/, ''),
__isSupport = __name in ab_optPreOpt,
__newStr = __isSupport ? "{" + idName + "@" + __name + "}" : str;
return __newStr;
});
};
/**
* 生成单个完整的任务对象
*
* @param {object} taskOpt : [] 从文本转换成的基本对象(结构与 ab_optOptions 一致)
* @param {object} baseOpt : [ {} ] 公共参数对象(结构与 ab_optTask 一致)
*
* @return {object} : [] 处理完的 task 参数对象
*/
exports.createTask = function(taskOpt, baseOpt) {
// 退出 -> 参数类型错误
if (ab_getType(taskOpt) !== "object") {
throw "ERROR: createTask: 第一个参数必须为对象(第二个参数选填)<- " + taskOpt;
}
var
_taskOpt = ab_extend({}, ab_optTask, taskOpt),
_baseOpt = baseOpt || {},
_baseOpt = ab_extend({}, ab_optOptions, baseOpt),
_fold = _taskOpt.fold,
_files = [], // 指定文件夹中的文件列表
_re_fName = /[^\/\\]+?$/, // 路径中,最末的文件名
_re_lastSep = /[\\\/]+?$/,
_now = new Date();; // 去除完文件名后的最末的 "/" 或 "\"
var __func_add0;
_func_add0 = function(num) {
return (num < 10 ? "0" : "") + num;
};
// (内部变量)id、时间
_taskOpt._dateRaw
= _now.getTime();
_taskOpt._dateNow
= ""
+ _now.getFullYear()
+ _func_add0(_now.getMonth() + 1)
+ _func_add0(_now.getDate())
+ _func_add0(_now.getHours())
+ _func_add0(_now.getMinutes())
+ _func_add0(_now.getSeconds());
_taskOpt._id
= _taskOpt._dateRaw
+ Math.random()
.toString(16)
.replace(/^0\./, "");
// img 和 css 的路径值中的预处理变量进行处理(如 "{$now}" -> "{nnn:$now}")
_taskOpt.img = preOpt2IdPreOpt(_taskOpt.img, _taskOpt._id);
_taskOpt.css = preOpt2IdPreOpt(_taskOpt.css, _taskOpt._id);
var
_imgUrl = url.parse(_taskOpt.img),
_imgSearch = _imgUrl.search || "",
_cssUrl = url.parse(_taskOpt.css),
_cssSearch = _cssUrl.search || "";
// 解码 search 部分
_taskOpt._imgSearch = decodeURIComponent(_imgSearch);
_taskOpt._cssSearch = decodeURIComponent(_cssSearch);
// 去除 search 部分
_taskOpt.img = _taskOpt.img.replace(/\?[^?]+$/, "");
_taskOpt.css = _taskOpt.css.replace(/\?[^?]+$/, "");
// 提取目录部分
_taskOpt.imgFold = _taskOpt.img.replace(_re_fName, '').replace(_re_lastSep, '');
_taskOpt.cssFold = _taskOpt.css.replace(_re_fName, '').replace(_re_lastSep, '');
// 退出 <- 仅支持 png 或 jpg 输出
if ( !_taskOpt.img.match(/\.(png|jpg)$/i) ) {
throw "WARM: createTask: 仅支持 png 或 jpg 输出 <- " + _taskOpt.img;
}
// 退出 <- 目录不存在
if (ab_getPath(_fold).status !== 1) {
throw "ERROR: createTask: 目录不存在或为外链 <- " + _fold;
}
_files = fs.readdirSync(_fold);
// 退出 <- 指定文件夹不存在图片文件
if (!_files || _files.length === 0) {
throw "ERROR: createTask: 指定文件夹不存在图片文件 <- " + _fold;
}
// 读取图片,并进行相关操作
for (var i = 0, len = _files.length; i < len; i++) {
var __checkVal = _files[i].match(/\.(jpg|png|gif)$/i);
// 不添加到操作列表中 <- 文件后缀不为 jpg/png/gif
if (!__checkVal) {
continue;
}
var __imgPath = path.join(_fold, _files[i]);
// 不添加到操作列表中 <- 文件后缀与其文件 mime 类型不匹配
// (总处理时间增加大约 50ms)
if (!ab_checkMime(__imgPath, __checkVal[0].replace(/^\./, ""))) {
continue;
}
var
__img = images(__imgPath);
__imgW = __img.width(),
__imgH = __img.height(),
__name = _files[i]
.replace(/\.(jpg|png|gif)$/i, ''), // 去掉后缀(.jpg | .png | .gif)的文件名
__cssOptStr = (/#/.test(__name)) ?
__name.replace(/^[^#]*?#/, '') :
'' ,
__cName = __name
.replace(__cssOptStr, '')
.replace(/^\d+[\s]*/g,'')
.replace("#",'')
.replace(/[ ]+/g, '_');
// 不添加到操作列表中 <- 文件名前缀为 #
if (/^#/.test(__name)) {
continue;
}
_taskOpt.filename.push(__name);
_taskOpt.cssname.push(__cName);
_taskOpt.cssOptStr.push(__cssOptStr);
_taskOpt.images.push(__img);
_taskOpt.imagesPath.push(__imgPath);
_taskOpt.widths.push(__imgW);
_taskOpt.heights.push(__imgH);
_taskOpt.maxWidth = (__imgW > _taskOpt.maxWidth) ? __imgW : _taskOpt.maxWidth;
_taskOpt.maxHeight = (__imgH > _taskOpt.maxHeight) ? __imgH : _taskOpt.maxHeight;
_taskOpt.totalWidth += __imgW;
_taskOpt.totalHeight += __imgH;
// 子类操作参数继承基类操作参数
_taskOpt.opt = ab_extend({}, _baseOpt, _taskOpt.opt);
}
return _taskOpt;
};
|
angular.module('ira.gobiernosLocales', ['ira.core']).config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('gobiernosLocales', {
abstract: true,
url: '/gobiernosLocales',
template: '<ui-view/>'
});
}]);
|
version https://git-lfs.github.com/spec/v1
oid sha256:2c3b21c8a49c14ad439fc2110acb23f5c059f92e96b26b09dbe8761d4b912e09
size 21510
|
'use strict';
module.exports = {
id: 0x6E,
type: 'MONEYN',
name: 'MoneyN',
dataLengthLength: 1
};
|
<!-- GLOBAL VARIABLES -->
<!-- TOTAL NUMBER OF JOURNAL ITEMS -->
var totalJournalItems = 0;
<!-- ARRAY OF JOURNAL TYPES FOR FILTER -->
var journalFilterArr = new Array('All','Blood Glucose','Basal Profile','Temp Basal','Bolus','Food','Activity','Events');
<!-- ARRAY OF JOURNAL ITEM TYPES -->
var journalTypeArr = new Array();
$(window).load(function(){
createJournalItemEvent();
<!-- CLICK FILTER ON JOURNAL PAGE -->
$('#journalOverviewFilter').click(function(){
$('#journal').hide(0);
$('#journalFilterList').show(0);
$('.journalFilterSelected').unbind('click');
$('.journalFilterSelected').bind('click',function(){
toggleJournalFilterSelected(this);
});
});
<!-- CLICK BACK ON JOURNAL FILTER PAGE -->
$('#journalFilterBack').click(function(){
$('#journalFilterList').hide(0);
$('#journal').show(0);
});
<!-- CLICK OK ON JOURNAL FILTER PAGE -->
$('#journalFilterOk').click(function(){
$('#journalFilterList').hide(0);
resetJournal();
$('#journal').show(0);
});
<!-- CLICK NEXT ON DOWN ARROW TO GO TO NEXT PAGE OF JOURNAL ITEMS -->
$('#journalItemNavigationNext').click(function(){
if(journalPageIndex < journalPageCount){
journalPageIndex++;
updateJournalNavigation();
var marginTop = (journalPageIndex*294)-294;
$('#journalList').animate({"slide": "show", top:"-"+marginTop+"px"}, 1000);
}
});
<!-- CLICK NEXT ON UP ARROW TO GO TO PREVIOUS PAGE OF JOURNAL ITEMS -->
$('#journalItemNavigationPrev').click(function(){
if(journalPageIndex > 1){
journalPageIndex--;
updateJournalNavigation();
var marginTop = 294 - (journalPageIndex*294);
$('#journalList').animate({"slide": "show", top:""+marginTop+"px"}, 1000);
}
});
<!-- CLICK HIDE ON JOURNAL POPUP -->
$('#journalPopupHide').click(function(){
$('#journalPopup').hide(0);
});
});
<!-- TOGGLE SELECTED JOURNAL ITEMS FOR FILTERING -->
function toggleJournalFilterSelected(butWhichItem){
var journalFilterIndex = (butWhichItem.id).split('-')[1];
selectedJournalFilter = journalFilterArr[journalFilterIndex-1];
$('.journalFilterSelected').removeClass('journalFilterSelectedActive');
$('#journalFilterSelect-'+journalFilterIndex).addClass('journalFilterSelectedActive');
}
<!-- CREATE EVENT JOURNAL ITEM -->
function createJournalItemEvent(){
var journalIndex = totalJournalItems+1;
var journalListItem = '<div class="journalItem" id="journalItem-'+journalIndex+'">';
journalListItem += '<div class="journalTypeIcon"><img src="Images/journal_icon_web.png" /></div>';
journalListItem += '<div class="left">';
journalListItem += '<div class="foodItemName white bold left" id="journalTitle-'+journalIndex+'">Server Update</div>';
journalListItem += '<div class="journalTime med white" id="journalTime-'+journalIndex+'">'+getCurrentTime()+'</div>';
journalListItem += '<div class="journalDate med white" id="journalDate-'+journalIndex+'">'+getTodaysDate()+'</div>';
journalListItem += '</div>';
journalListItem += '<div class="right"><div class="journalInfo" id="journalInfo-'+journalIndex+'"></div>';
journalListItem += '</div>';
$('#journalList').prepend(journalListItem);
totalJournalItems++;
journalTypeArr[journalIndex-1] = 'Events';
$('#journalInfo-'+journalIndex).bind('click',function(){
$('.popupInfo').hide(0);
$('#journalPopupTitle').html(getLanguageString('BackUp_Completed'));
$('#journalPopupDate').html($('#journalTime-'+journalIndex).html() + ' ' + $('#journalDate-'+journalIndex).html());
$('#journalPopup').show(0);
});
}
<!-- CREATE BLOOD GLUCOSE JOURNAL ITEM -->
function createJournalItemBG(amount, note, wellbeing, diet, range){
var journalIndex = totalJournalItems+1;
var journalListItem = '<div class="journalItem" id="journalItem-'+journalIndex+'">';
journalListItem += '<div class="journalTypeIcon"><img src="Images/journal_icon_bg.png" /></div>';
journalListItem += '<div class="left">';
journalListItem += '<div class="foodItemName purple bold left" id="journalTitle-'+journalIndex+'">'+amount+' mmol/l</div>';
journalListItem += '<div class="journalTime med white" id="journalTime-'+journalIndex+'">'+$('#bgResultsTime').html()+'</div>';
journalListItem += '<div class="journalDate med white" id="journalDate-'+journalIndex+'">'+$('#bgResultsDate').html()+'</div>';
journalListItem += '</div>';
journalListItem += '<div class="right"><div class="journalInfo" id="journalInfo-'+journalIndex+'"></div>';
journalListItem += '</div>';
$('#journalList').prepend(journalListItem);
totalJournalItems++;
journalTypeArr[journalIndex-1] = 'Blood Glucose';
$('#journalInfo-'+journalIndex).bind('click',function(){
$('.popupInfo').hide(0);
$('#journalPopupTitle').html(getLanguageString('bloodGlucoseReading'));
$('#journalPopupDate').html($('#journalTime-'+journalIndex).html() + ' ' + $('#journalDate-'+journalIndex).html());
$('#journalBGInfo').show(0);
$('#journalBGAmount').html(amount);
$('#journalBGRange').html(range);
$('#journalBGWellbeing').html(wellbeing);
$('#journalBGDiet').html(diet);
$('#journalBGNote').html(note);
$('#journalPopup').show(0);
});
}
<!-- CREATE BASAL PROFILE JOURNAL ITEM -->
function createJournalItemBasalProfile(name, amount){
var journalIndex = totalJournalItems+1;
var journalListItem = '<div class="journalItem" id="journalItem-'+journalIndex+'">';
journalListItem += '<div class="journalTypeIcon"><img src="Images/journal_icon_basal.png" /></div>';
journalListItem += '<div class="left">';
journalListItem += '<div class="foodItemName blue bold left" id="journalTitle-'+journalIndex+'">'+name+'</div>';
journalListItem += '<div class="journalTime med white" id="journalTime-'+journalIndex+'">'+getCurrentTime()+'</div>';
journalListItem += '<div class="journalDate med white" id="journalDate-'+journalIndex+'">'+getTodaysDate()+'</div>';
journalListItem += '</div>';
journalListItem += '<div class="right"><div class="journalInfo" id="journalInfo-'+journalIndex+'"></div>';
journalListItem += '</div>';
$('#journalList').prepend(journalListItem);
totalJournalItems++;
journalTypeArr[journalIndex-1] = 'Basal Profile';
$('#journalInfo-'+journalIndex).bind('click',function(){
$('.popupInfo').hide(0);
$('#journalPopupTitle').html(getLanguageString('journalbasalProfile'));
$('#journalPopupDate').html($('#journalTime-'+journalIndex).html() + ' ' + $('#journalDate-'+journalIndex).html());
$('#journalBasalInfo').show(0);
$('#journalBasalName').html(name);
$('#journalBasalAmount').html(amount);
$('#journalPopup').show(0);
});
}
<!-- CREATE TEMPORARY BASAL JOURNAL ITEM -->
function createJournalItemTempBasal(duration,adjust){
var journalIndex = totalJournalItems+1;
var journalListItem = '<div class="journalItem" id="journalItem-'+journalIndex+'">';
journalListItem += '<div class="journalTypeIcon"><img src="Images/journal_icon_temp_basal.png" /></div>';
journalListItem += '<div class="left">';
journalListItem += '<div class="foodItemName blue bold left" id="journalTitle-'+journalIndex+'">Temporary Basal</div>';
journalListItem += '<div class="journalTime med white" id="journalTime-'+journalIndex+'">'+getCurrentTime()+'</div>';
journalListItem += '<div class="journalDate med white" id="journalDate-'+journalIndex+'">'+getTodaysDate()+'</div>';
journalListItem += '</div>';
journalListItem += '<div class="right"><div class="journalInfo" id="journalInfo-'+journalIndex+'"></div>';
journalListItem += '</div>';
$('#journalList').prepend(journalListItem);
totalJournalItems++;
journalTypeArr[journalIndex-1] = 'Temp Basal';
$('#journalInfo-'+journalIndex).bind('click',function(){
$('.popupInfo').hide(0);
$('#journalPopupTitle').html(getLanguageString('tab/tempbasal'));
$('#journalPopupDate').html($('#journalTime-'+journalIndex).html() + ' ' + $('#journalDate-'+journalIndex).html());
$('#journalTempBasalInfo').show(0);
$('#journalTempBasalDuration').html(duration);
$('#journalTempBasalAdjust').html(adjust);
$('#journalPopup').show(0);
});
}
<!-- CREATE BOLUS JOURNAL ITEM -->
function createJournalItemBolus(total,type,delivery,foodAmount,bgAmount){
var journalIndex = totalJournalItems+1;
var journalListItem = '<div class="journalItem" id="journalItem-'+journalIndex+'">';
journalListItem += '<div class="journalTypeIcon"><img src="Images/journal_icon_bolus.png" /></div>';
journalListItem += '<div class="left">';
journalListItem += '<div class="foodItemName blue bold left" id="journalTitle-'+journalIndex+'">'+total+'u '+type+'</div>';
journalListItem += '<div class="journalTime med white" id="journalTime-'+journalIndex+'">'+getCurrentTime()+'</div>';
journalListItem += '<div class="journalDate med white" id="journalDate-'+journalIndex+'">'+getTodaysDate()+'</div>';
journalListItem += '</div>';
journalListItem += '<div class="right"><div class="journalInfo" id="journalInfo-'+journalIndex+'"></div>';
journalListItem += '</div>';
$('#journalList').prepend(journalListItem);
totalJournalItems++;
journalTypeArr[journalIndex-1] = 'Bolus';
$('#journalInfo-'+journalIndex).bind('click',function(){
$('.popupInfo').hide(0);
$('#journalPopupTitle').html(getLanguageString('bolusStarted'));
$('#journalPopupDate').html($('#journalTime-'+journalIndex).html() + ' ' + $('#journalDate-'+journalIndex).html());
$('#journalBolusInfo').show(0);
$('#journalBolusTotal').html(''+total+'');
$('#bolusDeliveryType').html(''+type+'');
$('#journalBolusDelivery').html(''+delivery+'');
$('#journalBolusFood').html(''+foodAmount+'');
$('#journalBolusBG').html(''+bgAmount+'');
$('#journalPopup').show(0);
});
}
<!-- CREATE FOOD JOURNAL ITEM -->
function createJournalItemFood(count, total){
var journalIndex = totalJournalItems+1;
var journalListItem = '<div class="journalItem" id="journalItem-'+journalIndex+'">';
journalListItem += '<div class="journalTypeIcon"><img src="Images/journal_icon_food.png" /></div>';
journalListItem += '<div class="left">';
journalListItem += '<div class="foodItemName yellow bold left" id="journalTitle-'+journalIndex+'">'+count + ' Item';
if(count > 1){
journalListItem += 's';
}
journalListItem += ' = '+total+'g</div>';
journalListItem += '<div class="journalTime med white" id="journalTime-'+journalIndex+'">'+getCurrentTime()+'</div>';
journalListItem += '<div class="journalDate med white" id="journalDate-'+journalIndex+'">'+getTodaysDate()+'</div>';
journalListItem += '</div>';
journalListItem += '<div class="right"><div class="journalInfo" id="journalInfo-'+journalIndex+'"></div>';
journalListItem += '</div>';
$('#journalList').prepend(journalListItem);
totalJournalItems++;
journalTypeArr[journalIndex-1] = 'Food';
$('#journalInfo-'+journalIndex).bind('click',function(){
$('.popupInfo').hide(0);
$('#journalPopupTitle').html(getLanguageString('journalfoodLogged'));
$('#journalPopupDate').html($('#journalTime-'+journalIndex).html() + ' ' + $('#journalDate-'+journalIndex).html());
$('#journalFoodInfo').show(0);
$('#journalFoodTotalCarbs').html(total);
$('#journalFoodItems').html(count);
$('#journalPopup').show(0);
});
}
<!-- CREATE ACTIVITY JOURNAL ITEM -->
function createJournalItemActivity(type, duration, score){
var journalIndex = totalJournalItems+1;
var journalListItem = '<div class="journalItem" id="journalItem-'+journalIndex+'">';
journalListItem += '<div class="journalTypeIcon"><img src="Images/journal_icon_activity.png" /></div>';
journalListItem += '<div class="left">';
journalListItem += '<div class="foodItemName orange bold left" id="journalTitle-'+journalIndex+'">'+type+'</div>';
journalListItem += '<div class="journalTime med white" id="journalTime-'+journalIndex+'">'+getCurrentTime()+'</div>';
journalListItem += '<div class="journalDate med white" id="journalDate-'+journalIndex+'">'+getTodaysDate()+'</div>';
journalListItem += '</div>';
journalListItem += '<div class="right"><div class="journalInfo" id="journalInfo-'+journalIndex+'"></div>';
journalListItem += '</div>';
$('#journalList').prepend(journalListItem);
totalJournalItems++;
journalTypeArr[journalIndex-1] = 'Activity';
var durationDisplay = '';
var durationArr = duration.split(":");
var durationHours = durationArr[0];
var durationMins = durationArr[1];
var durationSecs = durationArr[2];
if(durationHours == '00'){
if(durationMins == '00'){
durationDisplay = durationSecs+'sec';
}else{
durationDisplay = durationMins+'min:'+durationSecs+'sec';
}
}else{
durationDisplay = durationHours + 'hr:'+durationMins+'min';
}
$('#journalInfo-'+journalIndex).bind('click',function(){
$('.popupInfo').hide(0);
$('#journalPopupTitle').html(getLanguageString('activityEvent'));
$('#journalPopupDate').html($('#journalTime-'+journalIndex).html() + ' ' + $('#journalDate-'+journalIndex).html());
$('#journalActivityInfo').show(0);
$('#journalActivityType').html(type);
$('#journalActivityDuration').html(durationDisplay);
$('#journalActivityScore').html(score);
$('#journalPopup').show(0);
});
}
<!-- RESET JOURNAL PAGE -->
function resetJournal(){
filterJournal();
journalPageIndex = 1;
$('#journaList').css('top','0px');
updateJournalNavigation();
}
<!-- UPDATE JOURNAL PAGINATION -->
function updateJournalNavigation(){
if(journalPageCount > 1){
//DISPLAY PAGINATION
$('#journalItemNavigation').show(0);
var pageCountStr = '';
var pageIndexStr = '';
if(journalPageIndex < 10){
pageIndexStr = '0'+journalPageIndex;
}else{
pageIndexStr = ''+journalPageIndex;
}
if(journalPageCount < 10){
pageCountStr = '0'+journalPageCount;
}else{
pageCountStr = ''+ journalPageCount;
}
$('#journalItemNavigationPageNo').html(pageIndexStr+'/'+pageCountStr);
}else{
$('#journalItemNavigation').hide(0);
}
}
<!-- FILTER JOURNAL ITEMS -->
function filterJournal(){
var journalFilterIndex;
for(var i = 1; i <= 7; i++){
if($('#journalFilterSelect-'+i).hasClass('journalFilterSelectedActive')){
journalFilterIndex = i-1;
break;
}
}
var journalItemCount = 0;
for(var i = 0; i < journalTypeArr.length; i++){
var journalIndex = i+1;
if(journalTypeArr[i] != null){
if(journalFilterIndex == 0){
//ALL
$('#journalItem-'+journalIndex).show(0);
journalItemCount++;
}else if(journalTypeArr[i] == journalFilterArr[journalFilterIndex]){
$('#journalItem-'+journalIndex).show(0);
journalItemCount++;
}else{
$('#journalItem-'+journalIndex).hide(0);
}
}
}
journalPageCount = Math.ceil(journalItemCount / 5);
}
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.6-4-531-11
description: >
Object.defineProperty will update [[Get]] and [[Set]] attributes
of named accessor property 'P' successfully when [[Configurable]]
attribute is true, 'A' is an Array object (8.12.9 step 11)
includes: [propertyHelper.js]
---*/
var obj = [];
obj.verifySetFunction = "data";
Object.defineProperty(obj, "prop", {
get: function () {
return obj.verifySetFunction;
},
set: function (value) {
obj.verifySetFunction = value;
},
configurable: true
});
obj.verifySetFunction1 = "data1";
var getFunc = function () {
return obj.verifySetFunction1;
};
var setFunc = function (value) {
obj.verifySetFunction1 = value;
};
Object.defineProperty(obj, "prop", {
get: getFunc,
set: setFunc
});
verifyEqualTo(obj, "prop", getFunc());
verifyWritable(obj, "prop", "verifySetFunction1");
verifyNotEnumerable(obj, "prop");
verifyConfigurable(obj, "prop");
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema ({
patchId: {
type: Schema.Types.ObjectId,
ref: 'Patch'
},
sequence: {
type: Array,
required: [true, 'Sequence array required.']
},
tempo: {
type: Number,
default: 120
}
// key: {
// type: String,
// default: 'C'
// }
});
module.exports = mongoose.model('Sequence', schema);
|
"use strict";
//# sourceMappingURL=cli.js.map
|
function scoreS(p1, px, p2, e1, ex, e2) {
var checksum1 = p1 + px + p2;
var checksum2 = e1 + ex + e2;
if (checksum1 > 0 && checksum2 > 0) {
p1 = p1 / checksum1;
px = px / checksum1;
p2 = p2 / checksum1;
e1 = e1 / checksum2;
ex = ex / checksum2;
e2 = e2 / checksum2;
return 100 - 50 * ((e1 - p1) * (e1 - p1) + (ex - px) * (ex - px) + (e2 - p2) * (e2 - p2));
} else return 0;
}
//funzione di score T con ass. prob. (p1,px,p2) e risultato di verità (e1,ex,e2)
function scoreT(p1, px, p2, e1, ex, e2) {
var checksum1 = p1 + px + p2;
var checksum2 = e1 + ex + e2;
if (checksum1 > 0 && checksum2 > 0) {
p1 = p1 / checksum1;
px = px / checksum1;
p2 = p2 / checksum1;
e1 = e1 / checksum2;
ex = ex / checksum2;
e2 = e2 / checksum2;
var v1 = e1 - p1,
v2 = v1 + ex - px;
return 100 - 50 * (v1 * v1 + v2 * v2);
} else return 0;
}
function calcola_classifica_scoreS(array_giocatori, array_risultati) {
var ret = [];
var c, d, iniz_giocatori = 0,
score_non_valido = 0;
var temp = [],
temp2 = [],
tt = 0;
var min_score, lista_score_mancanti = [];
for (var week in array_risultati) {
for (var partita in array_risultati[week]) {
c = 0;
d = 0;
lista_score_mancanti = [];
min_score = 100;
for (var giocatore in array_giocatori) {
if (iniz_giocatori == 0) {
temp[c] = array_giocatori[giocatore]["name"];
temp2[c] = 0;
}
var p = [];
if (array_giocatori[giocatore]["bets"] && array_giocatori[giocatore]["bets"][week] && array_giocatori[giocatore]["bets"][week][partita]) {
p = array_giocatori[giocatore]["bets"][week][partita];
if (!isNaN(p[0]) && !isNaN(p[2]) && !isNaN(p[1])) {
var e = [];
p = array_giocatori[giocatore]["bets"][week][partita];
e = array_risultati[week][partita];
tt = scoreS(p[0] / 100, p[1] / 100, p[2] / 100, e[0], e[1], e[2]);
if (tt <= min_score) {
min_score = tt;
}
temp2[c] += tt;
} else
score_non_valido = 1;
} else
score_non_valido = 1;
if (score_non_valido == 1) {
lista_score_mancanti[d] = c;
d++;
score_non_valido = 0;
}
c++;
}
if (d > 0)
for (var i = 0; i < d; i++)
temp2[lista_score_mancanti[i]] += min_score;
iniz_giocatori = 1;
}
}
return toArray(temp, temp2, c);
}
//score tipo T
function calcola_classifica_scoreT(array_giocatori, array_risultati) {
var ret = [];
var c, d, iniz_giocatori = 0,
score_non_valido = 0;
var temp = [],
temp2 = [],
tt = 0;
var min_score, lista_score_mancanti = [];
for (var week in array_risultati) {
for (var partita in array_risultati[week]) {
c = 0;
d = 0;
lista_score_mancanti = [];
min_score = 100;
for (var giocatore in array_giocatori) {
if (iniz_giocatori == 0) {
temp[c] = array_giocatori[giocatore]["name"];
temp2[c] = 0;
}
var p = [];
if (array_giocatori[giocatore]["bets"] && array_giocatori[giocatore]["bets"][week] && array_giocatori[giocatore]["bets"][week][partita]) {
p = array_giocatori[giocatore]["bets"][week][partita];
if (!isNaN(p[0]) && !isNaN(p[2]) && !isNaN(p[1])) {
var e = [];
p = array_giocatori[giocatore]["bets"][week][partita];
e = array_risultati[week][partita];
tt = scoreT(p[0] / 100, p[1] / 100, p[2] / 100, e[0], e[1], e[2]);
if (tt <= min_score) {
min_score = tt;
}
temp2[c] += tt;
} else
score_non_valido = 1;
} else
score_non_valido = 1;
if (score_non_valido == 1) {
lista_score_mancanti[d] = c;
d++;
score_non_valido = 0;
}
c++;
}
if (d > 0)
for (var i = 0; i < d; i++)
temp2[lista_score_mancanti[i]] += min_score;
iniz_giocatori = 1;
}
}
return toArray(temp, temp2, c);
}
function toArray(origin, origin2, count) {
var ret = [];
for (var i = 0; i < count; i++)
ret.push({
name: origin[i],
score: parseFloat(origin2[i].toFixed(2))
});
return ret.sort(function(a, b) {
return a.score < b.score;
});
}
exports.calcola_classifica_scoreS = calcola_classifica_scoreS;
exports.calcola_classifica_scoreT = calcola_classifica_scoreT;
|
export const addTestCase = function() {
return {
type: 'EDITOR/VARIABLE_ADD_CASE'
};
};
export const setProperty = function(index, name, value) {
return {
type: 'EDITOR/VARIABLE_SET_PROPERTY',
payload: {
index,
name,
value
}
};
};
export const addVariable = function(index) {
return {
type: 'EDITOR/VARIABLE_ADD_VARIABLE',
payload: {
index
}
};
};
export const setVariable = function(checkIndex, index, name, value, type) {
return {
type: 'EDITOR/VARIABLE_SET_VARIABLE',
payload: {
checkIndex,
index,
name,
value,
type
}
};
};
export default {
addTestCase,
addVariable,
setProperty,
setVariable,
};
|
'use strict';
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
doneFilters: false
};
}
componentDidUpdate() {
if (this.props.filters && !this.state.doneFilters) {
$('.button-collapse').sideNav();
this.setState({ doneFilters: true });
}
}
render() {
var buttonClasses = 'button-collapse';
var filters = null;
if (!this.props.filters) {
buttonClasses += ' hidden';
} else {
filters = React.createElement(Filters, this.props);
}
return React.createElement(
'nav',
{ className: 'red', role: 'navigation' },
React.createElement(
'div',
{ className: 'nav-wrapper container' },
React.createElement(
'a',
{ id: 'logo-container', href: '#', className: 'brand-logo' },
'ExQuery'
),
React.createElement(
'div',
{ id: 'slide-out', className: 'side-nav' },
filters
),
React.createElement(
'a',
{
href: '#',
'data-activates': 'slide-out',
className: buttonClasses },
React.createElement('i', { className: 'mdi-navigation-menu' })
)
)
);
}
}
|
// Routes everything '/helper' related.
exports.index = function(app) {
app.get('/datasets', function(req, res) {
res.render('misc/error', {
'info': 'Work in Progress'
});
});
}
|
var core = require("./core").dom.level2.core,
events = require("./core").dom.level2.events,
applyDocumentFeatures = require('../browser/documentfeatures').applyDocumentFeatures,
URL = require("url"),
Path = require('path'),
fs = require("fs"),
http = require('http'),
https = require('https');
// modify cloned instance for more info check: https://github.com/tmpvar/jsdom/issues/325
core = Object.create(core);
// Setup the javascript language processor
core.languageProcessors = {
javascript : require("./languages/javascript").javascript
};
core.resourceLoader = {
load: function(element, href, callback) {
var ownerImplementation = element._ownerDocument.implementation;
if (ownerImplementation.hasFeature('FetchExternalResources', element.tagName.toLowerCase())) {
var full = this.resolve(element._ownerDocument, href);
var url = URL.parse(full);
if (ownerImplementation.hasFeature('SkipExternalResources', full)) {
return false;
}
if (url.hostname) {
this.download(url, this.baseUrl(element._ownerDocument), this.enqueue(element, callback, full));
}
else {
this.readFile(url.pathname, this.enqueue(element, callback, full));
}
}
},
enqueue: function(element, callback, filename) {
var loader = this,
doc = element.nodeType === core.Node.DOCUMENT_NODE ?
element :
element._ownerDocument;
if (!doc._queue) {
return function() {};
}
return doc._queue.push(function(err, data) {
var ev = doc.createEvent('HTMLEvents');
if (!err) {
try {
callback.call(element, data, filename || doc.URL);
ev.initEvent('load', false, false);
}
catch(e) {
err = e;
}
}
if (err) {
ev.initEvent('error', false, false);
ev.error = err;
}
element.dispatchEvent(ev);
});
},
baseUrl: function(document) {
var baseElements = document.getElementsByTagName('base'),
baseUrl = document.URL;
if (baseElements.length > 0) {
baseUrl = baseElements.item(0).href || baseUrl;
}
return baseUrl;
},
resolve: function(document, href) {
if (href.match(/^\w+:\/\//)) {
return href;
}
var baseUrl = this.baseUrl(document);
// See RFC 2396 section 3 for this weirdness. URLs without protocol
// have their protocol default to the current one.
// http://www.ietf.org/rfc/rfc2396.txt
if (href.match(/^\/\//)) {
return baseUrl ? baseUrl.match(/^(\w+:)\/\//)[1] + href : null;
} else if (!href.match(/^\/[^\/]/)) {
href = href.replace(/^\//, "");
}
return URL.resolve(baseUrl, href);
},
download: function(url, referrer, callback) {
var path = url.pathname + (url.search || ''),
options = {'method': 'GET', 'host': url.hostname, 'path': path},
request;
if (url.protocol === 'https:') {
options.port = url.port || 443;
request = https.request(options);
} else {
options.port = url.port || 80;
request = http.request(options);
}
// set header.
if (referrer) {
request.setHeader('Referer', referrer);
}
request.on('response', function (response) {
var data = '';
function success () {
if ([301, 302, 303, 307].indexOf(response.statusCode) > -1) {
var redirect = URL.resolve(url, response.headers["location"]);
core.resourceLoader.download(URL.parse(redirect), referrer, callback);
} else {
callback(null, data);
}
}
response.setEncoding('utf8');
response.on('data', function (chunk) {
data += chunk.toString();
});
response.on('end', function() {
// According to node docs, 'close' can fire after 'end', but not
// vice versa. Remove 'close' listener so we don't call success twice.
response.removeAllListeners('close');
success();
});
response.on('close', function (err) {
if (err) {
callback(err);
} else {
success();
}
});
});
request.on('error', callback);
request.end();
},
readFile: function(url, callback) {
fs.readFile(url.replace(/^file:\/\//, "").replace(/^\/([a-z]):\//i, '$1:/').replace(/%20/g, ' '), 'utf8', callback);
}
};
function define(elementClass, def) {
var tagName = def.tagName,
tagNames = def.tagNames || (tagName? [tagName] : []),
parentClass = def.parentClass || core.HTMLElement,
attrs = def.attributes || [],
proto = def.proto || {};
var elem = core[elementClass] = function(document, name) {
parentClass.call(this, document, name || tagName.toUpperCase());
if (elem._init) {
elem._init.call(this);
}
};
elem._init = def.init;
elem.prototype = proto;
elem.prototype.__proto__ = parentClass.prototype;
attrs.forEach(function(n) {
var prop = n.prop || n,
attr = n.attr || prop.toLowerCase();
if (!n.prop || n.read !== false) {
elem.prototype.__defineGetter__(prop, function() {
var s = this.getAttribute(attr);
if (n.type && n.type === 'boolean') {
return !!s;
}
if (n.type && n.type === 'long') {
return +s;
}
if (typeof n === 'object' && n.normalize) { // see GH-491
return n.normalize(s);
}
return s;
});
}
if (!n.prop || n.write !== false) {
elem.prototype.__defineSetter__(prop, function(val) {
if (!val) {
this.removeAttribute(attr);
}
else {
var s = val.toString();
if (n.normalize) {
s = n.normalize(s);
}
this.setAttribute(attr, s);
}
});
}
});
tagNames.forEach(function(tag) {
core.Document.prototype._elementBuilders[tag.toLowerCase()] = function(doc, s) {
var el = new elem(doc, s);
return el;
};
});
}
core.HTMLCollection = function HTMLCollection(element, query) {
core.NodeList.call(this, element, query);
};
core.HTMLCollection.prototype = {
namedItem : function(name) {
var results = this.toArray(),
l = results.length,
node,
matchingName = null;
for (var i=0; i<l; i++) {
node = results[i];
if (node.getAttribute('id') === name) {
return node;
} else if (node.getAttribute('name') === name) {
matchingName = node;
}
}
return matchingName;
},
toString: function() {
return '[ jsdom HTMLCollection ]: contains ' + this.length + ' items';
}
};
core.HTMLCollection.prototype.__proto__ = core.NodeList.prototype;
core.HTMLOptionsCollection = core.HTMLCollection;
function closest(e, tagName) {
tagName = tagName.toUpperCase();
while (e) {
if (e.nodeName.toUpperCase() === tagName ||
(e.tagName && e.tagName.toUpperCase() === tagName))
{
return e;
}
e = e._parentNode;
}
return null;
}
function descendants(e, tagName, recursive) {
var owner = recursive ? e._ownerDocument || e : e;
return new core.HTMLCollection(owner, core.mapper(e, function(n) {
return n.nodeName === tagName && typeof n._publicId == 'undefined';
}, recursive));
}
function firstChild(e, tagName) {
if (!e) {
return null;
}
var c = descendants(e, tagName, false);
return c.length > 0 ? c[0] : null;
}
function ResourceQueue(paused) {
this.paused = !!paused;
}
ResourceQueue.prototype = {
push: function(callback) {
var q = this;
var item = {
prev: q.tail,
check: function() {
if (!q.paused && !this.prev && this.fired){
callback(this.err, this.data);
if (this.next) {
this.next.prev = null;
this.next.check();
}else{//q.tail===this
q.tail = null;
}
}
}
};
if (q.tail) {
q.tail.next = item;
}
q.tail = item;
return function(err, data) {
item.fired = 1;
item.err = err;
item.data = data;
item.check();
};
},
resume: function() {
if(!this.paused){
return;
}
this.paused = false;
var head = this.tail;
while(head && head.prev){
head = head.prev;
}
if(head){
head.check();
}
}
};
core.HTMLDocument = function HTMLDocument(options) {
options = options || {};
if (!options.contentType) {
options.contentType = 'text/html';
}
core.Document.call(this, options);
this._referrer = options.referrer;
this._cookie = options.cookie;
this._URL = options.url || '/';
this._documentRoot = options.documentRoot || Path.dirname(this._URL);
this._queue = new ResourceQueue(options.deferClose);
this.readyState = 'loading';
// Add level2 features
this.implementation.addFeature('core' , '2.0');
this.implementation.addFeature('html' , '2.0');
this.implementation.addFeature('xhtml' , '2.0');
this.implementation.addFeature('xml' , '2.0');
};
core.HTMLDocument.prototype = {
_referrer : "",
get referrer() {
return this._referrer || '';
},
get domain() {
return "";
},
_URL : "",
get URL() {
return this._URL;
},
get images() {
return this.getElementsByTagName('IMG');
},
get applets() {
return new core.HTMLCollection(this, core.mapper(this, function(el) {
if (el && el.tagName) {
var upper = el.tagName.toUpperCase();
if (upper === "APPLET") {
return true;
} else if (upper === "OBJECT" &&
el.getElementsByTagName('APPLET').length > 0)
{
return true;
}
}
}));
},
get links() {
return new core.HTMLCollection(this, core.mapper(this, function(el) {
if (el && el.tagName) {
var upper = el.tagName.toUpperCase();
if (upper === "AREA" || (upper === "A" && el.href)) {
return true;
}
}
}));
},
get forms() {
return this.getElementsByTagName('FORM');
},
get anchors() {
return this.getElementsByTagName('A');
},
open : function() {
this._childNodes = [];
this._documentElement = null;
this._modified();
},
close : function() {
this._queue.resume();
// Set the readyState to 'complete' once all resources are loaded.
// As a side-effect the document's load-event will be dispatched.
core.resourceLoader.enqueue(this, function() {
this.readyState = 'complete';
var ev = this.createEvent('HTMLEvents');
ev.initEvent('DOMContentLoaded', false, false);
this.dispatchEvent(ev);
})(null, true);
},
write : function(text) {
if (this.readyState === "loading") {
// During page loading, document.write appends to the current element
// Find the last child that has been added to the document.
var node = this;
while (node.lastChild && node.lastChild.nodeType === this.ELEMENT_NODE) {
node = node.lastChild;
}
node.innerHTML = text;
} else {
this.innerHTML = text;
}
},
writeln : function(text) {
this.write(text + '\n');
},
getElementsByName : function(elementName) {
return new core.HTMLCollection(this, core.mapper(this, function(el) {
return (el.getAttribute && el.getAttribute("name") === elementName);
}));
},
get title() {
var head = this.head,
title = head ? firstChild(head, 'TITLE') : null;
return title ? title.textContent : '';
},
set title(val) {
var title = firstChild(this.head, 'TITLE');
if (!title) {
title = this.createElement('TITLE');
var head = this.head;
if (!head) {
head = this.createElement('HEAD');
this.documentElement.insertBefore(head, this.documentElement.firstChild);
}
head.appendChild(title);
}
title.textContent = val;
},
get head() {
return firstChild(this.documentElement, 'HEAD');
},
set head() { /* noop */ },
get body() {
var body = firstChild(this.documentElement, 'BODY');
if (!body) {
body = firstChild(this.documentElement, 'FRAMESET');
}
return body;
},
get documentElement() {
if (!this._documentElement) {
this._documentElement = firstChild(this, 'HTML');
}
return this._documentElement;
},
_cookie : "",
get cookie() { return this._cookie || ''; },
set cookie(val) { this._cookie = val; }
};
core.HTMLDocument.prototype.__proto__ = core.Document.prototype;
define('HTMLElement', {
parentClass: core.Element,
proto : {
// Add default event behavior (click link to navigate, click button to submit
// form, etc). We start by wrapping dispatchEvent so we can forward events to
// the element's _eventDefault function (only events that did not incur
// preventDefault).
dispatchEvent : function (event) {
var outcome = core.Node.prototype.dispatchEvent.call(this, event)
if (!event._preventDefault &&
event.target._eventDefaults[event.type] &&
typeof event.target._eventDefaults[event.type] === 'function')
{
event.target._eventDefaults[event.type](event)
}
return outcome;
},
_eventDefaults : {}
},
attributes: [
'id',
'title',
'lang',
'dir',
{prop: 'className', attr: 'class', normalize: function(s) { return s || ''; }}
]
});
core.Document.prototype._defaultElementBuilder = function(document, tagName) {
return new core.HTMLElement(document, tagName);
};
//http://www.w3.org/TR/html5/forms.html#category-listed
var listedElements = /button|fieldset|input|keygen|object|select|textarea/i;
define('HTMLFormElement', {
tagName: 'FORM',
proto: {
get elements() {
return new core.HTMLCollection(this._ownerDocument, core.mapper(this, function(e) {
return listedElements.test(e.nodeName) ; // TODO exclude <input type="image">
}));
},
get length() {
return this.elements.length;
},
_dispatchSubmitEvent: function() {
var ev = this._ownerDocument.createEvent('HTMLEvents');
ev.initEvent('submit', true, true);
if (!this.dispatchEvent(ev)) {
this.submit();
};
},
submit: function() {
},
reset: function() {
this.elements.toArray().forEach(function(el) {
el.value = el.defaultValue;
});
}
},
attributes: [
'name',
{prop: 'acceptCharset', attr: 'accept-charset'},
'action',
'enctype',
'method',
'target'
]
});
define('HTMLLinkElement', {
tagName: 'LINK',
proto: {
get href() {
return core.resourceLoader.resolve(this._ownerDocument, this.getAttribute('href'));
}
},
attributes: [
{prop: 'disabled', type: 'boolean'},
'charset',
'href',
'hreflang',
'media',
'rel',
'rev',
'target',
'type'
]
});
define('HTMLMetaElement', {
tagName: 'META',
attributes: [
'content',
{prop: 'httpEquiv', attr: 'http-equiv'},
'name',
'scheme'
]
});
define('HTMLHtmlElement', {
tagName: 'HTML',
attributes: [
'version'
]
});
define('HTMLHeadElement', {
tagName: 'HEAD',
attributes: [
'profile'
]
});
define('HTMLTitleElement', {
tagName: 'TITLE',
proto: {
get text() {
return this.innerHTML;
},
set text(s) {
this.innerHTML = s;
}
}
});
define('HTMLBaseElement', {
tagName: 'BASE',
attributes: [
'href',
'target'
]
});
//**Deprecated**
define('HTMLIsIndexElement', {
tagName : 'ISINDEX',
parentClass : core.Element,
proto : {
get form() {
return closest(this, 'FORM');
}
},
attributes : [
'prompt'
]
});
define('HTMLStyleElement', {
tagName: 'STYLE',
attributes: [
{prop: 'disabled', type: 'boolean'},
'media',
'type',
]
});
define('HTMLBodyElement', {
proto: (function() {
var proto = {};
// The body element's "traditional" event handlers are proxied to the
// window object.
// See: http://dev.w3.org/html5/spec/Overview.html#the-body-element
['onafterprint', 'onbeforeprint', 'onbeforeunload', 'onblur', 'onerror',
'onfocus', 'onhashchange', 'onload', 'onmessage', 'onoffline', 'ononline',
'onpagehide', 'onpageshow', 'onpopstate', 'onresize', 'onscroll',
'onstorage', 'onunload'].forEach(function (name) {
proto.__defineSetter__(name, function (handler) {
this._ownerDocument.parentWindow[name] = handler;
});
proto.__defineGetter__(name, function () {
return this._ownerDocument.parentWindow[name];
});
});
return proto;
})(),
tagName: 'BODY',
attributes: [
'aLink',
'background',
'bgColor',
'link',
'text',
'vLink'
]
});
define('HTMLSelectElement', {
tagName: 'SELECT',
proto: {
get options() {
return new core.HTMLOptionsCollection(this, core.mapper(this, function(n) {
return n.nodeName === 'OPTION';
}));
},
get length() {
return this.options.length;
},
get selectedIndex() {
return this.options.toArray().reduceRight(function(prev, option, i) {
return option.selected ? i : prev;
}, -1);
},
set selectedIndex(index) {
this.options.toArray().forEach(function(option, i) {
option.selected = i === index;
});
},
get value() {
var i = this.selectedIndex;
if (this.options.length && (i === -1)) {
i = 0;
}
if (i === -1) {
return '';
}
return this.options[i].value;
},
set value(val) {
var self = this;
this.options.toArray().forEach(function(option) {
if (option.value === val) {
option.selected = true;
} else {
if (!self.hasAttribute('multiple')) {
// Remove the selected bit from all other options in this group
// if the multiple attr is not present on the select
option.selected = false;
}
}
});
},
get form() {
return closest(this, 'FORM');
},
get type() {
return this.multiple ? 'select-multiple' : 'select-one';
},
add: function(opt, before) {
if (before) {
this.insertBefore(opt, before);
}
else {
this.appendChild(opt);
}
},
remove: function(index) {
var opts = this.options.toArray();
if (index >= 0 && index < opts.length) {
var el = opts[index];
el._parentNode.removeChild(el);
}
},
blur : function() {
this._ownerDocument.activeElement = this._ownerDocument.body;
},
focus : function() {
this._ownerDocument.activeElement = this;
}
},
attributes: [
{prop: 'disabled', type: 'boolean'},
{prop: 'multiple', type: 'boolean'},
'name',
{prop: 'size', type: 'long'},
{prop: 'tabIndex', type: 'long'},
]
});
define('HTMLOptGroupElement', {
tagName: 'OPTGROUP',
attributes: [
{prop: 'disabled', type: 'boolean'},
'label'
]
});
define('HTMLOptionElement', {
tagName: 'OPTION',
proto: {
_attrModified: function(name, value) {
if (name === 'selected') {
this.selected = this.defaultSelected;
}
core.HTMLElement.prototype._attrModified.call(this, arguments);
},
get form() {
return closest(this, 'FORM');
},
get defaultSelected() {
return !!this.getAttribute('selected');
},
set defaultSelected(s) {
if (s) this.setAttribute('selected', 'selected');
else this.removeAttribute('selected');
},
get text() {
return this.innerHTML;
},
get value() {
return (this.hasAttribute('value')) ? this.getAttribute('value') : this.innerHTML;
},
set value(val) {
this.setAttribute('value', val);
},
get index() {
return closest(this, 'SELECT').options.toArray().indexOf(this);
},
get selected() {
if (this._selected === undefined) {
this._selected = this.defaultSelected;
}
return this._selected;
},
set selected(s) {
// TODO: The 'selected' content attribute is the initial value of the
// IDL attribute, but the IDL attribute should not relfect the content
this._selected = !!s;
if (s) {
//Remove the selected bit from all other options in this select
var select = this._parentNode;
if (!select) return;
if (select.nodeName !== 'SELECT') {
select = select._parentNode;
if (!select) return;
if (select.nodeName !== 'SELECT') return;
}
if (!select.multiple) {
var o = select.options;
for (var i = 0; i < o.length; i++) {
if (o[i] !== this) {
o[i].selected = false;
}
}
}
}
}
},
attributes: [
{prop: 'disabled', type: 'boolean'},
'label'
]
});
define('HTMLInputElement', {
tagName: 'INPUT',
proto: {
_initDefaultValue: function() {
if (this._defaultValue === undefined) {
var attr = this.getAttributeNode('value');
this._defaultValue = attr ? attr.value : null;
}
return this._defaultValue;
},
_initDefaultChecked: function() {
if (this._defaultChecked === undefined) {
this._defaultChecked = !!this.getAttribute('checked');
}
return this._defaultChecked;
},
get form() {
return closest(this, 'FORM');
},
get defaultValue() {
return this._initDefaultValue();
},
get defaultChecked() {
return this._initDefaultChecked();
},
get checked() {
return !!this._attributes.getNamedItem('checked');
},
set checked(checked) {
this._initDefaultChecked();
if (checked) {
this.setAttribute('checked', 'checked');
} else {
this.removeAttribute('checked');
}
},
get value() {
return this.getAttribute('value');
},
set value(val) {
this._initDefaultValue();
if (val === null) {
this.removeAttribute('value');
}
else {
this.setAttribute('value', val);
}
},
blur : function() {
this._ownerDocument.activeElement = this._ownerDocument.body;
},
focus : function() {
this._ownerDocument.activeElement = this;
},
select: function() {
},
click: function() {
if (this.type === 'checkbox' || this.type === 'radio') {
this.checked = !this.checked;
}
else if (this.type === 'submit') {
var form = this.form;
if (form) {
form._dispatchSubmitEvent();
}
}
}
},
attributes: [
'accept',
'accessKey',
'align',
'alt',
{prop: 'disabled', type: 'boolean'},
{prop: 'maxLength', type: 'long'},
'name',
{prop: 'readOnly', type: 'boolean'},
{prop: 'size', type: 'long'},
'src',
{prop: 'tabIndex', type: 'long'},
{prop: 'type', normalize: function(val) {
return val ? val.toLowerCase() : 'text';
}},
'useMap'
]
});
define('HTMLTextAreaElement', {
tagName: 'TEXTAREA',
proto: {
_initDefaultValue: function() {
if (this._defaultValue === undefined) {
this._defaultValue = this.textContent;
}
return this._defaultValue;
},
get form() {
return closest(this, 'FORM');
},
get defaultValue() {
return this._initDefaultValue();
},
get value() {
return this.textContent;
},
set value(val) {
this._initDefaultValue();
this.textContent = val;
},
get type() {
return 'textarea';
},
blur : function() {
this._ownerDocument.activeElement = this._ownerDocument.body;
},
focus : function() {
this._ownerDocument.activeElement = this;
},
select: function() {
}
},
attributes: [
'accessKey',
{prop: 'cols', type: 'long'},
{prop: 'disabled', type: 'boolean'},
{prop: 'maxLength', type: 'long'},
'name',
{prop: 'readOnly', type: 'boolean'},
{prop: 'rows', type: 'long'},
{prop: 'tabIndex', type: 'long'}
]
});
define('HTMLButtonElement', {
tagName: 'BUTTON',
proto: {
get form() {
return closest(this, 'FORM');
},
focus : function() {
this._ownerDocument.activeElement = this;
},
blur : function() {
this._ownerDocument.activeElement = this._ownerDocument.body;
}
},
attributes: [
'accessKey',
{prop: 'disabled', type: 'boolean'},
'name',
{prop: 'tabIndex', type: 'long'},
'type',
'value'
]
});
define('HTMLLabelElement', {
tagName: 'LABEL',
proto: {
get form() {
return closest(this, 'FORM');
}
},
attributes: [
'accessKey',
{prop: 'htmlFor', attr: 'for'}
]
});
define('HTMLFieldSetElement', {
tagName: 'FIELDSET',
proto: {
get form() {
return closest(this, 'FORM');
}
}
});
define('HTMLLegendElement', {
tagName: 'LEGEND',
proto: {
get form() {
return closest(this, 'FORM');
}
},
attributes: [
'accessKey',
'align'
]
});
define('HTMLUListElement', {
tagName: 'UL',
attributes: [
{prop: 'compact', type: 'boolean'},
'type'
]
});
define('HTMLOListElement', {
tagName: 'OL',
attributes: [
{prop: 'compact', type: 'boolean'},
{prop: 'start', type: 'long'},
'type'
]
});
define('HTMLDListElement', {
tagName: 'DL',
attributes: [
{prop: 'compact', type: 'boolean'}
]
});
define('HTMLDirectoryElement', {
tagName: 'DIR',
attributes: [
{prop: 'compact', type: 'boolean'}
]
});
define('HTMLMenuElement', {
tagName: 'MENU',
attributes: [
{prop: 'compact', type: 'boolean'}
]
});
define('HTMLLIElement', {
tagName: 'LI',
attributes: [
'type',
{prop: 'value', type: 'long'}
]
});
define('HTMLDivElement', {
tagName: 'DIV',
attributes: [
'align'
]
});
define('HTMLParagraphElement', {
tagName: 'P',
attributes: [
'align'
]
});
define('HTMLHeadingElement', {
tagNames: ['H1','H2','H3','H4','H5','H6'],
attributes: [
'align'
]
});
define('HTMLQuoteElement', {
tagNames: ['Q','BLOCKQUOTE'],
attributes: [
'cite'
]
});
define('HTMLPreElement', {
tagName: 'PRE',
attributes: [
{prop: 'width', type: 'long'}
]
});
define('HTMLBRElement', {
tagName: 'BR',
attributes: [
'clear'
]
});
define('HTMLBaseFontElement', {
tagName: 'BASEFONT',
attributes: [
'color',
'face',
{prop: 'size', type: 'long'}
]
});
define('HTMLFontElement', {
tagName: 'FONT',
attributes: [
'color',
'face',
'size'
]
});
define('HTMLHRElement', {
tagName: 'HR',
attributes: [
'align',
{prop: 'noShade', type: 'boolean'},
'size',
'width'
]
});
define('HTMLModElement', {
tagNames: ['INS', 'DEL'],
attributes: [
'cite',
'dateTime'
]
});
define('HTMLAnchorElement', {
tagName: 'A',
proto: {
blur : function() {
this._ownerDocument.activeElement = this._ownerDocument.body;
},
focus : function() {
this._ownerDocument.activeElement = this;
},
get href() {
return core.resourceLoader.resolve(this._ownerDocument, this.getAttribute('href'));
},
get hostname() {
return URL.parse(this.href).hostname;
},
get pathname() {
return URL.parse(this.href).pathname;
}
},
attributes: [
'accessKey',
'charset',
'coords',
{prop: 'href', type: 'string', read: false},
'hreflang',
'name',
'rel',
'rev',
'shape',
{prop: 'tabIndex', type: 'long'},
'target',
'type'
]
});
define('HTMLImageElement', {
tagName: 'IMG',
attributes: [
'name',
'align',
'alt',
'border',
{prop: 'height', type: 'long'},
{prop: 'hspace', type: 'long'},
{prop: 'isMap', type: 'boolean'},
'longDesc',
'src',
'useMap',
{prop: 'vspace', type: 'long'},
{prop: 'width', type: 'long'}
]
});
define('HTMLObjectElement', {
tagName: 'OBJECT',
proto: {
get form() {
return closest(this, 'FORM');
},
get contentDocument() {
return null;
}
},
attributes: [
'code',
'align',
'archive',
'border',
'codeBase',
'codeType',
'data',
{prop: 'declare', type: 'boolean'},
{prop: 'height', type: 'long'},
{prop: 'hspace', type: 'long'},
'name',
'standby',
{prop: 'tabIndex', type: 'long'},
'type',
'useMap',
{prop: 'vspace', type: 'long'},
{prop: 'width', type: 'long'}
]
});
define('HTMLParamElement', {
tagName: 'PARAM',
attributes: [
'name',
'type',
'value',
'valueType'
]
});
define('HTMLAppletElement', {
tagName: 'APPLET',
attributes: [
'align',
'alt',
'archive',
'code',
'codeBase',
'height',
{prop: 'hspace', type: 'long'},
'name',
'object',
{prop: 'vspace', type: 'long'},
'width'
]
});
define('HTMLMapElement', {
tagName: 'MAP',
proto: {
get areas() {
return this.getElementsByTagName("AREA");
}
},
attributes: [
'name'
]
});
define('HTMLAreaElement', {
tagName: 'AREA',
attributes: [
'accessKey',
'alt',
'coords',
'href',
{prop: 'noHref', type: 'boolean'},
'shape',
{prop: 'tabIndex', type: 'long'},
'target'
]
});
define('HTMLScriptElement', {
tagName: 'SCRIPT',
init: function() {
this.addEventListener('DOMNodeInsertedIntoDocument', function() {
if (this.src) {
core.resourceLoader.load(this, this.src, this._eval);
}
else {
var src = this.sourceLocation || {},
filename = src.file || this._ownerDocument.URL;
if (src) {
filename += ':' + src.line + ':' + src.col;
}
filename += '<script>';
core.resourceLoader.enqueue(this, this._eval, filename)(null, this.text);
}
});
},
proto: {
_eval: function(text, filename) {
if (this._ownerDocument.implementation.hasFeature("ProcessExternalResources", "script") &&
this.language &&
core.languageProcessors[this.language])
{
core.languageProcessors[this.language](this, text, filename);
}
},
get language() {
var type = this.type || "text/javascript";
return type.split("/").pop().toLowerCase();
},
get text() {
var i=0, children = this.childNodes, l = children.length, ret = [];
for (i; i<l; i++) {
ret.push(children.item(i).nodeValue);
}
return ret.join("");
},
set text(text) {
while (this.childNodes.length) {
this.removeChild(this.childNodes[0]);
}
this.appendChild(this._ownerDocument.createTextNode(text));
}
},
attributes : [
{prop: 'defer', 'type': 'boolean'},
'htmlFor',
'event',
'charset',
'type',
'src'
]
})
define('HTMLTableElement', {
tagName: 'TABLE',
proto: {
get caption() {
return firstChild(this, 'CAPTION');
},
get tHead() {
return firstChild(this, 'THEAD');
},
get tFoot() {
return firstChild(this, 'TFOOT');
},
get rows() {
if (!this._rows) {
var table = this;
this._rows = new core.HTMLCollection(this._ownerDocument, function() {
var sections = [table.tHead].concat(table.tBodies.toArray(), table.tFoot).filter(function(s) { return !!s });
if (sections.length === 0) {
return core.mapDOMNodes(table, false, function(el) {
return el.tagName === 'TR';
});
}
return sections.reduce(function(prev, s) {
return prev.concat(s.rows.toArray());
}, []);
});
}
return this._rows;
},
get tBodies() {
if (!this._tBodies) {
this._tBodies = descendants(this, 'TBODY', false);
}
return this._tBodies;
},
createTHead: function() {
var el = this.tHead;
if (!el) {
el = this._ownerDocument.createElement('THEAD');
this.appendChild(el);
}
return el;
},
deleteTHead: function() {
var el = this.tHead;
if (el) {
el._parentNode.removeChild(el);
}
},
createTFoot: function() {
var el = this.tFoot;
if (!el) {
el = this._ownerDocument.createElement('TFOOT');
this.appendChild(el);
}
return el;
},
deleteTFoot: function() {
var el = this.tFoot;
if (el) {
el._parentNode.removeChild(el);
}
},
createCaption: function() {
var el = this.caption;
if (!el) {
el = this._ownerDocument.createElement('CAPTION');
this.appendChild(el);
}
return el;
},
deleteCaption: function() {
var c = this.caption;
if (c) {
c._parentNode.removeChild(c);
}
},
insertRow: function(index) {
var tr = this._ownerDocument.createElement('TR');
if (this.childNodes.length === 0) {
this.appendChild(this._ownerDocument.createElement('TBODY'));
}
var rows = this.rows.toArray();
if (index < -1 || index > rows.length) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
if (index === -1 || (index === 0 && rows.length === 0)) {
this.tBodies.item(0).appendChild(tr);
}
else if (index === rows.length) {
var ref = rows[index-1];
ref._parentNode.appendChild(tr);
}
else {
var ref = rows[index];
ref._parentNode.insertBefore(tr, ref);
}
return tr;
},
deleteRow: function(index) {
var rows = this.rows.toArray(), l = rows.length;
if (index === -1) {
index = l-1;
}
if (index < 0 || index >= l) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
var tr = rows[index];
tr._parentNode.removeChild(tr);
}
},
attributes: [
'align',
'bgColor',
'border',
'cellPadding',
'cellSpacing',
'frame',
'rules',
'summary',
'width'
]
});
define('HTMLTableCaptionElement', {
tagName: 'CAPTION',
attributes: [
'align'
]
});
define('HTMLTableColElement', {
tagNames: ['COL','COLGROUP'],
attributes: [
'align',
{prop: 'ch', attr: 'char'},
{prop: 'chOff', attr: 'charoff'},
{prop: 'span', type: 'long'},
'vAlign',
'width',
]
});
define('HTMLTableSectionElement', {
tagNames: ['THEAD','TBODY','TFOOT'],
proto: {
get rows() {
if (!this._rows) {
this._rows = descendants(this, 'TR', false);
}
return this._rows;
},
insertRow: function(index) {
var tr = this._ownerDocument.createElement('TR');
var rows = this.rows.toArray();
if (index < -1 || index > rows.length) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
if (index === -1 || index === rows.length) {
this.appendChild(tr);
}
else {
var ref = rows[index];
this.insertBefore(tr, ref);
}
return tr;
},
deleteRow: function(index) {
var rows = this.rows.toArray();
if (index === -1) {
index = rows.length-1;
}
if (index < 0 || index >= rows.length) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
var tr = this.rows[index];
this.removeChild(tr);
}
},
attributes: [
'align',
{prop: 'ch', attr: 'char'},
{prop: 'chOff', attr: 'charoff'},
{prop: 'span', type: 'long'},
'vAlign',
'width',
]
});
define('HTMLTableRowElement', {
tagName: 'TR',
proto: {
get cells() {
if (!this._cells) {
this._cells = new core.HTMLCollection(this, core.mapper(this, function(n) {
return n.nodeName === 'TD' || n.nodeName === 'TH';
}, false));
}
return this._cells;
},
get rowIndex() {
return closest(this, 'TABLE').rows.toArray().indexOf(this);
},
get sectionRowIndex() {
return this._parentNode.rows.toArray().indexOf(this);
},
insertCell: function(index) {
var td = this._ownerDocument.createElement('TD');
var cells = this.cells.toArray();
if (index < -1 || index > cells.length) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
if (index === -1 || index === cells.length) {
this.appendChild(td);
}
else {
var ref = cells[index];
this.insertBefore(td, ref);
}
return td;
},
deleteCell: function(index) {
var cells = this.cells.toArray();
if (index === -1) {
index = cells.length-1;
}
if (index < 0 || index >= cells.length) {
throw new core.DOMException(core.INDEX_SIZE_ERR);
}
var td = this.cells[index];
this.removeChild(td);
}
},
attributes: [
'align',
'bgColor',
{prop: 'ch', attr: 'char'},
{prop: 'chOff', attr: 'charoff'},
'vAlign'
]
});
define('HTMLTableCellElement', {
tagNames: ['TH','TD'],
proto: {
_headers: null,
set headers(h) {
if (h === '') {
//Handle resetting headers so the dynamic getter returns a query
this._headers = null;
return;
}
if (!(h instanceof Array)) {
h = [h];
}
this._headers = h;
},
get headers() {
if (this._headers) {
return this._headers.join(' ');
}
var cellIndex = this.cellIndex,
headings = [],
siblings = this._parentNode.getElementsByTagName(this.tagName);
for (var i=0; i<siblings.length; i++) {
if (siblings.item(i).cellIndex >= cellIndex) {
break;
}
headings.push(siblings.item(i).id);
}
this._headers = headings;
return headings.join(' ');
},
get cellIndex() {
return closest(this, 'TR').cells.toArray().indexOf(this);
}
},
attributes: [
'abbr',
'align',
'axis',
'bgColor',
{prop: 'ch', attr: 'char'},
{prop: 'chOff', attr: 'charoff'},
{prop: 'colSpan', type: 'long'},
'height',
{prop: 'noWrap', type: 'boolean'},
{prop: 'rowSpan', type: 'long'},
'scope',
'vAlign',
'width'
]
});
define('HTMLFrameSetElement', {
tagName: 'FRAMESET',
attributes: [
'cols',
'rows'
]
});
function loadFrame (frame) {
if (frame._contentDocument) {
// We don't want to access document.parentWindow, since the getter will
// cause a new window to be allocated if it doesn't exist. Probe the
// private variable instead.
if (frame._contentDocument._parentWindow) {
// close calls delete on its document.
frame._contentDocument.parentWindow.close();
} else {
delete frame._contentDocument;
}
}
var src = frame.src;
var parentDoc = frame._ownerDocument;
var url = core.resourceLoader.resolve(parentDoc, src);
var contentDoc = frame._contentDocument = new core.HTMLDocument({
url: url,
documentRoot: Path.dirname(url)
});
applyDocumentFeatures(contentDoc, parentDoc.implementation._features);
var parent = parentDoc.parentWindow;
var contentWindow = contentDoc.parentWindow;
contentWindow.parent = parent;
contentWindow.top = parent.top;
core.resourceLoader.load(frame, url, function(html, filename) {
contentDoc.write(html);
contentDoc.close();
});
}
define('HTMLFrameElement', {
tagName: 'FRAME',
init : function () {
// Set up the frames array. window.frames really just returns a reference
// to the window object, so the frames array is just implemented as indexes
// on the window.
var parent = this._ownerDocument.parentWindow;
var frameID = parent._length++;
var self = this;
parent.__defineGetter__(frameID, function () {
return self.contentWindow;
});
// The contentDocument/contentWindow shouldn't be created until the frame
// is inserted:
// "When an iframe element is first inserted into a document, the user
// agent must create a nested browsing context, and then process the
// iframe attributes for the first time."
// (http://dev.w3.org/html5/spec/Overview.html#the-iframe-element)
this._initInsertListener = this.addEventListener('DOMNodeInsertedIntoDocument', function () {
var parentDoc = self._ownerDocument;
// Calling contentDocument creates the Document if it doesn't exist.
var doc = self.contentDocument;
applyDocumentFeatures(doc, parentDoc.implementation._features);
var window = self.contentWindow;
window.parent = parent;
window.top = parent.top;
}, false);
},
proto: {
setAttribute: function(name, value) {
core.HTMLElement.prototype.setAttribute.call(this, name, value);
var self = this;
if (name === 'name') {
// Set up named frame access.
this._ownerDocument.parentWindow.__defineGetter__(value, function () {
return self.contentWindow;
});
} else if (name === 'src') {
// Page we don't fetch the page until the node is inserted. This at
// least seems to be the way Chrome does it.
if (!this._attachedToDocument) {
if (!this._waitingOnInsert) {
// First, remove the listener added in 'init'.
this.removeEventListener('DOMNodeInsertedIntoDocument',
this._initInsertListener, false)
// If we aren't already waiting on an insert, add a listener.
// This guards against src being set multiple times before the frame
// is inserted into the document - we don't want to register multiple
// callbacks.
this.addEventListener('DOMNodeInsertedIntoDocument', function loader () {
self.removeEventListener('DOMNodeInsertedIntoDocument', loader, false);
this._waitingOnInsert = false;
loadFrame(self);
}, false);
this._waitingOnInsert = true;
}
} else {
loadFrame(self);
}
}
},
_contentDocument : null,
get contentDocument() {
if (this._contentDocument == null) {
this._contentDocument = new core.HTMLDocument();
}
return this._contentDocument;
},
get contentWindow() {
return this.contentDocument.parentWindow;
}
},
attributes: [
'frameBorder',
'longDesc',
'marginHeight',
'marginWidth',
'name',
{prop: 'noResize', type: 'boolean'},
'scrolling',
{prop: 'src', type: 'string', write: false}
]
});
define('HTMLIFrameElement', {
tagName: 'IFRAME',
parentClass: core.HTMLFrameElement,
attributes: [
'align',
'frameBorder',
'height',
'longDesc',
'marginHeight',
'marginWidth',
'name',
'scrolling',
'src',
'width'
]
});
exports.define = define;
exports.dom = {
level2 : {
html : core
}
}
|
define(['components/home-page/home'], function(homePage) {
var HomePageViewModel = homePage.viewModel;
var instance;
describe('Home page view model', function() {
beforeEach(function() {
spyOn(HomePageViewModel.prototype, 'loadYelpPlaces').and.callThrough();
instance = new HomePageViewModel();
});
it('should call loadYelpPlaces', function() {
expect(instance.loadYelpPlaces).toHaveBeenCalled();
});
it('filterOptions array should eqal ["all"]', function() {
expect(instance.filterOptions()).toEqual(['all']);
});
});
});
|
define([
"dojo/_base/array", // array.indexOf
"dojo/_base/declare", // declare
"dojo/dom", // dom.isDescendant domClass.replace
"dojo/dom-attr",
"dojo/dom-class", // domClass.replace
"dojo/_base/lang", // lang.hitch
"dojo/mouse", // mouse.enter, mouse.leave
"dojo/on",
"dojo/window",
"./a11yclick",
"./popup",
"./registry",
"./_Widget",
"./_CssStateMixin",
"./_KeyNavContainer",
"./_TemplatedMixin"
], function(array, declare, dom, domAttr, domClass, lang, mouse, on, winUtils, a11yclick, pm,
registry, _Widget, _CssStateMixin, _KeyNavContainer, _TemplatedMixin){
// module:
// dijit/_MenuBase
return declare("dijit._MenuBase", [_Widget, _TemplatedMixin, _KeyNavContainer, _CssStateMixin], {
// summary:
// Base class for Menu and MenuBar
// parentMenu: [readonly] Widget
// pointer to menu that displayed me
parentMenu: null,
// popupDelay: Integer
// number of milliseconds before hovering (without clicking) causes the popup to automatically open.
popupDelay: 500,
// autoFocus: Boolean
// A toggle to control whether or not a Menu gets focused when opened as a drop down from a MenuBar
// or DropDownButton/ComboButton. Note though that it always get focused when opened via the keyboard.
autoFocus: false,
childSelector: function(/*DOMNode*/ node){
// summary:
// Selector (passed to on.selector()) used to identify MenuItem child widgets, but exclude inert children
// like MenuSeparator. If subclass overrides to a string (ex: "> *"), the subclass must require dojo/query.
// tags:
// protected
var widget = registry.byNode(node);
return node.parentNode == this.containerNode && widget && widget.focus;
},
postCreate: function(){
var self = this,
matches = typeof this.childSelector == "string" ? this.childSelector : lang.hitch(this, "childSelector");
this.own(
on(this.containerNode, on.selector(matches, mouse.enter), function(){
self.onItemHover(registry.byNode(this));
}),
on(this.containerNode, on.selector(matches, mouse.leave), function(){
self.onItemUnhover(registry.byNode(this));
}),
on(this.containerNode, on.selector(matches, a11yclick), function(evt){
self.onItemClick(registry.byNode(this), evt);
evt.stopPropagation();
evt.preventDefault();
})
);
this.inherited(arguments);
},
onKeyboardSearch: function(/*MenuItem*/ item, /*Event*/ evt, /*String*/ searchString, /*Number*/ numMatches){
// summary:
// Attach point for notification about when a menu item has been searched for
// via the keyboard search mechanism.
// tags:
// protected
this.inherited(arguments);
if(!!item && (numMatches == -1 || (!!item.popup && numMatches == 1))){
this.onItemClick(item, evt);
}
},
_keyboardSearchCompare: function(/*dijit/_WidgetBase*/ item, /*String*/ searchString){
// summary:
// Compares the searchString to the widget's text label, returning:
// -1: a high priority match and stop searching
// 0: no match
// 1: a match but keep looking for a higher priority match
// tags:
// private
if(!!item.shortcutKey){
// accessKey matches have priority
return searchString == item.shortcutKey.toLowerCase() ? -1 : 0;
}
return this.inherited(arguments) ? 1 : 0; // change return value of -1 to 1 so that searching continues
},
onExecute: function(){
// summary:
// Attach point for notification about when a menu item has been executed.
// This is an internal mechanism used for Menus to signal to their parent to
// close them, because they are about to execute the onClick handler. In
// general developers should not attach to or override this method.
// tags:
// protected
},
onCancel: function(/*Boolean*/ /*===== closeAll =====*/){
// summary:
// Attach point for notification about when the user cancels the current menu
// This is an internal mechanism used for Menus to signal to their parent to
// close them. In general developers should not attach to or override this method.
// tags:
// protected
},
_moveToPopup: function(/*Event*/ evt){
// summary:
// This handles the right arrow key (left arrow key on RTL systems),
// which will either open a submenu, or move to the next item in the
// ancestor MenuBar
// tags:
// private
if(this.focusedChild && this.focusedChild.popup && !this.focusedChild.disabled){
this.onItemClick(this.focusedChild, evt);
}else{
var topMenu = this._getTopMenu();
if(topMenu && topMenu._isMenuBar){
topMenu.focusNext();
}
}
},
_onPopupHover: function(/*Event*/ /*===== evt =====*/){
// summary:
// This handler is called when the mouse moves over the popup.
// tags:
// private
// if the mouse hovers over a menu popup that is in pending-close state,
// then stop the close operation.
// This can't be done in onItemHover since some popup targets don't have MenuItems (e.g. ColorPicker)
if(this.currentPopup && this.currentPopup._pendingClose_timer){
var parentMenu = this.currentPopup.parentMenu;
// highlight the parent menu item pointing to this popup
if(parentMenu.focusedChild){
parentMenu.focusedChild._setSelected(false);
}
parentMenu.focusedChild = this.currentPopup.from_item;
parentMenu.focusedChild._setSelected(true);
// cancel the pending close
this._stopPendingCloseTimer(this.currentPopup);
}
},
onItemHover: function(/*MenuItem*/ item){
// summary:
// Called when cursor is over a MenuItem.
// tags:
// protected
// Don't do anything unless user has "activated" the menu by:
// 1) clicking it
// 2) opening it from a parent menu (which automatically focuses it)
if(this.isActive){
this.focusChild(item);
if(item.popup && !item.disabled && !this.hover_timer){
this.hover_timer = this.defer(lang.hitch(this, "_openPopup", item), this.popupDelay);
}
}
// if the user is mixing mouse and keyboard navigation,
// then the menu may not be active but a menu item has focus,
// but it's not the item that the mouse just hovered over.
// To avoid both keyboard and mouse selections, use the latest.
if(this.focusedChild){
this.focusChild(item);
}
this._hoveredChild = item;
item._set("hovering", true);
},
_onChildBlur: function(item){
// summary:
// Called when a child MenuItem becomes inactive because focus
// has been removed from the MenuItem *and* it's descendant menus.
// tags:
// private
this._stopPopupTimer();
item._setSelected(false);
// Close all popups that are open and descendants of this menu
var itemPopup = item.popup;
if(itemPopup){
this._stopPendingCloseTimer(itemPopup);
itemPopup._pendingClose_timer = this.defer(function(){
itemPopup._pendingClose_timer = null;
if(itemPopup.parentMenu){
itemPopup.parentMenu.currentPopup = null;
}
pm.close(itemPopup); // this calls onClose
}, this.popupDelay);
}
},
onItemUnhover: function(/*MenuItem*/ item){
// summary:
// Callback fires when mouse exits a MenuItem
// tags:
// protected
if(this.isActive){
this._stopPopupTimer();
}
if(this._hoveredChild == item){
this._hoveredChild = null;
}
item._set("hovering", false);
},
_stopPopupTimer: function(){
// summary:
// Cancels the popup timer because the user has stop hovering
// on the MenuItem, etc.
// tags:
// private
if(this.hover_timer){
this.hover_timer = this.hover_timer.remove();
}
},
_stopPendingCloseTimer: function(/*dijit/_WidgetBase*/ popup){
// summary:
// Cancels the pending-close timer because the close has been preempted
// tags:
// private
if(popup._pendingClose_timer){
popup._pendingClose_timer = popup._pendingClose_timer.remove();
}
},
_stopFocusTimer: function(){
// summary:
// Cancels the pending-focus timer because the menu was closed before focus occured
// tags:
// private
if(this._focus_timer){
this._focus_timer = this._focus_timer.remove();
}
},
_getTopMenu: function(){
// summary:
// Returns the top menu in this chain of Menus
// tags:
// private
for(var top = this; top.parentMenu; top = top.parentMenu){
;
}
return top;
},
onItemClick: function(/*dijit/_WidgetBase*/ item, /*Event*/ evt){
// summary:
// Handle clicks on an item.
// tags:
// private
// this can't be done in _onFocus since the _onFocus events occurs asynchronously
if(typeof this.isShowingNow == 'undefined'){ // non-popup menu
this._markActive();
}
this.focusChild(item);
if(item.disabled){
return false;
}
if(item.popup){
this._openPopup(item, /^key/.test(evt.type));
}else{
// before calling user defined handler, close hierarchy of menus
// and restore focus to place it was when menu was opened
this.onExecute();
// user defined handler for click
item._onClick ? item._onClick(evt) : item.onClick(evt);
}
},
_openPopup: function(/*dijit/MenuItem*/ from_item, /*Boolean*/ focus){
// summary:
// Open the popup to the side of/underneath the current menu item, and optionally focus first item
// tags:
// protected
this._stopPopupTimer();
var popup = from_item.popup;
if(!popup.isShowingNow){
if(this.currentPopup){
this._stopPendingCloseTimer(this.currentPopup);
pm.close(this.currentPopup);
}
popup.parentMenu = this;
popup.from_item = from_item; // helps finding the parent item that should be focused for this popup
var self = this;
pm.open({
parent: this,
popup: popup,
around: from_item.domNode,
orient: this._orient || ["after", "before"],
onCancel: function(){ // called when the child menu is canceled
// set isActive=false (_closeChild vs _cleanUp) so that subsequent hovering will NOT open child menus
// which seems aligned with the UX of most applications (e.g. notepad, wordpad, paint shop pro)
self.focusChild(from_item); // put focus back on my node
self._cleanUp(); // close the submenu (be sure this is done _after_ focus is moved)
from_item._setSelected(true); // oops, _cleanUp() deselected the item
self.focusedChild = from_item; // and unset focusedChild
},
onExecute: lang.hitch(this, "_cleanUp")
});
this.currentPopup = popup;
this.currentPopupParent = from_item;
// detect mouseovers to handle lazy mouse movements that temporarily focus other menu items
popup.own(on(popup.domNode, "mouseenter", lang.hitch(self, "_onPopupHover"))); // cleaned up when the popped-up widget is destroyed on close
}
if(focus && popup.focus){
// If user is opening the popup via keyboard (right arrow, or down arrow for MenuBar), then focus the popup.
// If the cursor happens to collide with the popup, it will generate an onmouseover event
// even though the mouse wasn't moved. Use defer() to call popup.focus so that
// our focus() call overrides the onmouseover event, rather than vice-versa. (#8742)
popup._focus_timer = this.defer(lang.hitch(popup, function(){
this._focus_timer = null;
this.focus();
}));
}
},
_markActive: function(){
// summary:
// Mark this menu's state as active.
// Called when this Menu gets focus from:
//
// 1. clicking it (mouse or via space/arrow key)
// 2. being opened by a parent menu.
//
// This is not called just from mouse hover.
// Focusing a menu via TAB does NOT automatically set isActive
// since TAB is a navigation operation and not a selection one.
// For Windows apps, pressing the ALT key focuses the menubar
// menus (similar to TAB navigation) but the menu is not active
// (ie no dropdown) until an item is clicked.
this.isActive = true;
domClass.replace(this.domNode, "dijitMenuActive", "dijitMenuPassive");
},
onOpen: function(/*Event*/ /*===== e =====*/){
// summary:
// Callback when this menu is opened.
// This is called by the popup manager as notification that the menu
// was opened.
// tags:
// private
this.isShowingNow = true;
this._markActive();
},
_markInactive: function(){
// summary:
// Mark this menu's state as inactive.
this.isActive = false; // don't do this in _onBlur since the state is pending-close until we get here
domClass.replace(this.domNode, "dijitMenuPassive", "dijitMenuActive");
},
onClose: function(){
// summary:
// Callback when this menu is closed.
// This is called by the popup manager as notification that the menu
// was closed.
// tags:
// private
this._stopFocusTimer();
this._markInactive();
this.isShowingNow = false;
this.parentMenu = null;
},
_closeChild: function(){
// summary:
// Called when submenu is clicked or focus is lost. Close hierarchy of menus.
// tags:
// private
this._stopPopupTimer();
if(this.currentPopup){
// If focus is on a descendant MenuItem then move focus to me,
// because IE doesn't like it when you display:none a node with focus,
// and also so keyboard users don't lose control.
// Likely, immediately after a user defined onClick handler will move focus somewhere
// else, like a Dialog.
if(this.focused){
domAttr.set(this.currentPopupParent.focusNode, "tabIndex", this.tabIndex);
this.currentPopupParent.focusNode.focus();
}
// Close all popups that are open and descendants of this menu
pm.close(this.currentPopup);
this.currentPopup = this.currentPopupParent = null;
}
if(this.focusedChild){ // unhighlight the focused item
this.focusedChild._setSelected(false);
this.onItemUnhover(this.focusedChild);
}
// Repeat what _KeyNavContainer.onBlur() does, so that the MenuBar gets treated as blurred even though the user
// hasn't clicked or focused anywhere outside of the MenuBar yet. Otherwise, the Menu code gets confused since
// the menu is in a passive state but this.focusedChild is still set.
domAttr.set(this.domNode, "tabIndex", this.tabIndex);
if(this.focusedChild){
this.focusedChild.set("tabIndex", "-1");
this._set("focusedChild", null);
}
},
_onItemFocus: function(/*MenuItem*/ item){
// summary:
// Called when child of this Menu gets focus from:
//
// 1. clicking it
// 2. tabbing into it
// 3. being opened by a parent menu.
//
// This is not called just from mouse hover.
if(this._hoveredChild && this._hoveredChild != item){
this.onItemUnhover(this._hoveredChild); // any previous mouse movement is trumped by focus selection
}
},
_onBlur: function(){
// summary:
// Called when focus is moved away from this Menu and it's submenus.
// tags:
// protected
this._cleanUp();
this.inherited(arguments);
},
_cleanUp: function(){
// summary:
// Called when the user is done with this menu. Closes hierarchy of menus.
// tags:
// private
this._closeChild(); // don't call this.onClose since that's incorrect for MenuBar's that never close
if(typeof this.isShowingNow == 'undefined'){ // non-popup menu doesn't call onClose
this._markInactive();
}
}
});
});
|
import { vec2, vec3, vec4, quat, mat4 } from 'gl-matrix';
import toNDC from '../../util/toNDC';
export default class RotateMode {
constructor(entity, ndc, alignAxis = null) {
this.entity = entity;
this.startQuat = quat.create();
this.mouseHeld = true;
this.ndc = ndc;
this.angle = 0;
this.lastAngle = 0;
this.align = alignAxis != null;
this.alignAxis = alignAxis || [1, 1, 1];
this.alignGlobal = false;
}
enter(manager) {
this.manager = manager;
this.engine = manager.engine;
this.renderer = manager.renderer;
this.engine.actions.renderer.effect.add('axis');
this.setEffect();
let matrixSys = this.engine.systems.matrix;
let mat = matrixSys.get(this.entity);
mat4.getRotation(this.startQuat, mat);
quat.normalize(this.startQuat, this.startQuat);
this.camera = this.engine.systems.renderer.viewportList[0].camera;
let perspPos = vec4.fromValues(0, 0, 0, 1);
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.matrix.get(this.entity));
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.cameraMatrix.getProjectionView(this.camera));
let aspect = this.engine.systems.cameraMatrix.getCurrentAspect(this.camera);
vec4.scale(perspPos, perspPos, 1 / perspPos[3]);
vec2.subtract(perspPos, this.ndc, perspPos);
this.lastAngle = Math.atan2(perspPos[1], perspPos[0] * aspect);
}
exit() {
// Remove axis effect
this.engine.actions.renderer.effect.remove('axis');
}
setEffect() {
this.renderer.effects.axis.direction = this.align ? this.alignAxis : null;
this.renderer.effects.axis.color = this.align && this.alignAxis.concat([1]);
}
setRotation() {
let tmpQuat = quat.create();
let axis = this.alignAxis;
let modifier = 1;
// Shoot a ray from camera to model
let matrixSys = this.engine.systems.matrix;
let cameraPos = matrixSys.getPosition(this.camera);
let entityPos = matrixSys.getPosition(this.entity);
let cameraRay = vec3.create();
vec3.subtract(cameraRay, cameraPos, entityPos);
vec3.normalize(cameraRay, cameraRay);
if (!this.align) {
axis = cameraRay;
} else {
// Compare align axis and camera axis
let cos = vec3.dot(axis, cameraRay);
if (cos < 0) modifier = -1;
}
// Convert it to local space (if any)
let parentMat = matrixSys.getParent(this.entity);
let parentQuat = quat.create();
mat4.getRotation(parentQuat, parentMat);
quat.normalize(parentQuat, parentQuat);
quat.conjugate(parentQuat, parentQuat);
quat.setAxisAngle(tmpQuat, axis, this.angle * modifier);
quat.multiply(tmpQuat, parentQuat, tmpQuat);
quat.multiply(tmpQuat, tmpQuat, this.startQuat);
this.engine.actions.external.execute('transform.setRotation',
this.entity, tmpQuat);
}
mousemove(e) {
let ndc = toNDC(e.clientX, e.clientY, this.renderer);
this.ndc = ndc;
// Get angle :S
let perspPos = vec4.fromValues(0, 0, 0, 1);
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.matrix.get(this.entity));
vec4.transformMat4(perspPos, perspPos,
this.engine.systems.cameraMatrix.getProjectionView(this.camera));
vec4.scale(perspPos, perspPos, 1 / perspPos[3]);
let aspect = this.engine.systems.cameraMatrix.getCurrentAspect(this.camera);
vec2.subtract(perspPos, this.ndc, perspPos);
let angle = Math.atan2(perspPos[1], perspPos[0] * aspect);
let diff = angle - this.lastAngle;
if (diff > Math.PI) diff -= Math.PI * 2;
if (diff < -Math.PI) diff += Math.PI * 2;
this.angle += diff;
this.lastAngle = angle;
this.setRotation();
}
mouseup(e) {
if (e.buttons === 0) this.manager.pop();
}
keydown(e) {
if (e.keyCode === 27) {
this.engine.actions.external.execute('transform.setRotation',
this.entity, this.startQuat, true);
this.manager.pop();
} else if (e.keyCode === 67) {
this.align = false;
this.alignAxis = [1, 1, 1];
this.setRotation();
this.setEffect();
} else if (e.keyCode === 88) {
this.align = true;
this.alignAxis = [1, 0, 0];
this.setRotation();
this.setEffect();
} else if (e.keyCode === 89) {
this.align = true;
this.alignAxis = [0, 1, 0];
this.setRotation();
this.setEffect();
} else if (e.keyCode === 90) {
this.align = true;
this.alignAxis = [0, 0, 1];
this.setRotation();
this.setEffect();
}
}
}
|
import Relay from 'react-relay/classic';
class FindPublicTeamRoute extends Relay.Route {
static queries = {
team: () => Relay.QL`query FindPublicTeam { find_public_team(slug: $teamSlug) }`,
};
static paramDefinitions = {
teamSlug: { required: true },
};
static routeName = 'FindPublicTeamRoute';
}
export default FindPublicTeamRoute;
|
'use strict';
describe('Authentication Identity Specification', function()
{
var _authIdentity;
var _httpBackend;
var _identity = {
key1: 'value1',
key2: 'value2',
key3: {
subKey1: 'subValue1',
subKey2: 'subValue2'
}
};
var _authRequests;
beforeEach(angular.mock.module('dgAuth'));
beforeEach(function()
{
inject(function($injector)
{
_authIdentity = $injector.get('authIdentity');
_authRequests = $injector.get('authRequests');
_httpBackend = $injector.get('$httpBackend');
var http = $injector.get('$http');
spyOn(_authRequests, 'getPromise').andCallFake(function()
{
return http.post('/fake');
});
_httpBackend.whenPOST('/fake').respond(function()
{
return [201, '', ''];
});
});
});
afterEach(function()
{
_httpBackend.verifyNoOutstandingExpectation();
_httpBackend.verifyNoOutstandingRequest();
});
describe('tests access methods', function()
{
it('should get null values', function()
{
expect(_authIdentity.has()).toBeFalsy();
expect(_authIdentity.get()).toBeNull();
expect(_authIdentity.get('some_key')).toBeNull();
});
it('should set the values and gets them', function()
{
_authIdentity.set(null, _identity);
expect(_authIdentity.has()).toBeTruthy();
expect(_authIdentity.get('key1')).toEqual(_identity.key1);
expect(_authIdentity.get('key2')).toEqual(_identity.key2);
expect(_authIdentity.get('key3')).toEqual(_identity.key3);
expect(_authIdentity.get('fake')).toBeNull();
expect(_authIdentity.get()).toEqual(_identity);
});
it('should set one value and gets it', function()
{
_authIdentity.set('key', 'value');
expect(_authIdentity.has()).toBeTruthy();
expect(_authIdentity.get('key')).toEqual('value');
_authIdentity.set(null, _identity);
expect(_authIdentity.get()).toEqual(_identity);
expect(_authIdentity.get('key')).toBeNull();
});
it('should clear the identity', function()
{
_authIdentity.set(null, _identity);
expect(_authIdentity.has()).toBeTruthy();
_authIdentity.clear();
expect(_authIdentity.has()).toBeFalsy();
expect(_authIdentity.get()).toBeNull();
});
});
});
|
angular.module('keyringLogin', ['auth'])
.component('keyringLogin', {
templateUrl : 'users/login',
controllerAs: 'login',
controller: ['$scope', '$http', '$location', '$httpParamSerializerJQLike', 'auth', function($scope, $http, $location, $httpParamSerializerJQLike, auth) {
this.username = '';
this.password = '';
this.submit = function(e, url) {
var url = e.target.action;
e.preventDefault();
e.stopPropagation();
$http({
method: 'POST',
url: url,
data: $httpParamSerializerJQLike({
username: this.username,
password: this.password
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
auth.setToken(data.token);
$location.path('/');
}).error(function(e) {
this.error = e;
}.bind(this));
return false;
};
}]
})
|
var ffi = require('ffi'),
ref = require('ref'),
RefArray = require('ref-array'),
Struct = require('ref-struct'),
Union = require('ref-union'),
_library = require('./');
loadDependentSymbols();
_library._preload['the_dependent'] = [function () {
_library.the_dependent = _library.dependent;
}];
_library.my_enum = {
five: 555,
VAR_THREE: 24,
VAR_TWO: 23,
VAR_FOUR: 25,
VAR_ONE: -1
};
_library._preload['my_function'] = [function () {
_library.my_function = ['double', ['int32', 'int', ref.refType('uint'), 'float']];
_library._functions['my_function'] = _library.my_function;
}];
_library._preload['my_other_function'] = ['pointer', function () {
_library.my_other_function = [ref.refType('double'), [ref.refType('int32'), ref.refType('int'), ref.refType(ref.refType('uint')), ref.refType('float')]];
_library._functions['my_other_function'] = _library.my_other_function;
}];
_library.nothing = Struct({});
_library.nothing.size = 1;
_library._preload['nothing'] = [function () {
_library.nothing.size = 0;
_library.nothing.defineProperty("__ignore", 'char');
}];
_library._preload['nill'] = [function () {
_library.nill = _library.nothing;
}];
_library._preload['zilch'] = ['nill', function () {
_library.zilch = _library.nill;
}];
_library.something = Struct({});
_library.something.size = 1;
_library._preload['something'] = ['nothing', 'nothing', 'dependent', 'dependent', function () {
_library.something.size = 0;
_library.something.defineProperty("field", 'int');
_library.something.defineProperty("another", 'int32');
_library.something.defineProperty("firstfield", _library.__RefArray('int', 4));
_library.something.defineProperty("message", ref.refType('char'));
_library.something.defineProperty("nillo", _library.nothing);
_library.something.defineProperty("dependent", _library.dependent);
}];
_library.flying_struct = Struct({});
_library.flying_struct.size = 1;
_library._preload['flying_struct'] = ['something', 'something', 'flying_struct', function () {
_library.flying_struct.size = 0;
_library.flying_struct.defineProperty("identity", 'longlong');
_library.flying_struct.defineProperty("object", _library.something);
_library.flying_struct.defineProperty("recursive_pointer", ref.refType(_library.flying_struct));
}];
_library._preload['invasion_force'] = [function () {
_library.invasion_force = _library.__RefArray(_library.flying_struct, 64);
}];
_library.variant1 = Union({});
_library.variant1.size = 1;
_library._preload['variant1'] = ['flying_struct', 'flying_struct', 'something', 'something', 'zilch', 'nothing', function () {
_library.variant1.size = 0;
_library.variant1.defineProperty("val1", _library.flying_struct);
_library.variant1.defineProperty("val2", _library.something);
_library.variant1.defineProperty("val3", _library.zilch);
}];
_library.variant2 = Union({});
_library.variant2.size = 1;
_library._preload['variant2'] = ['variant1', 'variant1', 'stat', 'stat', function () {
_library.variant2.size = 0;
_library.variant2.defineProperty("v1", _library.variant1);
_library.variant2.defineProperty("v2", _library.__RefArray('int', 5));
_library.variant2.defineProperty("str", (function () {
var temp = Struct({});
temp.defineProperty("text", ref.refType('char'));
temp.defineProperty("length", 'ulong');
return temp;
})());
_library.variant2.defineProperty("gs", _library.stat);
}];
_library._preload['my_function_pointer'] = ['void (int, int *, struct flying_struct *)', function () {
_library.my_function_pointer = ffi.Function('void', ['int', ref.refType('int'), ref.refType(_library.flying_struct)]);
}];
_library._preload['my_other_function_pointer'] = ['unsigned int (long double, long double, long long)', function () {
_library.my_other_function_pointer = ffi.Function('uint', ['double', 'double', 'longlong']);
}];
_library._preload['my_undefined_struct_typedef'] = [function () {
_library.my_undefined_struct_typedef = 'void';
}];
_library._preload['my_struct_function'] = ['variant1', function () {
_library.my_struct_function = ['void', [ref.refType(_library.variant1)]];
_library._functions['my_struct_function'] = _library.my_struct_function;
}];
_library.my_unused_struct = Struct({});
_library.my_unused_struct.size = 1;
_library._preload['my_unused_struct'] = [function () {
_library.my_unused_struct.size = 0;
_library.my_unused_struct.defineProperty("a", 'int');
}];
function loadDependentSymbols() {
require('./used.js');
}
|
/**
* Created by ZhiyuanSun on 16/9/22.
*/
import React, {Component} from 'react';
import EventSelectionItemImage from './event-selection-item-image';
export default class EventSelectionItem extends Component{
static defaultProps = {
showImage: false,
lazyLoading: false
};
constructor(props){
super(props);
this.state = {
showImage: false
}
}
componentWillMount(){
}
componentWillUpdate(){
}
componentDidMount(){
}
render(){
let {item, lazyLoading} = this.props;
return (
<li>
<a href={item.url}>
<EventSelectionItemImage {...this.props} img={item.img}></EventSelectionItemImage>
<p>{item.description}</p>
</a>
</li>
);
}
}
|
new (require('front.js').Front)().init().start();
|
System.register([], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var RestMethod;
return {
setters: [],
execute: function () {
(function (RestMethod) {
RestMethod[RestMethod["POST"] = 0] = "POST";
RestMethod[RestMethod["GET"] = 1] = "GET";
RestMethod[RestMethod["PUT"] = 2] = "PUT";
RestMethod[RestMethod["DELETE"] = 3] = "DELETE";
})(RestMethod || (RestMethod = {}));
exports_1("RestMethod", RestMethod);
}
};
});
//# sourceMappingURL=type-rest-method.js.map
|
(function () {
"use strict";
// ReSharper disable once UndeclaredGlobalVariableUsing
angular
.module("umbraco.resources")
.filter("ujetAsGroup", ujetAsGroupFilter);
function ujetAsGroupFilter() {
return function (object) {
object.label = object.name;
return object;
};
};
})();
|
var _ = require('@sailshq/lodash');
var async = require('async');
var Promise = require('bluebird');
module.exports = function(self, options) {
// Every time a doc is saved, check whether its type is included in
// workflow. If so invoke `ensureWorkflowLocale` and
// `ensurePageSlugPrefix`.
self.docBeforeSave = function(req, doc, options) {
if (!self.includeType(doc.type)) {
return;
}
self.ensureWorkflowLocale(req, doc);
self.ensurePageSlugPrefix(doc);
};
// Every time a doc is saved, check whether its type is included in workflow. If it is,
// check for locales in which that workflowGuid does not exist yet, and bring it into existence
// there.
//
// These newly created docs in other locales are initially trash so they
// don't clutter reorganize as "unpublished."
//
// If `options.workflowMissingLocalesLocales` is set to an array of locales, the
// document is exported if needed only to those locales. Otherwise, by default,
// the document is exported if needed to all locales. If `replicateAcrossLocales` is
// `false` as a module-level option, it is replicated only between "draft" and "live"
// unless it is a parked page.
self.docAfterSave = function(req, doc, options, callback) {
var missingLocales;
if (doc._workflowPropagating) {
// Recursion guard
return callback(null);
}
if (!self.includeType(doc.type)) {
return callback(null);
}
return async.series([
findMissingLocales,
insertInMissingLocales,
permissionsAcrossLocales
], function(err) {
if (err) {
self.apos.utils.error(err);
}
return callback(err);
});
function findMissingLocales(callback) {
var criteria = {
workflowGuid: doc.workflowGuid,
workflowLocale: { $in: relevantLocales() }
};
return self.apos.docs.db.findWithProjection(criteria, { workflowLocale: 1 }).toArray(function(err, docs) {
if (err) {
return callback(err);
}
var locales = _.pluck(docs, 'workflowLocale');
missingLocales = _.filter(relevantLocales(), function(locale) {
if (_.contains(locales, locale)) {
return false;
}
return true;
});
return callback(null);
});
function relevantLocales() {
var candidates;
if (options.workflowMissingLocalesLocales) {
candidates = options.workflowMissingLocalesLocales;
} else {
candidates = _.keys(self.locales);
if ((!options.forceReplicate) && (!self.replicates(req, doc))) {
// We are not auto-replicating across locales, but we are still
// maintaining at least draft/live relationship for all workflow docs
candidates = [ self.draftify(doc.workflowLocale), self.liveify(doc.workflowLocale) ];
}
}
return _.filter(candidates, function(locale) {
if (locale === doc.workflowLocale) {
return false;
}
if (options.workflowMissingLocalesSubset === 'draft') {
if (!locale.match(/-draft$/)) {
return false;
}
}
if (options.workflowMissingLocalesSubset === 'live') {
if (locale.match(/-draft$/)) {
return false;
}
}
if (options.workflowMissingLocalesDescendantsOf) {
if (!self.isAncestorOf(options.workflowMissingLocalesDescendantsOf, locale)) {
return false;
}
}
return true;
});
}
}
function insertInMissingLocales(callback) {
if (!missingLocales.length) {
return callback(null);
}
// A new doc needs to be brought into existence across all locales.
// For performance, do this with a moderate degree of parallelism
return async.eachLimit(missingLocales, 5, function(locale, callback) {
var _doc = self.apos.utils.clonePermanent(doc);
if (locale === doc.workflowLocale) {
return setImmediate(callback);
}
// Strip the prefix that came from the originating locale
// so that the new locale can prepend its own successfully
var prefix = self.prefixes && self.prefixes[self.liveify(_doc.workflowLocale)];
if (prefix && (_doc.slug.indexOf(prefix) === 0)) {
_doc.slug = _doc.slug.substr(prefix.length);
}
delete _doc._id;
_doc.workflowLocale = locale;
_doc._workflowPropagating = true;
// Otherwise you can make something happen in public across
// all locales just by creating a new doc
// and watching it propagate.
//
// If the doc in question is the home page or global doc let it through
// for chicken and egg reasons. If the page is any other page trash it
// in the other locales, it can be activated for those locales later
// by removing it from the trash, or via exporting to it, which will
// export the fact that it is not trash.
if ((_doc.level === 0) || _doc.parked) {
// Let it through: for chicken and egg reasons, the home page
// exists in published form right away in all locales.
// Ditto any parked page
} else if (_doc.slug === 'global') {
// The global doc
} else if (options.workflowDefaultLocaleNotTrash && (doc.workflowLocale === self.defaultLocale)) {
// In default locale, and we've received the flag to ensure that is not in the trash; this flag
// is used when adding workflow for the first time, because it is the sensible migration path
// for a site that did not have workflow before
} else if ((options.workflowMissingLocalesLive === 'liveOnly') ||
(self.isAncestorOf(doc.workflowLocale, _doc.workflowLocale) && _doc.workflowLocale.match(/-draft$/))) {
// If it's a draft let it through matching the parent, otherwise
// start it in the trash. This is the least confusing behavior
// for the add-missing-locales task, or for manual creation of
// a new doc in the default locale.
if (!_doc.workflowLocale.match(/-draft$/)) {
_doc.trash = true;
}
} else if (!options.workflowMissingLocalesLive) {
_doc.trash = true;
}
self.ensureWorkflowLocaleForPathIndex(_doc);
return async.series([
resolve,
insert
], callback);
function resolve(callback) {
if (options.workflowResolveDeferred || _doc.workflowResolveDeferred) {
return callback(null);
}
return self.resolveRelationships(req, _doc, _doc.workflowLocale, callback);
}
function insert(callback) {
// This is tricky: for pieces, we need the beforeInsert/afterInsert etc.
// callbacks to run. Whereas for pages, not all of those exist, and those
// that do are methods of the pages module, not the manager for a
// particular page type.
var manager = self.apos.docs.getManager(_doc.type);
if (self.apos.instanceOf(manager, 'apostrophe-custom-pages')) {
// All page type managers extend apostrophe-custom-pages (eventually)
return async.series([ fixTree, beforeInsert, beforeSave, insertDoc ], callback);
} else if (manager.insert) {
// A piece, or something else with a direct insert method;
// simple
return manager.insert(req, _doc, { permissions: false, workflowMissingLocalesLive: options.workflowMissingLocalesLive }, callback);
} else {
// Something Else. Currently, nothing in this category, but
// inserting via docs.insert is a good fallback
return insertDoc(callback);
}
function fixTree(callback) {
if ((self.options.replicateAcrossLocales === true) || _doc.parkedId) {
// This is not necessary if we are replicating 100% of the time, could
// cause unnecessary peer order changes, and will lead to errors if we don't replicate
// in tree order, so skip it.
//
// Also unnecessary for parked pages because they are guaranteed to
// exist across all locales by the end of the replication.
return callback(null);
}
// Make the child a subpage of the closest ancestor that actually exists
// in the destination locale. The immediate parent might not exist
// if `replicateAcrossLocales` is `false`.
//
// If the parent does not change, we still need to reset the rank.
// Figuring out if various peers are exported or not would be
// expensive, and in a typical batch export or even manual export
// situation things will happen in the right order.
var components = _doc.path.split('/');
if (!_doc.level) {
// Homepage has no parent
return callback(null);
}
var paths = [];
var path = '';
_.each(components, function(component) {
path += component;
// Special case: the path of the homepage
// is /, not an empty string
var queryPath = path;
if (queryPath === '') {
queryPath = '/';
}
// Don't redundantly load ourselves
if (queryPath === _doc.path) {
return;
}
paths.push(queryPath);
path += '/';
});
return self.apos.docs.db.find({
path: {
$in: paths
},
workflowLocale: _doc.workflowLocale
}).project({
path: 1,
level: 1
}).sort({
path: -1
}).limit(1).toArray(function(err, pages) {
if (err) {
return callback(err);
}
if (!pages.length) {
return callback(new Error('Non-home page has no parent, should not be possible: ' + self.options.replicateAcrossLocales));
}
const newParent = pages[pages.length - 1];
const newPath = self.apos.utils.addSlashIfNeeded(newParent.path) + require('path').basename(_doc.path);
// Even though the parent may not have changed, we still need to fix the rank,
// so keep going on this path either way
_doc.path = newPath;
_doc.level = newParent.level + 1;
// Now we need to make it the last subpage of the new parent
const matchNewPeers = new RegExp('^' + self.apos.utils.regExpQuote(self.apos.utils.addSlashIfNeeded(newParent.path)));
return self.apos.docs.db.find({
path: matchNewPeers,
level: newParent.level + 1,
workflowLocale: _doc.workflowLocale
}).project({ _id: 1, rank: 1 }).sort({ rank: -1 }).limit(1).toArray(function(err, previous) {
if (err) {
return callback(err);
}
previous = previous[0];
if (previous) {
_doc.rank = (previous.rank || 0) + 1;
} else {
_doc.rank = 0;
}
return callback(null);
});
});
}
function beforeInsert(callback) {
return self.apos.pages.beforeInsert(req, _doc, { permissions: false, workflowMissingLocalesLive: options.workflowMissingLocalesLive }, callback);
}
function beforeSave(callback) {
return self.apos.pages.beforeSave(req, _doc, { permissions: false, workflowMissingLocalesLive: options.workflowMissingLocalesLive }, callback);
}
function insertDoc(callback) {
return self.apos.docs.insert(req, _doc, { permissions: false, workflowMissingLocalesLive: options.workflowMissingLocalesLive }, callback);
}
}
}, callback);
}
function permissionsAcrossLocales(callback) {
// If I can edit a specific page in ch-fr, I can also edit that same page in gb-en,
// PROVIDED THAT I can edit pages in gb-en at all (we have locale-specific
// permission checks). This eliminates complexities in the permissions interface.
if (!doc.docPermissions) {
return callback(null);
}
return self.apos.docs.db.update({
workflowGuid: doc.workflowGuid
}, {
$set: {
'loginRequired': doc.loginRequired,
'viewUsersIds': doc.viewUsersIds || [],
'viewGroupsIds': doc.viewGroupsIds || [],
'editUsersIds': doc.editUsersIds || [],
'editGroupsIds': doc.editGroupsIds || [],
'viewUsersRelationships': doc.viewUsersRelationships || {},
'viewGroupsRelationships': doc.viewGroupsRelationships || {},
'editUsersRelationships': doc.editUsersRelationships || {},
'editGroupsRelationships': doc.editGroupsRelationships || {},
'docPermissions': doc.docPermissions
}
}, {
multi: true
}, callback);
}
};
self.pageBeforeSend = function(req, callback) {
self.apos.templates.addBodyDataAttribute(req, 'locale', req.locale);
// If looking at a live locale, disable inline editing
// Also adds a class on <body> for both workflow modes
if (req.user) {
var workflowMode = req.session.workflowMode;
req.data.workflowPreview = req.session.workflowPreview;
if (workflowMode === 'live' || req.session.workflowPreview) {
req.disableEditing = true;
}
self.apos.templates.addBodyClass(req, 'apos-workflow-' + workflowMode + '-page');
}
// Pass on `data.workflow.context` which will be the page or piece
// the user thinks of as the "context" for the current page rendering
var context = self.getContext(req);
if (context && context.workflowGuid) {
req.data.workflow.context = context;
}
req.data.workflow.locale = self.liveify(req.locale);
return async.series([
getLocalizations,
userOnly
], callback);
function getLocalizations(callback) {
if (!(req.data.workflow.context && req.data.workflow.context.workflowGuid)) {
return callback(null);
}
return self.getLocalizations(req, req.data.workflow.context.workflowGuid, false, function(err, localizations) {
if (err) {
return callback(err);
}
req.data.workflow.localizations = localizations;
return callback(null);
});
}
function userOnly(callback) {
var id;
// If we're not logged in, this is as far as we need to go
if (!req.user) {
return callback(null);
}
// Invoke pushCreateSingleton after we have all this groovy information,
// so we get options.localizations on the browser side to power the
// locale picker modal
self.pushCreateSingleton(req);
if (req.query.workflowPreview) {
req.disableEditing = true;
id = self.apos.launder.id(req.query.workflowPreview);
self.apos.templates.addBodyClass(req, 'apos-workflow-preview-page');
req.browserCall('apos.modules["apostrophe-workflow"].enablePreviewIframe({ id: ? })', id);
}
// If we're not reviewing an old commit, this is as far as
// we need to go
if (!req.query.workflowReview) {
return callback(null);
}
req.disableEditing = true;
// A commit id, not a doc id
id = self.apos.launder.id(req.query.workflowReview);
self.apos.templates.addBodyClass(req, 'apos-workflow-preview-page');
var commit;
var contexts = [];
return async.series([
findDocAndCommit,
after
], function(err) {
if (err) {
return callback(err);
}
req.browserCall('apos.modules["apostrophe-workflow"].enablePreviewIframe({ commitId: ? })', id);
return callback(null);
});
function findDocAndCommit(callback) {
return self.findDocAndCommit(req, id, function(err, _doc, _commit) {
if (err) {
return callback(err);
}
commit = _commit;
// Walk recursively through req.data looking for instances of the doc of interest.
// Working in place, modify them to be copies of commit.from, which will be
// an older version of the doc. Since we're working in place, make
// an array of these to pass to after() later for joining
contexts = [];
self.apos.docs.walk(req.data, function(o, k, v, dotPath) {
if (v && (typeof (v) === 'object')) {
if (v._id === commit.fromId) {
_.each(_.keys(v), function(key) {
delete v[key];
});
_.assign(v, commit.from);
contexts.push(v);
}
}
});
return callback(null);
});
}
function after(callback) {
return self.after(req, contexts, callback);
}
}
};
self.loginDeserialize = function(user) {
user._permissionsLocales = {};
_.each(user._groups, function(group) {
_.merge(user._permissionsLocales, group.permissionsLocales || {});
});
};
// An afterSave handler is a good place to set or clear the
// workflowModified flag because it guarantees any properties
// added by beforeSave handlers are taken into account. It would
// be nice if promise events had a way to say "after all the
// others," but they don't so far.
self.on('apostrophe-docs:afterSave', 'setWorkflowModified', function(req, doc, options) {
if (!self.includeType(doc.type)) {
return;
}
if (!(doc.workflowLocale && doc.workflowLocale.match(/-draft$/))) {
// Only interested in changes to drafts
return;
}
const isModified = Promise.promisify(self.isModified);
return isModified(req, doc).then(function(modified) {
// If there is no modification and that's not news, no update.
// Otherwise always update so we get the last editor's name
if ((modified === doc.workflowModified) && (!modified)) {
return;
}
const $set = {
workflowModified: modified
};
if (req.user && req.user._id && req.user.title) {
$set.workflowLastEditor = req.user.title;
$set.workflowLastEditorId = req.user._id;
}
return self.apos.docs.db.update({
_id: doc._id
}, {
$set: $set
});
});
});
};
|
const StdLib = require('@doctormckay/stdlib');
const SteamID = require('steamid');
const Helpers = require('./helpers.js');
const EMsg = require('../enums/EMsg.js');
const SteamUserEcon = require('./econ.js');
class SteamUserFamilySharing extends SteamUserEcon {
/**
* Add new borrowers.
* @param {SteamID[]|string[]|SteamID|string} borrowersSteamID
* @param {function} [callback]
* @returns {Promise}
*/
addAuthorizedBorrowers(borrowersSteamID, callback) {
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, true, (resolve, reject) => {
if (!Array.isArray(borrowersSteamID)) {
borrowersSteamID = [borrowersSteamID];
}
this._sendUnified('DeviceAuth.AddAuthorizedBorrowers#1', {
steamid: this.steamID.getSteamID64(),
steamid_borrower: borrowersSteamID.map(sid => Helpers.steamID(sid).getSteamID64())
}, (body, hdr) => {
let err = Helpers.eresultError(hdr.proto);
return err ? reject(err) : resolve();
});
});
};
/**
* Remove borrowers.
* @param {SteamID[]|string[]} borrowersSteamID
* @param {function} [callback]
* @returns {Promise}
*/
removeAuthorizedBorrowers(borrowersSteamID, callback) {
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, true, (resolve, reject) => {
if (!Array.isArray(borrowersSteamID)) {
return reject(new Error('The \'borrowersSteamID\' argument must be an array'));
}
this._sendUnified('DeviceAuth.RemoveAuthorizedBorrowers#1', {
steamid: this.steamID.getSteamID64(),
steamid_borrower: borrowersSteamID.map(sid => Helpers.steamID(sid).getSteamID64())
}, (body, hdr) => {
let err = Helpers.eresultError(hdr.proto);
return err ? reject(err) : resolve();
});
});
};
/**
* Retrieve a list of Steam accounts authorized to borrow your library.
* @param {{includeCanceled?: boolean, includePending?: boolean}} [options]
* @param {function} [callback]
* @returns {Promise}
*/
getAuthorizedBorrowers(options, callback) {
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, (resolve, reject) => {
if (typeof options == 'function') {
callback = options;
}
options = options || {};
this._sendUnified('DeviceAuth.GetAuthorizedBorrowers#1', {
steamid: this.steamID.getSteamID64(),
include_canceled: options.includeCanceled || false,
include_pending: options.includePending || false
}, (body, hdr) => {
let err = Helpers.eresultError(hdr.proto);
return err ? reject(err) : resolve({
borrowers: body.borrowers.map((borrower) => {
return {
steamid: new SteamID(borrower.steamid),
isPending: borrower.is_pending,
isCanceled: borrower.is_canceled,
timeCreated: new Date(borrower.time_created * 1000)
};
})
});
})
});
};
/**
* Get a list of devices we have authorized.
* @param {{includeCanceled?: boolean}} [options]
* @param {function} [callback]
* @returns {Promise}
*/
getAuthorizedSharingDevices(options, callback) {
if (typeof options == 'function') {
callback = options;
options = {};
}
options = options || {};
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, (resolve, reject) => {
this._sendUnified('DeviceAuth.GetOwnAuthorizedDevices#1', {
steamid: this.steamID.getSteamID64(),
includeCancelled: !!options.includeCanceled
}, (body, hdr) => {
let err = Helpers.eresultError(hdr.proto);
return err ? reject(err) : resolve({
devices: body.devices.map((device) => {
return {
deviceToken: device.auth_device_token,
deviceName: device.device_name,
isPending: device.is_pending,
isCanceled: device.is_canceled,
isLimited: device.is_limited,
lastTimeUsed: device.last_time_used ? new Date(device.last_time_used * 1000) : null,
lastBorrower: device.last_borrower_id && device.last_borrower_id != '76561197960265728' ? new SteamID(device.last_borrower_id) : null,
lastAppPlayed: device.last_app_played || null
};
})
});
});
});
};
/**
* Authorize local device for library sharing.
* @param {string} deviceName
* @param {function} [callback]
* @returns {Promise}
*/
authorizeLocalSharingDevice(deviceName, callback) {
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, true, (resolve, reject) => {
if (!deviceName) {
return reject(new Error('The \'deviceName\' argument is required.'));
}
this._send(EMsg.ClientAuthorizeLocalDeviceRequest, {
device_description: deviceName,
owner_account_id: this.steamID.accountid
}, (body) => {
let err = Helpers.eresultError(body.eresult);
return err ? reject(err) : resolve({deviceToken: body.authed_device_token});
});
});
};
/**
* Deauthorize a device from family sharing.
* @param {string|{deviceToken: string}} deviceToken
* @param {function} [callback]
*/
deauthorizeSharingDevice(deviceToken, callback) {
return StdLib.Promises.timeoutCallbackPromise(5000, null, callback, true, (resolve, reject) => {
if (typeof deviceToken == 'object' && typeof deviceToken.deviceToken == 'string') {
deviceToken = deviceToken.deviceToken;
}
if (typeof deviceToken != 'string') {
return reject(new Error('The \'deviceToken\' parameter is required.'));
}
this._send(EMsg.ClientDeauthorizeDeviceRequest, {
deauthorization_account_id: this.steamID.accountid,
deauthorization_device_token: deviceToken
}, (body) => {
let err = Helpers.eresultError(body.eresult);
return err ? reject(err) : resolve();
});
});
};
/**
* Use local device authorizations to allow usage of shared licenses.
* If successful, `licenses` will be emitted with the newly-acquired licenses.
* @param {SteamID|string} ownerSteamID
* @param {string|{deviceToken: string}} deviceToken
*/
activateSharingAuthorization(ownerSteamID, deviceToken) {
if (!ownerSteamID) {
throw new Error('The \'ownerSteamID\' argument is required.');
}
if (typeof deviceToken == 'object' && typeof deviceToken.deviceToken == 'string') {
deviceToken = deviceToken.deviceToken;
}
if (typeof deviceToken != 'string') {
throw new Error('The \'deviceToken\' argument is required.');
}
ownerSteamID = Helpers.steamID(ownerSteamID);
this._send(EMsg.ClientUseLocalDeviceAuthorizations, {
authorization_account_id: [ownerSteamID.accountid],
device_tokens: [{owner_account_id: ownerSteamID.accountid, token_id: deviceToken}]
});
};
/**
* Deactivate family sharing authorizations. Removes shared licenses.
*/
deactivateSharingAuthorization() {
this._send(EMsg.ClientUseLocalDeviceAuthorizations, {
authorization_account_id: [],
device_tokens: []
});
};
}
module.exports = SteamUserFamilySharing;
|
const { expect } = require('chai');
const nock = require('nock');
const timekeeper = require('timekeeper');
const jose2 = require('jose2');
const { Issuer } = require('../../lib');
const fail = () => {
throw new Error('expected promise to be rejected');
};
describe('Validating Self-Issued OP responses', () => {
afterEach(timekeeper.reset);
afterEach(nock.cleanAll);
before(function () {
const issuer = new Issuer({
authorization_endpoint: 'openid:',
issuer: 'https://self-issued.me',
scopes_supported: ['openid', 'profile', 'email', 'address', 'phone'],
response_types_supported: ['id_token'],
subject_types_supported: ['pairwise'],
id_token_signing_alg_values_supported: ['RS256'],
request_object_signing_alg_values_supported: ['none', 'RS256'],
registration_endpoint: 'https://self-issued.me/registration/1.0/',
});
const client = new issuer.Client({
client_id: 'https://rp.example.com/cb',
response_types: ['id_token'],
token_endpoint_auth_method: 'none',
id_token_signed_response_alg: 'ES256',
});
Object.assign(this, { issuer, client });
});
const idToken = (claims = {}) => {
const jwk = jose2.JWK.generateSync('EC');
return jose2.JWT.sign(
{
sub_jwk: jwk.toJWK(),
sub: jwk.thumbprint,
...claims,
},
jwk,
{ expiresIn: '2h', issuer: 'https://self-issued.me', audience: 'https://rp.example.com/cb' },
);
};
describe('consuming an ID Token response', () => {
it('consumes a self-issued response', function () {
const { client } = this;
return client.callback(undefined, { id_token: idToken() });
});
it('expects sub_jwk to be in the ID Token claims', function () {
const { client } = this;
return client
.callback(undefined, { id_token: idToken({ sub_jwk: undefined }) })
.then(fail, (err) => {
expect(err.name).to.equal('RPError');
expect(err.message).to.equal('missing required JWT property sub_jwk');
expect(err).to.have.property('jwt');
});
});
it('expects sub_jwk to be a public JWK', function () {
const { client } = this;
return client
.callback(undefined, { id_token: idToken({ sub_jwk: 'foobar' }) })
.then(fail, (err) => {
expect(err.name).to.equal('RPError');
expect(err.message).to.equal('failed to use sub_jwk claim as an asymmetric JSON Web Key');
expect(err).to.have.property('jwt');
});
});
it('expects sub to be the thumbprint of the sub_jwk', function () {
const { client } = this;
return client.callback(undefined, { id_token: idToken({ sub: 'foo' }) }).then(fail, (err) => {
expect(err.name).to.equal('RPError');
expect(err.message).to.equal('failed to match the subject with sub_jwk');
expect(err).to.have.property('jwt');
});
});
});
});
|
/**
* at test
* @authors yanjixiong
* @date 2016-10-11 11:02:10
*/
const should = require('should')
const at = require('../../common/at')
describe('test/common/at.test.js', function() {
describe('fetchUsers()', function() {
it('should return a names array', function(done) {
const names = at.fetchUsers('@foo @bar')
names.should.be.Array
done()
})
})
describe('linkUsers()', function() {
it('should return text contains `/u/` path ', function(done) {
const result = at.linkUsers('@foo @bar')
result.should.containEql('/u/')
done()
})
})
})
|
global.add = function(){
return 20;
}
|
'use strict';
/*
1. Переместите 0 в конец массива, остальные числа должны остаться
неизменными
.сoncat();
example:
[1,false,2,0,3,null,0,4,0,25] => [1, false, 2, 3, null, 4, 25, 0, 0, 0]
[ 'a', 0, 0, 'b', null, 'c', 'd', 0, 1, false, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9 ] => ["a","b",null,"c","d",1,false,1,3,[],1,9,{},9,0,0,0,0,0,0,0,0,0,0]
[ 0, 1, null, 2, false, 1, 0 ] => [1,null,2,false,1,0,0]
*/
let arr1 = [1, false, 2, 0, 3, null, 0, 4, 0, 25];
arr1 = [ 'a', 0, 0, 'b', null, 'c', 'd', 0, 1, false, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9 ];
function moveZeroToEnd(arr){
let lookingFor = 0;
let zeroArray = [];
for (let i = 0; i < arr.length;){
if (arr[i] === lookingFor){
arr.splice(i, 1);
zeroArray.push(lookingFor);
continue;
}
i++;
}
return arr.concat(zeroArray);
}
console.log(moveZeroToEnd(arr1));
/*
2. Верните сумму двух найменьших чисел в массиве
[10,20,30,1,31,11,10] => 11
[-1,0,25] => -1
[-4,-10,25,10] => -14
[0,200,10,25,15] => 10
*/
function orderNumbers(a, b){// WTF????
return a - b;
}
function minimalNumber(arr){
let a = arr.sort(orderNumbers);//Вот эту МАГИЮ Я РЕАЛЬНО НЕ ВКУРИЛ КАК ЭТО РАБОТЕТ???
return a.shift() + a.shift();
}
console.log(minimalNumber([10,20,30,1,31,11,10]));
/*
3. Напишите функцию которая меняет местами имя и фамилию
nameShuffler('john McClane'); => "McClane john"
nameShuffler('Arnold Schwarzenegger'); => "Schwarzenegger Arnold"
nameShuffler('James Bond'); => "Bond James"
*/
function nameShuffler(name){
return name.split(' ').reverse().join(' ');
}
console.log(nameShuffler('john McClane'));
console.log(nameShuffler('Arnold Schwarzenegger'));
console.log(nameShuffler('James Bond'));
/*
// !
4. Напишите функцию которая принимает массив с именами и возвращает массив
в котором каждая буква становится заглавной
capMe(['jo', 'nelson', 'jurie']) // returns ['Jo', 'Nelson', 'Jurie']
capMe(['KARLY', 'DANIEL', 'KELSEY']) // returns ['Karly', 'Daniel', 'Kelsey']
*/
function capMe(arr){
for (var i = 0; i < arr.length; i++){
arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1).toLowerCase();
}
return arr;
}
console.log(capMe(['KARLY', 'DANIEL', 'KELSEY']));
console.log(capMe(['jo', 'nelson', 'jurie']));
//@SUPER
/*
1. Найдите число отсутствующее в заданной последовательности
example:
[1,3,5,9] => 7
[0,8,16,32] => 24
[4, 6, 8, 10] => 2 // число сначала
[0,16,24,32] => 8
*/
function steps(arr){
let maxStep = 0;
let index = 0;
if (arr[0] !== 0){
arr.unshift(0); // для коректного поиска с 0;
}
for (let i = 0; i + 1 < arr.length; i++){
if (maxStep < (arr[i + 1] - arr[i])){
maxStep = (arr[i + 1] - arr[i]);
index = i;
}
}
return arr[index] + maxStep/2;
}
function random(arr) {
console.log(arr);
console.log('Пропущеное число: ' + steps(arr));
}
random([1, 3, 5, 9]);
random([0, 8, 16, 32]);
random([4, 6, 8, 10]);
random([0, 16, 24, 32]);
/*
2. Напишите функция которая преобразовывает/открывает скобки всех
вложенных внутри массивов
Необходимо реализовать рекурсивный фызов функции.
Функция должна открывать любое количество внутренних массивов
example:
[[1,2],[3,[4]],5, 10] => [1,2,3,4,5,10]
[25,10,[10,[15]]] => [25,10,10,15]
*/
function openBraces(arr, arrNoBraces = []) {
for (let i = 0; i < arr.length; i++){
if (Array.isArray(arr[i])){
openBraces(arr[i], arrNoBraces);
}
else{
arrNoBraces.push(arr[i]);
}
}
return arrNoBraces;
}
console.log(openBraces ([[1,2],[3,[4]],5, 10]));
console.log(openBraces ([25,10,[10,[15]]]));
|
var searchData=
[
['thread_2eh',['thread.h',['../sys_2thread_8h.html',1,'(Global Namespace)'],['../lv2_2thread_8h.html',1,'(Global Namespace)']]],
['tty_2eh',['tty.h',['../tty_8h.html',1,'']]]
];
|
/*
* grunt-pip
* https://github.com/davidshrader/grunt-pip
*
* Copyright (c) 2014 david.shrader
* Licensed under the MIT license.
*/
module.exports = function(grunt) {
'use strict';
//var exec = require('exec');
var exec = require('child_process').exec;
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('pip', 'Grunt plug-in to install Python packages via PIP.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
vritualenv: 'venv',
verbose: false
});
var args = []
args.push(options.vritualenv);
if (options.verbose) {
args.push('-v');
}
grunt.log.writeln(args);
var done = this.async();
grunt.util.spawn({
cmd: 'virtualenv',
args: args
}, function(error, result, code) {
grunt.log.writeln(result);
done(error);
});
// grunt.util.spawn({
// cmd: ['ls'],
// args: ['-l']
// }, function(error, result, code) {
// grunt.log.writeln('hey there');
// grunt.log.writeln(error);
// grunt.log.writeln(code);
// done();
// });
// check to see if virtualenv command is available
// if (options.vritualenv !== 'venv') {
// grunt.fatal('\'virtualenv\' command not found');
// }
// exec('ls', function (error, stdout, stderr) {
// grunt.log.writeln('hey there');
// console.log('stdout: ' + stdout);
// console.log('stderr: ' + stderr);
// if (error !== null) {
// console.log('exec error: ' + error);
// };
// });
// exec(['ls', '-l'], function(err, out, code) {
// if (err instanceof Error)
// throw err;
// process.stderr.write(err);
// process.stdout.write(out);
// process.exit(code);
// });
// var cmd = 'virtualenv ' + options.virtualenv + '\n';
// cmd += 'python benjamint.py';
// exec(cmd, function(err, stdout) {
// if (err instanceof Error)
// throw err;
// process.stderr.write(err);
// process.stdout.write(out);
// process.exit(code);
// // grunt.log.write(stdout);
// });
// var vritualenv = options.virtualenv;
// grunt.log.writeln(vritualenv);
// var verbose = options.verbose;
// grunt.log.writeln(verbose);
// var modules = options.modules;
// grunt.log.writeln(modules);
});
};
|
'use strict';
const writeFile = require('../index');
const chai = require('chai');
const expect = chai.expect;
const rimraf = require('rimraf');
const root = process.cwd();
const fs = require('fs');
const broccoli = require('broccoli');
let builder;
chai.Assertion.addMethod('sameStatAs', function(otherStat) {
this.assert(
this._obj.mode === otherStat.mode,
'expected mode ' + this._obj.mode + ' to be same as ' + otherStat.mode,
'expected mode ' + this._obj.mode + ' to not the same as ' + otherStat.mode
);
this.assert(
this._obj.size === otherStat.size,
'expected size ' + this._obj.size + ' to be same as ' + otherStat.size,
'expected size ' + this._obj.size + ' to not the same as ' + otherStat.size
);
this.assert(
this._obj.mtime.getTime() === otherStat.mtime.getTime(),
'expected mtime ' + this._obj.mtime.getTime() + ' to be same as ' + otherStat.mtime.getTime(),
'expected mtime ' + this._obj.mtime.getTime() + ' to not the same as ' + otherStat.mtime.getTime()
);
});
describe('broccoli-file-creator', function() {
afterEach(function() {
if (builder) {
builder.cleanup();
}
});
function read(path) {
return fs.readFileSync(path, 'UTF8');
}
it('creates the file specified', function() {
const content = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('/something.js', content);
builder = new broccoli.Builder(tree);
return builder.build().then(result => {
expect(read(result.directory + '/something.js')).to.eql(content);
});
});
it('creates the file specified in a non-existent directory', function() {
const content = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('/somewhere/something.js', content);
builder = new broccoli.Builder(tree);
return builder.build().then(result => {
expect(read(result.directory + '/somewhere/something.js')).to.eql(content);
});
});
it('if the content is a function, that functions return value or fulfillment value is used', function() {
const CONTENT = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('the-file.txt', () => Promise.resolve(CONTENT));
builder = new broccoli.Builder(tree);
return builder.build().then(result => {
expect(read(result.directory + '/the-file.txt')).to.eql(CONTENT);
});
});
it('correctly caches', function() {
const content = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('/something.js', content);
builder = new broccoli.Builder(tree);
var stat;
return builder.build().then(result => {
stat = fs.lstatSync(result.directory + '/something.js');
return builder.build();
}).then(result => {
var newStat = fs.lstatSync(result.directory + '/something.js');
expect(newStat).to.be.sameStatAs(stat);
});
});
});
|
/**
* 邮件通知
*/
const config = require('../config').email
const nodemailer = require('nodemailer')
let smtpTransport = null
module.exports = {
send(tip, title, message) {
if (!smtpTransport) {
smtpTransport = nodemailer.createTransport({
pool:true,
service:config.service,
auth:{
user:config.from,
pass:config.pass
}
})
}
console.log(`sending email to ${config.to}:${title} ${message}`)
if (config.filter.indexOf(tip.level) > -1) {
console.log('email filterd')
return
}
smtpTransport.sendMail({
from:config.from,
to:config.to,
subject:message,
html:title
}, (e, res) => e ? console.error('send email failed:' + e) : console.log('send email success.'))
}
}
|
// Creates a hot reloading development environment
const path = require('path');
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const DashboardPlugin = require('webpack-dashboard/plugin');
const config = require('./config/webpack.config.development');
const app = express();
const compiler = webpack(config);
// Apply CLI dashboard for your webpack dev server
compiler.apply(new DashboardPlugin());
const host = process.env.HOST || 'localhost';
const port = process.env.PORT || 3000;
function log() {
arguments[0] = '\nWebpack: ' + arguments[0];
console.log.apply(console, arguments);
}
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: "/",
stats: {
colors: true
},
historyApiFallback: true
}));
app.use(webpackHotMiddleware(compiler));
app.get('/css/*', (req, res) => {
res.sendFile(path.join(__dirname, './src/app.html'),{
headers:{
"Content-Type":"text/css"
}
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './src/app.html'));
});
app.listen(port, host, (err) => {
if (err) {
log(err);
return;
}
const exec = require('child_process').exec;
exec("cd src && electron main.dev.js", (err, stdout, stderr) => {
if (err) {
log(err);
return;
}
log("Electron Started");
});
log(' App is listening at http://%s:%s', host, port);
});
|
/****************************************/
/* Level One - Concatenation Exercises */
/****************************************/
/*
Return a string that will add a "Hello" string in front of the name
ie:
sayHello("Jesse") => Hello Jesse
sayHello("Mat") => Hello Mat
*/
function sayHello(name) {
}
/*
Create a full name using the first and last parameters and store into a variable
Then return a string that will add a "Hello" string in front of the full name
ie:
sayHelloAdv("Jesse", "Wang") => Hello Jesse Wang
sayHelloAdv("Alex", "Pelan") => Hello Alex Pelan
*/
function sayHelloAdv(first, last) {
}
/*
Return a string that will display how many points a player made
ie:
playerStats("Steph Curry", 32") => Steph Curry made 32 points
playerStats("Meghan", 12) => Meghan made 12 points
*/
function playerStats(player, points) {
}
/*
Return a number that will be the total score in points made
ie:
calculateScore(1, 0) => 2
calculateScore(0, 1) => 3
calculateScore(8, 6) => 34
*/
function calculateScore(twoPointersMade, threePointersMade) {
}
/*
Calculates the totalScore a player has made
Then return a string that will display the total score a player made
ie:
playerStatsAdv("Steph Curry", 6, 7) => "Steph Curry made 33 points"
playerStatsAdv("Meghan", 4, 2) => "Meghan made 14 points"
*/
function playerStatsAdv(player, twoPointersMade, threePointersMade) {
}
|
var net = require('net');
var client = net.connect(4444, '192.168.99.100');
client.setEncoding('utf8');
setInterval(function() {
console.log("sending...")
var msg = Math.floor(Math.random()*10000);
client.write('send mytopic 123 bajs'+msg+'\n');
}, 250)
client.on('data', function(data) {
console.log('data was', data)
})
|
import Template7Context from './context';
const Template7Utils = {
quoteSingleRexExp: new RegExp('\'', 'g'),
quoteDoubleRexExp: new RegExp('"', 'g'),
isFunction(func) {
return typeof func === 'function';
},
escape(string = '') {
return string
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
},
helperToSlices(string) {
const { quoteDoubleRexExp, quoteSingleRexExp } = Template7Utils;
const helperParts = string.replace(/[{}#}]/g, '').trim().split(' ');
const slices = [];
let shiftIndex;
let i;
let j;
for (i = 0; i < helperParts.length; i += 1) {
let part = helperParts[i];
let blockQuoteRegExp;
let openingQuote;
if (i === 0) slices.push(part);
else if (part.indexOf('"') === 0 || part.indexOf('\'') === 0) {
blockQuoteRegExp = part.indexOf('"') === 0 ? quoteDoubleRexExp : quoteSingleRexExp;
openingQuote = part.indexOf('"') === 0 ? '"' : '\'';
// Plain String
if (part.match(blockQuoteRegExp).length === 2) {
// One word string
slices.push(part);
} else {
// Find closed Index
shiftIndex = 0;
for (j = i + 1; j < helperParts.length; j += 1) {
part += ` ${helperParts[j]}`;
if (helperParts[j].indexOf(openingQuote) >= 0) {
shiftIndex = j;
slices.push(part);
break;
}
}
if (shiftIndex) i = shiftIndex;
}
} else if (part.indexOf('=') > 0) {
// Hash
const hashParts = part.split('=');
const hashName = hashParts[0];
let hashContent = hashParts[1];
if (!blockQuoteRegExp) {
blockQuoteRegExp = hashContent.indexOf('"') === 0 ? quoteDoubleRexExp : quoteSingleRexExp;
openingQuote = hashContent.indexOf('"') === 0 ? '"' : '\'';
}
if (hashContent.match(blockQuoteRegExp).length !== 2) {
shiftIndex = 0;
for (j = i + 1; j < helperParts.length; j += 1) {
hashContent += ` ${helperParts[j]}`;
if (helperParts[j].indexOf(openingQuote) >= 0) {
shiftIndex = j;
break;
}
}
if (shiftIndex) i = shiftIndex;
}
const hash = [hashName, hashContent.replace(blockQuoteRegExp, '')];
slices.push(hash);
} else {
// Plain variable
slices.push(part);
}
}
return slices;
},
stringToBlocks(string) {
const blocks = [];
let i;
let j;
if (!string) return [];
const stringBlocks = string.split(/({{[^{^}]*}})/);
for (i = 0; i < stringBlocks.length; i += 1) {
let block = stringBlocks[i];
if (block === '') continue;
if (block.indexOf('{{') < 0) {
blocks.push({
type: 'plain',
content: block,
});
} else {
if (block.indexOf('{/') >= 0) {
continue;
}
block = block
.replace(/{{([#/])*([ ])*/, '{{$1')
.replace(/([ ])*}}/, '}}');
if (block.indexOf('{#') < 0 && block.indexOf(' ') < 0 && block.indexOf('else') < 0) {
// Simple variable
blocks.push({
type: 'variable',
contextName: block.replace(/[{}]/g, ''),
});
continue;
}
// Helpers
const helperSlices = Template7Utils.helperToSlices(block);
let helperName = helperSlices[0];
const isPartial = helperName === '>';
const helperContext = [];
const helperHash = {};
for (j = 1; j < helperSlices.length; j += 1) {
const slice = helperSlices[j];
if (Array.isArray(slice)) {
// Hash
helperHash[slice[0]] = slice[1] === 'false' ? false : slice[1];
} else {
helperContext.push(slice);
}
}
if (block.indexOf('{#') >= 0) {
// Condition/Helper
let helperContent = '';
let elseContent = '';
let toSkip = 0;
let shiftIndex;
let foundClosed = false;
let foundElse = false;
let depth = 0;
for (j = i + 1; j < stringBlocks.length; j += 1) {
if (stringBlocks[j].indexOf('{{#') >= 0) {
depth += 1;
}
if (stringBlocks[j].indexOf('{{/') >= 0) {
depth -= 1;
}
if (stringBlocks[j].indexOf(`{{#${helperName}`) >= 0) {
helperContent += stringBlocks[j];
if (foundElse) elseContent += stringBlocks[j];
toSkip += 1;
} else if (stringBlocks[j].indexOf(`{{/${helperName}`) >= 0) {
if (toSkip > 0) {
toSkip -= 1;
helperContent += stringBlocks[j];
if (foundElse) elseContent += stringBlocks[j];
} else {
shiftIndex = j;
foundClosed = true;
break;
}
} else if (stringBlocks[j].indexOf('else') >= 0 && depth === 0) {
foundElse = true;
} else {
if (!foundElse) helperContent += stringBlocks[j];
if (foundElse) elseContent += stringBlocks[j];
}
}
if (foundClosed) {
if (shiftIndex) i = shiftIndex;
if (helperName === 'raw') {
blocks.push({
type: 'plain',
content: helperContent,
});
} else {
blocks.push({
type: 'helper',
helperName,
contextName: helperContext,
content: helperContent,
inverseContent: elseContent,
hash: helperHash,
});
}
}
} else if (block.indexOf(' ') > 0) {
if (isPartial) {
helperName = '_partial';
if (helperContext[0]) {
if (helperContext[0].indexOf('[') === 0) helperContext[0] = helperContext[0].replace(/[[\]]/g, '');
else helperContext[0] = `"${helperContext[0].replace(/"|'/g, '')}"`;
}
}
blocks.push({
type: 'helper',
helperName,
contextName: helperContext,
hash: helperHash,
});
}
}
}
return blocks;
},
parseJsVariable(expression, replace, object) {
return expression.split(/([+ \-*/^()&=|<>!%:?])/g).reduce((arr, part) => {
if (!part) {
return arr;
}
if (part.indexOf(replace) < 0) {
arr.push(part);
return arr;
}
if (!object) {
arr.push(JSON.stringify(''));
return arr;
}
let variable = object;
if (part.indexOf(`${replace}.`) >= 0) {
part.split(`${replace}.`)[1].split('.').forEach((partName) => {
if (partName in variable) variable = variable[partName];
else variable = undefined;
});
}
if (
(typeof variable === 'string')
|| Array.isArray(variable)
|| (variable.constructor && variable.constructor === Object)
) {
variable = JSON.stringify(variable);
}
if (variable === undefined) variable = 'undefined';
arr.push(variable);
return arr;
}, []).join('');
},
parseJsParents(expression, parents) {
return expression.split(/([+ \-*^()&=|<>!%:?])/g).reduce((arr, part) => {
if (!part) {
return arr;
}
if (part.indexOf('../') < 0) {
arr.push(part);
return arr;
}
if (!parents || parents.length === 0) {
arr.push(JSON.stringify(''));
return arr;
}
const levelsUp = part.split('../').length - 1;
const parentData = levelsUp > parents.length ? parents[parents.length - 1] : parents[levelsUp - 1];
let variable = parentData;
const parentPart = part.replace(/..\//g, '');
parentPart.split('.').forEach((partName) => {
if (typeof variable[partName] !== 'undefined') variable = variable[partName];
else variable = 'undefined';
});
if (variable === false || variable === true) {
arr.push(JSON.stringify(variable));
return arr;
}
if (variable === null || variable === 'undefined') {
arr.push(JSON.stringify(''));
return arr;
}
arr.push(JSON.stringify(variable));
return arr;
}, []).join('');
},
getCompileVar(name, ctx, data = 'data_1') {
let variable = ctx;
let parts;
let levelsUp = 0;
let newDepth;
if (name.indexOf('../') === 0) {
levelsUp = name.split('../').length - 1;
newDepth = variable.split('_')[1] - levelsUp;
variable = `ctx_${newDepth >= 1 ? newDepth : 1}`;
parts = name.split('../')[levelsUp].split('.');
} else if (name.indexOf('@global') === 0) {
variable = 'Template7.global';
parts = name.split('@global.')[1].split('.');
} else if (name.indexOf('@root') === 0) {
variable = 'root';
parts = name.split('@root.')[1].split('.');
} else {
parts = name.split('.');
}
for (let i = 0; i < parts.length; i += 1) {
const part = parts[i];
if (part.indexOf('@') === 0) {
let dataLevel = data.split('_')[1];
if (levelsUp > 0) {
dataLevel = newDepth;
}
if (i > 0) {
variable += `[(data_${dataLevel} && data_${dataLevel}.${part.replace('@', '')})]`;
} else {
variable = `(data_${dataLevel} && data_${dataLevel}.${part.replace('@', '')})`;
}
} else if (Number.isFinite ? Number.isFinite(part) : Template7Context.isFinite(part)) {
variable += `[${part}]`;
} else if (part === 'this' || part.indexOf('this.') >= 0 || part.indexOf('this[') >= 0 || part.indexOf('this(') >= 0) {
variable = part.replace('this', ctx);
} else {
variable += `.${part}`;
}
}
return variable;
},
getCompiledArguments(contextArray, ctx, data) {
const arr = [];
for (let i = 0; i < contextArray.length; i += 1) {
if (/^['"]/.test(contextArray[i])) arr.push(contextArray[i]);
else if (/^(true|false|\d+)$/.test(contextArray[i])) arr.push(contextArray[i]);
else {
arr.push(Template7Utils.getCompileVar(contextArray[i], ctx, data));
}
}
return arr.join(', ');
},
};
export default Template7Utils;
|
const _evaluate = function(stateData) {
if(stateData.fireKey)
return "Yellow"
};
module.exports = function(Anystate) {
Anystate.prototype._evaluate = _evaluate
}
|
#!/usr/bin/env node
var fs = require("fs");
var path = require("path");
var optimist = require("optimist");
var argv = optimist.argv;
var to_center = [-119.95388, 37.913055];
var FILE_IN = path.resolve(argv._[0]);
var FILE_OUT = path.resolve(argv._[1]);
var geojson = JSON.parse(fs.readFileSync(FILE_IN));
var get_center = function(pg){
var b = [pg[0][0],pg[0][0],pg[0][1],pg[0][1]];
pg.forEach(function(p){
if (b[0] < p[0]) b[0] = p[0];
if (b[1] > p[0]) b[1] = p[0];
if (b[2] < p[1]) b[2] = p[1];
if (b[3] > p[1]) b[3] = p[1];
});
return [((b[0]+b[1])/2),((b[2]+b[3])/2)];
};
var from_center = null;
var move_shape = function(coords) {
var xScale = Math.cos(from_center[1]*3.14159/180)/Math.cos(to_center[1]*3.14159/180);
var dy = from_center[1]-to_center[1];
coords.forEach(function(v,k){
coords[k] = [
(v[0]-from_center[0])*xScale+to_center[0],
v[1]-dy
]
});
return coords;
}
switch (geojson["features"][0]["geometry"]["type"]) {
case "Polygon":
var from_center = get_center(geojson["features"][0]["geometry"]["coordinates"][0]);
geojson["features"][0]["geometry"]["coordinates"][0] = move_shape(geojson["features"][0]["geometry"]["coordinates"][0]);
break;
case "MultiPolygon":
var centers = [];
geojson["features"][0]["geometry"]["coordinates"].forEach(function(v){
centers.push(get_center(v[0]));
});
var from_center = get_center(centers);
geojson["features"][0]["geometry"]["coordinates"].forEach(function(v,k){
geojson["features"][0]["geometry"]["coordinates"][k][0] = move_shape(v[0])
});
break;
}
fs.writeFileSync(FILE_OUT, JSON.stringify(geojson,null,'\t'));
|
/*
hinclude.js -- HTML Includes (version 0.9)
Copyright (c) 2005-2011 Mark Nottingham <mnot@mnot.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
See http://www.mnot.net/javascript/hinclude/ for documentation.
*/
var hinclude = {
set_content_async: function (element, req) {
if (req.readyState == 4) {
if (req.status == 200 | req.status == 304) {
element.innerHTML = req.responseText;
}
element.className = "include_" + req.status;
}
},
buffer: new Array(),
set_content_buffered: function (element, req) {
if (req.readyState == 4) {
hinclude.buffer.push(new Array(element, req));
hinclude.outstanding--;
if (hinclude.outstanding == 0) {
hinclude.show_buffered_content();
}
}
},
show_buffered_content: function () {
while (hinclude.buffer.length > 0) {
var include = hinclude.buffer.pop();
if (include[1].status == 200 | include[1].status == 304) {
include[0].innerHTML = include[1].responseText;
}
include[0].className = "include_" + include[1].status;
}
},
outstanding: 0,
run: function () {
var mode = this.get_meta("include_mode", "buffered");
var callback = function(element, req) {};
var includes = document.getElementsByTagName("hx:include");
if (includes.length == 0) { // remove ns for IE
includes = document.getElementsByTagName("include");
}
if (mode == "async") {
callback = this.set_content_async;
} else if (mode == "buffered") {
callback = this.set_content_buffered;
var timeout = this.get_meta("include_timeout", 2.5) * 1000;
setTimeout("hinclude.show_buffered_content()", timeout);
}
for (var i=0; i < includes.length; i++) {
this.include(includes[i], includes[i].getAttribute("src"), callback);
}
},
include: function (element, url, incl_cb) {
var scheme = url.substring(0,url.indexOf(":"));
if (scheme.toLowerCase() == "data") { // just text/plain for now
var data = unescape(url.substring(url.indexOf(",") + 1, url.length));
element.innerHTML = data;
} else {
var req = false;
if(window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
if (req) {
this.outstanding++;
req.onreadystatechange = function() {
incl_cb(element, req);
};
try {
req.open("GET", url, true);
req.send("");
} catch (e) {
this.outstanding--;
alert("Include error: " + url + " (" + e + ")");
}
}
}
},
get_meta: function (name, value_default) {
var metas = document.getElementsByTagName("meta");
for (var m=0; m < metas.length; m++) {
var meta_name = metas[m].getAttribute("name");
if (meta_name == name) {
return metas[m].getAttribute("content");
}
}
return value_default;
},
/*
* (c)2006 Dean Edwards/Matthias Miller/John Resig
* Special thanks to Dan Webb's domready.js Prototype extension
* and Simon Willison's addLoadEvent
*
* For more info, see:
* http://dean.edwards.name/weblog/2006/06/again/
*
* Thrown together by Jesse Skinner (http://www.thefutureoftheweb.com/)
*/
addDOMLoadEvent: function(func) {
if (! window.__load_events) {
var init = function () {
// quit if this function has already been called
if (arguments.callee.done) return;
arguments.callee.done = true;
if (window.__load_timer) {
clearInterval(window.__load_timer);
window.__load_timer = null;
}
for (var i=0; i < window.__load_events.length; i++) {
window.__load_events[i]();
}
window.__load_events = null;
// clean up the __ie_onload event
/*@cc_on @*/
/*@if (@_win32)
document.getElementById("__ie_onload").onreadystatechange = "";
/*@end @*/
};
// for Mozilla/Opera9
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
// for Internet Explorer
/*@cc_on @*/
/*@if (@_win32)
document.write(
"<scr"
+ "ipt id=__ie_onload defer src=javascript:void(0)><\/scr"
+ "ipt>"
);
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
// for Safari
if (/WebKit/i.test(navigator.userAgent)) { // sniff
window.__load_timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init();
}
}, 10);
}
// for other browsers
window.onload = init;
window.__load_events = [];
}
window.__load_events.push(func);
}
};
hinclude.addDOMLoadEvent(function() { hinclude.run(); });
|
angular.module("soundipic.model", [
])
.service("model", function() {
var imageSrc,
imageData;
function srcToData(src) {
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0, width, height);
return context.getImageData(0, 0, width, height);
}
function dataToSrc(data) {
var canvas = document.createElement("canvas"),
context = canvas.getContext("2d");
context.putImageData(data, 0, 0);
return canvas.toDataURL("image/jpg");
}
function getImageData() {
if (!imageSrc) {
return null;
}
}
return {
imageSrc: function(src) {
if (src) {
imageSrc = src;
imageData = srcToData(src);
}
return imageSrc;
},
imageData: function(data) {
if (data) {
imageData = data;
imageSrc = dataToSrc(data);
}
return imageData;
}
};
})
;
|
version https://git-lfs.github.com/spec/v1
oid sha256:5a4b87becf4d55857fc2346606917d9c17ea96ba34d8cda9efdd44b97576c0f7
size 2824
|
/*global define*/
define({
"_widgetLabel": "Netoli manęs",
"searchHeaderText": "Ieškoti adreso arba rasti žemėlapyje",
"invalidSearchLayerMsg": "Netinkamai sukonfigūruota sluoksnių paieška",
"bufferSliderText": "Rezultatus pateikti ${BufferDistance} ${BufferUnit}",
"bufferTextboxLabel": "Rezultatus pateikti diapazone (${BufferUnit})",
"invalidBufferDistance": "Įvesta buferio atstumo reikšmė yra netinkama.",
"bufferSliderValueString": "Nurodykite atstumą, didesnį nei 0",
"unableToCreateBuffer": "Rezultatų nerasta",
"selectLocationToolTip": "Nustatyti vietą",
"noFeatureFoundText": "Nieko nerasta ",
"unableToFetchResults": "Nepavyko rasti rezultatų sluoksnyje (-iuose):",
"informationTabTitle": "Informacija",
"directionTabTitle": "Maršrutai",
"failedToGenerateRouteMsg": "Nepavyko sugeneruoti maršruto.",
"geometryServicesNotFound": "Geometrijos paslauga negalima.",
"allPopupsDisabledMsg": "Nesukonfigūruoti iškylantys langai, rezultatų pateikti negalima.",
"worldGeocoderName": "Adresas",
"searchLocationTitle": "Ieškota vieta",
"unknownAttachmentExt": "FAILAS",
"proximityButtonTooltip": "Paieška šalia",
"approximateDistanceTitle": "Apytikslis atstumas: ${DistanceToLocation}",
"toggleTip": "Spustelėkite, norėdami parodyti/paslėpti filtravimo nustatymus",
"filterTitle": "Pasirinkti taikytinus filtrus",
"clearFilterButton": "Išvalyti visus filtrus",
"bufferDistanceLabel": "Buferio atstumas",
"units": {
"miles": {
"displayText": "Mylios",
"acronym": "mi."
},
"kilometers": {
"displayText": "Kilometrai",
"acronym": "km"
},
"feet": {
"displayText": "Pėdos",
"acronym": "pėdos"
},
"meters": {
"displayText": "Metrai",
"acronym": "m"
}
}
});
|
(function() {
'use strict';
angular
.module('socialprofileApp')
.provider('AlertService', AlertService);
function AlertService () {
this.toast = false;
/*jshint validthis: true */
this.$get = getService;
this.showAsToast = function(isToast) {
this.toast = isToast;
};
getService.$inject = ['$timeout', '$sce', '$translate'];
function getService ($timeout, $sce,$translate) {
var toast = this.toast,
alertId = 0, // unique id for each alert. Starts from 0.
alerts = [],
timeout = 5000; // default timeout
return {
factory: factory,
isToast: isToast,
add: addAlert,
closeAlert: closeAlert,
closeAlertByIndex: closeAlertByIndex,
clear: clear,
get: get,
success: success,
error: error,
info: info,
warning : warning
};
function isToast() {
return toast;
}
function clear() {
alerts = [];
}
function get() {
return alerts;
}
function success(msg, params, position) {
return this.add({
type: 'success',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function error(msg, params, position) {
return this.add({
type: 'danger',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function warning(msg, params, position) {
return this.add({
type: 'warning',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function info(msg, params, position) {
return this.add({
type: 'info',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function factory(alertOptions) {
var alert = {
type: alertOptions.type,
msg: $sce.trustAsHtml(alertOptions.msg),
id: alertOptions.alertId,
timeout: alertOptions.timeout,
toast: alertOptions.toast,
position: alertOptions.position ? alertOptions.position : 'top right',
scoped: alertOptions.scoped,
close: function (alerts) {
return closeAlert(this.id, alerts);
}
};
if(!alert.scoped) {
alerts.push(alert);
}
return alert;
}
function addAlert(alertOptions, extAlerts) {
alertOptions.alertId = alertId++;
alertOptions.msg = $translate.instant(alertOptions.msg, alertOptions.params);
var that = this;
var alert = this.factory(alertOptions);
if (alertOptions.timeout && alertOptions.timeout > 0) {
$timeout(function () {
that.closeAlert(alertOptions.alertId, extAlerts);
}, alertOptions.timeout);
}
return alert;
}
function closeAlert(id, extAlerts) {
var thisAlerts = extAlerts ? extAlerts : alerts;
return closeAlertByIndex(thisAlerts.map(function(e) { return e.id; }).indexOf(id), thisAlerts);
}
function closeAlertByIndex(index, thisAlerts) {
return thisAlerts.splice(index, 1);
}
}
}
})();
|
jest
.dontMock('../resolvers')
.dontMock('../queries')
import { fromJS } from 'immutable'
describe('resolvers', () => {
let resolvers
beforeEach(() => {
resolvers = require('../resolvers')
})
it('retrieves a value', () => {
const {value} = resolvers
const mockVal = 'testing-wow'
expect(value(mockVal)).toBe(mockVal)
})
it('constructs a proper get query', () => {
const {get, value} = resolvers
expect(get('testing')).toEqual({
testing: value,
})
})
it('constructs a valid getIn query', () => {
const {getIn, value} = resolvers
expect(getIn('one', 'two', 'three')).toEqual({
one: {
two: {
three: value,
},
},
})
})
it('constructs a valid index query', () => {
const {index} = resolvers
const indexResolver = index(['users'])
const mockCache = fromJS({
users: {
'123': {
name: 'one',
friends: {
'456': true,
'789': true,
},
},
'456': { name: 'two' },
'789': { name: 'three' },
},
})
const mockState = { firebase: mockCache }
const value = mockCache.getIn(['users', '123', 'friends'])
expect(
indexResolver.subscriptions(value)
).toEqual([
['users', '456'],
['users', '789'],
])
expect(
indexResolver.values(value, mockState, {}).toJS()
).toEqual({
'456': { name: 'two' },
'789': { name: 'three' },
})
})
})
|
import React from 'react'
import { renderRoutes } from 'react-router-config'
import { Header } from '../containers/Header'
const App = ({ route }) => (
<div>
<Header
title="reSolve Styled-Components Example"
name="Styled-Components Example"
favicon="/favicon.png"
css={['/bootstrap.min.css']}
/>
{renderRoutes(route.routes)}
</div>
)
export default App
|
$(document).ready(function(){
var nbSlots = 1;
var roles = [];
$('.captain-role option').each(function(){
roles.push([$(this).val(), $(this).text()]);
});
$(".crew-slots").append(generateDivSlot(nbSlots));
$('#add_slot').click(function(){
nbSlots++;
$(".crew-slots").append(generateDivSlot(nbSlots));
})
$(document).on('click', '.remove-slot', function(){
var crewSlot = $(this).parent("div");
$('#' + crewSlot.attr('id')).remove();
renameCrewSlotDiv();
})
function generateDivSlot(nbSlots)
{
var str = "<div id=slot" + nbSlots + " class='crew-slot'>";
str += " <label for='crew-role'>Slot " + nbSlots + " : </label>";
str += " <select name='crew-role[]'>";
$(roles).each(function(){
str += " <option value='" + $(this)[0] + "'>" + $(this)[1] + "</option>";
})
str += " </select>";
if(nbSlots > 1){
str += " <button type='button' class='btn btn-default btn-xs remove-slot'>";
str += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>";
str += " </button>";
}
str += "<br />";
str += "</div>";
return str;
}
function renameCrewSlotDiv()
{
var slotNum = 0;
$(".crew-slot").each(function(){
slotNum++;
$(this).attr('id', 'slot' + slotNum);
$(this).find("label").text("Slot " + slotNum + " : ");
})
nbSlots = slotNum;
}
})
|
const { Router } = require('director');
const ReactDOM = require('react-dom');
const { computed, observable } = require('../../core');
const React = require('../../react');
const { Todo, todos } = require('./model');
const { StatsView } = require('./StatsView');
const { TodoView } = require('./TodoView');
const { cat } = require('../../cat');
class AppView extends React.Component {
constructor() {
super();
this.newTodoTitle = observable("");
this.todoFilter = observable("all");
this.todoFiltered = computed(() => todos[this.todoFilter.$].$);
this.footerStyle = computed(() => {
let result = {};
if (todos.all.$.length === 0)
result.display = "none";
return result;
});
this.allComplete = computed({
read: () => !todos.active.$.length,
write: (v) => {
todos.all.$.forEach(todo => {
todo.completed.$ = Boolean(v);
});
},
});
}
componentDidMount() {
let router = Router({
'/': () => {
this.todoFilter.$ = "all";
},
'/active': () => {
this.todoFilter.$ = "active";
},
'/completed': () => {
this.todoFilter.$ = "completed";
},
});
router.init('/');
}
render() {
return <div>
<section className="todoAppView">
<header className="header">
<h1>todos</h1>
<input className="new-todo"
placeholder="What needs to be done?"
autoFocus
value={ this.newTodoTitle }
onKeyPress={ this.createOnEnter.bind(this) }
/>
</header>
<section className="main">
<input className="toggle-all"
id="toggle-all"
type="checkbox"
checked={ this.allComplete }/>
<label htmlFor="toggle-all">Mark all as complete</label>
<ul className="todo-list">
{this.todoFiltered.$.map(todo => <TodoView key={todo.id.$} todo={todo} />)}
</ul>
</section>
<footer className="footer" style={this.footerStyle}>
<StatsView todoFilter={ this.todoFilter }/>
</footer>
</section>
</div>;
}
createOnEnter(event) {
if (event.key === "Enter" && this.newTodoTitle.$.trim().length) {
todos.add(new Todo(this.newTodoTitle.$));
this.newTodoTitle.$ = "";
}
}
}
cat(__filename).providesEach({
AppView,
});
ReactDOM.render(
<AppView/>,
document.getElementById("main")
);
module.exports = {
AppView,
}
|
(function () {
'use strict';
angular
.module('buildings')
.controller('BuildingsController', BuildingsController);
BuildingsController.$inject = ['$scope', '$state', 'projectResolve', '$window', 'Authentication'];
function BuildingsController ($scope, $state, project, $window, Authentication) {
var vm = this;
// initialization objects
vm.project = project;
vm.project.isNewBuilding = false;
vm.project.removeBuilding = false;
vm.project.isUpdateBuilding = false;
vm.building = {};
// functionality
vm.save = save;
vm.remove = remove;
vm.edit = edit;
// initialization variables
vm.parentName = $state.params.projectName;
vm.index = $state.params.index ? $state.params.index : 0;
// implementation
function save(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.buildingForm');
return false;
}
if (vm.project._id) {
vm.project.addBuilding = vm.building;
vm.project.isNewBuilding = true;
vm.project.$update(successCallBack, errorCallBack);
} else {
// throw error , can't exist building without project
}
}
function successCallBack(res) {
$state.go('projects.view', {
projectId: res._id
});
}
function successCallBackUpdateBuilding(res) {
$state.go('buildings.view', {
projectId: res._id,
buildingId: res.buildings[vm.index]._id
});
}
function errorCallBack(res) {
vm.error = res.data + ' ' + res.statusText;
}
function remove(index) {
if ($window.confirm('Are you sure you want to remove building ')) {
vm.project.removeBuilding = true;
vm.project.index = index;
vm.project.$update(successCallBack, errorCallBack);
}
}
function edit(isValid) {
vm.project.isUpdateBuilding = true;
vm.project.index = vm.index;
vm.project.$update(successCallBackUpdateBuilding, errorCallBack);
}
}
}());
|
export { default } from 'ember-flexberry-gis/components/layer-treenode-contents/base';
|
var path = require('path')
var webpack = require('webpack')
const config = {
entry: path.join(__dirname, './src/index.js'),
output: {
filename: 'ajax-manager.js',
library: 'ajaxManager',
libraryTarget: 'umd',
path: path.join(__dirname, './dist')
},
module: {
rules: [
{
test: /\.js$/,
use: [
{ loader: 'babel-loader' }
]
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
})
]
}
module.exports = config
|
if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('../alasql.js');
};
if(false) {
describe('Test 16b', function() {
it('Grouping', function(done){
alasql('create database test16;use test16');
alasql.tables.students = new alasql.Table({data: [
{studentid:58,studentname:'Sarah Patrik',courseid:1, startdate: new Date(2014,0,10), amt:10, schoolid:1},
{studentid:102,studentname:'John Stewart', courseid:2, startdate: new Date(2014,0,20), amt:20, schoolid:1},
{studentid:103,studentname:'Joan Blackmore', courseid:2, startdate: new Date(2014,0,20), amt:20, schoolid:1},
{studentid:104,studentname:'Anna Wooden', courseid:4, startdate: new Date(2014,0,15), amt:30, schoolid:2},
{studentid:150,studentname:'Astrid Carlson', courseid:7, startdate: new Date(2014,0,15), amt:30, schoolid:1},
]});
alasql.tables.courses = new alasql.Table({data:[
{courseid:1, coursename: 'first', schoolid:1},
{courseid:2, coursename: 'second', schoolid:1},
{courseid:3, coursename: 'third', schoolid:2},
{courseid:4, coursename: 'fourth', schoolid:2},
{courseid:5, coursename: 'fifth', schoolid:2}
]});
alasql.tables.schools = new alasql.Table({data:[
{schoolid:1, schoolname: 'Northern School', regionid:'north'},
{schoolid:2, schoolname: 'Southern School', regionid:'south'},
{schoolid:3, schoolname: 'Eastern School', regionid:'east'},
{schoolid:4, schoolname: 'Western School', regionid:'west'},
]});
var res = alasql.exec('SELECT * '+
' FROM students '+
' LEFT JOIN courses ON students.courseid = courses.courseid AND students.schoolid = courses.schoolid'+
' LEFT JOIN schools ON students.schoolid = schools.schoolid '+
' GROUP BY schoolid, courseid, studentname '+
' ORDER BY studentname DESC' );
console.log(res);
assert.equal(5, res.length);
assert.equal(1, res[0].courseid);
assert.equal(2, res[1].courseid);
assert.equal(2, res[2].courseid);
assert.equal(7, res[3].courseid);
assert.equal(4, res[4].courseid);
alasql('drop database test16');
done();
});
});
}
|
/*
* jQuery File Upload Image Preview & Resize Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* jshint nomen:false */
/* global define, require, window, Blob */
;(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'load-image',
'load-image-meta',
'load-image-scale',
'load-image-exif',
'canvas-to-blob',
'jquery.fileupload-process'
], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(
require('jquery'),
require('blueimp-load-image/js/load-image'),
require('blueimp-load-image/js/load-image-meta'),
require('blueimp-load-image/js/load-image-scale'),
require('blueimp-load-image/js/load-image-exif'),
require('blueimp-canvas-to-blob'),
require('./jquery.fileupload-process')
);
} else {
// Browser globals:
factory(
window.jQuery,
window.loadImage
);
}
}(function ($, loadImage) {
'use strict';
// Prepend to the default processQueue:
$.blueimp.fileupload.prototype.options.processQueue.unshift(
{
action: 'loadImageMetaData',
disableImageHead: '@',
disableExif: '@',
disableExifThumbnail: '@',
disableExifSub: '@',
disableExifGps: '@',
disabled: '@disableImageMetaDataLoad'
},
{
action: 'loadImage',
// Use the action as prefix for the "@" options:
prefix: true,
fileTypes: '@',
maxFileSize: '@',
noRevoke: '@',
disabled: '@disableImageLoad'
},
{
action: 'resizeImage',
// Use "image" as prefix for the "@" options:
prefix: 'image',
maxWidth: '@',
maxHeight: '@',
minWidth: '@',
minHeight: '@',
crop: '@',
orientation: '@',
forceResize: '@',
disabled: '@disableImageResize'
},
{
action: 'saveImage',
quality: '@imageQuality',
type: '@imageType',
disabled: '@disableImageResize'
},
{
action: 'saveImageMetaData',
disabled: '@disableImageMetaDataSave'
},
{
action: 'resizeImage',
// Use "preview" as prefix for the "@" options:
prefix: 'preview',
maxWidth: '@',
maxHeight: '@',
minWidth: '@',
minHeight: '@',
crop: '@',
orientation: '@',
thumbnail: '@',
canvas: '@',
disabled: '@disableImagePreview'
},
{
action: 'setImage',
name: '@imagePreviewName',
disabled: '@disableImagePreview'
},
{
action: 'deleteImageReferences',
disabled: '@disableImageReferencesDeletion'
}
);
// The File Upload Resize plugin extends the fileupload widget
// with image resize functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// The regular expression for the types of images to load:
// matched against the file type:
loadImageFileTypes: /^image\/(gif|jpeg|png|svg\+xml)$/,
// The maximum file size of images to load:
loadImageMaxFileSize: 10000000, // 10MB
// The maximum width of resized images:
imageMaxWidth: 1920,
// The maximum height of resized images:
imageMaxHeight: 1080,
// Defines the image orientation (1-8) or takes the orientation
// value from Exif data if set to true:
imageOrientation: false,
// Define if resized images should be cropped or only scaled:
imageCrop: false,
// Disable the resize image functionality by default:
disableImageResize: true,
// The maximum width of the preview images:
previewMaxWidth: 80,
// The maximum height of the preview images:
previewMaxHeight: 80,
// Defines the preview orientation (1-8) or takes the orientation
// value from Exif data if set to true:
previewOrientation: true,
// Create the preview using the Exif data thumbnail:
previewThumbnail: true,
// Define if preview images should be cropped or only scaled:
previewCrop: false,
// Define if preview images should be resized as canvas elements:
previewCanvas: true
},
processActions: {
// Loads the image given via data.files and data.index
// as img element, if the browser supports the File API.
// Accepts the options fileTypes (regular expression)
// and maxFileSize (integer) to limit the files to load:
loadImage: function (data, options) {
if (options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
dfd = $.Deferred();
if (($.type(options.maxFileSize) === 'number' &&
file.size > options.maxFileSize) ||
(options.fileTypes &&
!options.fileTypes.test(file.type)) ||
!loadImage(
file,
function (img) {
if (img.src) {
data.img = img;
}
dfd.resolveWith(that, [data]);
},
options
)) {
return data;
}
return dfd.promise();
},
// Resizes the image given as data.canvas or data.img
// and updates data.canvas or data.img with the resized image.
// Also stores the resized image as preview property.
// Accepts the options maxWidth, maxHeight, minWidth,
// minHeight, canvas and crop:
resizeImage: function (data, options) {
if (options.disabled || !(data.canvas || data.img)) {
return data;
}
options = $.extend({canvas: true}, options);
var that = this,
dfd = $.Deferred(),
img = (options.canvas && data.canvas) || data.img,
resolve = function (newImg) {
if (newImg && (newImg.width !== img.width ||
newImg.height !== img.height ||
options.forceResize)) {
data[newImg.getContext ? 'canvas' : 'img'] = newImg;
}
data.preview = newImg;
dfd.resolveWith(that, [data]);
},
thumbnail;
if (data.exif) {
if (options.orientation === true) {
options.orientation = data.exif.get('Orientation');
}
if (options.thumbnail) {
thumbnail = data.exif.get('Thumbnail');
if (thumbnail) {
loadImage(thumbnail, resolve, options);
return dfd.promise();
}
}
// Prevent orienting the same image twice:
if (data.orientation) {
delete options.orientation;
} else {
data.orientation = options.orientation;
}
}
if (img) {
resolve(loadImage.scale(img, options));
return dfd.promise();
}
return data;
},
// Saves the processed image given as data.canvas
// inplace at data.index of data.files:
saveImage: function (data, options) {
if (!data.canvas || options.disabled) {
return data;
}
var that = this,
file = data.files[data.index],
dfd = $.Deferred();
if (data.canvas.toBlob) {
data.canvas.toBlob(
function (blob) {
if (!blob.name) {
if (file.type === blob.type) {
blob.name = file.name;
} else if (file.name) {
blob.name = file.name.replace(
/\.\w+$/,
'.' + blob.type.substr(6)
);
}
}
// Don't restore invalid meta data:
if (file.type !== blob.type) {
delete data.imageHead;
}
// Store the created blob at the position
// of the original file in the files list:
data.files[data.index] = blob;
dfd.resolveWith(that, [data]);
},
options.type || file.type,
options.quality
);
} else {
return data;
}
return dfd.promise();
},
loadImageMetaData: function (data, options) {
if (options.disabled) {
return data;
}
var that = this,
dfd = $.Deferred();
loadImage.parseMetaData(data.files[data.index], function (result) {
$.extend(data, result);
dfd.resolveWith(that, [data]);
}, options);
return dfd.promise();
},
saveImageMetaData: function (data, options) {
if (!(data.imageHead && data.canvas &&
data.canvas.toBlob && !options.disabled)) {
return data;
}
var file = data.files[data.index],
blob = new Blob([
data.imageHead,
// Resized images always have a head size of 20 bytes,
// including the JPEG marker and a minimal JFIF header:
this._blobSlice.call(file, 20)
], {type: file.type});
blob.name = file.name;
data.files[data.index] = blob;
return data;
},
// Sets the resized version of the image as a property of the
// file object, must be called after "saveImage":
setImage: function (data, options) {
if (data.preview && !options.disabled) {
data.files[data.index][options.name || 'preview'] = data.preview;
}
return data;
},
deleteImageReferences: function (data, options) {
if (!options.disabled) {
delete data.img;
delete data.canvas;
delete data.preview;
delete data.imageHead;
}
return data;
}
}
});
}));
|
/*Problem 2. Divisible by 7 and 5
Write a boolean expression that checks for given integer if it can be divided (without remainder) by 7 and 5 in the same time.
Examples:
n Divided by 7 and 5?
3 false
0 true
5 false
7 false
35 true
140 true*/
var number = 35,
devidedBySevenandFive = true;
if (number % 7 == 0 && number % 5 == 0) {
console.log(devidedBySevenandFive)
}
else {
console.log(!devidedBySevenandFive)
}
|
/* global describe, expect, it */
const fishNames = require('../src/index');
const allFish = fishNames.all;
describe('fish names', function() {
describe('all', function() {
it('should return an object containing all 200 fish names', function() {
expect(Object.keys(allFish).length).toEqual(200);
});
});
describe('random', function() {
it('should return a random fish', function() {
expect(Object.keys(allFish).map(fish => allFish[fish])).toContain(
fishNames.random()
);
});
it('should return an array of random fish names if passed a number as a param', function() {
const threeRandomFish = fishNames.random(3);
expect(threeRandomFish.length).toBe(3);
});
});
describe('male/female fish', function() {
const allMaleFish = Object.keys(fishNames.allMaleFish).map(
fish => fishNames.allMaleFish[fish]
);
const allFemaleFish = Object.keys(fishNames.allFemaleFish).map(
fish => fishNames.allFemaleFish[fish]
);
it('should ONLY contain names of male fish', function() {
expect(allMaleFish).not.toEqual(expect.arrayContaining(allFemaleFish));
});
it('should ONLY contain names of female fish', function() {
expect(allFemaleFish).not.toEqual(expect.arrayContaining(allMaleFish));
});
});
});
|
import produce from 'immer';
import homeReducer, { initialState } from '../reducer';
import {
loadGalleries,
galleriesLoadingSuccess,
galleriesLoadingError,
} from '../actions';
/* eslint-disable default-case, no-param-reassign */
describe('homeReducer', () => {
let state;
beforeEach(() => {
state = initialState;
});
test('should return the initial state', () => {
const expectedResult = state;
expect(homeReducer(undefined, {})).toEqual(expectedResult);
});
test('should handle the loadGalleries action correctly', () => {
const expectedResult = produce(state, draft => {
draft.galleryLoadings = true;
});
expect(homeReducer(state, loadGalleries())).toEqual(expectedResult);
});
test('should handle the galleriesLoadingSuccess action correctly', () => {
const fixture = {
entries: [{ name: 'demo', path_lower: '/public/galleries/demo' }],
};
const expectedResult = produce(state, draft => {
draft.galleryLoadings = false;
draft.contents = fixture.entries;
});
expect(homeReducer(state, galleriesLoadingSuccess(fixture))).toEqual(
expectedResult,
);
});
test('should handle the galleriesLoadingError action correctly', () => {
const fixture = { type: 'ReferenceError' };
const expectedResult = produce(state, draft => {
draft.galleryErrors = fixture;
draft.host = 'cdn';
});
expect(homeReducer(state, galleriesLoadingError(fixture, 'cdn'))).toEqual(
expectedResult,
);
});
});
|
var x;
var y;
var d;
var speedX;
var speedY;
function setup() {
createCanvas(windowWidth, windowHeight);
background(0, 255, 255);
d = 100;
x = random(d, width-d);
y = random(d, height-d);
speedX = random(5, 15);
speedY = random(5, 15);
}
function draw() {
background(0, 255, 255);
ellipse(x, y, d, d);
x = x + speedX;
y = y + speedY;
//d = d + 1;
if(y > height - d/2) {
speedY = -1 * abs(speedY);
fill(random(255), random(255), random(255))
}
if(y < d/2) {
speedY = abs(speedY);
}
if(x > width - d/2) {
speedX = -1 * abs(speedX);
}
if(x < d/2) {
speedX = abs(speedX);
}
}
|
/* eslint-disable no-console,func-names,react/no-multi-comp */
const React = require('react');
const ReactDOM = require('react-dom');
const Table = require('table-v7');
require('table-v7/assets/index.less');
const columns = [
{ title: '表头1', dataIndex: 'a', key: 'a', width: 100, fixed: 'left' },
{ title: '表头2', dataIndex: 'b', key: 'b', width: 100, fixed: 'left' },
{ title: '表头3', dataIndex: 'c', key: 'c' },
{ title: '表头4', dataIndex: 'b', key: 'd' },
{ title: '表头5', dataIndex: 'b', key: 'e' },
{ title: '表头6', dataIndex: 'b', key: 'f' },
{ title: '表头7', dataIndex: 'b', key: 'g' },
{ title: '表头8', dataIndex: 'b', key: 'h' },
{ title: '表头9', dataIndex: 'b', key: 'i' },
{ title: '表头10', dataIndex: 'b', key: 'j' },
{ title: '表头11', dataIndex: 'b', key: 'k' },
{ title: '表头12', dataIndex: 'b', key: 'l', width: 100, fixed: 'right' },
];
const data = [
{ a: '123', b: 'xxxxxxxx', d: 3, key: '1' },
{ a: 'cdd', b: 'edd12221', d: 3, key: '2' },
{ a: '133', c: 'edd12221', d: 2, key: '3' },
{ a: '133', c: 'edd12221', d: 2, key: '4' },
{ a: '133', c: 'edd12221', d: 2, key: '5' },
{ a: '133', c: 'edd12221', d: 2, key: '6' },
{ a: '133', c: 'edd12221', d: 2, key: '7' },
{ a: '133', c: 'edd12221', d: 2, key: '8' },
{ a: '133', c: 'edd12221', d: 2, key: '9' },
];
ReactDOM.render(
<div style={{ width: 800 }}>
<h2>Fixed columns</h2>
<Table
columns={columns}
expandedRowRender={record => record.title}
expandIconAsCell
scroll={{ x: 1200 }}
data={data}
/>
</div>
, document.getElementById('__react-content'));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.