code stringlengths 2 1.05M |
|---|
App.addChild('MixPanel', {
el: 'body',
activate: function(){
this.VISIT_MIN_TIME = 10000;
this.user = null;
this.controller = this.$el.data('controller');
this.action = this.$el.data('action');
this.user = this.$el.data('user');
if(window.mixpanel){
this.detectLogin();
this.startTracking();
this.trackTwitterShare();
this.trackFacebookShare();
try {
this.trackOnFacebookLike();
} catch(e) {
console.log(e);
}
}
},
startTracking: function(){
var self = this;
this.trackPageVisit('projects', 'show', 'Visited project page');
this.trackPageVisit('explore', 'index', 'Explored projects');
this.trackPageLoad('contributions', 'show', 'Finished contribution');
this.trackPageLoad('contributions', 'edit', 'Selected reward');
},
trackPageLoad: function(controller, action, text){
var self = this;
this.trackOnPage(controller, action, function(){
self.track(text);
});
},
trackPageVisit: function(controller, action, text){
var self = this;
this.trackOnPage(controller, action, function(){
self.trackVisit(text);
});
},
trackOnPage: function(controller, action, callback){
if(this.controller == controller && this.action == action){
callback();
}
},
trackTwitterShare: function() {
var self = this;
this.$('#twitter_share_button').on('click', function(event){
self.track('Share a project', { ref: $(event.currentTarget).data('title'), social_network: 'Twitter' });
});
},
trackFacebookShare: function() {
var self = this;
this.$('a#facebook_share').on('click', function(event){
self.track('Share a project', { ref: $(event.currentTarget).data('title'), social_network: 'Facebook' });
});
},
trackOnFacebookLike: function() {
var self = this;
FB.Event.subscribe('edge.create', function(url, html_element){
self.track('Liked a project', { ref: $(html_element).data('title') });
});
},
onLogin: function(){
mixpanel.alias(this.user.id);
if(this.user.created_today){
this.track("Signed up");
}
else{
this.track("Logged in");
}
},
detectLogin: function(){
if(this.user){
if(this.user.id != store.get('user_id')){
this.onLogin();
store.set('user_id', this.user.id);
}
}
else{
store.set('user_id', null);
}
},
identifyUser: function(){
if (this.user){
mixpanel.name_tag(this.user.email);
mixpanel.identify(this.user.id);
mixpanel.people.set({
"$email": this.user.email,
"$created": this.user.created_at,
"$last_login": this.user.last_sign_in_at,
"contributions": this.user.total_contributed_projects
});
}
},
track: function(text, options){
this.identifyUser();
var opt = options || {};
var obj = $(this);
var ref = (obj.attr('href') != undefined) ? obj.attr('href') : (opt.ref ? opt.ref : null);
var default_options = {
'page name': document.title,
'user_id': null,
'created': null,
'last_login': null,
'contributions': null,
'has_contributions': null,
'project': ref,
'url': window.location
};
if(this.user){
default_options.user_id = this.user.id;
default_options.created = this.user.created_at;
default_options.last_login = this.user.last_sign_in_at;
default_options.contributions = this.user.total_contributed_projects;
default_options.has_contributions = (this.user.total_contributed_projects > 0);
}
var opt = $.fn.extend(default_options, opt);
mixpanel.track(text, opt);
},
mixPanelEvent: function(target, event, text, options){
var self = this;
this.$(target).on(event, function(){
self.track(text, options);
});
},
trackVisit: function(eventName){
var self = this;
window.setTimeout(function(){
self.track(eventName);
}, this.VISIT_MIN_TIME);
}
});
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Sébastien CAPARROS (GlitchyVerse)
*
* 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.
*/
/**
* Converts a degree maesure into radians
* @param Float Degrees maesure
* @return Float Radians
*/
function degToRad(degrees) {
return degrees * Math.PI / 180;
}
/**
* Converts a radians maesure into degree
* @param Float Radians maesure
* @return Float degrees
*/
function radToDeg(radians) {
return (radians * 180) / Math.PI;
}
/**
* Returns the euler rotation from a Quaternion
* @param quat The rotation quaternion
* @return vec3 The euler angles
*/
/*function quatToEuler(q) {
var x = q[0], y = q[1], z = q[2], w = q[3];
return vec3.fromValues(
Math.atan2( 2 * (y * z + w * x), w * w - x * x - y * y + z * z),
Math.asin (-2 * (x * z - w * y)),
Math.atan2( 2 * (x * y + w * z), w * w + x * x - y * y - z * z)
);
}*/
/**
* Returns the quaternion rotation from a vec3 (euler)
* @param vec3 The euler rotation vector (degrees)
* @return quat The quaternion
*/
function eulerToQuat(e) {
var q = quat.create();
if(e[0] != 0) quat.rotateX(q, q, degToRad(e[0]));
if(e[1] != 0) quat.rotateY(q, q, degToRad(e[1]));
if(e[2] != 0) quat.rotateZ(q, q, degToRad(e[2]));
return q;
}
/**
* Rotates a point around origin by a euler vec3
* @param vec3 OUT The point to rotate around origin
* @param rotation The euler rotation (radians)
*/
function rotatePoint(point, rotation) {
var cos = [Math.cos(rotation[0]), Math.cos(rotation[1]), Math.cos(rotation[2])];
var sin = [Math.sin(rotation[0]), Math.sin(rotation[1]), Math.sin(rotation[2])];
// Temp vars
var p0, p1, p2;
// Rotating X
p1 = point[1] * cos[0] + point[2] * sin[0];
p2 = point[2] * cos[0] - point[1] * sin[0];
point[1] = p1, point[2] = p2;
// Rotating Y
p0 = point[0] * cos[1] - point[2] * sin[1];
p2 = point[2] * cos[1] + point[0] * sin[1];
point[0] = p0, point[2] = p2;
// Rotating Z
p0 = point[0] * cos[2] - point[1] * sin[2];
p1 = point[1] * cos[2] + point[0] * sin[2];
point[0] = p0, point[1] = p1;
}
/**
* Function which allows heritage and parent constructor calling.
* Usage :
* var Child = function() {
* this.parent([parent constructor parameters]);
* };
* Child.extend(Parent);
*/
Function.prototype.extend = function(Parent) {
this.prototype = Object.create(Parent.prototype);
this.prototype.constructor = this;
this.prototype.parent = function(/* any args */) {
Parent.apply(this, arguments);
};
};
/**
* Debug function. Unlimited number of parameters can be passed
*/
function print(/* any objects, any type, any quantity */) {
var s = "";
var seen = [];
for(i = 0 ; i < arguments.length ; i++) {
if(i != 0) {
s += "<br />";
}
s += JSON.stringify(
arguments[i],
function(key, val) {
if (typeof val == "object") {
if (seen.indexOf(val) >= 0)
return undefined;
seen.push(val);
}
return val;
}
);
}
// Showing it in the debut container
var container = document.getElementById('print');
if(container !== null) {
container.innerHTML = s;
}
}
// TODO make windows movable to the left, but always seeing the title bar
// TODO dynamic size of window for small screens ?
/**
* Draws an image as a tile, as many times needed to cover the given surface
* @param CanvasRenderingContext2D The context where to draw image
* @param Image The image to draw
* @param int Left side position of the destination surface
* @param int Upper side position of the destination surface
* @param int Width of the destination surface
* @param int Height of the destination surface
* @param int The size of a tile
*/
function canvasDrawTiledImage(context, image, x, y, width, height, tileSize) {
var xTimes = width / tileSize;
var yTimes = height / tileSize;
var xLast = xTimes - Math.floor(xTimes);
var yLast = yTimes - Math.floor(yTimes);
xTimes = Math.ceil(xTimes);
yTimes = Math.ceil(yTimes);
// Now we know which part to take for the last images (right and bottom), and the repeat number
for(var i = 0 ; i < xTimes ; i++) {
var isLastAndNotFullWidth = i == xTimes - 1 && xLast > 0;
var destX = Math.floor(x + i * tileSize);
var destW = Math.ceil(isLastAndNotFullWidth ? tileSize * xLast : tileSize);
var sourceW = Math.ceil(isLastAndNotFullWidth ? image.width * xLast : image.width);
for(var j = 0 ; j < yTimes ; j++) {
var isLastAndNotFullHeight = j == yTimes - 1 && yLast > 0;
var destY = Math.floor(y + j * tileSize);
var destH = Math.ceil(isLastAndNotFullHeight ? tileSize * yLast : tileSize);
var sourceH = Math.ceil(isLastAndNotFullHeight ? image.height * yLast : image.height);
context.drawImage(
image,
0, // Source X
0, // Source Y
sourceW, // Source width
sourceH, // Source height
destX, // Destination X
destY, // Destination Y
destW, // Destination width
destH // Destination height
);
}
}
};
|
// import LineSeries from '../line-series';
xdescribe('LineSeries', () => {
});
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'eventsource-polyfill', // necessary for hot reloading with IE
'webpack-hot-middleware/client',
'./examples/js/app'
],
output: {
path: path.join(__dirname, 'build'),
filename: 'app.js',
publicPath: '/js/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js/,
loaders: ['babel'],
include: [path.join(__dirname, 'src'), path.join(__dirname, 'examples')]
}]
}
}; |
var ROUTES_INDEX = {"name":"<root>","kind":"module","className":"AppModule","children":[{"name":"routes","filename":"src/app/routing.module.ts","module":"RoutingModule","children":[{"path":"","redirectTo":"main-board","pathMatch":"full"},{"path":"","component":"AppComponent"},{"path":"main-board","component":"BoardComponent"},{"path":"detail","component":"DetailComponent"}],"kind":"module"}]}
|
version https://git-lfs.github.com/spec/v1
oid sha256:baf210740a956fe0d42748a238afec96d1bbcf94cd5ffbda12f3103eb0f20615
size 1898
|
// requestAnimationFrame polyfill
// Thanks Paul Irish (www.paulirish.com/2011/requestanimationframe-for-smart-animating/)
window.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(e){window.setTimeout(e,1e3/60)}}();
/*
// NOTE declare global helpers like this to make them available everywhere
function globalHelper() {
// instructions
// …
}
*/
|
'use strict';
import React from 'react';
import App from './app';
React.render(
<App/>,
document.getElementById('root')
); |
// Copyright 2016-2022, University of Colorado Boulder
/**
* a Scenery Node that represents the sun, clouds, and a slider to control the level of cloudiness in the view
*
* @author John Blanco
* @author Andrew Adare
*/
import NumberProperty from '../../../../axon/js/NumberProperty.js';
import Property from '../../../../axon/js/Property.js';
import Matrix3 from '../../../../dot/js/Matrix3.js';
import Range from '../../../../dot/js/Range.js';
import Vector2 from '../../../../dot/js/Vector2.js';
import { Shape } from '../../../../kite/js/imports.js';
import ModelViewTransform2 from '../../../../phetcommon/js/view/ModelViewTransform2.js';
import PhetFont from '../../../../scenery-phet/js/PhetFont.js';
import { HBox } from '../../../../scenery/js/imports.js';
import { Image } from '../../../../scenery/js/imports.js';
import { Node } from '../../../../scenery/js/imports.js';
import { Path } from '../../../../scenery/js/imports.js';
import { Text } from '../../../../scenery/js/imports.js';
import { VBox } from '../../../../scenery/js/imports.js';
import { Color } from '../../../../scenery/js/imports.js';
import { RadialGradient } from '../../../../scenery/js/imports.js';
import Panel from '../../../../sun/js/Panel.js';
import VSlider from '../../../../sun/js/VSlider.js';
import cloud_png from '../../../images/cloud_png.js';
import EFACConstants from '../../common/EFACConstants.js';
import EFACQueryParameters from '../../common/EFACQueryParameters.js';
import EnergyChunkLayer from '../../common/view/EnergyChunkLayer.js';
import energyFormsAndChangesStrings from '../../energyFormsAndChangesStrings.js';
import energyFormsAndChanges from '../../energyFormsAndChanges.js';
import Cloud from '../model/Cloud.js';
import SunEnergySource from '../model/SunEnergySource.js';
import LightRays from './LightRays.js';
import MoveFadeModelElementNode from './MoveFadeModelElementNode.js';
const cloudsString = energyFormsAndChangesStrings.clouds;
const lotsString = energyFormsAndChangesStrings.lots;
const noneString = energyFormsAndChangesStrings.none;
// constants
const CONTROL_PANEL_TITLE_FONT = new PhetFont( 16 );
const CONTROL_PANEL_TEXT_MAX_WIDTH = 50;
const SLIDER_LABEL_FONT = new PhetFont( 12 );
class SunNode extends MoveFadeModelElementNode {
/**
* @param {SunEnergySource} sun Sun model element
* @param {Property} energyChunksVisibleProperty
* @param {ModelViewTransform2} modelViewTransform
* @param {Tandem} tandem
*/
constructor( sun, energyChunksVisibleProperty, modelViewTransform, tandem ) {
super( sun, modelViewTransform, tandem );
const sunCenter = modelViewTransform.modelToViewDelta( SunEnergySource.OFFSET_TO_CENTER_OF_SUN );
const sunRadius = modelViewTransform.modelToViewDeltaX( sun.radius );
const lightRays = new LightRays( sunCenter, sunRadius, 1000, 40, Color.YELLOW );
this.addChild( lightRays );
// turn off light rays when energy chunks are visible
energyChunksVisibleProperty.link( chunksVisible => {
lightRays.setVisible( !chunksVisible );
} );
// add the sun
const sunShape = Shape.ellipse( 0, 0, sunRadius, sunRadius );
const sunPath = new Path( sunShape, {
fill: new RadialGradient( 0, 0, 0, 0, 0, sunRadius )
.addColorStop( 0, 'white' )
.addColorStop( 0.25, 'white' )
.addColorStop( 1, '#FFD700' ),
lineWidth: 1,
stroke: 'yellow'
} );
sunPath.setTranslation( sunCenter );
// create a scale-only MVT since translation of the absorption shapes is done separately
const scaleOnlyMVT = ModelViewTransform2.createSinglePointScaleInvertedYMapping(
Vector2.ZERO,
Vector2.ZERO,
modelViewTransform.getMatrix().getScaleVector().x
);
// add clouds, initially transparent
sun.clouds.forEach( cloud => {
// make a light-absorbing shape from the cloud's absorption ellipse
const cloudAbsorptionShape = cloud.getCloudAbsorptionReflectionShape();
const translatedCloudAbsorptionShape = cloudAbsorptionShape.transformed( Matrix3.translation(
-sun.positionProperty.value.x,
-sun.positionProperty.value.y
) );
const scaledAndTranslatedCloudAbsorptionShape = scaleOnlyMVT.modelToViewShape( translatedCloudAbsorptionShape );
const lightAbsorbingShape = new LightAbsorbingShape( scaledAndTranslatedCloudAbsorptionShape, 0 );
cloud.existenceStrengthProperty.link( existenceStrength => {
lightAbsorbingShape.absorptionCoefficientProperty.set( existenceStrength / 10 );
} );
lightRays.addLightAbsorbingShape( lightAbsorbingShape );
const cloudNode = new CloudNode( cloud, modelViewTransform );
cloudNode.opacity = 0;
this.addChild( cloudNode );
if ( EFACQueryParameters.showHelperShapes ) {
this.addChild( new Path( scaledAndTranslatedCloudAbsorptionShape, {
stroke: 'red'
} ) );
}
} );
// add the energy chunks, which reside on their own layer
this.addChild( new EnergyChunkLayer( sun.energyChunkList, modelViewTransform, {
parentPositionProperty: sun.positionProperty
} ) );
this.addChild( sunPath );
const cloudsPanelTandem = tandem.createTandem( 'cloudsPanel' );
// add slider panel to control cloudiness
const slider = new VSlider(
sun.cloudinessProportionProperty,
new Range( 0, 1 ), {
top: 0, left: 0,
tandem: cloudsPanelTandem.createTandem( 'slider' )
}
);
const tickLabel = label => {
return new Text( label, {
font: SLIDER_LABEL_FONT,
maxWidth: CONTROL_PANEL_TEXT_MAX_WIDTH
} );
};
slider.addMajorTick( 0, tickLabel( noneString ) );
slider.addMajorTick( 1, tickLabel( lotsString ) );
const titleText = new Text( cloudsString, {
font: CONTROL_PANEL_TITLE_FONT,
maxWidth: CONTROL_PANEL_TEXT_MAX_WIDTH
} );
const iconNode = new Image( cloud_png, { scale: 0.25 } );
const titleBox = new HBox( {
children: [ titleText, iconNode ],
spacing: 10
} );
const panelContent = new VBox( {
children: [ titleBox, slider ],
spacing: 10,
resize: false
} );
this.addChild( new Panel( panelContent, {
fill: EFACConstants.CONTROL_PANEL_BACKGROUND_COLOR,
stroke: EFACConstants.CONTROL_PANEL_OUTLINE_STROKE,
lineWidth: EFACConstants.CONTROL_PANEL_OUTLINE_LINE_WIDTH,
cornerRadius: EFACConstants.CONTROL_PANEL_CORNER_RADIUS,
centerX: 0,
centerY: 0,
resize: false,
tandem: cloudsPanelTandem
} ) );
// add/remove the light-absorbing shape for the solar panel
let currentLightAbsorbingShape = null;
// visible absorption shape used for debugging
let helperAbsorptionNode = null;
Property.multilink(
[ sun.activeProperty, sun.solarPanel.activeProperty ],
( sunActive, solarPanelActive ) => {
if ( sunActive && solarPanelActive ) {
const absorptionShape = sun.solarPanel.getAbsorptionShape();
const translatedAbsorptionShape = absorptionShape.transformed( Matrix3.translation(
-sun.positionProperty.value.x,
-sun.positionProperty.value.y
) );
const scaledAndTranslatedAbsorptionShape = scaleOnlyMVT.modelToViewShape( translatedAbsorptionShape );
currentLightAbsorbingShape = new LightAbsorbingShape( scaledAndTranslatedAbsorptionShape, 1 );
lightRays.addLightAbsorbingShape( currentLightAbsorbingShape );
// for debug, show absorption shape outline with dotted line visible on top of SolarPanel's helper shape
if ( EFACQueryParameters.showHelperShapes ) {
helperAbsorptionNode = new Path( scaledAndTranslatedAbsorptionShape, {
stroke: 'lime',
lineDash: [ 4, 8 ]
} );
this.addChild( helperAbsorptionNode );
}
}
else if ( currentLightAbsorbingShape !== null ) {
lightRays.removeLightAbsorbingShape( currentLightAbsorbingShape );
currentLightAbsorbingShape = null;
// for debug
if ( EFACQueryParameters.showHelperShapes && helperAbsorptionNode ) {
this.removeChild( helperAbsorptionNode );
helperAbsorptionNode = null;
}
}
}
);
}
}
class LightAbsorbingShape {
/**
* inner type - a shape with observable light absorption coefficient
* @param {Shape} shape
* @param {number} initialAbsorptionCoefficient
*/
constructor( shape, initialAbsorptionCoefficient ) {
// @public {NumberProperty}
this.absorptionCoefficientProperty = new NumberProperty( initialAbsorptionCoefficient, {
range: new Range( 0, 1 )
} );
// @public (read-only) {Shape}
this.shape = shape;
}
}
class CloudNode extends Node {
/**
* inner type - a cloud
* @param cloud
* @param modelViewTransform
*/
constructor( cloud, modelViewTransform ) {
super();
const cloudNode = new Image( cloud_png );
cloudNode.scale(
modelViewTransform.modelToViewDeltaX( Cloud.WIDTH ) / cloudNode.width,
-modelViewTransform.modelToViewDeltaY( Cloud.HEIGHT ) / cloudNode.height
);
this.addChild( cloudNode );
this.center = modelViewTransform.modelToViewDelta( cloud.offsetFromParent );
cloud.existenceStrengthProperty.link( opacity => {
this.opacity = opacity;
} );
}
}
energyFormsAndChanges.register( 'SunNode', SunNode );
export default SunNode; |
'use strict';
angular.module('spedycjacentralaApp')
.controller('RegisterController', function ($scope, $translate, $timeout, Auth) {
$scope.success = null;
$scope.error = null;
$scope.doNotMatch = null;
$scope.errorUserExists = null;
$scope.registerAccount = {};
$timeout(function (){angular.element('[ng-model="registerAccount.login"]').focus();});
$scope.register = function () {
if ($scope.registerAccount.password !== $scope.confirmPassword) {
$scope.doNotMatch = 'ERROR';
} else {
$scope.registerAccount.langKey = $translate.use();
$scope.doNotMatch = null;
$scope.error = null;
$scope.errorUserExists = null;
$scope.errorEmailExists = null;
Auth.createAccount($scope.registerAccount).then(function () {
$scope.success = 'OK';
}).catch(function (response) {
$scope.success = null;
if (response.status === 400 && response.data === 'login already in use') {
$scope.errorUserExists = 'ERROR';
} else if (response.status === 400 && response.data === 'e-mail address already in use') {
$scope.errorEmailExists = 'ERROR';
} else {
$scope.error = 'ERROR';
}
});
}
};
});
|
/* jQuery.Feyn.js, version 1.0.1, MIT License
* plugin for drawing Feynman diagrams with SVG
*
* https://github.com/photino/jquery-feyn
*
* author: Zan Pan <panzan89@gmail.com>
* date: 2014-2-28
*
* usage: $(container).feyn(options);
*/
;(function($) {
'use strict';
// add method to jQuery prototype
$.fn.feyn = function(options) {
// iterate over the current set of matched elements
return this.each(function() {
// return early if this element already has an instance
if($(this).data('feyn')) {
return;
}
// create an Feyn instance
try {
$(this).html(new Feyn(this, options).output());
$(this).data('feyn', true);
} catch(error) {
$(this).html('JavaScript ' + error.name + ': ' + error.message);
}
});
};
// create Feyn object as a constructor
var Feyn = function(container, options) {
// count instances
Feyn.counter = (Feyn.counter || 0) + 1;
Feyn.prefix = 'feyn' + (Feyn.counter > 1 ? Feyn.counter : '');
// merge options with defaults
var opts = $.extend(true, {
xmlns: 'http://www.w3.org/2000/svg', // the "xmlns" attribute of <svg>
xlink: 'http://www.w3.org/1999/xlink', // the "xlink:href" attribute of <svg>
version: '1.1', // the "version" attribute of <svg>
x: 0, // the "x" attribute of <svg>
y: 0, // the "y" attribute of <svg>
width: 200, // the "width" attribute of <svg>
height: 200, // the "height" attribute of <svg>
title: '', // the "title" attribute of <svg>
description: 'Feynman diagram generated by jQuery.Feyn', // the "desc" attribute of <svg>
standalone: false, // disable the SVG code editor
selector: false, // don't set the "id" and "class" attributes for SVG elements
grid: {
show: false, // don't display a grid system
unit: 20 // length of subdivision for the grid system
},
color: 'black', // global "stroke" attribute for SVG elements
thickness: 1.6, // global "stroke-width" attribute for SVG elements
tension: 1, // global parameter of arc radius and zigzag amplitude
ratio: 1, // global parameter of elliptical arc, i.e. the ratio of y-radius to x-radius
clockwise: false, // global clockwise parameter for propagators
incoming: {}, // graph nodes for incoming particles
outgoing: {}, // graph nodes for outgoing particles
vertex: {}, // graph nodes for vertices
auxiliary: {}, // graph nodes for miscellaneous symbols
fermion: {
arrow: true // show arrows for fermion propagators
},
photon: {
period: 5, // the period parameter for photon propagators, i.e. 1/4 of the period of sine curve
amplitude: 5 // the amplitude parameter for photon propagators, i.e. the amplitude of sine curve
},
scalar: {
arrow: false, // don't show arrows for scalar propagators
dash: '5 5', // the "stroke-dasharray" attribute for <g> into which scalar propagators are grouped
offset: 2 // the "stroke-offset" attribute for <g> into which scalar propagators are grouped
},
ghost: {
arrow: true, // show arrows for ghost propagators
thickness: 3, // direction of arrows for arc and loop ghost propagators
dotsep: 8, // the "stroke-dasharray" attribute for <g> into which ghost propagators are grouped
offset: 5 // the "stroke-offset" attribute for <g> into which ghost propagators are grouped
},
gluon: {
width: 15, // the coil width of gluon propagators
height: 15, // the coil height of gluon propagators
factor: 0.75, // the factor parameter for gluon propagators
percent: 0.6, // the percent parameter for gluon propagators
scale: 1.15 // the scale parameter for gluon arcs and loops
},
symbol: {}, // elements for symbols
node: {
show: false, // don't show nodes
thickness: 1, // the "stroke-width" attribute for <g> into which nodes are grouped
type: 'dot', // the node type
radius: 3, // the radius parameter of nodes
fill: 'white' // the "fill" attribute for <g> into which nodes are grouped
},
label: {
family: 'Georgia', // the "font-family" attribute for <g> into which labels are grouped
size: 15, // the "font-size" attribute for <g> into which labels are grouped
face: 'italic' // the "font-style" attribute for <g> into which labels are grouped
},
image: {}, // include external image
mathjax: false, // don't use MathJax to typeset mathematics in labels
ajax: false // don't merge the code of external SVG image directly
}, options);
// constants
var PI = Math.PI;
// style of propagator for different particles
var all = {
fill: 'none', // the "fill" attribute for all SVG elements
color: opts.color, // the "stroke" attribute for all SVG elements
thickness: opts.thickness // the "stroke-width" attribute for all SVG elements
},
sty = {
fermion: {}, // the style for fermion propagators
photon: {}, // the style for photon propagators
gluon: {}, // the styles for gluon propagators
scalar: {
dash: opts.scalar.dash, // the "stroke-dasharray" attribute for scalar propagators
offset: opts.scalar.offset // the "stroke-offset" attribute for scalar propagators
},
ghost: {
dash: '0.1 ' + opts.ghost.dotsep, // the "stroke-offset" attribute for ghost propagators
offset: opts.ghost.offset // the "stroke-offset" attribute for ghost propagators
}
};
// set global attributes for propagators
for(var key in sty) {
sty[key] = $.extend(true, {}, all, {
color: opts[key].color,
thickness: opts[key].thickness,
linecap: 'round'
}, sty[key]);
}
// graph nodes for Feynman diagram
var nd = $.extend({},
opts.incoming,
opts.outgoing,
opts.vertex,
opts.auxiliary
);
for(key in nd) {
// remove extra space characters in node coordinates
nd[key] = nd[key].replace(/\s/g, ',').split(/,+/, 2);
}
// graph edges for Feynman diagram
var fd = {
fermion: {},
photon: {},
scalar: {},
ghost: {},
gluon: {}
};
for(var par in fd) {
fd[par] = $.extend({}, opts[par]);
for(key in fd[par]) {
if(!key.match(/line|arc|loop/)) {
// ensure that graph edges don't have attributes for style
delete fd[par][key];
} else {
// remove extra space characters in edge connections
fd[par][key] = fd[par][key].replace(/\s/g, '').split(',');
for(var ind in fd[par][key]) {
// remove extra dash marks in edge connections
fd[par][key][ind] = fd[par][key][ind].replace(/-+/g, '-').split('-');
}
}
}
}
// attributes for labels
var lb = {
sty: {
fill: opts.label.fill || opts.label.color || all.color,
color: opts.label.color || all.color,
thickness: opts.label.thickness || 0,
family: opts.label.family,
size: opts.label.size,
weight: opts.label.weight,
face: opts.label.face,
align: opts.label.align || 'middle'
},
pos: opts.label
};
for(key in lb.pos) {
if(lb.sty[key]) {
delete lb.pos[key];
}
}
// collector for SVG elements
var svg = {
defs: [], // collector for <defs>
body: [], // collector for graphics elements
tags: [ // self-closing tags
'path',
'line',
'rect',
'circle',
'ellipse',
'polygon',
'polyline',
'image',
'use'
],
attr: { // map JavaScript object attributes into SVG attributes
xlink: 'xmlns:xlink',
href: 'xlink:href',
color: 'stroke',
thickness: 'stroke-width',
dash: 'stroke-dasharray',
linecap: 'stroke-linecap',
linejoin: 'stroke-linejoin',
offset: 'stroke-dashoffset',
family: 'font-family',
size: 'font-size',
face: 'font-style',
weight: 'font-weight',
align: 'text-anchor'
}
};
// create SVG element
var create = function(elem, attr, sty, child) {
var str = '';
attr = $.extend({}, attr, sty);
for(var key in attr) {
str += ' ' + (svg.attr[key] || key) + '="' + attr[key] + '"';
}
return '<' + elem + str + (svg.tags.indexOf(elem) >= 0 ? '/>' :
'>' + (elem.match(/title|desc|tspan|body/) ? '': '\n') + (child ?
child.replace(/</g, ' <').replace(/\s+<\/(title|desc|tspan|body)/g,
'</$1') : '') + '</' + elem + '>') + '\n';
};
// convert float number to string
var normalize = function() {
var str = '';
for(var i = 0, l = arguments.length, item; i < l; i++) {
item = arguments[i];
str += ' ' + (typeof item !== 'number' ? item :
item.toFixed(3).replace(/(.\d*?)0+$/, '$1').replace(/\.$/, ''));
}
return $.trim(str).replace(/ ?, ?/g, ',');
};
// transform coordinate system
var system = function(sx, sy, ex, ey) {
var dx = ex - sx,
dy = ey - sy;
return {angle: Math.atan2(dy, dx), distance: Math.sqrt(dx * dx + dy * dy)};
};
// set transformation
var transform = function(x, y, angle) {
return 'translate(' + normalize(x, ',', y) + ')' +
(angle ? ' rotate(' + normalize(angle * 180 / PI) + ')' : '');
};
// get coordinate pairs
var point = function(sx, sy, ex, ey, x, y) {
var ang = Math.atan2(ey - sy, ex - sx);
return normalize(x * Math.cos(ang) - y * Math.sin(ang) + sx, ',',
x * Math.sin(ang) + y * Math.cos(ang) + sy);
};
// parse position string
var position = function(pos) {
return nd[pos] || pos.replace(/\s/g, ',').split(/,+/, 2);
};
// set the "id" attribute for SVG elements
var setId = function(name) {
return opts.selector ? {id: Feyn.prefix + '_' + name} : {};
};
// set the "class" attribute for <g>
var setClass = function(name) {
return opts.selector ? {'class': name} : {};
};
// set arrows for fermion, scalar, and ghost propagators
var setArrow = function(par, x, y, angle, name) {
var t = 2 * (par == 'ghost' ? sty.fermion.thickness : sty[par].thickness);
return opts[par].arrow ? create('polygon', $.extend({points:
normalize('0,0', -t, ',', 1.25 * t, 1.5 * t, ',0', -t, ',', -1.25 * t)},
{transform: transform(x, y, angle)}), setId(name)) : '';
};
// get path for photon and gluon line
var linePath = function(tile, period, distance) {
var bezier = ['M'],
num = Math.floor(distance / period),
extra = distance - period * num + 0.1;
for(var n = 0; n <= num; n++) {
for(var i = 0, l = tile.length, item; i < l; i++) {
item = tile[i];
if($.isArray(item)) {
// ensure that the number of tiles is an integer
if(n < num || item[0] < extra) {
bezier.push(normalize(item[0] + period * n, ',', item[1]));
} else {
break;
}
} else {
bezier.push(item);
}
}
}
return bezier.join(' ').replace(/\s[A-Z][^A-Z]*$/, '');
};
// get path for photon and gluon arc
var arcPath = function(par, tile, period, distance) {
var t = 0.25 * Math.max(opts[par].tension || opts.tension, 2),
phi = Math.acos(-0.5 / t),
theta = -2 * Math.asin(period / (t * distance)),
segment = [],
bezier = ['M', '0,0'];
// get coordinate pairs for the endpoint of segment
for(var n = 0; n <= (PI - 2 * phi) / theta; n++) {
segment.push([distance * (t * Math.cos(theta * n + phi) + 0.5),
distance * (t * Math.sin(theta * n + phi) - Math.sqrt(t * t - 0.25))]);
}
for(var i = 0, l = segment.length - 1, model; i < l; i++) {
// two photon tiles form a period whereas one gluon tile is a period
model = (par == 'photon' ? tile[i % 2] : tile);
// get bezier path for photon and gluon arc
for(var j = 0, m = model.length, item; j < m; j++) {
item = model[j];
bezier.push($.isArray(item) ? point(segment[i][0], segment[i][1],
segment[i+1][0], segment[i+1][1], item[0], item[1]) : item);
}
}
return bezier.join(' ').replace(/\s[A-Z]$/, '');
};
// get path for photon and gluon loop
var loopPath = function(par, tile, period, distance) {
var theta = 2 * Math.asin(2 * period / distance),
num = 2 * PI / theta,
segment = [],
lift = (opts[par].clockwise ? -0.5 : 0.5),
bezier = ['M', (par == 'gluon' ? lift + ',0' : '0,' + lift)];
// find the modified distance such that the number of tiles is an integer
for(var x = -0.1, dis = distance; Math.floor(num) % 4 ||
num - Math.floor(num) > 0.1; x += 0.001) {
distance = (1 + x) * dis;
theta = 2 * Math.asin(2 * period / distance);
num = 2 * PI / theta;
}
// get coordinate pairs for the endpoint of segment
for(var n = 0; n <= num; n++) {
segment.push([0.5 * distance * (1 - Math.cos(theta * n)),
0.5 * distance * Math.sin(theta * n)]);
}
for(var i = 0, l = segment.length - 1, model; i < l; i++) {
// two photon tiles form a period whereas one gluon tile is a period
model = (par == 'photon' ? tile[i % 2] : tile);
// get bezier path for photon and gluon arc
for(var j = 0, m = model.length, item; j < m; j++) {
item = model[j];
bezier.push($.isArray(item) ? point(segment[i][0], segment[i][1],
segment[i+1][0], segment[i+1][1], item[0], item[1]) : item);
}
}
return bezier.join(' ').replace(/\s[A-Z]$/, '') + ' Z';
};
// get path for photon propagator
var photonPath = function(distance, shape) {
var lambda = 0.51128733,
a = opts.photon.amplitude || 5,
b = 0.5 * lambda * a,
p = opts.photon.period || 5,
q = 2 * p / PI,
t = lambda * p / PI,
dir = opts.photon.clockwise || opts.clockwise,
/*
* reference: http://mathb.in/1447
*
* the approximation of the first quarter of one period of sine curve
* is a cubic Bezier curve with the following control points:
*
* (0, 0) (lambda * p / PI, lambda * a / 2) (2 * p / PI, a) (p, a)
*/
pts = (dir ? [[0, 0], 'C', [t, -b], [q, -a], [p, -a],
'S', [2 * p - t, -b], [2 * p, 0], 'S', [2 * p + q, a], [3 * p, a],
'S', [4 * p - t, b]] :
[[0, 0], 'C', [t, b], [q, a], [p, a],
'S', [2 * p - t, b], [2 * p, 0], 'S', [2 * p + q, -a], [3 * p, -a],
'S', [4 * p - t, -b]]),
tile = (dir ? [['C', [t, -b], [q, -a], [p, -a],
'S', [2 * p - t, -b], [2 * p + 0.5, 0]],
['C', [t, b], [q, a], [p, a],
'S', [2 * p - t, -b], [2 * p - 0.5, 0]]] :
[['C', [t, b], [q, a], [p, a],
'S', [2 * p - t, b], [2 * p - 0.5, 0]],
['C', [t, -b], [q, -a], [p, -a],
'S', [2 * p - t, -b], [2 * p + 0.5, 0]]]);
return {
line: linePath(pts, 4 * p, distance),
arc: arcPath('photon', tile, p, distance),
loop: loopPath('photon', tile, p, distance)
}[shape];
};
// get path for gluon propagator
var gluonPath = function(distance, shape) {
var kappa = 0.55191502,
// a and b are one-half of the ellipse's major and minor axes
a = opts.gluon.height * opts.gluon.factor,
b = opts.gluon.width * opts.gluon.percent,
// c and d are one-half of major and minor axes of the other ellipse
c = opts.gluon.height * (opts.gluon.factor - 0.5),
d = opts.gluon.width * (1 - opts.gluon.percent),
dir = opts.gluon.clockwise || opts.clockwise,
pts = (dir ? [[0, 0], 'A ' + a + ' ' + b, 0, 0, 1, [a, b], 'A ' +
c + ' ' + d, 0, 1, 1, [a - 2 * c, b], 'A ' + a + ' ' + b, 0, 0, 1] :
[[0, 0], 'A ' + a + ' ' + b, 0, 0, 0, [a, -b], 'A ' + c + ' ' + d,
0, 1, 0, [a - 2 * c, -b], 'A ' + a + ' ' + b, 0, 0, 0]);
a = (dir ? a : opts.gluon.scale * a);
var lift = a / Math.pow(distance, 0.6),
/*
* reference: http://spencermortensen.com/articles/bezier-circle/
*
* the approximation of the first quarter of the ellipse
* is a cubic Bezier curve with the following control points:
*
* (0, b) (kappa * a, b) (a, kappa * b) (a, 0)
*
* a lift is used to remove mitered join of two tiles
*/
tile = (dir ? ['C', [kappa * a, lift], [a, b - kappa * b], [a, b],
'C', [a, b + kappa * d], [a - c + kappa * c, b + d], [a - c, b + d],
'S', [a - 2 * c, b + kappa * d], [a - 2 * c, b], 'C', [a - 2 * c,
b - kappa * b], [2 * (a - c) - kappa * a, 0], [2 * (a - c), -lift]] :
['C', [kappa * a, lift], [a, -b + kappa * b], [a, -b],
'C', [a, -b - kappa * d], [a - c + kappa * c, -b - d], [a - c, -b - d],
'S', [a - 2 * c, -b - kappa * d], [a - 2 * c, -b], 'C', [a - 2 * c,
-b + kappa * b], [2 * (a - c) - kappa * a, 0], [2 * (a - c), -lift]]);
return {
line: linePath(pts, opts.gluon.height, distance),
arc: arcPath('gluon', tile, a - c, distance),
loop: loopPath('gluon', tile, a - c, distance)
}[shape];
};
// plot propagator line
var plotLine = function(sx, sy, ex, ey, par, name) {
var path = {
photon: photonPath,
gluon: gluonPath
},
axis = system(sx, sy, ex, ey),
id = setId(name + '_line');
/*
* for photon and gluon line, we use the method photonPath and gluonPath;
* for fermion, scalar, and ghost line, we create <line> directly
*/
return par.match(/photon|gluon/) ?
[create('path', {d: path[par](axis.distance, 'line'),
transform: transform(sx, sy, axis.angle)}, id), ''] :
[create('line', {x1: sx, y1: sy, x2: ex, y2: ey}, id),
setArrow(par, 0.5 * (sx + ex), 0.5 * (sy + ey), axis.angle,
name + '_line_arrow')];
};
// plot propagator arc
var plotArc = function(sx, sy, ex, ey, par, name) {
var path = {
photon: photonPath,
gluon: gluonPath
},
axis = system(sx, sy, ex, ey),
id = setId(name + '_arc'),
t = 0.5 * Math.max(opts[par].tension || opts.tension, 1),
f = t - Math.sqrt(Math.abs(t * t - 0.25)),
w = axis.distance,
ang = axis.angle,
hx = f * w * Math.sin(ang),
hy = f * w * Math.cos(ang),
dir = opts[par].clockwise || opts.clockwise;
/*
* for photon and gluon arc, we use the method photonPath and gluonPath;
* for fermion, scalar, and ghost arc, we create elliptical arc directly
*/
return par.match(/photon|gluon/) ? [create('path', {d: path[par]
(w, 'arc'), transform: transform(sx, sy, ang)}, id), ''] :
[create('path', {d: normalize('M 0,0 A', t * w, t * w,
'0 0 1', w, ',0'), transform: transform(sx, sy, ang)}, id),
setArrow(par, 0.5 * (sx + ex) + hx, 0.5 * (sy + ey) - hy,
ang + (dir ? PI : 0), name + '_arc_arrow')];
};
// plot propagator loop
var plotLoop = function(sx, sy, ex, ey, par, name) {
var path = {
photon: photonPath,
gluon: gluonPath
},
axis = system(sx, sy, ex, ey),
id = setId(name + '_loop'),
arrow = name + '_loop_arrow_',
ratio = opts[par].ratio || opts.ratio,
w = 0.5 * axis.distance,
ang = axis.angle,
hx = ratio * w * Math.sin(ang),
hy = ratio * w * Math.cos(ang),
dir = opts[par].clockwise || opts.clockwise;
/*
* for photon and gluon loop, we use the method photonPath and gluonPath;
* for fermion, scalar, and ghost loop, we create <ellipse> directly
*/
return par.match(/photon|gluon/) ? [create('path', {d: path[par]
(2 * w, 'loop'), transform: transform(sx, sy, ang)}, id), ''] :
[create('ellipse', {cx: normalize(w), cy: 0, rx: normalize(w),
ry: normalize(ratio * w), transform: transform(sx, sy, ang)}, id),
setArrow(par, 0.5 * (sx + ex) + hx, 0.5 * (sy + ey) - hy, ang +
(dir ? PI : 0), arrow + '1') + setArrow(par, 0.5 * (sx + ex) - hx,
0.5 * (sy + ey) + hy, ang + (dir ? 0 : PI), arrow + '2')];
};
// set graph edges
var setEdge = function() {
var elems = [],
edge = [],
pts = [],
funcs = {
line: plotLine,
arc: plotArc,
loop: plotLoop
};
for(var par in fd) {
var group = [],
shape = '',
arrow = '';
for(var key in fd[par]) {
for(var ind in fd[par][key]) {
edge = fd[par][key][ind];
pts[0] = nd[edge[0]];
for(var i = 1, l = edge.length; i < l; i++) {
pts[i] = nd[edge[i]];
group = funcs[key](+pts[i-1][0], +pts[i-1][1], +pts[i][0],
+pts[i][1], par, edge[i-1] + '_' + edge[i]);
shape += group[0];
arrow += group[1];
}
}
}
// group the propagators with the same type
elems.push(shape ? create('g', setClass(par), sty[par], shape +
(opts[par].arrow ? create('g', setClass(par + '_' + 'arrow'),
{fill: sty[par].color, thickness: 0}, arrow) : '')) : '');
}
return elems.join('');
};
// set symbols
var setSymbol = function() {
var style = $.extend({}, all, {
color: opts.symbol.color,
thickness: opts.symbol.thickness
}),
t = style.thickness,
h = 0,
group = '';
delete opts.symbol.color;
delete opts.symbol.thickness;
for(var key in opts.symbol) {
var item = opts.symbol[key],
coord = position(item[0]),
trans = {transform: transform(coord[0], coord[1], item[1] * PI / 180)},
type = item[2],
s = item[3] || 20,
p = item[4] || 4,
variant = item[5],
id = setId(key + '_' + type),
pts = '0,0';
if(type == 'arrow') {
h = (2 * p > s ? Math.sqrt(p * p - s * s / 4) : (2 * p == s ? 1 : 0));
} else if(type == 'zigzag') {
for(var i = 0; i <= 0.5 * s / p; i++) {
pts += ' ' + normalize(p * (2 * i + 1), ',', (opts.tension + 0.2) *
p * (1 - 2 * (i % 2)), 2 * p * (i + 1), ',0');
}
}
group += {
/*
* for straight-line arrow symbol, it only depends on the distance parameter;
* for the arc variant, two parameters are needed: one is for the distance,
* the other is for the radius
*/
arrow: create('g', trans, id,
create('path', {d: (h ? normalize('M 0,0 A', p, p, '0 0 1', s, ',0') :
normalize('M 0,0 L', s, ',0'))}) +
create('polygon', {points: (h ? (variant ? '0,0 ' +
point(0, 0, -2 * h * h / s, h, -2 * t, 2.5 * t) + ' ' +
point(0, 0, -2 * h * h / s, h, 3 * t, 0) + ' ' +
point(0, 0, -2 * h * h / s, h, -2 * t, -2.5 * t) :
normalize(s, ',0') + ' ' +
point(s, 0, s + 2 * h * h / s, h, -2 * t, 2.5 * t) + ' ' +
point(s, 0, s + 2 * h * h / s, h, 3 * t, 0) + ' ' +
point(s, 0, s + 2 * h * h / s, h, -2 * t, -2.5 * t)) :
normalize(s, ',0', s - 2 * t, ',', 2.5 * t, s + 3 * t, ',0',
s - 2 * t, ',', -2.5 * t))}, {fill: style.color, thickness: 0})),
// the blob symbol needs the distance parameter and the height parameter
blob: (variant ? create('path', $.extend({d: normalize('M', p, ',',
-p, 'A', p, p, '0 1 0', p, ',', p, 'L', 2 * s, ',', p, 'A', p,
p, '0 1 0', 2 * s, ',', -p, 'L', p, ',', -p, 'Z')}, trans),
$.extend({fill: 'silver'}, id)) :
create('ellipse', $.extend({cx: s, cy: 0, rx: s, ry: p}, trans),
$.extend({fill: 'silver'}, id))),
// the bubble symbol needs the distance parameter and the height parameter
bubble: create('path', $.extend({d: normalize('M 0,0 C', p, ',',
p, s, ',', p, s, ',0 S', p, ',', -p, '0,0 Z')}, trans), id),
// the condensate symbol needs the distance parameter and the height parameter
condensate: create('g', trans, $.extend({fill: 'black'}, id),
create('rect', {x: -0.5 * s, y: -p, width: s, height: 2 * p},
{fill: 'white', thickness: 0}) +
create('circle', {cx: -0.5 * s, cy: 0, r: p}) +
create('circle', {cx: 0.5 * s, cy: 0, r: p})),
// the hadron symbol needs the distance parameter and the height parameter
hadron: create('g', trans, id, create('path', {d: normalize('M 0,0 L',
s, ',0', 'M 0,', p, 'L', s, ',', p, 'M 0,', -p, 'L', s, ',', -p)}) +
create('polygon', {points: (variant ? normalize(s, ',', 2 * p,
s + 3.6 * p, ',0', s, ',', -2 * p) : normalize(0.5 * s - 1.6 * p,
',', 2 * p, 0.5 * s + 2 * p, ',0', 0.5 * s - 1.6 * p, ',', -2 * p))},
{fill: 'white'})),
// the zigzag symbol needs the distance parameter and the height parameter
zigzag: create('polyline', $.extend({points: pts}, trans), id)
}[type];
}
return group ? create('g', setClass('symbol'), style, group) : '';
};
// set graph nodes
var setNode = function() {
var show = (opts.node.show === true ? 'iova' : opts.node.show),
type = opts.node.type,
style = $.extend({}, all, {
fill: opts.node.fill,
color: opts.node.color,
thickness: opts.node.thickness
}),
nr = opts.node.radius + style.thickness,
a = nr / Math.SQRT2 - (type == 'cross' ? 0 : style.thickness),
group = '';
for(var key in nd) {
if(show.indexOf(key.charAt(0)) >= 0) {
var id = setId(key + '_' + type),
x = +nd[key][0],
y = +nd[key][1],
square = {x: x - nr, y: y - nr, width: 2 * nr, height: 2 * nr},
circle = {cx: x, cy: y, r: nr},
path = {d: normalize('M', -a, ',', -a, 'L', a, ',', a, 'M', -a,
',', a, 'L', a, ',', -a) , transform: transform(x, y, 0)};
// support three node types: cross, dot, and otimes
group += {
box: create('rect', square, id),
boxtimes: create('g', {}, id,
create('rect', square) + create('path', path)),
cross: create('path', path, id),
dot: create('circle', circle, id),
otimes: create('g', {}, id,
create('circle', circle) + create('path', path))
}[type];
}
}
return group ? create('g', setClass('node'), style, group) : '';
};
// format label string
var formatStr = function(str) {
str = str.replace(/[\s\{\}]+/g, '').replace(/(_[^_]+)(\^[^\^]+)/g, '$2$1');
var font = lb.sty.size,
small = {size: Math.round(0.8 * font)},
head = str.charAt(0),
sup = str.indexOf('^') + 1,
sub = str.indexOf('_') + 1,
ind = (sup ? sup : sub),
hx = -0.15 * font,
vy = 0.4 * font;
// support subscript, superscript, bar and tilde accents
return (head.match(/-|~/) ? create('tspan', {dx: normalize('0', 4 * hx),
dy: normalize(-vy, vy)}, {}, (head == '-' ? '–' : head) +
(ind ? str.slice(1, ind - 1) : str.slice(1))) : create('tspan',
{}, {}, (ind ? str.slice(0, ind - 1) : str.slice(0)))) +
(sup ? create('tspan', {dx: normalize(hx), dy: normalize(-vy)}, small,
(sub ? str.slice(sup, sub - 1) : str.slice(sup))) : '') +
(sub ? create('tspan', {dx: normalize((sup ? 5 : 1) * hx),
dy: normalize((sup ? 2 : 1) * vy)}, small, str.slice(sub)) : '');
};
// set annotation labels
var setLabel = function() {
var group = '',
size = lb.sty.size * 2;
for(var key in lb.pos) {
var item = lb.pos[key],
coord = position(item[0]),
attr = {
x: normalize(coord[0]),
y: normalize(coord[1])
},
id = setId(key);
// put label texts in <foreignObject> to provide mathjax support
group += (opts.mathjax ? create('foreignObject', $.extend({}, attr,
{'width': item[2] || size * 0.6, 'height': item[3] || size}), id,
create('body', {'xmlns': 'http://www.w3.org/1999/xhtml'}, {}, item[1])) :
create('text', attr, id, formatStr(item[1])));
}
return group ? create('g', setClass('label'), lb.sty, group) : '';
};
// set annotation images
var setImage = function() {
var group = '';
for(var key in opts.image) {
var item = opts.image[key],
coord = position(item[0]),
x = normalize(coord[0]),
y = normalize(coord[1]),
id = setId(key);
if(opts.ajax) {
// use ajax to load external SVG file
id = (opts.selector ? id.id + '_' : '');
$.ajax({url: item[1], dataType: 'text', async: false,
success: function(data) {
data = data.replace(/<\?.*\?>\n*/, '');
// set the "x" and "y" attributes of <svg>
data = data.slice(0, data.search('>')).replace(/ x=.\d+./, '')
.replace(/ y=.\d+./, '') + data.slice(data.search('>'));
group += data.replace(/>/, ' x="' + x + '" y="' + y + '">')
.replace(/(id=.)/g, '$1' + id).replace(/(href=.#)/g, '$1' + id);
}, error: function() {
throw new Error('fail to load ' + item[1]);
}
});
} else {
group += create('image', {href: item[1], x: x, y: y},
$.extend({width: item[2] || 32, height: item[3] || 32},
(item[3] ? {} : {preserveAspectRatio: 'xMinYMin meet'}), id));
}
}
return group ? create('g', setClass('image'), {}, group) : '';
};
// generate SVG output
this.output = function() {
// detect SVG support
if(!(document.createElementNS &&
document.createElementNS(opts.xmlns, 'svg').createSVGRect)) {
return 'Your browser does not support SVG.';
}
// show SVG grids
if(opts.grid.show) {
var u = normalize(opts.grid.unit);
svg.defs.push(create('pattern', {x: 0, y: 0, width: u, height: u,
viewBox: normalize(0, 0, u, u)}, {patternUnits: 'userSpaceOnUse',
id: Feyn.prefix + '_grid'}, create('polyline', {points:
u + ',0 0,0 0,' + u}, {fill: 'none', color: 'silver'})));
svg.body.push(create('rect', {x: 0, y: 0, width: '100%', height: '100%'},
{fill: 'url(#' + Feyn.prefix + '_grid)', color: 'silver'}));
}
// show graph edges and symbols
svg.body.push(setEdge() + setSymbol());
// show graph nodes
if(opts.node.show) {
svg.body.push(setNode());
}
// show labels and images
svg.body.push(setLabel() + setImage());
// generate SVG source code
var src = create('svg', {xmlns: opts.xmlns, xlink: opts.xlink,
version: opts.version, x: opts.x, y: opts.y,
width: opts.width, height: opts.height,
viewBox: normalize(opts.x, opts.y, opts.width, opts.height)},
(opts.selector ? {id: Feyn.prefix} : {}),
(opts.title ? create('title', {}, {}, opts.title) : '') +
(opts.description ? create('desc', {}, {}, opts.description) : '') +
(svg.defs.length ? create('defs', {}, {}, svg.defs.join('')) : '') +
(svg.body.length ? svg.body.join('') : ''));
// get standalone SVG
if(opts.standalone) {
var code = '<?xml version="1.0" encoding="UTF-8"?>\n' +
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"' +
' "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n' + src;
src = '<div class="feyn" style="display:inline-block;">' + src +
'</div><textarea cols="80" style="margin-left:5px;padding:3px;' +
'height:' + (opts.height - 8) + 'px;" spellcheck="false">' +
code.replace(/&/g, '&').replace(/"(.+?)"/g, ""$1"")
.replace(/</g, '<').replace(/>/g, '>') + '</textarea>';
// update the SVG rendering when the code has changed
$(container).change(function() {
src = $(this).children('textarea').val();
$(this).children('.feyn').html(src.slice(src.search('<svg')));
});
}
return src;
};
};
})(jQuery);
|
window.onload = function() {
// 绘制棋盘
boardRendering();
cvs.onclick = function(e) {
if (gameOver) return;
var i = Math.floor(e.offsetX / 30);
var j = Math.floor(e.offsetY / 30);
if (board[i][j] === 0) {
moves.push({
x: i,
y: j,
color: pieceColor
});
// 悔棋后又下了一步则之前存储的已悔棋清空,无法再撤销
retractions = [];
pieceRendering(i, j, pieceColor);
}
}
retractBtn.onclick = function() {
retract();
}
abortRetractBtn.onclick = function() {
abortRetract();
}
restartBtn.onclick = function() {
window.location.reload();
}
}
|
import template from './user-auth.html';
export default {
template,
bindings: {
success: '&'
},
controller
};
function controller() {
this.action = 'signin';
}
|
let mySet = new Set();
mySet.add(1);
mySet.add(5);
mySet.add('some text');
let o = {a: 1, b: 2};
mySet.add(o);
mySet.has(1); // true
mySet.has(3); // false, 3 has not been added to the set
mySet.has(5); // true
mySet.has(Math.sqrt(25)); // true
mySet.has('Some Text'.toLowerCase()); // true
mySet.has(o); // true
mySet.size; // 4
mySet.delete(5); // removes 5 from the set
mySet.has(5); // false, 5 has been removed
mySet.size; // 3, we just removed one value
|
function parseInterval(value) {
var result = new Date(1,1,1);
result.setMilliseconds(value*1000);
return result;
} |
var request = require('request');
var util = require('../util');
var _ = require('underscore');
// load all the required json files
var config = require('../config.json');
var mapping = require('./mapping.json');
var meta = require('./river.json');
// set up the local config vars
var index = util.dbUrl(config.elasticsearch);
var river = util.riverUrl(config.elasticsearch);
meta.couchdb.db = config.couchdb.db;
meta.index.index = config.elasticsearch.db;
// short hand for the promises later
var log = console.log.bind(console);
var del = _.partial(util.promise, request.del);
// Attempt to delete the old rivers, but create new
// ones regardless of the outcome.
_.when(del(river), del(index))
.then(createThings, createThings)
.done(function(){ log('Created ES search Index'); })
.fail(function(){ log('ES search Index failed'); });
function createThings() {
return _.when(
put(index, mapping),
put(river + '/_meta', meta)
);
}
function put(url, data) {
return util.promise(request.put, {
url: url,
json: data
});
}
|
// @flow
export { default } from './SubCardSelectSearchField';
|
// All symbols in the Variation Selectors block as per Unicode v3.2.0:
[
'\uFE00',
'\uFE01',
'\uFE02',
'\uFE03',
'\uFE04',
'\uFE05',
'\uFE06',
'\uFE07',
'\uFE08',
'\uFE09',
'\uFE0A',
'\uFE0B',
'\uFE0C',
'\uFE0D',
'\uFE0E',
'\uFE0F'
]; |
export const signIn = (body) => ({
path: '/auth/sign-in',
method: 'POST',
body: body
})
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: String.prototype.match (regexp)
es5id: 15.5.4.10_A1_T10
description: Call match (regexp) function with object argument
---*/
var __obj = {toString:function(){return "\u0041B";}}
var __str = "ABB\u0041BABAB";
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
with(__str){
if (match(__obj)[0] !=="AB") {
$ERROR('#1: var x; var __obj = {toString:function(){return "\u0041B";}}; var __str = "ABB\u0041BABAB"; match(__obj)[0] ==="AB". Actual: '+match(__obj)[0] );
}
}
//
//////////////////////////////////////////////////////////////////////////////
var x;
|
'use strict';
/* Controllers */
angular.module(
'sfAdmin.controllers',
[ 'sf.services', 'palaso.ui.listview', 'palaso.ui.typeahead', 'ui.bootstrap' ]
)
.controller('UserCtrl', ['$scope', 'userService', function UserCtrl($scope, userService) {
$scope.vars = {
selectedIndex: -1,
editButtonName: "",
editButtonIcon: "",
inputfocus: false,
showPasswordForm: false,
};
$scope.focusInput = function() {
$scope.vars.inputfocus = true;
};
$scope.blurInput = function() {
$scope.vars.inputfocus = false;
};
$scope.selected = [];
$scope.updateSelection = function(event, item) {
var selectedIndex = $scope.selected.indexOf(item);
var checkbox = event.target;
if (checkbox.checked && selectedIndex == -1) {
$scope.selected.push(item);
} else if (!checkbox.checked && selectedIndex != -1) {
$scope.selected.splice(selectedIndex, 1);
}
};
$scope.isSelected = function(item) {
return item != null && $scope.selected.indexOf(item) >= 0;
};
$scope.users = [];
$scope.queryUsers = function(invalidateCache) {
var forceReload = (invalidateCache || (!$scope.users) || ($scope.users.length == 0));
if (forceReload) {
userService.list(function(result) {
if (result.ok) {
$scope.users = result.data.entries;
} else {
$scope.users = [];
};
});
} else {
// No need to refresh the cache: do nothing
}
};
//$scope.queryUsers(); // And run it right away to fetch the data for our list.
$scope.selectRow = function(index, record) {
// console.log("Called selectRow(", index, ", ", record, ")");
$scope.vars.selectedIndex = index;
if (index < 0) {
$scope.vars.record = {};
} else {
$scope.vars.record = record;
$scope.vars.editButtonName = "Save";
$scope.vars.editButtonIcon = "pencil";
}
};
$scope.$watch("vars.record.id", function(newId, oldId) {
// attrs.$observe("userid", function(newval, oldval) {
// console.log("Watch triggered with oldval '" + oldId + "' and newval '" + newId + "'");
if (newId) {
userService.read(newId, function(result) {
$scope.record = result.data;
});
} else {
// Clear data table
$scope.record = {};
}
});
$scope.addRecord = function() {
$scope.selectRow(-1); // Make a blank entry in the "User data" area
// TODO: Signal the user somehow that he should type in the user data area and hit Save
// Right now this is not intuitive, so we need some kind of visual signal
$scope.vars.editButtonName = "Add";
$scope.vars.editButtonIcon = "plus";
$scope.focusInput();
};
// Roles in list
$scope.roles = {
'user': {name: 'User'},
'system_admin': {name: 'System Admin'}
};
$scope.roleLabel = function(role) {
if (role == undefined) {
return '';
}
return $scope.roles[role].name;
};
$scope.updateRecord = function(record) {
// console.log("updateRecord() called with ", record);
if (record === undefined || JSON.stringify(record) == "{}") {
// Avoid adding blank records to the database
return null; // TODO: Or maybe just return a promise object that will do nothing...?
}
var isNewRecord = false;
if (record.id === undefined) {
isNewRecord = true; // Will be used below
record.id = '';
// if (record.groups === undefined) {
// record.groups = [null]; // TODO: Should we put something into the form to allow setting gropus? ... Later, not now.
// }
}
var afterUpdate;
if (record.password) {
afterUpdate = function(result) {
record.id = result.data;
// TODO Don't do this as a separate API call here. CP 2013-07
$scope.changePassword(record);
};
} else {
afterUpdate = function(result) {
// Do nothing
};
}
userService.update(record, function(result) {
afterUpdate(result);
$scope.queryUsers(true);
if (isNewRecord) {
$scope.record = {};
$scope.focusInput();
} else {
$scope.blurInput();
}
});
return true;
};
$scope.removeUsers = function() {
// console.log("removeUsers");
var userIds = [];
for(var i = 0, l = $scope.selected.length; i < l; i++) {
userIds.push($scope.selected[i].id);
}
if (l == 0) {
// TODO ERROR
return;
}
userService.remove(userIds, function(result) {
// Whether result was OK or error, wipe selected list and reload data
$scope.selected = [];
$scope.vars.selectedIndex = -1;
$scope.queryUsers(true);
});
};
$scope.changePassword = function(record) {
// console.log("changePassword() called with ", record);
userService.changePassword(record.id, record.password, function(result) {
// console.log("Password successfully changed.");
});
};
$scope.showPasswordForm = function() {
$scope.vars.showPasswordForm = true;
};
$scope.hidePasswordForm = function() {
$scope.vars.showPasswordForm = false;
};
$scope.togglePasswordForm = function() {
$scope.vars.showPasswordForm = !$scope.vars.showPasswordForm;
};
}])
.controller('PasswordCtrl', ['$scope', 'jsonRpc', function($scope, jsonRpc) {
$scope.changePassword = function(record) {
// Validation
if (record.password != record.confirmPassword) {
console.log("Error: passwords do not match");
// TODO: Learn how to do Angular validation so I can give control back to the user. RM 2013-07
return null;
}
jsonRpc.connct("/api/sf");
params = {
"userid": record.id,
"newPassword": record.password,
};
};
}])
;
|
import registerPromiseWorker from 'promise-worker/register';
import markdownProcessor from './markdownProcessor';
import xssFilter from './xssFilter';
/**
* Process a given markdown string and update the HTML string
* @param {string} markdown - can be mixed with html and css
*/
/*
export default function worker(self) {
self.addEventListener('message', (event) => {
const markdownString = event.data;
let data = markdownProcessor.process(markdownString);
data = xssFilter.filter(data);
self.postMessage(data);
});
}
*/
/* eslint arrow-body-style: 0 */
registerPromiseWorker((data) => {
const markdownString = data;
let processedData = markdownProcessor.process(markdownString);
processedData = xssFilter.filter(processedData);
return processedData;
/*
return Promise.resolve().then((rawData) => {
const markdownString = rawData;
let processedData = markdownProcessor.process(markdownString);
processedData = xssFilter.filter(processedData);
return processedData;
});
*/
});
// to pacify webworkify-webpack
export default function worker() {}
|
class Textbox {
constructor(selector, regex) {
this._elements = $(selector);
this.value = $(this._elements[0]).val();
this.invalidSymbols = regex;
this.elements.on('input', (event) => {
let text = $(event.target).val();
this.value = text;
});
}
get value() {
return this._value;
}
set value(val) {
this._value = val;
for (let element of this.elements) {
$(element).val(val);
}
}
get elements() {
return this._elements;
}
isValid() {
return !this.invalidSymbols.test(this._value);
}
} |
const round = require('./round');
const { mean, median, stddev } = require('./stats');
const arr = [
40.73,
80.2,
59.54,
54.91,
93.57,
35.69,
99.44,
98.14,
89.3,
21.7,
54.26,
64.02,
18.05,
0.18,
14.79,
60.44,
47.63,
52.33,
75.62,
65.03,
];
describe('Stats', () => {
describe('mean', () => {
it('should return 0 for an empty array', () => {
const expected = 0;
expect(mean([])).toEqual(expected);
});
it('should return mean for an array', () => {
const expected = 56.2785;
const actual = round(mean(arr), 4);
expect(actual).toEqual(expected);
});
});
describe('median', () => {
it('should return 0 for an empty array', () => {
const expected = 0;
expect(median([])).toEqual(expected);
});
it('should return median for an array', () => {
const expected = 57.225;
const actual = round(median(arr), 4);
expect(actual).toEqual(expected);
});
});
describe('stddev', () => {
it('should return 0 for an empty array', () => {
const expected = 0;
expect(stddev([])).toEqual(expected);
});
it('should return std for an array', () => {
const expected = 27.834;
const actual = round(stddev(arr), 4);
expect(actual).toEqual(expected);
});
});
});
|
"use strict";
function PauseButton(spriteSheet, layer, id) {
powerupjs.Button.call(this, spriteSheet, layer, id);
this.isPaused = false;
this.position = new powerupjs.Vector2(30, 30);
}
PauseButton.prototype = Object.create(powerupjs.Button.prototype);
PauseButton.prototype.handleInput = function(delta) {
powerupjs.Button.prototype.handleInput.call(this, delta);
// Toggle pause button
if (this.pressed) {
this.isPaused = !this.isPaused;
this.sheetIndex = 1 - this.sheetIndex; // Toggle sheet index between 0 and 1
}
};
|
function TemplateBuilder(){
}
TemplateBuilder.BUILD_MODE = {
NORMAL : 1,
IMAGE_MAP : 2,
BITLY : 3,
IMAGE_MAP_WITH_BITLY : 4
}
TemplateBuilder.create = function(FileSystem, JSDOM, name, htmlToolKit, templateFile, outputDirectory, buildMode){
name = name.replace(/\s/g, "");
//var output = "<span>test3</span>";
var outputFile = outputDirectory + "/" + name;
FileSystem.readFile(templateFile, "utf-8", function(error, data){
if(error){
console.log(error);
throw error;
}
//console.log("Reading: " + data);
var document = JSDOM(data);
var window = document.parentWindow;
console.log(window.document.innerHTML)
var links = window.document.getElementsByTagName("a");
console.log(links);
switch(buildMode){
case TemplateBuilder.BUILD_MODE.IMAGE_MAP:
TemplateBuilder.imageMap(data, outputFile + ".jpg");
break;
default:
break;
}
//
//manipulate template here
FileSystem.writeFile(outputFile, data, function(error){
if(error){
console.log(error);
throw error;
}
//console.log(data);
//console.log("Saved!");
});
});
}
TemplateBuilder.shortenFromDomain = function(fromDomain){
return shortFromDomain;
}
TemplateBuilder.build = function(template, domain){
//if(bitlyDomain == undefined){ bitlyDomain = ""; }
/*
' _ space.repeat(tt.number(3,12)) _ '
*/
//var domainFragments = domain.split("", 3);
//var shatteredDomain =
//template = template.replace(new RegExp("[#domain#]", "gm"), domain);
template = template.replace(/\[\!\#domain\#\!\]/g, domain);
template = template.replace(/\[\!\#domain_fragments\#\!\]/g, TemplateBuilder.domainToFragments(domain));
//template = template.replace(/\[\!\#bitly_domain\#\!\]/g, bitlyDomain);
return template;
}
//does not support subdomains currently
TemplateBuilder.domainToFragments = function(domain){
var domainName = domain.split(".")[0];
var domainNameCharacters = domainName.split("");
var domainNameCharactersCount = domainNameCharacters.length;
var domainFragments = "'";
for(var i=0; i < domainNameCharactersCount; i++){
var domainNameCharacter = domainNameCharacters[i];
domainFragments += domainNameCharacter;
if(( (i + 1) % 3) == 0){
if(i != (domainNameCharactersCount - 1)){
domainFragments += "' _ space.repeat(tt.number(3,12)) _ '";
}
}
}
domainFragments += "'";
return domainFragments;
}
TemplateBuilder.imageMap = function(html, outputFile){
htmlToolKit.htmlToImage(templateFile, outputFile, 800, 0);
//to do --- upload generated image to hosting
}
TemplateBuilder.test = function(){
}
TemplateBuilder.processTokenValues = function(){
}
TemplateBuilder.createWithBitly = function(){
}
TemplateBuilder.createWithImageMapAndBitly = function(){
}
module.exports = TemplateBuilder; |
import {mount} from 'enzyme';
import {expect} from 'chai';
import React from 'react';
import ReactDOM from 'react-dom';
import Alert from '../SAlert';
import sAlertStore from '../s-alert-parts/s-alert-store';
import SAlertContent from '../SAlertContent';
import SAlertContentTmpl from '../SAlertContentTmpl';
import getAlertData from '../s-alert-parts/s-alert-data-prep';
import sAlertTools from '../s-alert-parts/s-alert-tools';
describe('Alert warning function', () => {
let renderedComp;
before(() => {
renderedComp = mount(<Alert />);
Alert.warning('Test warning message...', {timeout: 'none', stack: true, position: 'top-right'});
});
it('should be s-alert warning in the s-alert store', () => {
expect(sAlertStore.getState()[0].message).to.equal('Test warning message...');
expect(sAlertStore.getState()[0].condition).to.equal('warning');
});
it('should be ".s-alert-warning" element in the DOM', () => {
expect(renderedComp.find('.s-alert-warning').length).to.be.equal(1);
});
after(() => Alert.closeAll());
});
describe('Alert info function', () => {
let renderedComp;
before(() => {
renderedComp = mount(<Alert />);
Alert.info('Test info message...', {timeout: 'none', stack: true, position: 'top-right'});
});
it('should be s-alert info in the s-alert store', () => {
expect(sAlertStore.getState()[0].message).to.equal('Test info message...');
expect(sAlertStore.getState()[0].condition).to.equal('info');
});
it('should be ".s-alert-info" element in the DOM', () => {
expect(renderedComp.find('.s-alert-info').length).to.be.equal(1);
});
after(() => Alert.closeAll());
});
describe('Alert success function', () => {
let renderedComp;
before(() => {
renderedComp = mount(<Alert />);
Alert.success('Test success message...', {timeout: 'none', stack: true, position: 'top-right'});
});
it('should be s-alert success in the s-alert store', () => {
expect(sAlertStore.getState()[0].message).to.equal('Test success message...');
expect(sAlertStore.getState()[0].condition).to.equal('success');
});
it('should be ".s-alert-success" element in the DOM', () => {
expect(renderedComp.find('.s-alert-success').length).to.be.equal(1);
});
after(() => Alert.closeAll());
});
describe('Alert error function', () => {
let renderedComp;
before(() => {
renderedComp = mount(<Alert />);
Alert.error('Test error message...', {timeout: 'none', stack: true, position: 'top-right'});
});
it('should be s-alert error in the s-alert store', () => {
expect(sAlertStore.getState()[0].message).to.equal('Test error message...');
expect(sAlertStore.getState()[0].condition).to.equal('error');
});
it('should be ".s-alert-error" element in the DOM', () => {
expect(renderedComp.find('.s-alert-error').length).to.be.equal(1);
});
after(() => Alert.closeAll());
});
describe('sAlert close function by alert id', () => {
let renderedComp;
let sAlertId;
before(() => {
renderedComp = mount(<Alert />);
sAlertId = Alert.success('Test success message...', {timeout: 'none', stack: true, position: 'top-right'});
});
it('should be s-alert in store and element in DOM', () => {
let alerts = sAlertStore.getState().slice().filter(a => a.id === sAlertId);
expect(alerts.length).to.not.equal(0);
expect(renderedComp.find('.s-alert-box').length).to.be.equal(1);
});
it('should be no s-alert in store after Alert.close function is called', () => {
Alert.close(sAlertId);
let alerts = sAlertStore.getState().slice().filter(a => a.id === sAlertId);
expect(alerts.length).to.equal(0);
});
it('should be no s-alert element in the DOM after sAlert.close function is called', () => {
expect(renderedComp.find('.s-alert-box').length).to.be.equal(0);
});
after(() => Alert.closeAll());
});
describe('sAlert 1000ms timeout', () => {
let renderedComp;
let sAlertId;
before((done) => {
renderedComp = mount(<Alert />);
sAlertId = Alert.success('Test success message...', {timeout: 1000, stack: true, position: 'top-right'});
setTimeout(() => {
done();
}, 1500);
});
it('should not be s-alert document in the collection after 1500ms', (done) => {
let alerts = sAlertStore.getState().slice().filter(a => a.id === sAlertId);
expect(alerts.length).to.equal(0);
done();
});
after(() => Alert.closeAll());
});
describe('sAlert mount after issuing alert', () => {
let renderedComp;
let sAlertId;
before((done) => {
sAlertId = Alert.success('Test delayed mount...', {timeout: 'none', position: 'top-right'});
setTimeout(() => {
renderedComp = mount(<Alert />);
done();
}, 1000);
});
it('should be s-alert in the s-alert store', () => {
expect(sAlertStore.getState()[0].message).to.equal('Test delayed mount...');
expect(sAlertStore.getState()[0].condition).to.equal('success');
});
it('should be ".s-alert-success" element in the DOM', () => {
expect(renderedComp.find('.s-alert-success').length).to.be.equal(1);
});
after(() => Alert.closeAll());
});
describe('sAlert position bottom-left', () => {
let renderedComp;
let sAlertId;
before(() => {
renderedComp = mount(<Alert />);
sAlertId = Alert.success('Test position...', {position: 'bottom-left', timeout: 'none'});
});
it('should have s-alert-bottom-left class', () => {
expect(renderedComp.find('.s-alert-bottom-left')).to.have.length(1);
});
it('should have document with position bottom-left in the store', () => {
let alerts = sAlertStore.getState().slice().filter(a => a.id === sAlertId);
expect(alerts[0].position).to.equal('bottom-left');
});
after(() => Alert.closeAll());
});
describe('sAlert global position config', () => {
let renderedComp;
let sAlertId;
before(() => {
renderedComp = mount(<Alert position='bottom-right' timeout='none' />);
sAlertId = Alert.success('Test global position...');
});
it('should have s-alert-bottom-right class', () => {
expect(renderedComp.find('.s-alert-bottom-right')).to.have.length(1);
});
after(() => Alert.closeAll());
});
describe('sAlert position full width top', () => {
let renderedComp;
let sAlertId;
before(() => {
renderedComp = mount(<Alert />);
sAlertId = Alert.success('Test position...', {position: 'top', timeout: 'none'});
});
it('should have s-alert-top class', () => {
expect(renderedComp.find('.s-alert-top')).to.have.length(1);
});
it('should have document with position top in the store', () => {
let alerts = sAlertStore.getState().slice().filter(a => a.id === sAlertId);
expect(alerts[0].position).to.equal('top');
});
after(() => Alert.closeAll());
});
describe('sAlert offset', () => {
let renderedComp;
let sAlertId;
before(() => {
renderedComp = mount(<Alert />);
sAlertId = Alert.success('Test position...', {position: 'top', timeout: 'none', offset: 100});
});
it('should have document with offset in the store', () => {
let alerts = sAlertStore.getState().slice().filter(a => a.id === sAlertId);
expect(alerts[0].offset).to.equal(100);
});
after(() => Alert.closeAll());
});
describe('sAlert stack', () => {
let renderedComp;
let sAlertId;
before(() => {
renderedComp = mount(<Alert />);
sAlertId = Alert.success('Test position...', {position: 'top', timeout: 'none', stack: true});
});
it('should have document with stack in the store', () => {
let alerts = sAlertStore.getState().slice().filter(a => a.id === sAlertId);
expect(alerts[0].stack).to.be.true;
});
after(() => Alert.closeAll());
});
describe('sAlert onShow function callback', () => {
let renderedComp;
let sAlertId1;
let isShowed1 = false;
before(() => {
renderedComp = mount(<Alert />);
sAlertId1 = Alert.success('Test position...', {
position: 'top',
timeout: 'none',
onShow: () => {
isShowed1 = true
}
});
});
it('should get called when specifically openning the alert', () => {
expect(isShowed1).to.be.true;
});
after(() => Alert.closeAll());
});
describe('sAlert onClose function callback', () => {
let renderedComp;
let sAlertId1;
let sAlertId2;
let isClosed1 = false;
let isClosed2 = false;
before(() => {
renderedComp = mount(<Alert />);
sAlertId1 = Alert.success('Test position...', {
position: 'top',
timeout: 'none',
onClose: () => {
isClosed1 = true
}
});
sAlertId2 = Alert.success('Test position...', {
position: 'top',
timeout: 'none',
onClose: () => {
isClosed2 = true
}
});
});
it('should get called when specifically closing the alert', () => {
Alert.close(sAlertId1);
expect(isClosed1).to.be.true;
expect(isClosed2).to.be.false;
});
after(() => Alert.closeAll());
});
describe('sAlert tools', () => {
it('should generate random id', () => {
let random1 = sAlertTools.randomId();
let random2 = sAlertTools.randomId();
expect(random1).to.not.be.equal(random2);
});
it('should return first defined value', () => {
expect(sAlertTools.returnFirstDefined(undefined, false, 0)).to.be.equal(false);
expect(sAlertTools.returnFirstDefined(undefined, undefined, 0)).to.be.equal(0);
expect(sAlertTools.returnFirstDefined(1, undefined, 0)).to.be.equal(1);
});
it('should return styles object from string', () => {
let styleObj = sAlertTools.styleToObj('color: red; width: 100px');
expect(styleObj).to.be.an.instanceof(Object);
expect(styleObj).to.have.property('color', 'red');
expect(styleObj).to.have.property('width', '100px');
});
}); |
var TypeValidator = require('../Classes/TypeValidator');
var isNumeric = function(data, options){
options = (options == null) ? {'type' : 'numeric'} : options;
options['type'] = 'numeric';
var _validator = new TypeValidator(options);
_validator.validate(data);
return _validator.isValid() ? true : false;
};
module.exports = isNumeric; |
var webpack = require('webpack')
var DevServer = require('webpack-dev-server')
var base = require('./webpack.base.conf.js')
var webConfig = base('vue', true)
var weexConfig = base('weex', true)
var port = process.env.DEMO_PORT | 3456
webConfig.entry = {
app: [
'./demo/src/render.js',
'./demo/src/app.js',
'webpack/hot/dev-server',
'webpack-dev-server/client/?http://0.0.0.0:' + port
]
}
webConfig.plugins.push(new webpack.HotModuleReplacementPlugin())
// weex 版跑在 playground,里不需要热替换
weexConfig.entry = {
app: ['./demo/src/app.js']
}
new DevServer(webpack([webConfig, weexConfig]), {
port: port,
host: '0.0.0.0',
// disable host check to avoid `Invalid Host header` issue
disableHostCheck: true,
hot: true,
stats: { colors: true }
}).listen('' + port, '0.0.0.0')
console.log('Project is running at http://0.0.0.0:' + port + '/')
|
// [], target
module.exports = [{
input: [[[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]],
output: 16,
},
// {
// input: [[1,-5]],
// output: -4,
// },
// {
// input: [[100,200,50,0],150],
// output: [0,2],
// },
] |
// @ts-check
const path = require('path')
const { promises: fs } = require('fs')
const terminate = require('terminate')
const { app } = require('electron')
const logger = require('../logger')
/**
* Check for existing orphaned processes and terminate them. Writes the current
* pid to file so that this process can be cleaned up later if necessary
*
* @returns {Promise<void>}
*/
module.exports = async function cleanUpOrphanProcesses () {
const pidFilepath = path.join(app.getPath('userData'), 'pid')
/** @type {number | undefined} */
let existingPid
try {
existingPid = parseInt((await fs.readFile(pidFilepath)).toString())
} catch (e) {}
const asyncTasks = [fs.writeFile(pidFilepath, process.pid.toString())]
if (existingPid) {
asyncTasks.push(terminatePromise(existingPid))
}
// Minimize wait, run async tasks in parallel
await Promise.all(asyncTasks)
// Not registering exit handlers for cleanup of the PID, since this could
// cause race conditions. Better leave the PID file there, even if process
// exists gracefully, and try and fail to terminate it on startup
}
/**
* async terminate
*
* @param {number} pid
* @returns {Promise<void>}
*/
async function terminatePromise (pid) {
return new Promise((resolve, reject) => {
terminate(pid, err => {
if (err && err.code !== 'ESRCH') {
// A problem terminating an orphaned process, but we can't do much about
// it other than log the problem
logger.error('pid-manager', err)
resolve()
} else {
logger.debug('Cleaned up existing process pid:', pid)
resolve()
}
})
})
}
|
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
admin.initializeApp(functions.config().firebase);
exports.updateStat = functions.https.onRequest((req, res) => {
if (req.query.key == functions.config().bluesense.key) {
require('./stat')()
.then(() => require('./cleanup')())
.then(() => {
res.status(200).send('success');
});
} else {
res.status(403).send('Invaild Key');
}
});
exports.cleanUp = functions.https.onRequest((req, res) => {
if (req.query.key == functions.config().bluesense.key) {
require('./cleanup')().then(() => {
res.status(200).send('success');
});
} else {
res.status(403).send('Invaild Key');
}
});
exports.feed = functions.https.onRequest((req, res) => {
require('./rss')().then((xml) => {
res.status(200).set('Content-Type', 'application/xml').send(xml);
});
});
exports.feed = functions.https.onRequest((req, res) => {
require('./rss')().then((xml) => {
res.status(200).set('Content-Type', 'application/xml').send(xml);
});
});
const report = require('express')();
report.get('/:id', (req, res) => {
require('./canvas')(req.params.id).then(stream => {
res.set('Cache-Control', 'public, max-age=60, s-maxage=31536000');
res.writeHead(200, { 'Content-Type': 'image/png' });
stream.pipe(res);
});
});
exports.report = functions.https.onRequest(report);
|
import { mount } from '@vue/test-utils'
import { waitNT, waitRAF } from '../../../tests/utils'
import { BDropdown } from './dropdown'
import { BDropdownItem } from './dropdown-item'
describe('dropdown', () => {
const originalCreateRange = document.createRange
const origGetBCR = Element.prototype.getBoundingClientRect
beforeEach(() => {
// https://github.com/FezVrasta/popper.js/issues/478#issuecomment-407422016
// Hack to make Popper not bork out during tests
// Note popper still does not do any positioning calculation in JSDOM though
// So we cannot test actual positioning of the menu, just detect when it is open
document.createRange = () => ({
setStart: () => {},
setEnd: () => {},
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document
}
})
// Mock `getBoundingClientRect()` so that the `isVisible(el)` test returns `true`
// Needed for keyboard navigation testing
Element.prototype.getBoundingClientRect = jest.fn(() => ({
width: 24,
height: 24,
top: 0,
left: 0,
bottom: 0,
right: 0
}))
})
afterEach(() => {
// Reset overrides
document.createRange = originalCreateRange
Element.prototype.getBoundingClientRect = origGetBCR
})
it('has expected default structure', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
// Wait for auto ID to be generated
await waitNT(wrapper.vm)
expect(wrapper.classes()).toContain('dropdown')
expect(wrapper.classes()).toContain('btn-group')
expect(wrapper.classes()).toContain('b-dropdown')
expect(wrapper.classes().length).toBe(3)
expect(wrapper.attributes('id')).toBeDefined()
const wrapperId = wrapper.attributes('id')
expect(wrapper.findAll('button').length).toBe(1)
const $button = wrapper.find('button')
expect($button.classes()).toContain('btn')
expect($button.classes()).toContain('btn-secondary')
expect($button.classes()).toContain('dropdown-toggle')
expect($button.classes().length).toBe(3)
expect($button.attributes('aria-haspopup')).toBeDefined()
expect($button.attributes('aria-haspopup')).toEqual('menu')
expect($button.attributes('aria-expanded')).toBeDefined()
expect($button.attributes('aria-expanded')).toEqual('false')
expect($button.attributes('id')).toBeDefined()
expect($button.attributes('id')).toEqual(`${wrapperId}__BV_toggle_`)
expect($button.text()).toEqual('')
expect(wrapper.findAll('.dropdown-menu').length).toBe(1)
const $menu = wrapper.find('.dropdown-menu')
expect($menu.element.tagName).toBe('UL')
expect($menu.classes().length).toBe(1)
expect($menu.attributes('role')).toBeDefined()
expect($menu.attributes('role')).toEqual('menu')
expect($menu.attributes('tabindex')).toBeDefined()
expect($menu.attributes('tabindex')).toEqual('-1')
expect($menu.attributes('aria-labelledby')).toBeDefined()
expect($menu.attributes('aria-labelledby')).toEqual(`${wrapperId}__BV_toggle_`)
expect($menu.text()).toEqual('')
wrapper.destroy()
})
it('split mode has expected default structure', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
split: true
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
// Wait for auto ID to be generated
await waitNT(wrapper.vm)
expect(wrapper.classes()).toContain('dropdown')
expect(wrapper.classes()).toContain('btn-group')
expect(wrapper.classes()).toContain('b-dropdown')
expect(wrapper.classes().length).toBe(3)
expect(wrapper.attributes('id')).toBeDefined()
const wrapperId = wrapper.attributes('id')
expect(wrapper.findAll('button').length).toBe(2)
const $buttons = wrapper.findAll('button')
const $split = $buttons.at(0)
const $toggle = $buttons.at(1)
expect($split.classes()).toContain('btn')
expect($split.classes()).toContain('btn-secondary')
expect($split.attributes('id')).toBeDefined()
expect($split.attributes('id')).toEqual(`${wrapperId}__BV_button_`)
expect($split.attributes('type')).toBeDefined()
expect($split.attributes('type')).toEqual('button')
expect($split.text()).toEqual('')
expect($toggle.classes()).toContain('btn')
expect($toggle.classes()).toContain('btn-secondary')
expect($toggle.classes()).toContain('dropdown-toggle')
expect($toggle.classes()).toContain('dropdown-toggle-split')
expect($toggle.classes().length).toBe(4)
expect($toggle.attributes('aria-haspopup')).toBeDefined()
expect($toggle.attributes('aria-haspopup')).toEqual('menu')
expect($toggle.attributes('aria-expanded')).toBeDefined()
expect($toggle.attributes('aria-expanded')).toEqual('false')
expect($toggle.attributes('id')).toBeDefined()
expect($toggle.attributes('id')).toEqual(`${wrapperId}__BV_toggle_`)
expect($toggle.attributes('type')).toBeDefined()
expect($toggle.attributes('type')).toEqual('button')
expect($toggle.findAll('span.sr-only').length).toBe(1)
expect($toggle.find('span.sr-only').text()).toEqual('Toggle dropdown')
expect($toggle.text()).toEqual('Toggle dropdown')
expect(wrapper.findAll('.dropdown-menu').length).toBe(1)
const $menu = wrapper.find('.dropdown-menu')
expect($menu.element.tagName).toBe('UL')
expect($menu.classes().length).toBe(1)
expect($menu.attributes('role')).toBeDefined()
expect($menu.attributes('role')).toEqual('menu')
expect($menu.attributes('tabindex')).toBeDefined()
expect($menu.attributes('tabindex')).toEqual('-1')
expect($menu.attributes('aria-labelledby')).toBeDefined()
expect($menu.attributes('aria-labelledby')).toEqual(`${wrapperId}__BV_button_`)
expect($menu.text()).toEqual('')
wrapper.destroy()
})
it('split mode accepts split-button-type value', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
split: true,
splitButtonType: 'submit'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
await waitNT(wrapper.vm)
expect(wrapper.classes()).toContain('dropdown')
expect(wrapper.findAll('button').length).toBe(2)
const $buttons = wrapper.findAll('button')
const $split = $buttons.at(0)
const $toggle = $buttons.at(1)
expect($split.attributes('type')).toBeDefined()
expect($split.attributes('type')).toEqual('submit')
expect($toggle.attributes('type')).toBeDefined()
expect($toggle.attributes('type')).toEqual('button')
wrapper.destroy()
})
it('renders default slot inside menu', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
slots: {
default: 'foobar'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('.dropdown-menu').length).toBe(1)
const $menu = wrapper.find('.dropdown-menu')
expect($menu.text()).toEqual('foobar')
wrapper.destroy()
})
it('renders button-content slot inside toggle button', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
slots: {
'button-content': 'foobar'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('button').length).toBe(1)
expect(wrapper.findAll('.dropdown-toggle').length).toBe(1)
const $toggle = wrapper.find('.dropdown-toggle')
expect($toggle.text()).toEqual('foobar')
wrapper.destroy()
})
it('renders button-content slot inside split button', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
split: true
},
slots: {
'button-content': 'foobar'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('button').length).toBe(2)
const $buttons = wrapper.findAll('button')
const $split = $buttons.at(0)
const $toggle = $buttons.at(1)
expect($split.text()).toEqual('foobar')
expect($toggle.classes()).toContain('dropdown-toggle')
// Toggle has `sr-only` hidden text
expect($toggle.text()).toEqual('Toggle dropdown')
wrapper.destroy()
})
it('does not render default slot inside menu when prop lazy set', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
lazy: true
},
slots: {
default: 'foobar'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('.dropdown-menu').length).toBe(1)
const $menu = wrapper.find('.dropdown-menu')
expect($menu.text()).not.toEqual('foobar')
wrapper.destroy()
})
it('has user supplied ID', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
id: 'test'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.attributes('id')).toBeDefined()
expect(wrapper.attributes('id')).toEqual('test')
const wrapperId = wrapper.attributes('id')
expect(wrapper.findAll('button').length).toBe(1)
const $button = wrapper.find('button')
expect($button.attributes('id')).toEqual(`${wrapperId}__BV_toggle_`)
expect(wrapper.findAll('.dropdown-menu').length).toBe(1)
const $menu = wrapper.find('.dropdown-menu')
expect($menu.attributes('aria-labelledby')).toBeDefined()
expect($menu.attributes('aria-labelledby')).toEqual(`${wrapperId}__BV_toggle_`)
wrapper.destroy()
})
it('should not have "btn-group" class when block is true', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
block: true
}
})
expect(wrapper.classes()).not.toContain('btn-group')
wrapper.destroy()
})
it('should have "btn-group" and "d-flex" classes when block and split are true', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
block: true,
split: true
}
})
expect(wrapper.classes()).toContain('btn-group')
expect(wrapper.classes()).toContain('d-flex')
wrapper.destroy()
})
it('should have "dropdown-toggle-no-caret" class when no-caret is true', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
noCaret: true
}
})
expect(wrapper.find('.dropdown-toggle').classes()).toContain('dropdown-toggle-no-caret')
wrapper.destroy()
})
it('should not have "dropdown-toggle-no-caret" class when no-caret and split are true', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
noCaret: true,
split: true
}
})
expect(wrapper.find('.dropdown-toggle').classes()).not.toContain('dropdown-toggle-no-caret')
wrapper.destroy()
})
it('should have a toggle with the given toggle tag', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
toggleTag: 'div'
}
})
expect(wrapper.find('.dropdown-toggle').element.tagName).toBe('DIV')
wrapper.destroy()
})
it('should have attributes on toggle when "toggle-attrs" prop is set', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
toggleAttrs: { 'data-foo-bar': 'foo-bar' }
}
})
expect(wrapper.find('.dropdown-toggle').attributes('data-foo-bar')).toBe('foo-bar')
wrapper.destroy()
})
it('should have class dropup when prop dropup set', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
dropup: true
}
})
expect(wrapper.classes()).toContain('dropdown')
expect(wrapper.classes()).toContain('dropup')
expect(wrapper.classes()).not.toContain('show')
expect(wrapper.find('.dropdown-menu').classes()).not.toContain('show')
wrapper.vm.show()
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.classes()).toContain('dropdown')
expect(wrapper.classes()).toContain('dropup')
expect(wrapper.classes()).toContain('show')
expect(wrapper.find('.dropdown-menu').classes()).toContain('show')
wrapper.destroy()
})
it('should have class dropright when prop dropright set', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
dropright: true
}
})
expect(wrapper.classes()).toContain('dropdown')
expect(wrapper.classes()).toContain('dropright')
expect(wrapper.classes()).not.toContain('show')
expect(wrapper.find('.dropdown-menu').classes()).not.toContain('show')
wrapper.vm.show()
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.classes()).toContain('dropdown')
expect(wrapper.classes()).toContain('dropright')
expect(wrapper.classes()).toContain('show')
expect(wrapper.find('.dropdown-menu').classes()).toContain('show')
wrapper.destroy()
})
it('should have class dropleft when prop dropleft set', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
dropleft: true
}
})
expect(wrapper.classes()).toContain('dropdown')
expect(wrapper.classes()).toContain('dropleft')
expect(wrapper.classes()).not.toContain('show')
expect(wrapper.find('.dropdown-menu').classes()).not.toContain('show')
wrapper.vm.show()
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.classes()).toContain('dropdown')
expect(wrapper.classes()).toContain('dropleft')
expect(wrapper.classes()).toContain('show')
expect(wrapper.find('.dropdown-menu').classes()).toContain('show')
wrapper.destroy()
})
it('split should have class specified in split class property', () => {
const splitClass = 'custom-button-class'
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
splitClass,
split: true
}
})
const $buttons = wrapper.findAll('button')
const $split = $buttons.at(0)
expect($split.classes()).toContain(splitClass)
wrapper.destroy()
})
it('menu should have class dropdown-menu-right when prop right set', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
right: true
}
})
expect(wrapper.classes()).toContain('dropdown')
expect(wrapper.classes()).not.toContain('show')
expect(wrapper.find('.dropdown-menu').classes()).toContain('dropdown-menu-right')
expect(wrapper.find('.dropdown-menu').classes()).not.toContain('show')
wrapper.vm.show()
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.classes()).toContain('dropdown')
expect(wrapper.classes()).toContain('show')
expect(wrapper.find('.dropdown-menu').classes()).toContain('dropdown-menu-right')
expect(wrapper.find('.dropdown-menu').classes()).toContain('show')
wrapper.destroy()
})
it('split mode emits click event when split button clicked', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
split: true
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.emitted('click')).toBeUndefined()
expect(wrapper.findAll('button').length).toBe(2)
const $buttons = wrapper.findAll('button')
const $split = $buttons.at(0)
await $split.trigger('click')
expect(wrapper.emitted('click')).toBeDefined()
expect(wrapper.emitted('click').length).toBe(1)
wrapper.destroy()
})
it('dropdown opens and closes', async () => {
const App = {
props: {
disabled: { type: Boolean, default: false }
},
render(h) {
const { disabled } = this
return h('div', { attrs: { id: 'container' } }, [
h(BDropdown, { props: { id: 'test', disabled } }, [h(BDropdownItem, 'item')]),
h('input', { attrs: { id: 'input' } })
])
}
}
const wrapper = mount(App, {
attachTo: document.body
})
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('.dropdown').length).toBe(1)
expect(wrapper.findAll('.dropdown-toggle').length).toBe(1)
expect(wrapper.findAll('.dropdown-menu').length).toBe(1)
expect(wrapper.findAll('.dropdown-menu .dropdown-item').length).toBe(1)
const $container = wrapper.find('#container')
const $dropdown = wrapper.findComponent('.dropdown')
const $toggle = wrapper.find('.dropdown-toggle')
const $menu = wrapper.find('.dropdown-menu')
const $item = wrapper.find('.dropdown-item')
const $input = wrapper.find('#input')
expect($dropdown.vm).toBeDefined()
expect($toggle.attributes('aria-haspopup')).toBeDefined()
expect($toggle.attributes('aria-haspopup')).toEqual('menu')
expect($toggle.attributes('aria-expanded')).toBeDefined()
expect($toggle.attributes('aria-expanded')).toEqual('false')
expect($dropdown.classes()).not.toContain('show')
// Open menu by clicking toggle
await $toggle.trigger('click')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($toggle.attributes('aria-haspopup')).toBeDefined()
expect($toggle.attributes('aria-haspopup')).toEqual('menu')
expect($toggle.attributes('aria-expanded')).toBeDefined()
expect($toggle.attributes('aria-expanded')).toEqual('true')
expect($dropdown.classes()).toContain('show')
expect(document.activeElement).toBe($menu.element)
// Close menu by clicking toggle again
await $toggle.trigger('click')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($toggle.attributes('aria-expanded')).toEqual('false')
expect($dropdown.classes()).not.toContain('show')
// Open menu again
await $toggle.trigger('click')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($toggle.attributes('aria-expanded')).toEqual('true')
expect(document.activeElement).toBe($menu.element)
expect($dropdown.classes()).toContain('show')
// Close by clicking dropdown-item
await $item.trigger('click')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($toggle.attributes('aria-expanded')).toEqual('false')
expect($dropdown.classes()).not.toContain('show')
// Open menu via ´.show()´ method
$dropdown.vm.show()
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($toggle.attributes('aria-expanded')).toEqual('true')
expect($dropdown.classes()).toContain('show')
// Close menu via ´.hide()´ method
$dropdown.vm.hide()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($toggle.attributes('aria-expanded')).toEqual('false')
expect($dropdown.classes()).not.toContain('show')
// Open menu via ´.show()´ method again
$dropdown.vm.show()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($toggle.attributes('aria-expanded')).toEqual('true')
expect($dropdown.classes()).toContain('show')
expect(document.activeElement).toBe($menu.element)
// Close menu by moving focus away from menu
await $input.trigger('focusin')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($dropdown.classes()).not.toContain('show')
expect($toggle.attributes('aria-expanded')).toEqual('false')
// Open menu via keydown.down event on toggle button
await $toggle.trigger('keydown.down')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($dropdown.classes()).toContain('show')
expect($toggle.attributes('aria-expanded')).toEqual('true')
expect(document.activeElement).toBe($menu.element)
// Close menu by clicking outside
await $container.trigger('click')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($dropdown.classes()).not.toContain('show')
expect($toggle.attributes('aria-expanded')).toEqual('false')
// Open menu via ´.show()´ method again
$dropdown.vm.show()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($dropdown.classes()).toContain('show')
expect($toggle.attributes('aria-expanded')).toEqual('true')
// Close menu by keydown.esc event on dropdown item
await $item.trigger('keydown.esc')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($dropdown.classes()).not.toContain('show')
expect($toggle.attributes('aria-expanded')).toEqual('false')
// Open menu via ´.show()´ method again
$dropdown.vm.show()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($dropdown.classes()).toContain('show')
expect($toggle.attributes('aria-expanded')).toEqual('true')
// When disabled changes to true, menu should close
await wrapper.setProps({ disabled: true })
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($dropdown.classes()).not.toContain('show')
expect($toggle.attributes('aria-expanded')).toEqual('false')
// When disabled, show() wont open menu
$dropdown.vm.show()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($dropdown.classes()).not.toContain('show')
expect($toggle.attributes('aria-expanded')).toEqual('false')
// Re-enable dropdown and open it
await wrapper.setProps({ disabled: false })
await waitRAF()
$dropdown.vm.show()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($dropdown.classes()).toContain('show')
expect($toggle.attributes('aria-expanded')).toEqual('true')
// Should close on root emit when argument is not self
wrapper.vm.$root.$emit('bv::dropdown::shown')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect($dropdown.classes()).not.toContain('show')
expect($toggle.attributes('aria-expanded')).toEqual('false')
wrapper.destroy()
})
it('preventDefault() works on show event', async () => {
let prevent = true
const wrapper = mount(BDropdown, {
attachTo: document.body,
listeners: {
show: bvEvent => {
if (prevent) {
bvEvent.preventDefault()
}
}
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.emitted('show')).toBeUndefined()
expect(wrapper.findAll('button').length).toBe(1)
expect(wrapper.findAll('.dropdown').length).toBe(1)
const $toggle = wrapper.find('button')
const $dropdown = wrapper.find('.dropdown')
expect($toggle.attributes('aria-haspopup')).toBeDefined()
expect($toggle.attributes('aria-haspopup')).toEqual('menu')
expect($toggle.attributes('aria-expanded')).toBeDefined()
expect($toggle.attributes('aria-expanded')).toEqual('false')
expect($dropdown.classes()).not.toContain('show')
// Should prevent menu from opening
await $toggle.trigger('click')
await waitRAF()
expect(wrapper.emitted('show')).toBeDefined()
expect(wrapper.emitted('show').length).toBe(1)
expect($toggle.attributes('aria-haspopup')).toBeDefined()
expect($toggle.attributes('aria-haspopup')).toEqual('menu')
expect($toggle.attributes('aria-expanded')).toBeDefined()
expect($toggle.attributes('aria-expanded')).toEqual('false')
expect($dropdown.classes()).not.toContain('show')
// Allow menu to open
prevent = false
await $toggle.trigger('click')
await waitRAF()
expect(wrapper.emitted('show')).toBeDefined()
expect(wrapper.emitted('show').length).toBe(2)
expect($toggle.attributes('aria-haspopup')).toBeDefined()
expect($toggle.attributes('aria-haspopup')).toEqual('menu')
expect($toggle.attributes('aria-expanded')).toBeDefined()
expect($toggle.attributes('aria-expanded')).toEqual('true')
expect($dropdown.classes()).toContain('show')
wrapper.destroy()
})
it('Keyboard navigation works when open', async () => {
const App = {
render(h) {
return h('div', [
h(BDropdown, { props: { id: 'test' } }, [
h(BDropdownItem, { attrs: { id: 'item-1' } }, 'item'),
h(BDropdownItem, { attrs: { id: 'item-2' } }, 'item'),
h(BDropdownItem, { attrs: { id: 'item-3' }, props: { disabled: true } }, 'item'),
h(BDropdownItem, { attrs: { id: 'item-4' } }, 'item')
])
])
}
}
const wrapper = mount(App, {
attachTo: document.body
})
expect(wrapper.vm).toBeDefined()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.findAll('.dropdown').length).toBe(1)
expect(wrapper.findAll('.dropdown-toggle').length).toBe(1)
expect(wrapper.findAll('.dropdown-menu').length).toBe(1)
expect(wrapper.findAll('.dropdown-menu .dropdown-item').length).toBe(4)
const $toggle = wrapper.find('.dropdown-toggle')
const $menu = wrapper.find('.dropdown-menu')
const $items = wrapper.findAll('.dropdown-item')
// Expect menu to be closed
expect($toggle.attributes('aria-expanded')).toBeDefined()
expect($toggle.attributes('aria-expanded')).toEqual('false')
// Trigger keydown.down on toggle to open menu
await $toggle.trigger('keydown.down')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
expect($toggle.attributes('aria-expanded')).toEqual('true')
expect(document.activeElement).toBe($menu.element)
// Move to first menu item
await $menu.trigger('keydown.down')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
expect(document.activeElement).toBe($items.at(0).element)
// Move to second menu item
await $items.at(0).trigger('keydown.down')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
expect(document.activeElement).toBe($items.at(1).element)
// Move down to next menu item (should skip disabled item)
await $items.at(1).trigger('keydown.down')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
expect(document.activeElement).toBe($items.at(3).element)
// Move down to next menu item (should remain on same item)
await $items.at(3).trigger('keydown.down')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
expect(document.activeElement).toBe($items.at(3).element)
// Move up to previous menu item (should skip disabled item)
await $items.at(3).trigger('keydown.up')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
expect(document.activeElement).toBe($items.at(1).element)
// Move up to previous menu item
await $items.at(1).trigger('keydown.up')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
expect(document.activeElement).toBe($items.at(0).element)
// Move up to previous menu item (should remain on first item)
await $items.at(0).trigger('keydown.up')
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
await waitRAF()
expect(document.activeElement).toBe($items.at(0).element)
wrapper.destroy()
})
it('when boundary not set should not have class position-static', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
await waitNT(wrapper.vm)
expect(wrapper.classes()).not.toContain('position-static')
wrapper.destroy()
})
it('when boundary set to viewport should have class position-static', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
boundary: 'viewport'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
await waitNT(wrapper.vm)
expect(wrapper.classes()).toContain('position-static')
wrapper.destroy()
})
it('toggle button size works', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
size: 'lg'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('.btn').length).toBe(1)
const $toggle = wrapper.find('.btn')
expect($toggle.element.tagName).toBe('BUTTON')
expect($toggle.classes()).toContain('btn-lg')
wrapper.destroy()
})
it('split button size works', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
split: true,
size: 'lg'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('.btn').length).toBe(2)
const $split = wrapper.findAll('.btn').at(0)
const $toggle = wrapper.findAll('.btn').at(1)
expect($split.element.tagName).toBe('BUTTON')
expect($split.classes()).toContain('btn-lg')
expect($toggle.element.tagName).toBe('BUTTON')
expect($toggle.classes()).toContain('btn-lg')
wrapper.destroy()
})
it('toggle button content works', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
text: 'foobar'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('.btn').length).toBe(1)
const $toggle = wrapper.find('.btn')
expect($toggle.element.tagName).toBe('BUTTON')
expect($toggle.text()).toEqual('foobar')
wrapper.destroy()
})
it('split button content works', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
split: true,
text: 'foobar'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('.btn').length).toBe(2)
const $split = wrapper.findAll('.btn').at(0)
expect($split.element.tagName).toBe('BUTTON')
expect($split.text()).toEqual('foobar')
wrapper.destroy()
})
it('variant works on non-split button', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
variant: 'primary'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('.btn').length).toBe(1)
const $toggle = wrapper.find('.btn')
expect($toggle.element.tagName).toBe('BUTTON')
expect($toggle.classes()).toContain('btn-primary')
expect($toggle.classes()).not.toContain('btn-secondary')
wrapper.destroy()
})
it('variant works on split button', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
split: true,
variant: 'primary'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('.btn').length).toBe(2)
const $split = wrapper.findAll('.btn').at(0)
const $toggle = wrapper.findAll('.btn').at(1)
expect($split.element.tagName).toBe('BUTTON')
expect($split.classes()).toContain('btn-primary')
expect($split.classes()).not.toContain('btn-secondary')
expect($toggle.element.tagName).toBe('BUTTON')
expect($toggle.classes()).toContain('btn-primary')
expect($toggle.classes()).not.toContain('btn-secondary')
// Change split button variant
await wrapper.setProps({
splitVariant: 'danger'
})
expect($split.classes()).toContain('btn-danger')
expect($toggle.classes()).toContain('btn-primary')
wrapper.destroy()
})
it('split mode has href when prop split-href set', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
split: true,
splitHref: '/foo'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('.btn').length).toBe(2)
const $buttons = wrapper.findAll('.btn')
const $split = $buttons.at(0)
const $toggle = $buttons.at(1)
expect($toggle.element.tagName).toBe('BUTTON')
expect($split.element.tagName).toBe('A')
expect($split.classes()).toContain('btn')
expect($split.classes()).toContain('btn-secondary')
expect($split.attributes('href')).toBeDefined()
expect($split.attributes('href')).toEqual('/foo')
wrapper.destroy()
})
it('split mode has href when prop split-to set', async () => {
const wrapper = mount(BDropdown, {
attachTo: document.body,
propsData: {
split: true,
splitTo: '/foo'
}
})
expect(wrapper.element.tagName).toBe('DIV')
expect(wrapper.vm).toBeDefined()
expect(wrapper.findAll('.btn').length).toBe(2)
const $buttons = wrapper.findAll('.btn')
const $split = $buttons.at(0)
const $toggle = $buttons.at(1)
expect($toggle.element.tagName).toBe('BUTTON')
expect($split.element.tagName).toBe('A')
expect($split.classes()).toContain('btn')
expect($split.classes()).toContain('btn-secondary')
expect($split.attributes('href')).toBeDefined()
expect($split.attributes('href')).toEqual('/foo')
wrapper.destroy()
})
})
|
var LEFT, MIDDLE, RIGHT, timeStamp;
LEFT = 0;
MIDDLE = 1;
RIGHT = 2;
timeStamp = 0;
var newDiv;
function remove()
{
document.body.removeChild(newDiv);
}
function draw(e, clickType)
{
console.log(clickType);
console.log(e);
newDiv = document.createElement("div");
newDiv.setAttribute("style", "position: absolute; left: " + (e.pageX-6) + "px; top: " + (e.pageY-6) + "px; height: 10px; width: 10px; border: 1px dotted red; border-radius: 10px; z-index: 1000;");
newDiv.setAttribute("id", "toDelete");
//var t = document.createTextNode(clickType);
//newDiv.appendChild(t);
document.body.appendChild(newDiv);
window.setTimeout(remove, 300);
}
document.body.addEventListener('contextmenu', function (e) {
remove();
//console.log(e.screenX, e.screenY);
if (e.timeStamp - timeStamp < 350 && e.button === LEFT){
timeStamp = e.timeStamp;
draw(e, "double");
return;
}
if(e.button === LEFT){
timeStamp = e.timeStamp;
draw(e, "left");
}
else if(e.button === MIDDLE) {
draw(e, "middle");
}
else if(e.button === RIGHT) {
draw(e, "right");
}
}, true);
document.body.addEventListener('click', function (e) {
//console.log(e.screenX, e.screenY);
if (e.timeStamp - timeStamp < 350 && e.button === LEFT){
timeStamp = e.timeStamp;
draw(e, "double");
return;
}
if(e.button === LEFT){
timeStamp = e.timeStamp;
draw(e, "left");
}
else if(e.button === MIDDLE) {
draw(e, "middle");
}
else if(e.button === RIGHT) {
draw(e, "right");
}
}, true);
|
import * as storybook from '@kadira/storybook';
import { setOptions } from '@kadira/storybook-addon-options';
import infoAddon from '@kadira/react-storybook-addon-info';
storybook.setAddon(infoAddon);
setOptions({
name: 'React Theming',
url: 'https://github.com/sm-react/react-theming',
goFullScreen: false,
showLeftPanel: true,
showDownPanel: true,
showSearchBox: false,
downPanelInRight: false,
});
storybook.configure(
() => {
require('../src/stories');
},
module
);
|
module.exports = function(RED) {
"use strict";
var http = require("follow-redirects").http;
var https = require("follow-redirects").https;
var urllib = require("url");
var mustache = require("mustache");
var querystring = require("querystring");
var cookie = require("cookie");
var hashSum = require("hash-sum");
var request = require("request");
function SORequest(n) {
RED.nodes.createNode(this,n);
var node = this;
var nodeSeriosUrl = n.seriosurl;
var nodeSOID = n.soid;
var nodeStream = n.stream;
if (RED.settings.httpRequestTimeout) {
this.reqTimeout = parseInt(RED.settings.httpRequestTimeout) || 120000;
} else {
this.reqTimeout = 120000;
}
this.on("input",function(msg) {
var preRequestTimestamp = process.hrtime();
node.status({fill:"blue",shape:"dot",text:"httpin.status.requesting"});
var url = nodeSeriosUrl || msg.seriosurl;
if (msg.seriosurl && nodeSeropsUrl && (nodeSeriosUrl !== msg.seriosurl)) { // revert change below when warning is finally removed
node.warn(RED._("common.errors.nooverride"));
}
if (!url) {
node.error(RED._("httpin.errors.no-url"),msg);
return;
}
// url must start http:// or https:// so assume http:// if not set
if (url.indexOf("://") !== -1 && url.indexOf("http") !== 0) {
node.warn(RED._("httpin.errors.invalid-transport"));
node.status({fill:"red",shape:"ring",text:"httpin.errors.invalid-transport"});
return;
}
if (!((url.indexOf("http://") === 0) || (url.indexOf("https://") === 0))) {
if (tlsNode) {
url = "https://"+url;
} else {
url = "http://"+url;
}
}
var opts = {};
opts.url = "http://localhost:3000/oauth2/token";
opts.method = "POST";
opts.form = {grant_type: 'client_credentials'},
opts.headers = {'Authorization': 'Basic '+new Buffer(this.credentials.client+":"+this.credentials.password).toString('base64')}
console.log("opts: ", opts);
var userToken = null;
var tokenReq = request(opts, function(terror, tresponse, tbody) {
console.log(tbody);
try {
var parsed = JSON.parse(tbody);
console.log("parsed: ", parsed['access_token']);
userToken = parsed["access_token"];
} catch(e) {
console.log(e);
}
console.log("userToken: ", userToken);
url = url + "/"+nodeSOID+"/streams/"+nodeStream+"/lastUpdate";
console.log("url: ", url);
opts.url = url;
opts.method = "GET";
opts.headers = {
'Authorization': 'bearer ' + userToken,
'Content-Type': 'application/json'
};
request(opts, function(err, res, body) {
if(err === null) {
var jsonBody = null;
console.log(body);
try { jsonBody = JSON.parse(body) }
catch(e) { node.warn(RED._("httpin.errors.json-error")); }
msg.payload = jsonBody;
node.send(msg);
node.status({});
} else {
node.error(err,msg);
msg.payload = err.toString() + " : " + url;
msg.statusCode = err.code;
node.send(msg);
node.status({fill:"red",shape:"ring",text:err.code});
}
});
});
});
this.on("close",function() {
node.status({});
});
}
RED.nodes.registerType("so request", SORequest,{
credentials: {
client: {type:"text"},
password: {type: "password"}
}
});
}
|
// Constant overrides
//app.run(function ($rootScope) {
// $rootScope.title = "Configuration Management";
//}); |
angular.module('myApp', ['ui.router', 'ui.bootstrap', 'smoothScroll', 'ngStorage', 'ngSanitize', 'myApp.controllers', 'myApp.directives', 'myApp.filters'])
.run(
[ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
// It's very handy to add references to $state and $stateParams to the $rootScope
// so that you can access them from any scope within your applications.For example,
// <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li>
// to active whenever 'contacts.list' or one of its decendents is active.
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$state.transitionTo('root.home');
}
]
)
.config(
[ '$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
//////////////////////////
// State Configurations //
//////////////////////////
// Use $stateProvider to configure your states.
$stateProvider
// Root state to master all
.state('root', {
abstract: true,
views: {
'header': {
templateUrl: 'partials/header.html',
controller: 'RootCtrl'
},
'main': {
template: '<div ui-view="master"></div>',
controller: 'RootCtrl'
},
'footer': {
templateUrl: 'partials/footer.html',
controller: 'RootCtrl'
},
}
})
// Home
.state('root.home', {
url: '/',
views: {
'master@root': {
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
}
}
})
}
]
);
|
var reddit = require('../index.js');
reddit.prototype.me = function(callback) {
var self = this;
this._apiRequest("me", {"version": 1}, function(err, response, body) {
self._rawJSON(err, body, callback);
});
};
reddit.prototype.getPrefs = function(prefs, callback) {
if(typeof prefs == 'function') {
callback = prefs;
prefs = [];
}
var self = this;
this._apiRequest("prefs", {"path": "/api/v1/me", "qs": {"fields": prefs.join(',')}}, function(err, response, body) {
self._rawJSON(err, body, callback);
});
};
reddit.prototype.trophies = function(callback) {
var self = this;
this._apiRequest("trophies", {"path": "/api/v1/me"}, function(err, response, body) {
var json;
try {
json = JSON.parse(body);
} catch(e) {
callback("reddit API returned invalid response: " + e);
return;
}
if(json.error) {
callback(json.error);
return;
}
callback(null, json.data.trophies);
});
}; |
function getData(q, $rootScope) {
var d = q.defer();
setTimeout(function() {
$rootScope.$apply(function() {
d.resolve(data);
});
}, 2000);
return d.promise;
}
var data = [
{
"count": 4,
"img": "http://placekitten.com/500/500",
"desc": "Id consequat non ut Lorem et est sint. Sit anim consequat ipsum ad culpa mollit aute. Officia dolore laborum magna qui fugiat sunt commodo non aliqua. Sint excepteur officia commodo velit magna voluptate anim adipisicing excepteur sit ullamco. Proident cillum esse sint sit officia aute veniam Lorem esse pariatur esse proident culpa.\r\n",
"episodes": [
{
"guid": "f15944c8-4ec6-4b34-947e-c3d701a90b5b",
"thumb": "http://placekitten.com/100/100",
"title": "incididunt sunt",
"desc": "Ut quis ut quis anim ipsum ut laboris veniam. Consectetur ex reprehenderit esse dolore reprehenderit velit consectetur veniam quis mollit ipsum eiusmod.",
"url": "http://episodeurl"
},
{
"guid": "13374a89-440a-4d37-9b3c-fb9792ecc164",
"thumb": "http://placekitten.com/100/100",
"title": "ea pariatur",
"desc": "Tempor nostrud sunt ex eu consequat consequat. Proident non quis elit exercitation cupidatat id elit duis voluptate exercitation quis dolore id.",
"url": "http://episodeurl"
},
{
"guid": "7c2ddded-76eb-437a-b515-b8f78bfe498e",
"thumb": "http://placekitten.com/100/100",
"title": "tempor mollit",
"desc": "Et velit fugiat exercitation cupidatat id ea pariatur. Culpa labore aliquip qui nostrud esse commodo occaecat consequat qui voluptate.",
"url": "http://episodeurl"
},
{
"guid": "8e21bb2e-d211-429a-9401-cad173722201",
"thumb": "http://placekitten.com/100/100",
"title": "consequat ex",
"desc": "Est elit dolore cupidatat ea commodo cillum sint minim. Non laboris aliqua culpa qui fugiat sunt velit dolore cupidatat proident minim pariatur consectetur.",
"url": "http://episodeurl"
}
]
},
{
"count": 19,
"img": "http://placekitten.com/500/500",
"desc": "Do dolor laboris tempor exercitation. Veniam mollit id consequat mollit occaecat elit ex consectetur laboris ipsum velit. Esse amet occaecat elit excepteur. Laboris est velit veniam ullamco fugiat sit magna magna ullamco incididunt id ad Lorem et. Labore ad esse nisi et ea elit cupidatat est nostrud mollit. Ea cillum pariatur duis et amet.\r\n",
"episodes": [
{
"guid": "14605a48-9e96-4c54-9fb1-f91774f3ae8a",
"thumb": "http://placekitten.com/100/100",
"title": "dolore fugiat",
"desc": "Minim sint et excepteur eiusmod nostrud exercitation sint amet ex reprehenderit commodo proident eiusmod. Consequat ipsum exercitation reprehenderit ut duis in id cillum consectetur.",
"url": "http://episodeurl"
},
{
"guid": "09d0dc21-203c-40f6-a0d9-63f2f0e17614",
"thumb": "http://placekitten.com/100/100",
"title": "do aliqua",
"desc": "Aliqua occaecat exercitation Lorem esse mollit amet eiusmod amet. Enim velit laboris aliqua elit id nulla minim culpa ad incididunt sint officia in incididunt.",
"url": "http://episodeurl"
},
{
"guid": "32cd8fac-7508-4c45-aaaf-f2170a5141cf",
"thumb": "http://placekitten.com/100/100",
"title": "non Lorem",
"desc": "Amet aute ex eu ex veniam labore id minim. Eu sunt ad laborum non aliqua.",
"url": "http://episodeurl"
},
{
"guid": "5ab0ccb9-96f9-4ff5-bca4-0755a2537134",
"thumb": "http://placekitten.com/100/100",
"title": "occaecat adipisicing",
"desc": "Do veniam duis nostrud duis laboris. Non cillum officia exercitation aute aliquip anim eiusmod esse.",
"url": "http://episodeurl"
},
{
"guid": "1306fe3e-2fe7-4c9a-a054-a961dcfc9920",
"thumb": "http://placekitten.com/100/100",
"title": "commodo nulla",
"desc": "Veniam culpa nostrud eiusmod voluptate et. Pariatur duis incididunt eu id elit ea culpa magna excepteur dolore sit minim laboris.",
"url": "http://episodeurl"
},
{
"guid": "c2206b47-1dbc-4cac-9aa6-94aee747801f",
"thumb": "http://placekitten.com/100/100",
"title": "sunt sit",
"desc": "Commodo enim irure est magna esse adipisicing fugiat irure nostrud irure esse minim. Dolor cillum ipsum cillum reprehenderit et aliquip anim labore laboris in consequat amet non ipsum.",
"url": "http://episodeurl"
},
{
"guid": "003894a2-00f6-41b6-be2e-6084bff738c3",
"thumb": "http://placekitten.com/100/100",
"title": "labore proident",
"desc": "Sunt anim nisi laboris esse. Incididunt do sunt eu magna.",
"url": "http://episodeurl"
},
{
"guid": "3656192d-83ca-4311-8f26-fef34ae7e4bd",
"thumb": "http://placekitten.com/100/100",
"title": "sit nisi",
"desc": "Dolore ex officia ut nisi minim sit voluptate fugiat non mollit duis duis laboris. Fugiat consectetur aute ut excepteur ea dolor do qui occaecat in et sit deserunt esse.",
"url": "http://episodeurl"
},
{
"guid": "0417d022-8875-4e52-b501-c575fcbfefb9",
"thumb": "http://placekitten.com/100/100",
"title": "dolore magna",
"desc": "Laboris proident nulla excepteur aliquip enim officia Lorem. Deserunt eiusmod officia in do veniam aliquip incididunt voluptate labore nisi.",
"url": "http://episodeurl"
},
{
"guid": "db552cfd-7bad-43a0-afab-adc7c52c171d",
"thumb": "http://placekitten.com/100/100",
"title": "ut qui",
"desc": "Labore incididunt eiusmod aute irure non. Duis enim aliqua ex occaecat magna in dolore officia.",
"url": "http://episodeurl"
},
{
"guid": "64f9b4c5-ef00-43aa-bae8-dbc99bee6e0f",
"thumb": "http://placekitten.com/100/100",
"title": "adipisicing ut",
"desc": "Sunt eiusmod aliqua proident voluptate proident consequat. Est ut labore cupidatat nulla consectetur nulla incididunt nostrud.",
"url": "http://episodeurl"
},
{
"guid": "9ff7671f-75d0-48eb-9cd1-b7aa8c999f3b",
"thumb": "http://placekitten.com/100/100",
"title": "consequat quis",
"desc": "Irure laboris laboris ad duis reprehenderit Lorem veniam non incididunt velit est. Aute magna dolore laborum exercitation adipisicing voluptate incididunt laboris irure laborum esse aute.",
"url": "http://episodeurl"
},
{
"guid": "9bbf135a-7645-4134-a713-fc702d5bec77",
"thumb": "http://placekitten.com/100/100",
"title": "sint excepteur",
"desc": "Culpa sint aliquip sint pariatur magna anim. Velit aliquip sint nulla proident excepteur id ullamco fugiat incididunt.",
"url": "http://episodeurl"
},
{
"guid": "744e6b6e-3000-4255-8d11-518b6f27697d",
"thumb": "http://placekitten.com/100/100",
"title": "Lorem laborum",
"desc": "Ea id cillum voluptate sint excepteur incididunt sint voluptate Lorem. Enim quis sit aute reprehenderit enim fugiat.",
"url": "http://episodeurl"
},
{
"guid": "dbb3a326-16ce-4407-b5f3-2a0e12fcba09",
"thumb": "http://placekitten.com/100/100",
"title": "irure dolore",
"desc": "Occaecat labore aute cupidatat anim amet. Nulla Lorem occaecat aliqua ad ex id.",
"url": "http://episodeurl"
},
{
"guid": "7cb54558-3c38-4883-9bf9-2068518325c9",
"thumb": "http://placekitten.com/100/100",
"title": "esse laborum",
"desc": "Ea laborum magna adipisicing exercitation esse in cillum aute irure magna excepteur incididunt et ea. Do ipsum voluptate officia aliquip ex.",
"url": "http://episodeurl"
},
{
"guid": "957bf8c4-2cd5-47fa-9ee2-e610114a0b3f",
"thumb": "http://placekitten.com/100/100",
"title": "occaecat tempor",
"desc": "Consectetur occaecat elit irure fugiat nisi consequat magna sint ex exercitation sunt. Minim ex id ipsum Lorem cillum commodo velit anim.",
"url": "http://episodeurl"
},
{
"guid": "8cf27509-c1f0-462f-b81f-840321bd832a",
"thumb": "http://placekitten.com/100/100",
"title": "labore commodo",
"desc": "Fugiat minim nisi Lorem minim qui voluptate consectetur mollit aliquip ad aliquip culpa cillum. Esse incididunt qui enim non sint excepteur ipsum quis consectetur pariatur aliquip ut reprehenderit.",
"url": "http://episodeurl"
},
{
"guid": "826a34be-2bae-4dd7-b870-a314f4feb589",
"thumb": "http://placekitten.com/100/100",
"title": "in eiusmod",
"desc": "Ut eu qui eiusmod est elit culpa ex incididunt magna Lorem deserunt esse sit. Sunt veniam adipisicing dolor ea minim pariatur.",
"url": "http://episodeurl"
}
]
},
{
"count": 8,
"img": "http://placekitten.com/500/500",
"desc": "Proident fugiat ad ipsum ex adipisicing excepteur irure dolore enim. Lorem magna aliquip dolor elit nostrud laboris eiusmod qui mollit nisi ullamco aliqua Lorem. Dolor ea laborum pariatur occaecat anim velit elit id deserunt id mollit irure sit labore.\r\n",
"episodes": [
{
"guid": "9a7320ce-6a8d-401e-adc2-10b6ad4184a8",
"thumb": "http://placekitten.com/100/100",
"title": "mollit mollit",
"desc": "Sit sit non irure labore est culpa incididunt anim. Enim ad aute velit duis.",
"url": "http://episodeurl"
},
{
"guid": "9f685b6a-80be-4d2c-829c-70b28891a9f0",
"thumb": "http://placekitten.com/100/100",
"title": "culpa aute",
"desc": "Adipisicing dolor ut deserunt consequat laboris minim proident magna officia magna duis. Esse laborum sunt minim ex sit enim in pariatur.",
"url": "http://episodeurl"
},
{
"guid": "ef49fb06-0f55-4ae2-af38-c9beb7569c25",
"thumb": "http://placekitten.com/100/100",
"title": "eu do",
"desc": "Nisi culpa consectetur esse minim qui est aliquip magna veniam minim eu veniam. Adipisicing nisi ex incididunt pariatur occaecat nisi occaecat ex laborum.",
"url": "http://episodeurl"
},
{
"guid": "a8a03981-a9e0-4b44-8571-042befbf883d",
"thumb": "http://placekitten.com/100/100",
"title": "enim laboris",
"desc": "Lorem mollit minim voluptate esse dolor laboris quis. Aliqua reprehenderit amet elit in cupidatat commodo ullamco.",
"url": "http://episodeurl"
},
{
"guid": "93a9fbb1-f3b9-4c28-a8aa-72b7fe881cff",
"thumb": "http://placekitten.com/100/100",
"title": "eiusmod enim",
"desc": "Ut reprehenderit nisi eu elit dolor. Cupidatat cupidatat anim cillum dolore consequat est exercitation cupidatat culpa sit nostrud cupidatat aute.",
"url": "http://episodeurl"
},
{
"guid": "d5dd2ae5-d3de-40e6-bdc4-8102a38834d5",
"thumb": "http://placekitten.com/100/100",
"title": "irure est",
"desc": "Labore in ipsum laborum laboris officia minim excepteur. Sint consectetur commodo nulla anim adipisicing consectetur labore ut id ipsum.",
"url": "http://episodeurl"
},
{
"guid": "03bd38bb-0119-4d69-b9ce-c41086c95363",
"thumb": "http://placekitten.com/100/100",
"title": "culpa esse",
"desc": "Laboris Lorem sit minim cillum proident reprehenderit laborum qui mollit ad elit veniam veniam tempor. Mollit mollit laboris voluptate eiusmod pariatur sit aliquip officia excepteur eu ut ullamco magna.",
"url": "http://episodeurl"
},
{
"guid": "9625fcaf-94c5-4ff0-a5fc-65952a16c9cd",
"thumb": "http://placekitten.com/100/100",
"title": "quis aliquip",
"desc": "Minim cupidatat ex enim veniam esse qui aliquip sint enim. Excepteur consectetur culpa amet ipsum id occaecat nostrud ipsum minim.",
"url": "http://episodeurl"
}
]
},
{
"count": 14,
"img": "http://placekitten.com/500/500",
"desc": "Elit non irure irure id fugiat non officia enim et do velit dolor. Ad amet reprehenderit do non voluptate. Laboris incididunt ullamco amet nostrud sit commodo culpa ea irure mollit in dolor sunt. Non amet ut reprehenderit et. Ad nisi nisi veniam ex consequat duis mollit ut eu ad. Eu adipisicing tempor ipsum ullamco. Non ex fugiat qui ex exercitation eiusmod.\r\n",
"episodes": [
{
"guid": "fc5fafc7-8329-4ccf-bbd1-9eb1dea24410",
"thumb": "http://placekitten.com/100/100",
"title": "officia commodo",
"desc": "Minim eiusmod sit reprehenderit ipsum labore sunt quis duis nulla anim nulla et mollit aliquip. Consectetur anim est aliqua cupidatat.",
"url": "http://episodeurl"
},
{
"guid": "6f3338d5-12fe-46b2-a47e-c529e5e36da5",
"thumb": "http://placekitten.com/100/100",
"title": "mollit laboris",
"desc": "Esse consequat ea tempor id dolor irure consectetur id do id sunt nisi. Pariatur occaecat proident et est sunt minim ipsum.",
"url": "http://episodeurl"
},
{
"guid": "4d5cded6-b895-4abb-a31c-7c31f87d05df",
"thumb": "http://placekitten.com/100/100",
"title": "non reprehenderit",
"desc": "Amet qui sunt id amet nisi. Occaecat nostrud ad enim Lorem ea excepteur aute ut dolore ipsum dolore.",
"url": "http://episodeurl"
},
{
"guid": "54017966-10ed-4b50-b827-03e7b1793107",
"thumb": "http://placekitten.com/100/100",
"title": "incididunt velit",
"desc": "Officia tempor aliquip minim ut non id labore ipsum pariatur laborum commodo eu. Aliqua laborum esse est ipsum esse.",
"url": "http://episodeurl"
},
{
"guid": "6f6a86c6-76f2-48c1-82a5-67499442c392",
"thumb": "http://placekitten.com/100/100",
"title": "velit magna",
"desc": "Id quis nisi deserunt ea velit velit est id consectetur. Fugiat laboris aliqua aute tempor eiusmod dolore occaecat laboris eiusmod aute eiusmod ea.",
"url": "http://episodeurl"
},
{
"guid": "cf45da42-b199-4d3e-aa10-377592ae7bc0",
"thumb": "http://placekitten.com/100/100",
"title": "voluptate reprehenderit",
"desc": "Sunt cillum commodo ea laborum commodo velit ullamco ipsum ad fugiat amet. Minim ex qui eu nisi amet esse consectetur labore irure ea nisi.",
"url": "http://episodeurl"
},
{
"guid": "f90bee13-d641-4825-a1dc-82b1fb6ed753",
"thumb": "http://placekitten.com/100/100",
"title": "deserunt qui",
"desc": "Cupidatat non eu qui consectetur aliqua elit adipisicing aliquip. Et dolor proident mollit enim laboris.",
"url": "http://episodeurl"
},
{
"guid": "fcfced03-1f63-4260-b0b9-01bb7ad78cec",
"thumb": "http://placekitten.com/100/100",
"title": "Lorem Lorem",
"desc": "Duis labore proident id esse aute ea irure cillum ad sint pariatur. Quis minim ex cillum labore ex laboris nostrud cupidatat dolor exercitation quis exercitation incididunt.",
"url": "http://episodeurl"
},
{
"guid": "c83a7f3c-3729-4c7b-b637-953e1b89c4fa",
"thumb": "http://placekitten.com/100/100",
"title": "pariatur cupidatat",
"desc": "Id excepteur ex cillum laborum laborum duis reprehenderit minim et. Ullamco anim velit quis labore ipsum aute id consequat velit.",
"url": "http://episodeurl"
},
{
"guid": "11695c48-809d-4b30-bde0-31c05cd96d8e",
"thumb": "http://placekitten.com/100/100",
"title": "Lorem ullamco",
"desc": "Ullamco ea tempor labore officia quis aliqua. Aliquip velit aute deserunt consectetur amet qui anim aliquip aute minim duis.",
"url": "http://episodeurl"
},
{
"guid": "2a4f2151-3293-463b-a0b1-eda69043be9b",
"thumb": "http://placekitten.com/100/100",
"title": "ut Lorem",
"desc": "Sit anim ut non laborum culpa non nostrud ad. Aute nulla elit reprehenderit ea anim dolore aliquip.",
"url": "http://episodeurl"
},
{
"guid": "915dfab3-5b84-4d42-92d4-50438fc9ef5d",
"thumb": "http://placekitten.com/100/100",
"title": "ut in",
"desc": "Voluptate cupidatat quis est dolor ea est culpa consequat est. Sint amet incididunt exercitation anim consectetur sunt velit commodo.",
"url": "http://episodeurl"
},
{
"guid": "f05cd739-16ca-4d22-b70b-b392f0990ae4",
"thumb": "http://placekitten.com/100/100",
"title": "magna aliquip",
"desc": "Culpa esse non amet do sit cupidatat cillum cillum cupidatat cillum excepteur do tempor voluptate. Magna officia eu est quis sit cupidatat mollit elit incididunt consectetur voluptate exercitation.",
"url": "http://episodeurl"
},
{
"guid": "a7ddfa04-3cdf-4ccb-add0-2da65ccaab03",
"thumb": "http://placekitten.com/100/100",
"title": "amet exercitation",
"desc": "Nulla anim deserunt nisi sit enim ut pariatur quis sint nisi nostrud cillum. Est nulla dolor deserunt nisi proident enim.",
"url": "http://episodeurl"
}
]
}
]; |
function pr_dca(url, auth, auth_cb, timeout, async_job_check_time_ms, service_version) {
var self = this;
this.url = url;
var _url = url;
this.timeout = timeout;
var _timeout = timeout;
this.async_job_check_time_ms = async_job_check_time_ms;
if (!this.async_job_check_time_ms)
this.async_job_check_time_ms = 100;
this.async_job_check_time_scale_percent = 150;
this.async_job_check_max_time_ms = 300000; // 5 minutes
this.service_version = service_version;
var _auth = auth ? auth : { 'token' : '', 'user_id' : ''};
var _auth_cb = auth_cb;
this._check_job = function (job_id, _callback, _errorCallback) {
if (typeof job_id === 'function')
throw 'Argument job_id can not be a function';
if (_callback && typeof _callback !== 'function')
throw 'Argument _callback must be a function if defined';
if (_errorCallback && typeof _errorCallback !== 'function')
throw 'Argument _errorCallback must be a function if defined';
if (typeof arguments === 'function' && arguments.length > 3)
throw 'Too many arguments ('+arguments.length+' instead of 3)';
return json_call_ajax(_url, "pr_dca._check_job",
[job_id], 1, _callback, _errorCallback);
};
this.run_dbcan = function (DBCanParams, _callback, _errorCallback, json_rpc_context) {
if (self.service_version) {
if (!json_rpc_context)
json_rpc_context = {};
json_rpc_context['service_ver'] = self.service_version;
}
var async_job_check_time_ms = self.async_job_check_time_ms;
self._run_dbcan_submit(DBCanParams, function(job_id) {
var _checkCallback = null;
_checkCallback = function(job_state) {
if (job_state.finished != 0) {
if (!job_state.hasOwnProperty('result'))
job_state.result = null;
_callback(job_state.result[0]);
} else {
setTimeout(function () {
async_job_check_time_ms = async_job_check_time_ms *
self.async_job_check_time_scale_percent / 100;
if (async_job_check_time_ms > self.async_job_check_max_time_ms)
async_job_check_time_ms = self.async_job_check_max_time_ms;
self._check_job(job_id, _checkCallback, _errorCallback);
}, async_job_check_time_ms);
}
};
_checkCallback({finished: 0});
}, _errorCallback, json_rpc_context);
};
this._run_dbcan_submit = function (DBCanParams, _callback, _errorCallback, json_rpc_context) {
if (typeof DBCanParams === 'function')
throw 'Argument DBCanParams can not be a function';
if (_callback && typeof _callback !== 'function')
throw 'Argument _callback must be a function if defined';
if (_errorCallback && typeof _errorCallback !== 'function')
throw 'Argument _errorCallback must be a function if defined';
if (typeof arguments === 'function' && arguments.length > 1+2)
throw 'Too many arguments ('+arguments.length+' instead of '+(1+2)+')';
return json_call_ajax(_url, "pr_dca._run_dbcan_submit",
[DBCanParams], 1, _callback, _errorCallback, json_rpc_context);
};
this.status = function (_callback, _errorCallback) {
if (_callback && typeof _callback !== 'function')
throw 'Argument _callback must be a function if defined';
if (_errorCallback && typeof _errorCallback !== 'function')
throw 'Argument _errorCallback must be a function if defined';
if (typeof arguments === 'function' && arguments.length > 2)
throw 'Too many arguments ('+arguments.length+' instead of 2)';
return json_call_ajax(_url, "pr_dca.status",
[], 1, _callback, _errorCallback);
};
/*
* JSON call using jQuery method.
*/
function json_call_ajax(srv_url, method, params, numRets, callback, errorCallback, json_rpc_context, deferred) {
if (!deferred)
deferred = $.Deferred();
if (typeof callback === 'function') {
deferred.done(callback);
}
if (typeof errorCallback === 'function') {
deferred.fail(errorCallback);
}
var rpc = {
params : params,
method : method,
version: "1.1",
id: String(Math.random()).slice(2),
};
if (json_rpc_context)
rpc['context'] = json_rpc_context;
var beforeSend = null;
var token = (_auth_cb && typeof _auth_cb === 'function') ? _auth_cb()
: (_auth.token ? _auth.token : null);
if (token != null) {
beforeSend = function (xhr) {
xhr.setRequestHeader("Authorization", token);
}
}
var xhr = jQuery.ajax({
url: srv_url,
dataType: "text",
type: 'POST',
processData: false,
data: JSON.stringify(rpc),
beforeSend: beforeSend,
timeout: _timeout,
success: function (data, status, xhr) {
var result;
try {
var resp = JSON.parse(data);
result = (numRets === 1 ? resp.result[0] : resp.result);
} catch (err) {
deferred.reject({
status: 503,
error: err,
url: srv_url,
resp: data
});
return;
}
deferred.resolve(result);
},
error: function (xhr, textStatus, errorThrown) {
var error;
if (xhr.responseText) {
try {
var resp = JSON.parse(xhr.responseText);
error = resp.error;
} catch (err) { // Not JSON
error = "Unknown error - " + xhr.responseText;
}
} else {
error = "Unknown Error";
}
deferred.reject({
status: 500,
error: error
});
}
});
var promise = deferred.promise();
promise.xhr = xhr;
return promise;
}
}
|
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
var JiraApi = require('jira-client');
function responder (jira, config) {
return function (match, callback) {
var issueId = match[2];
var link = config.protocol + '://' + config.host + ':' + config.port + '/browse/' + issueId;
var slackLink = '<' + link + '|' + issueId + '>';
jira.findIssue(issueId)
.then(function (issue) {
callback(slackLink + ': ' + issue.fields.summary);
})
.catch(function (err) {
if (err.statusCode === 404) {
callback(slackLink + ' - I couldn\'t find this one... (404)');
} else {
console.error(err);
callback(slackLink + ' - Oh no! An error occured (' + err.statusCode + ')');
}
});
};
}
function finder (jira, config) {
return function (match, callback) {
var originalText = match[1];
var issueId = originalText.replace(/\+|\.|\,|\;|\?|\*|\/|\%|\^|\$|\#|\@|\[|\]/g, " ");
var originalException = match[2];
var escapedException = originalException.replace(/\+|\.|\,|\;|\?|\*|\/|\%|\^|\$|\#|\@|\[|\]/g, " ");
var query = "(text ~ \"" + issueId + "\" OR text ~ \"" + escapedException + "\") AND (project = \" ITDev - Collections Board\" AND Status NOT IN (\"Rejected\", \"Live Done\"))";
console.log("Searching with query " + query);
jira.searchJira(query)
.then(function (results) {
var queryLink = config.protocol + '://' + config.host + ':' + config.port + '/issues/?jql=' + encodeURI(query)
var querySlackLink = '<' + queryLink + '|' + originalText + '>';
if (results.total > 0)
{
var issue = results.issues[0];
var link = config.protocol + '://' + config.host + ':' + config.port + '/browse/' + issue.key;
var slackLink = '<' + link + '|' + issue.key + '>';
callback(":sleuth_or_spy: I searched for \"" + querySlackLink + "\" and the first result was " + slackLink + ': ' + issue.fields.summary);
}
else
{
callback(":sleuth_or_spy: I searched for \"" + querySlackLink + "\" but couldn't find anything");
}
})
.catch(function (err) {
//if (err.statusCode === 404) {
// callback(slackLink + ' - I couldn\'t find this one... (404)');
// } else {
console.error(err);
// callback(slackLink + ' - Oh no! An error occured (' + err.statusCode + ')');
//}
});
};
}
function JiraResponder (config) {
var jira = new JiraApi(config);
return {
regex: /(^|\s)([A-Za-z]+-[0-9]+)/g,
message: responder(jira, config)
};
}
function JiraFinder (config) {
var jira = new JiraApi(config);
return {
regex: /One or more exceptions have occurred - first message is (.*) exception is (.*)/g,
message: finder(jira, config)
};
}
module.exports = { JiraResponder, JiraFinder };
|
import React, { Component } from 'react';
export default class extends Component {
constructor(props) {
super(props);
this.renderFileList = this.renderFileList.bind(this);
}
componentDidMount() {
//console.log(this.props);
}
renderFileList() {
let { data } = this.props;
console.log(data)
if( data ) {
let files = data.allFile.edges;
return files.map((file,i) => {
return <p key={i}>File <span style={{'backgroundColor':'#f56',padding:'5px'}}>{file.node.relativePath}</span> , {file.node.birthTime}</p>
})
}
}
render () {
return (
<div>
{ this.renderFileList() }
</div>
);
}
}
export const query = graphql`
query MyFilesQuery {
allFile {
edges {
node {
relativePath
prettySize
extension
birthTime(fromNow: true)
}
}
}
}
` |
define(['ko', 'text!app/components/flanders-keg-body/template.html'], function (ko, htmlString) {
function FlandersKegBody(model) {
var self = this;
};
return {
viewModel: FlandersKegBody,
template: htmlString
};
}); |
const path = require('path');
const webpack = require('webpack');
const WebpackBar = require('webpackbar');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackTagsPlugin = require('html-webpack-tags-plugin');
const isProd = process.env.NODE_ENV === 'production';
const distPath = path.resolve(__dirname, 'dist');
const externals = {
'es5-shim.min.js': 'node_modules/es5-shim/es5-shim.min.js',
'es5-sham.min.js': 'node_modules/es5-shim/es5-sham.min.js',
'console-polyfill.js': 'node_modules/console-polyfill/index.js',
};
module.exports = {
mode: isProd ? 'production' : 'development',
entry: './src/index.js',
output: {
path: distPath,
filename: 'js/[name].[hash].js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
],
},
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
extensions: ['.js', '.jsx'],
},
optimization: {
moduleIds: 'hashed',
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
},
},
},
minimizer: [
new TerserPlugin({
cache: true,
parallel: true,
sourceMap: true, // Must be set to true if using source-maps in production
terserOptions: {
// https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions
ie8: true,
},
}),
],
},
devtool: 'source-map',
devServer: {
historyApiFallback: true,
port: 3000,
contentBase: ['./'],
inline: true,
publicPath: '/',
hot: true,
},
plugins: [
new WebpackBar(),
new FriendlyErrorsPlugin(),
new CleanWebpackPlugin(),
new CopyWebpackPlugin(
Object.keys(externals).map((k) => ({
from: externals[k],
to: path.join(distPath, 'libs', k),
}))
),
new HTMLWebpackPlugin({
title: 'Webpack-Babel-IE8',
template: 'src/index.ejs',
}),
new HtmlWebpackTagsPlugin({
tags: Object.keys(externals).map((k) => 'libs/' + k),
append: false,
}),
].concat(isProd ? [] : [new webpack.HotModuleReplacementPlugin()]),
};
|
import PIXI from 'pixi.js';
import Hexagon from './hexagon.js';
import GroundLayer from './layer/groundLayer.js';
import UnitLayer from './layer/unitLayer.js';
let hexagon = new Hexagon(80);
/**
* Represents a tile in the game.
*/
export default class Tile {
constructor(x, y, entities) {
this.x = x;
this.y = y;
this.entities = entities;
this.selected = false;
this.hover = false;
this.sprite = new PIXI.Container();
this.layers = [];
this.addLayer(new GroundLayer(this));
this.addLayer(new UnitLayer(this));
}
addLayer(layer) {
this.layers.push(layer);
this.sprite.addChild(layer.getSprite());
}
shouldComponentUpdate() {
return !this.layers.every((e) => !e.shouldComponentUpdate());
}
update(renderer) {
this.layers.forEach((e) => {
if (e.shouldComponentUpdate()) e.update(renderer);
});
}
static get hexagon() {
return hexagon;
}
}
|
/* */
module.exports = function(hljs) {
var LITERALS = {literal: 'true false null'};
var TYPES = [
hljs.QUOTE_STRING_MODE,
hljs.C_NUMBER_MODE
];
var VALUE_CONTAINER = {
end: ',', endsWithParent: true, excludeEnd: true,
contains: TYPES,
keywords: LITERALS
};
var OBJECT = {
begin: '{', end: '}',
contains: [
{
className: 'attr',
begin: /"/, end: /"/,
contains: [hljs.BACKSLASH_ESCAPE],
illegal: '\\n',
},
hljs.inherit(VALUE_CONTAINER, {begin: /:/})
],
illegal: '\\S'
};
var ARRAY = {
begin: '\\[', end: '\\]',
contains: [hljs.inherit(VALUE_CONTAINER)], // inherit is a workaround for a bug that makes shared modes with endsWithParent compile only the ending of one of the parents
illegal: '\\S'
};
TYPES.splice(TYPES.length, 0, OBJECT, ARRAY);
return {
contains: TYPES,
keywords: LITERALS,
illegal: '\\S'
};
}; |
import test from 'ava';
import challenge from '.';
// https://www.reddit.com/4msu2x/
test('Challenge #270 [Easy] Transpose the input text', t => {
// Some
// text.
const input = [['S', 'o', 'm', 'e', ' '], ['t', 'e', 'x', 't', '.']];
const output = [['S', 't'], ['o', 'e'], ['m', 'x'], ['e', 't'], [' ', '.']];
t.deepEqual(challenge(input), output);
});
|
import { getModule } from '../../store/index.js';
import { getOutline, renderOutline } from './renderSegmentationOutline.js';
import external from '../../externalModules.js';
import * as drawing from '../../drawing/index.js';
const { state } = getModule('segmentation');
jest.mock('../../drawing/index.js', () => ({
getNewContext: () => ({
globalAlpha: 1.0,
}),
draw: (context, callback) => {
callback(context);
},
drawLines: jest.fn(),
drawJoinedLines: jest.fn(),
}));
jest.mock('../../externalModules', () => ({
cornerstone: {
pixelToCanvas: (element, imageCoord) => {
// Mock some transformation.
const { viewport, canvas } = mockGetEnabledElement(element);
const m = [1, 0, 0, 1, 0, 0];
function translate(x, y) {
m[4] += m[0] * x + m[2] * y;
m[5] += m[1] * x + m[3] * y;
}
function rotate(rad) {
const c = Math.cos(rad);
const s = Math.sin(rad);
const m11 = m[0] * c + m[2] * s;
const m12 = m[1] * c + m[3] * s;
const m21 = m[0] * -s + m[2] * c;
const m22 = m[1] * -s + m[3] * c;
m[0] = m11;
m[1] = m12;
m[2] = m21;
m[3] = m22;
}
function scale(sx, sy) {
m[0] *= sx;
m[1] *= sx;
m[2] *= sy;
m[3] *= sy;
}
// Move to center of canvas
translate(canvas.width / 2, canvas.height / 2);
// Apply the rotation before scaling
const angle = viewport.rotation;
if (angle !== 0) {
rotate((angle * Math.PI) / 180);
}
// Apply the scale
const widthScale = viewport.scale;
const heightScale = viewport.scale;
const width =
viewport.displayedArea.brhc.x - (viewport.displayedArea.tlhc.x - 1);
const height =
viewport.displayedArea.brhc.y - (viewport.displayedArea.tlhc.y - 1);
scale(widthScale, heightScale);
// Unrotate to so we can translate unrotated
if (angle !== 0) {
rotate((-angle * Math.PI) / 180);
}
// Apply the pan offset
translate(viewport.translation.x, viewport.translation.y);
// Rotate again
if (angle !== 0) {
rotate((angle * Math.PI) / 180);
}
// Apply Flip if required
if (viewport.hflip) {
scale(-1, 1);
}
if (viewport.vflip) {
scale(1, -1);
}
// Move back from center of image
translate(-width / 2, -height / 2);
const x = imageCoord.x;
const y = imageCoord.y;
const px = x * m[0] + y * m[2] + m[4];
const py = x * m[1] + y * m[3] + m[5];
return {
x: px,
y: py,
};
},
},
}));
let eventData;
let evt;
let labelmap3D;
let labelmap2D;
let lineWidth;
const mockGetEnabledElement = element => ({
element,
viewport: eventData.viewport,
image: eventData.image,
canvas: eventData.canvasContext.canvas,
});
function resetEvents() {
const width = 256;
const length = width * width;
const currentImageIdIndex = 0;
const canvasScale = 1.0;
lineWidth = 1;
eventData = {
element: null,
image: {
width: 256,
height: 256,
},
viewport: {
rotation: 0,
scale: canvasScale,
translation: { x: 0, y: 0 },
hflip: false,
vflip: false,
displayedArea: {
brhc: { x: 256, y: 256 },
tlhc: { x: 1, y: 1 },
},
},
canvasContext: {
canvas: {
width: canvasScale * width,
height: canvasScale * width,
},
},
};
evt = {
detail: eventData,
};
labelmap3D = {
buffer: new ArrayBuffer(length * 2),
labelmaps2D: [],
metadata: [],
activeSegmentIndex: 0,
segmentsHidden: [],
};
labelmap2D = {
pixelData: new Uint16Array(labelmap3D.buffer, 0, length),
segmentsOnLabelmap: [0, 1, 2],
};
const pixelData = labelmap2D.pixelData;
const cols = eventData.image.width;
// Add segment 1 as an L shape, so should have 1 interior corner.
pixelData[64 * cols + 64] = 1;
pixelData[65 * cols + 64] = 1;
pixelData[65 * cols + 65] = 1;
// Add segment 2 as a rectangle.
for (let x = 201; x <= 210; x++) {
pixelData[200 * cols + x] = 2;
pixelData[201 * cols + x] = 2;
}
labelmap3D.labelmaps2D[currentImageIdIndex] = labelmap2D;
}
function setCanvasTransform(options = {}) {
const viewport = eventData.viewport;
if (options.scale) {
const { scale } = options;
const { width, height } = eventData.image;
eventData.viewport.scale = scale;
eventData.canvasContext.canvas = {
width: scale * width,
height: scale * height,
};
}
if (options.rotation) {
viewport.rotation = options.rotation;
}
if (options.translation) {
viewport.translation = options.translation;
}
if (options.hflip) {
viewport.hflip = options.hflip;
}
if (options.vflip) {
viewport.vflip = options.vflip;
}
}
describe('renderSegmentationOutline.js', () => {
beforeEach(() => {
resetEvents();
});
describe('Initialization', () => {
it('should have a test image of 256 x 256 pixels.', () => {
const { width, height } = eventData.image;
expect(width * height).toBe(65536);
});
it('should map point 100,100 in image to 100,100 on canvas.', () => {
const canvasPoint = external.cornerstone.pixelToCanvas(
eventData.element,
{ x: 100, y: 100 }
);
expect(canvasPoint.x).toBe(100);
expect(canvasPoint.y).toBe(100);
});
it('should map point 0,0 in image to 256,0 on canvas.', () => {
setCanvasTransform({
rotation: 90,
});
const canvasPoint = external.cornerstone.pixelToCanvas(
eventData.element,
{ x: 0, y: 0 }
);
expect(canvasPoint.x).toBe(256);
expect(canvasPoint.y).toBe(0);
});
});
describe('getOutline', () => {
it('Should produce two segment outlines with 9 and 24 lines.', () => {
const outline = getOutline(evt, labelmap3D, labelmap2D, lineWidth);
const { start, end } = outline[1][0];
expect(outline[1].length).toBe(9);
expect(outline[2].length).toBe(24);
});
it('Should correctly scale the line segments to the canvas size whilst keeping thickness the same on canvas', () => {
setCanvasTransform({
scale: 4.0,
});
const outline = getOutline(evt, labelmap3D, labelmap2D, lineWidth);
const { start, end } = outline[1][0];
expect(start.x).toBeCloseTo(256);
expect(start.y).toBeCloseTo(256.5);
expect(end.x).toBeCloseTo(260);
expect(end.y).toBeCloseTo(256.5);
});
it('Should correctly change the line thickness to 3 pixels, regardless of the canvas scale factor', () => {
setCanvasTransform({
scale: 4.0,
});
lineWidth = 2;
const outline = getOutline(evt, labelmap3D, labelmap2D, lineWidth);
const { start, end } = outline[1][0];
expect(start.x).toBeCloseTo(256);
expect(start.y).toBeCloseTo(257);
expect(end.x).toBeCloseTo(260);
expect(end.y).toBeCloseTo(257);
});
it('Should correctly rotate the line segments to the canvas (90 degrees)', () => {
setCanvasTransform({
rotation: 90,
});
const outline = getOutline(evt, labelmap3D, labelmap2D, lineWidth);
const { start, end } = outline[1][0];
// First horizontal line now vertical after rotation:
expect(start.x).toBeCloseTo(191.5);
expect(start.y).toBeCloseTo(64);
expect(end.x).toBeCloseTo(191.5);
expect(end.y).toBeCloseTo(65);
});
it('Should correctly horizontally flip the line segments to the canvas', () => {
setCanvasTransform({
hflip: true,
});
const outline = getOutline(evt, labelmap3D, labelmap2D, lineWidth);
const { start, end } = outline[1][0];
// First horizontal line now flipped horrizontally:
expect(start.x).toBeCloseTo(192);
expect(start.y).toBeCloseTo(64.5);
expect(end.x).toBeCloseTo(191);
expect(end.y).toBeCloseTo(64.5);
});
it('Should correctly vertically flip the line segments to the canvas', () => {
setCanvasTransform({
vflip: true,
});
const outline = getOutline(evt, labelmap3D, labelmap2D, lineWidth);
const { start, end } = outline[1][0];
// First horrizontal line now flipped vertically (pushed inside pixel even though its flipped):
expect(start.x).toBeCloseTo(64);
expect(start.y).toBeCloseTo(191.5);
expect(end.x).toBeCloseTo(65);
expect(end.y).toBeCloseTo(191.5);
});
it('Should correctly translate the line segments with the canvas', () => {
setCanvasTransform({
translation: { x: 10, y: 10 },
});
const outline = getOutline(evt, labelmap3D, labelmap2D, lineWidth);
const { start, end } = outline[1][0];
// First horrizontal line now translated (10,10) with canvas:
expect(start.x).toBeCloseTo(74);
expect(start.y).toBeCloseTo(74.5);
expect(end.x).toBeCloseTo(75);
expect(end.y).toBeCloseTo(74.5);
});
});
describe('renderOutline', () => {
it('Should call drawLines twice', () => {
const outline = getOutline(evt, labelmap3D, labelmap2D, lineWidth);
// Fake colormap to stop renderOutline breaking.
state.colorLutTables[0] = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
renderOutline(evt, outline, 0, true);
expect(drawing.drawLines).toBeCalledTimes(2);
});
});
});
|
describe('dsds', function () {
it('asdsa', function () {
expect(10).toEqual(123);
});
}); |
const settings = {};
export default settings;
|
const Discord = require('discord.js');
exports.run = (client, message, args) => {
let reason = args.slice(1).join(' ');
let user = message.mentions.users.first();
let modlog = client.channels.find('name', 'delet-this');
let muteRole = client.guilds.get(message.guild.id).roles.find('name', 'MUTED');
let modRole = message.guild.roles.find('name', 'delet Mod');
if (!message.member.roles.has(modRole.id)) {
return message.reply('you have insufficient permissions to use this command.').catch(console.error);
}
if (!modlog) return message.reply('I cannot find a mod-log channel!').catch(console.error);
if (!muteRole) return message.reply('I cannot find a mute role!').catch(console.error);
if (reason.length < 1) return message.reply('you must supply a reason and user for the mute command.').catch(console.error);
if (message.mentions.users.size < 1) return message.reply('you must mention a user to mute.').catch(console.error);
const embed = new Discord.RichEmbed()
.setColor(16737894)
.setTimestamp()
.setAuthor(`🔇 ${user.tag} (${user.id}) was muted/unmuted`, `${user.avatarURL}`)
.setDescription(`\`\`\`fix\nReason: ${reason}\nResponsible moderator: ${message.author.tag} (${message.author.id})\`\`\``)
.setFooter('Distinguishing between a mute/unmute isn\'t currently supported');
if (!message.guild.member(client.user).hasPermission('MANAGE_ROLES_OR_PERMISSIONS')) return message.reply('I have __insufficient permissions__ to carry this out.').catch(console.error);
if (message.guild.member(user).roles.has(muteRole.id)) {
message.guild.member(user).removeRole(muteRole).then(() => {
client.channels.get(modlog.id).send({embed}).catch(console.error);
});
} else {
message.guild.member(user).addRole(muteRole).then(()=>{
client.channels.get(modlog.id).send({embed}).catch(console.error);
});
}
user.send(`🔇 You were **muted** in ${message.guild.name} for the reason "${reason}". This means that you will not be able to send messages or speak in any text or voice channels respectively.`)
message.channel.send(`You successfully muted/unmuted \`${user.tag}\` \`(${user.id})\`. A mute summary was sent to the modlog channel. :ok_hand:`)
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};
exports.help = {
name: 'mute',
description: 'Mutes/unmutes the mentioned user.',
usage: 'mute [user] [reason]'
}; |
'use strict';
module.exports = {
default: {
options: {
syntax: 'scss',
failOnError: false
},
src: [
'source/**/*.scss'
]
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:804e6cd63076c116c7b20658b9f678161264c776a86abc12a984011681b0abcc
size 1518
|
var _ = require('lodash');
var fs = require('fs-extra');
var path = require('path');
var pathsHelper = require('../helpers/paths.helper');
exports.ADDABLE_NODES = ['Component', 'Layout', 'Page'];
exports.SCSS_PLACEHOLDER_DELIMITERS = [
'/* insert new ',
' */'
];
exports.JS_COMPONENT_STRING = 'addcomponenttothis';
exports.JS_AUTOIMPORT_STRING = 'autoimportcomponent';
exports.JS_COMPONENT_REGEX = new RegExp(`\/\/ ${this.JS_COMPONENT_STRING}`, 'g');
exports.JS_AUTOIMPORT_REGEX = new RegExp(`\/\/ ${this.JS_AUTOIMPORT_STRING}`, 'g');
exports.FIND_REPLACES = [
{
label: 'NODE_NAME',
value: 'file'
},
{
label: 'CLASS_NAME',
value: 'classWithPrefix'
},
{
label: 'COMP_NAME',
value: 'component',
},
{
label: 'COMP_TITLE',
value: 'title',
}
];
exports.NON_NODE_DIRECTORIES = [
'.DS_Store'
];
exports.normalizeNodeName = function(nodeName, nodeType) {
var baseName = _.camelCase(nodeName);
return {
title: nodeName,
directory: _.upperFirst(baseName),
component: _.upperFirst(baseName),
class: _.kebabCase(baseName),
file: baseName,
classWithPrefix: this.getNodeTypePrefix(nodeType) + _.kebabCase(baseName),
};
};
exports.getNodeTypePrefix = function(nodeType) {
switch (nodeType) {
case 'Layout':
return 'l_';
case 'Page':
return 'p_';
default:
return '';
};
};
exports.getAllNodesByNodeType = function(nodeType) {
var directoryPath = `${pathsHelper.src}/${nodeType.toLowerCase()}s/`;
if (fs.existsSync(directoryPath)) {
var isDirectory = fs.lstatSync(directoryPath).isDirectory();
var that = this;
var directories = [];
if (isDirectory) {
directories = fs.readdirSync(directoryPath).filter(function (dir) {
var isInNotANode = that.NON_NODE_DIRECTORIES.indexOf(dir);
var isADirectory = fs.lstatSync(path.join(directoryPath, dir)).isDirectory();
return isInNotANode === -1 && isADirectory;
});
}
return directories;
}
return [];
};
exports.getFileTypesToPipe = function(hasJS, hasSCSS, isCraft) {
var fileTypes = isCraft ? ['html'] : ['twig', 'yml', 'md'];
hasJS ? fileTypes.push('js') : null;
hasSCSS ? fileTypes.push('scss') : null;
return fileTypes.join();
};
exports.isNodeAlreadyExisting = function(nodeType, nodeName) {
var nodesByNodeType = this.getAllNodesByNodeType(nodeType);
var nodeNameNormalized = _.upperFirst(_.camelCase(nodeName));
return nodesByNodeType.indexOf(nodeNameNormalized) === -1;
};
exports.isCraftPath = function(isCraft) {
return isCraft ? '/craft' : '';
}
|
(function() {
'use strict';
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../client')));
app.use('/', routes);
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
module.exports = app;
}()); |
import fetch from 'dva/fetch';
const parseJSON = (response) => {
return response.json();
}
const checkStatus = (response) => {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(response.statusText);
error.response = response;
throw error;
}
/**
* Requests a URL, returning a promise.
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
// export default function request(url, options) {
// return fetch(url, options)
// .then(checkStatus)
// .then(parseJSON)
// .then(data => ({ data }))
// .catch(err => ({ err }));
// }
/**
* Requests a URL, returning a promise.
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
export default async function request(url, options) {
const response = await fetch(url, options);
checkStatus(response);
const data = await response.json();
const ret = {
data,
headers: {},
};
if (response.headers.get('x-total-count')) {
ret.headers['x-total-count'] = response.headers.get('x-total-count');
}
return ret;
} |
(function (exports, $) {
const Module = exports.Helpers.API || {}
// Internal cache
let internalCache = {}
let formControls
// Default config
const settings = {
// This is the ajax config object
ajax: {
url: '/establishments.json',
type: 'GET',
dataType: 'json'
},
// The init requires 2 values to be set on a page:
// $(init.selector).data(init.dataAttr)
//
init: {
// Context selector to obtain the feature flag value
selector: '#expenses',
// This attr should contain: true | false
dataAttr: 'featureDistance'
},
// Success / Fail events via $.publish()
events: {
cacheLoaded: '/API/establishments/loaded/',
cacheLoadError: '/API/establishments/load/error/'
}
}
// Init
function loadData (ajaxConfig) {
// This module is a simple cache of data
// It will self init and publish success and failure
// events when the promise resolves
return query(ajaxConfig).then(function (results) {
// Load the results into the internal cache
internalCache = results.sort(function (a, b) {
const nameA = a.name.toUpperCase() // ignore upper and lowercase
const nameB = b.name.toUpperCase() // ignore upper and lowercase
if (nameA < nameB) {
return -1
}
if (nameA > nameB) {
return 1
}
return 0
})
// Publish the success event
$.publish(settings.events.cacheLoaded)
}, function (status, error) {
// Load the error status and response
// in the the internal cache
internalCache = {
error: error,
status: status
}
// Publish the success settings.events.cacheLoadError
$.publish(settings.events.cacheLoadError, internalCache)
})
}
// Query will merge the settings
// and delegate to ..API.CORE
function query (ajaxConfig) {
const mergedSettings = $.extend(settings.ajax, ajaxConfig)
return moj.Helpers.API._CORE.query(mergedSettings)
}
// Filter by category
function getLocationByCategory (category) {
// If no catebory return the entire internalCache
if (!category) {
return internalCache
}
// Filter the internalCache on category
// Examples: 'crown_court', 'prison', etc
return internalCache.filter(function (obj) {
return obj.category.indexOf(category) > -1
})
}
// init with jquery based on a dom selector
function init () {
// Checking DOM for feature flag value
if ($(settings.init.selector).data(settings.init.dataAttr)) {
formControls = moj.Helpers.FormControls
return loadData()
}
}
// leaving in place for possible refactor
function getAsSelectWithOptions (a, b) {
return getAsOptions(a, b)
}
// This method will return an array of <option> tags
// It is also wrapped in a promise to ensure
// the entire operation completes before other
// events are triggered
function getAsOptions (category, selected) {
const results = getLocationByCategory(category)
if (results.length === 0) throw Error('Missing results: no data to build options with')
const def = $.Deferred()
formControls.getOptions(results, selected).then(function (els) {
def.resolve(els)
}, function () {
def.reject(arguments)
})
return def.promise()
}
Module.Establishments = {
init: init,
loadData: loadData,
getLocationByCategory: getLocationByCategory,
getAsOptions: getAsOptions,
getAsSelectWithOptions: getAsSelectWithOptions
}
$(document).ready(init)
exports.Helpers.API = Module
}(moj, jQuery))
|
import React from 'react';
import renderer from 'react-test-renderer';
import Enzyme, { mount } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import RatingMenu from '../RatingMenu';
Enzyme.configure({ adapter: new Adapter() });
describe('RatingMenu', () => {
it('supports passing max/min values', () => {
const tree = renderer
.create(
<RatingMenu
createURL={() => '#'}
refine={() => null}
min={1}
max={5}
currentRefinement={{ min: 1, max: 5 }}
count={[
{ value: '1', count: 1 },
{ value: '2', count: 2 },
{ value: '3', count: 3 },
{ value: '4', count: 4 },
{ value: '5', count: 5 },
]}
canRefine={true}
/>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
it('supports passing max/min values smaller than count max & min', () => {
const tree = renderer
.create(
<RatingMenu
createURL={() => '#'}
refine={() => null}
min={2}
max={4}
currentRefinement={{}}
count={[
{ value: '1', count: 1 },
{ value: '2', count: 2 },
{ value: '3', count: 3 },
{ value: '4', count: 4 },
{ value: '5', count: 5 },
]}
canRefine={true}
/>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
it('supports passing custom className', () => {
const tree = renderer
.create(
<RatingMenu
className="MyCustomRatingMenu"
createURL={() => '#'}
refine={() => null}
min={1}
max={5}
currentRefinement={{ min: 1, max: 5 }}
count={[
{ value: '1', count: 1 },
{ value: '2', count: 2 },
{ value: '3', count: 3 },
{ value: '4', count: 4 },
{ value: '5', count: 5 },
]}
canRefine={true}
/>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
it('expect to render without refinement', () => {
const tree = renderer
.create(
<RatingMenu
createURL={() => '#'}
refine={() => null}
min={1}
max={5}
currentRefinement={{ min: 1, max: 5 }}
count={[
{ value: '1', count: 1 },
{ value: '2', count: 2 },
{ value: '3', count: 3 },
{ value: '4', count: 4 },
{ value: '5', count: 5 },
]}
canRefine={false}
/>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
it('applies translations', () => {
const tree = renderer
.create(
<RatingMenu
createURL={() => '#'}
refine={() => null}
translations={{
ratingLabel: ' & Up',
}}
min={1}
max={5}
currentRefinement={{ min: 1, max: 5 }}
count={[
{ value: '1', count: 1 },
{ value: '2', count: 2 },
{ value: '3', count: 3 },
{ value: '4', count: 4 },
{ value: '5', count: 5 },
]}
canRefine={true}
/>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
it('expect to not throw when only min is defined', () => {
expect(() => {
renderer.create(
<RatingMenu
createURL={() => '#'}
refine={() => null}
translations={{
ratingLabel: ' & Up',
}}
min={3}
currentRefinement={{ min: 1, max: 5 }}
count={[
{ value: '1', count: 1 },
{ value: '2', count: 2 },
{ value: '3', count: 3 },
{ value: '4', count: 4 },
{ value: '5', count: 5 },
]}
canRefine={true}
/>
);
}).not.toThrow();
});
it('expect to render when only max is defined', () => {
const tree = renderer
.create(
<RatingMenu
createURL={() => '#'}
refine={() => null}
translations={{
ratingLabel: ' & Up',
}}
max={3}
currentRefinement={{ min: 1, max: 5 }}
count={[
{ value: '1', count: 1 },
{ value: '2', count: 2 },
{ value: '3', count: 3 },
{ value: '4', count: 4 },
{ value: '5', count: 5 },
]}
canRefine={true}
/>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
it('expect to render from from 1 when min is negative', () => {
const tree = renderer
.create(
<RatingMenu
createURL={() => '#'}
refine={() => null}
translations={{
ratingLabel: ' & Up',
}}
min={-5}
max={5}
currentRefinement={{ min: 1, max: 5 }}
count={[
{ value: '1', count: 1 },
{ value: '2', count: 2 },
{ value: '3', count: 3 },
{ value: '4', count: 4 },
{ value: '5', count: 5 },
]}
canRefine={true}
/>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
it('expect to render nothing when min is higher than max', () => {
const tree = renderer
.create(
<RatingMenu
createURL={() => '#'}
refine={() => null}
translations={{
ratingLabel: ' & Up',
}}
min={5}
max={3}
currentRefinement={{ min: 1, max: 5 }}
count={[
{ value: '1', count: 1 },
{ value: '2', count: 2 },
{ value: '3', count: 3 },
{ value: '4', count: 4 },
{ value: '5', count: 5 },
]}
canRefine={true}
/>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
const refine = jest.fn();
const createURL = jest.fn();
const ratingMenu = (
<RatingMenu
createURL={createURL}
refine={refine}
min={1}
max={5}
currentRefinement={{ min: 1, max: 5 }}
count={[
{ value: '1', count: 4 },
{ value: '2', count: 2 },
{ value: '3', count: 3 },
{ value: '4', count: 3 },
{ value: '5', count: 0 },
]}
canRefine={true}
/>
);
beforeEach(() => {
refine.mockClear();
createURL.mockClear();
});
it('should create an URL for each row except for the largest: the default selected one', () => {
const wrapper = mount(ratingMenu);
expect(createURL.mock.calls).toHaveLength(3);
expect(createURL.mock.calls[0][0]).toEqual({ min: 4, max: 5 });
expect(createURL.mock.calls[1][0]).toEqual({ min: 3, max: 5 });
expect(createURL.mock.calls[2][0]).toEqual({ min: 2, max: 5 });
wrapper.unmount();
});
it('refines its value on change', () => {
const wrapper = mount(ratingMenu);
const links = wrapper.find('.ais-RatingMenu-link');
expect(links).toHaveLength(5);
let selectedItem = wrapper.find('.ais-RatingMenu-item--selected');
expect(selectedItem).toHaveLength(1);
links.first().simulate('click');
expect(refine.mock.calls).toHaveLength(0);
selectedItem = wrapper.find('.ais-RatingMenu-item--selected');
expect(selectedItem).toBeDefined();
const disabledIcon = wrapper
.find('.ais-RatingMenu-item--disabled')
.find('.ais-RatingMenu-starIcon');
expect(disabledIcon).toHaveLength(5);
wrapper.unmount();
});
it('should display the right number of stars', () => {
const wrapper = mount(ratingMenu);
wrapper.find('.ais-RatingMenu-link').last().simulate('click');
const selectedItem = wrapper.find('.ais-RatingMenu-item--selected');
const fullIcon = selectedItem.find('.ais-RatingMenu-starIcon--full');
const emptyIcon = selectedItem.find('.ais-RatingMenu-starIcon--empty');
expect(fullIcon).toHaveLength(1);
expect(emptyIcon).toHaveLength(4);
wrapper.unmount();
});
it('clicking on the selected refinement should select the largest range', () => {
const wrapper = mount(ratingMenu);
wrapper.setProps({ currentRefinement: { min: 4, max: 5 } });
const links = wrapper.find('.ais-RatingMenu-link');
links.at(1).simulate('click');
expect(refine.mock.calls).toHaveLength(1);
expect(refine.mock.calls[0][0]).toEqual({ min: 1, max: 5 });
wrapper.unmount();
});
});
|
var Backbone = require('backbone'),
Calendario = require('../models/calendario');
module.exports = Backbone.Collection.extend({
url: '/api/pistas/',
model: Calendario,
fecha: "",
getFecha: function(){
return this.fecha;
},
setFecha: function(newFecha){
this.fecha = newFecha;
}
}); |
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var __decorate = this && this.__decorate || function (decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {
if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
}return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = this && this.__metadata || function (k, v) {
if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component, Input, ViewEncapsulation } from '@angular/core';
import { Config } from '../../config/config';
import { InfiniteScroll } from './infinite-scroll';
/**
* @private
*/
export var InfiniteScrollContent = function () {
function InfiniteScrollContent(inf, _config) {
_classCallCheck(this, InfiniteScrollContent);
this.inf = inf;
this._config = _config;
}
/**
* @private
*/
_createClass(InfiniteScrollContent, [{
key: "ngOnInit",
value: function ngOnInit() {
if (!this.loadingSpinner) {
this.loadingSpinner = this._config.get('infiniteLoadingSpinner', this._config.get('spinner', 'ios'));
}
}
}]);
return InfiniteScrollContent;
}();
__decorate([Input(), __metadata('design:type', String)], InfiniteScrollContent.prototype, "loadingSpinner", void 0);
__decorate([Input(), __metadata('design:type', String)], InfiniteScrollContent.prototype, "loadingText", void 0);
InfiniteScrollContent = __decorate([Component({
selector: 'ion-infinite-scroll-content',
template: '<div class="infinite-loading">' + '<div class="infinite-loading-spinner" *ngIf="loadingSpinner">' + '<ion-spinner [name]="loadingSpinner"></ion-spinner>' + '</div>' + '<div class="infinite-loading-text" [innerHTML]="loadingText" *ngIf="loadingText"></div>' + '</div>',
host: {
'[attr.state]': 'inf.state'
},
encapsulation: ViewEncapsulation.None
}), __metadata('design:paramtypes', [typeof (_a = typeof InfiniteScroll !== 'undefined' && InfiniteScroll) === 'function' && _a || Object, typeof (_b = typeof Config !== 'undefined' && Config) === 'function' && _b || Object])], InfiniteScrollContent);
var _a, _b; |
version https://git-lfs.github.com/spec/v1
oid sha256:a97a6fcdd4778db5080eab0aa923f0d19da2b4b6815eec4c2e4cadce2fab6a95
size 2589527
|
function formatScheduleURL(options){
var base = "https://citadelcollege.zportal.nl/api/v3/"
var start = new Date() // Sunday before, 12am (start of sunday)
start.setDate( start.getDate() + (7*options.offset) - start.getDay() )
start.setHours( 0,0,0,0 )
var end = new Date( start.getTime() )
end.setDate( end.getDate() + 7 )
start = start.getTime() / 1000
end = end.getTime() / 1000
if( options.scheduleFor.type == "student" || options.scheduleFor.type == "employee" ){
return base + "appointments?user=" + options.scheduleFor.id + "&start=" + start + "&end=" + end + "&access_token=" + token + "&valid=true"
}else if( options.scheduleFor.type == "class" ){
return base + "appointments?containsStudentsFromGroupInDepartment=" + options.scheduleFor.id + "&start=" + start + "&end=" + end + "&access_token=" + token + "&valid=true"
}else if( options.scheduleFor.type == "location" ){
return base + "appointments?locationsOfBranch=" + options.scheduleFor.id + "&start=" + start + "&end=" + end + "&access_token=" + token + "&valid=true"
}else if( options.scheduleFor.type == "name" ){
return base + "appointments?user=" + options.scheduleFor.id + "&start=" + start + "&end=" + end + "&access_token=" + token + "&valid=true"
}
}
function formatDataURL(type){
var base = "https://citadelcollege.zportal.nl/api/v3/"
if( type == "classes" ){
return base + "groupindepartments?schoolInSchoolYear=" + departments + "&access_token=" + token
}else if( type == "locations" ){
return base + "locationofbranches?schoolInSchoolYear=" + departments + "&access_token=" + token
}else if( type == "students" ){
return base + "users?fields=code&isStudent=true&schoolInSchoolYear=" + departments + "&access_token=" + token
}else if( type == "employees" ){
return base + "users?fields=code,prefix,lastName&isEmployee=true&schoolInSchoolYear=" + departments + "&access_token=" + token
}else if( type == "departments" ){
return base + "schoolsinschoolyears?access_token=" + token
}
}
async function getUser(input){
input = (typeof input == "string") ? input.toLowerCase() : ""
if( input == "" ){
// Invalid input
return await getUser(defaultUser)
}
if( $.isEmptyObject(users) ){
await getUsers()
}
if( $.isEmptyObject(users) ){
console.log( new Error("Web request failed") )
return false
}
if( users[input] ){
// Student/employee code, first name, class, location
return users[input][0]
}else{
// Full name (student names no longer available, unauthorized :'( )
return false
var name = input.match(/[a-z]+/g)
if( !name ){ return false };
var firstName = name[0]
var lastName = name.slice(1).join(" ")
// var lastName = (name[1] ? name[1] : "") + (name[2] ? " "+name[2] : "")
if( users[firstName] ){
for( var i = 0; i < users[firstName].length; i++ ){
if( users[firstName][i].lastName == lastName ){
return users[firstName][i]
}
}
return users[firstName][0]
}else{
return false
}
}
}
async function getUsers(){
// Offline
if( localStorage.users ){
var offlineUsers = JSON.parse(localStorage.users)
if( offlineUsers.date + 604800000 > Date.now() ){ // Newer than 1 week
users = offlineUsers.data
return true
}
}
// Online
var students = async function(){
var data = await $.getJSON(formatDataURL("students"))
data = data.response.data
for( var i = 0; i < data.length; i++ ){
// Names no longer available, unauthorized :'(
/*var firstName = data[i].firstName.toLowerCase()
var lastName = data[i].prefix ? data[i].prefix.toLowerCase()+" " : ""
lastName += data[i].lastName.toLowerCase()*/
var about = {
type: "student",
/*firstName: firstName,
lastName: lastName,
name: firstName + " " + lastName,*/
id: data[i].code
}
users[ data[i].code ] = users[ data[i].code ] || []
users[ data[i].code ].push(about)
/*users[firstName] = users[firstName] || []
users[firstName].push(about)*/
}
}
var employees = async function(){
var data = await $.getJSON(formatDataURL("employees"))
data = data.response.data
for( var i = 0; i < data.length; i++ ){
var lastName = data[i].prefix ? data[i].prefix.toLowerCase()+" " : ""
lastName += data[i].lastName ? data[i].lastName.toLowerCase() : ""
var about = {
type: "employee",
lastName: lastName,
name: lastName,
id: data[i].code
}
users[ data[i].code ] = users[ data[i].code ] || []
users[ data[i].code ].push(about)
users[lastName] = users[lastName] || []
users[lastName].push(about)
}
}
var locations = async function(){
var data = await $.getJSON(formatDataURL("locations"))
data = data.response.data
for( var i = 0; i < data.length; i++ ){
users[data[i].name.toLowerCase()] = users[data[i].name.toLowerCase()] || []
users[data[i].name.toLowerCase()].push({
type: "location",
name: data[i].name.toLowerCase(),
id: data[i].id
})
}
}
var classes = async function(){
var data = await $.getJSON(formatDataURL("classes"))
data = data.response.data
for( var i = 0; i < data.length; i++ ){
users[data[i].name.toLowerCase()] = users[data[i].name.toLowerCase()] || []
users[data[i].name.toLowerCase()].push({
type: "class",
name: data[i].name.toLowerCase(),
id: data[i].id
})
}
}
await Promise.all([ students(), employees(), locations(), classes() ])
localStorage.setItem( "users", JSON.stringify({date: Date.now(), data: users}) )
}
async function getDepartments(){
// Offline
if( localStorage.departments ){
var offlineDepartments = JSON.parse(localStorage.departments)
if( offlineDepartments.date + 3600000 > Date.now() ){ // Newer than 1 hour (was 2419200000, 4 weeks)
departments = offlineDepartments.data
return true
}
}
// Online
try{
var data = await $.getJSON(formatDataURL("departments"))
var data = data.response.data
var d = new Date()
var yearCode = d.getFullYear()
if( d.getMonth() < 6 ){
yearCode--
}
for( var i = 0; i < data.length; i++ ){
if( data[i].year == yearCode && data[i].schoolName == "Citadel GD" ){ // This year, only for GD
departments += data[i].id + ","
}
}
departments = departments.slice(0, -1) // Remove last ","
localStorage.setItem( "departments", JSON.stringify({date: Date.now(), data: departments}) )
}catch(e){
console.log( new Error("Web request failed") )
return false
}
}
async function checkChange(thisWeek, options){
// No schedule data before 2 weeks, display no change
if( options.offset <= -2 ){
return thisWeek
}
// Copy options object and modify it to get last week
var getOptions = Object.assign({}, options)
getOptions.offset -= 1
var lastWeek = await get(getOptions)
var arrayEqual = function( arr1, arr2 ){
if( arr1.length != arr2.length ){
return false
}
for( var i = 0; i < arr1.length; i++ ){
if( arr1[i] !== arr2[i] ){
return false
}
}
return true
}
for( var i = 0; i < thisWeek.length; i++ ){
var thisLesson = thisWeek[i]
for( var j = 0; j < lastWeek.length; j++ ){
var prevLesson = lastWeek[j]
// Check if lesson on same location (same lesson)
if( prevLesson.startdate.getDay() == thisLesson.startdate.getDay() && prevLesson.startslot == thisLesson.startslot ){
// Same lesson, check if changed
if( !arrayEqual(prevLesson.locations, thisLesson.locations) ){
thisLesson.locationChanged = true
}
if( !arrayEqual(prevLesson.subjects, thisLesson.subjects) ){
thisLesson.subjectChanged = true
}
break;
}else if( j == lastWeek.length - 1 ){ // Not the same lesson, last option (new lesson)
thisLesson.locationChanged = true
thisLesson.subjectChanged = true
} // End if same lesson
} // End for prevLesson
} // End for thisLesson
return thisWeek
}
function removeOldSchedules(){
for( key in localStorage ){
if( key.substring(0,7) == "lessons" ){
var weekNumber = Number( key.substring(8) )
if( weekNumber != NaN && weekNumber + 2 < new Date().getWeek() ){
localStorage.removeItem(key)
}else{
// Check for pre-1.8.5 schedule data
var data = JSON.parse( localStorage[key] )
if( data.data[0] && data.data[0].desc ){
localStorage.removeItem(key)
}
}
}
}
}
function format(data){
// get date of special days
var year = new Date().getFullYear()
var firstDayOfMonth = new Date( year, new Date().getMonth(), 1 )
var purplefriday = new Date( year, 11, 8 + mod(5-firstDayOfMonth.getDay(), 7) )
var kingsday = new Date( new Date().getFullYear(), 3, 27 )
if( kingsday.getDay() === 0 ){
kingsday.setDate( kingsDay.getDate() - 1 )
}
for( var i = 0; i < data.length; i++ ){
data[i].startdate = new Date(data[i].start * 1000)
data[i].starttime = data[i].startdate.getHours() + data[i].startdate.getMinutes() / 60
data[i].startslot = data[i].startTimeSlot
data[i].enddate = new Date(data[i].end * 1000)
data[i].endtime = data[i].enddate.getHours() + data[i].enddate.getMinutes() / 60
data[i].endslot = data[i].endTimeSlot
data[i].day = data[i].startdate.getDay()
data[i].size = data[i].endtime - data[i].starttime
// Sort arrays for comparison
data[i].subjects = data[i].subjects.sort()
data[i].groups = data[i].groups.sort()
data[i].teachers = data[i].teachers.sort()
data[i].locations = data[i].locations.sort()
// Add special day checks
data[i].purpleFriday = data[i].startdate.getMonth() == purplefriday.getMonth()
&& data[i].startdate.getDate() == purplefriday.getDate()
data[i].kingsday = data[i].startdate.getMonth() == kingsday.getMonth()
&& data[i].startdate.getDate() == kingsday.getDate()
// Change check flags
data[i].locationChanged = false
data[i].subjectChanged = false
}
return data
}
function getOffline(options){
if( options.scheduleFor.id == defaultUser ){
var offline = localStorage["lessons-"+(new Date().getWeek()+options.offset)]
if( offline != undefined ){
var data = JSON.parse(offline)
if( data.date + 43200000 > Date.now() ){ // 12 Hours
console.log("Loaded offline schedule ("+options.scheduleFor.type+": "+options.scheduleFor.name+" ("+options.scheduleFor.id+") (default), week: "+options.offset+")")
data = data.data
for( var i = 0; i < data.length; i++ ){
data[i].startdate = new Date(data[i].startdate)
data[i].enddate = new Date(data[i].enddate)
}
return data
}
}
}
return false
}
async function getOnline(options){
try{
var data = await $.getJSON(formatScheduleURL(options))
var formattedData = format(data.response.data)
console.log("Loaded online schedule ("+options.scheduleFor.type+": "+options.scheduleFor.name+" ("+options.scheduleFor.id+") (default), week: "+options.offset+")")
if( options.scheduleFor.id == defaultUser ){ // Store offline
localStorage.setItem( "lessons-" + (new Date().getWeek()+options.offset), JSON.stringify({date: Date.now(), data: formattedData}) )
}
return formattedData
}catch(e){
console.log(e, e.getResponseHeader("status"))
return false
}
}
async function updateOffline(options){
var data = getOffline(options)
if( data ){
data = await checkChange(data, options)
formatSchedule( data, options )
lessons[options.scheduleFor.id] = lessons[options.scheduleFor.id] || []
lessons[options.scheduleFor.id][options.offset+2] = data
$("span.offline").css("display", "block")
return true
}
return false
}
async function updateOnline(options){
var data = await getOnline(options)
if( data ){
data = await checkChange(data, options)
formatSchedule( data, options )
lessons[options.scheduleFor.id] = lessons[options.scheduleFor.id] || []
lessons[options.scheduleFor.id][options.offset+2] = data
$("span.offline").css("display", "none")
}
}
async function update(options){
if( !options || !options.scheduleFor ){
return false
}
removeOldSchedules()
if( lessons[options.scheduleFor.id] && lessons[options.scheduleFor.id][options.offset+2] ){ // Saved locally
formatSchedule( lessons[options.scheduleFor.id][options.offset+2], options )
if( options.scheduleFor.id == defaultUser && localStorage["lessons-"+(new Date().getWeek()+options.offset)] ){
$("span.offline").css("display", "block")
}else{
$("span.offline").css("display", "none")
}
}else{
if( !await updateOffline(options) ){
updateOnline(options)
}
}
}
async function get(options){
if( lessons[options.scheduleFor.id] && lessons[options.scheduleFor.id][options.offset+2] ){ // Saved locally
return lessons[options.scheduleFor.id][options.offset+2]
}
// Get offline schedule
lessons[options.scheduleFor.id] = lessons[options.scheduleFor.id] || []
var data = getOffline(options)
if( data ){
lessons[options.scheduleFor.id][options.offset+2] = data
return data
}else{
// Get online schedule
var data = await getOnline(options)
if( data ){
lessons[options.scheduleFor.id][options.offset+2] = data
return data
}
}
}
|
/**
* Visitor Model for schema validation
* @type {Object}
*/
module.exports = {
"properties": {
"city": {
"type": "string"
},
"country_code": {
"type": "string"
},
"country_name": {
"type": "string"
},
"latitude": {
"type": "string"
},
"longitude": {
"type": "string"
},
"metro_code": {
"type": "string"
},
"region_code": {
"type": "string"
},
"region_name": {
"type": "string"
},
"time_zone": {
"type": "string"
},
"zip_code": {
"type": "string"
}
}
};
|
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var common=require("../common"),assert=require("assert"),Readable=require("../../readable").Readable,r=new Readable,N=262144;process.maxTickDepth=N+2;var reads=0;r._read=function(e){var t=reads++===N?null:new Buffer(1);r.push(t)};r.on("readable",function(){r._readableState.length%256||console.error("readable",r._readableState.length);r.read(N*2)});var ended=!1;r.on("end",function(){ended=!0});r.read(0);process.on("exit",function(){assert(ended);console.log("ok")}); |
var SecretHandshake = require('./secret_handshake');
describe("Secret Handshake", function() {
it("1 is a wink", function() {
var handshake = new SecretHandshake(1);
expect(handshake.commands()).toEqual(["wink"]);
});
xit("10 is a double blink", function() {
var handshake = new SecretHandshake(2);
expect(handshake.commands()).toEqual(["double blink"]);
});
xit("100 is close your eyes", function() {
var handshake = new SecretHandshake(4);
expect(handshake.commands()).toEqual(["close your eyes"]);
});
xit("1000 is jump", function() {
var handshake = new SecretHandshake(8);
expect(handshake.commands()).toEqual(["jump"]);
});
xit("11 is wink and double blink", function() {
var handshake = new SecretHandshake(3);
expect(handshake.commands()).toEqual(["wink","double blink"]);
});
xit("10011 is double blink and wink", function() {
var handshake = new SecretHandshake(19);
expect(handshake.commands()).toEqual(["double blink","wink"]);
});
xit("11111 is jump, close your eyes, double blink, and wink", function() {
var handshake = new SecretHandshake(31);
expect(handshake.commands()).toEqual(["jump","close your eyes","double blink","wink"]);
});
xit("text is an invalid secret handshake", function() {
expect( function () {
var handshake = new SecretHandshake("piggies");
}).toThrow(new Error("Handshake must be a number"));
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var iosFastforwardOutline = exports.iosFastforwardOutline = { "viewBox": "0 0 512 512", "children": [{ "name": "path", "attribs": { "d": "M48,155l183.5,101L48,356.9V155 M272,155.8L448,256L272,356.4v-95.6v-27.1V156 M256,128v123.2L32,128v256l224-123.2V384\r\n\tl224-128L256,128L256,128z" }, "children": [] }] }; |
const {ul, li, i, button} = require('dom-gen')
const {on, component} = $.cc
/**
* TaskSection component.
*/
class TaskSection {
/**
* @param {jQuery} elem
*/
constructor (elem) {
this.tasks = elem.data('tasks')
this.elem = elem
}
appendTaskList (elem) {
return ul(this.tasks.map(task => li(this.icon(), ' ', task.title))).appendTo(elem)
}
}
@component
class DoneSection extends TaskSection {
constructor (elem) {
super(elem)
if (this.tasks.length > 0) {
this.appendShowMoreBtn(elem)
this.appendTaskList(elem).addClass('task-list task-list-hidden gray-out')
}
}
appendShowMoreBtn (elem) {
button(i().addClass('fa fa-check-square-o'), ' ', 'Show dones').appendTo(elem)
}
@on('click').at('button')
onButtonClick () {
this.elem.find('ul').toggleClass('task-list-hidden')
}
icon () {
return i().addClass('fa fa-check-square-o')
}
}
@component
class TodoSection extends TaskSection {
constructor (elem) {
super(elem)
this.appendTaskList(elem).addClass('task-list')
}
icon () {
return i().addClass('fa fa-thumb-tack')
}
}
exports.DoneSection = DoneSection
exports.TodoSection = TodoSection
|
import State, {makeInvalidMessage, isValidDataTypes} from '../../core/State';
import Data, {DataTypes} from '../../core/Data';
export default class Equal extends State {
constructor() {
super(
makeInvalidMessage("Equal", ["any", "any"]),
DataTypes.boolean
);
}
isValid(childrenNode) {
const nodesNum = childrenNode.length;
if (nodesNum == 2) {
if (isValidDataTypes(childrenNode, [DataTypes.any, DataTypes.any])) {
return true;
}
}
return false;
}
process(childrenNode) {
let res = childrenNode[0].data.value == childrenNode[1].data.value;
return new Data(res, this.dataType);
}
}
|
import { combineReducers } from 'redux';
import dashboard from './dashboard';
export default combineReducers({
dashboard,
});
|
var DebugHelper = require('./../../lib/debug-helper');
var should = require('should');
var FakeLogger = function(){
this.logStack = [];
var self = this;
this.log = function(message){
self.logStack.push(message);
};
};
describe('log function', function(){
it('should correctly log simple messages', function(done) {
var fakeLogger = new FakeLogger(),
debugHelper = new DebugHelper(fakeLogger);
debugHelper.simpleLog("Message");
fakeLogger.logStack[0].should.be.eql("Message");
done();
});
it('should correctly log messages', function(done) {
var fakeLogger = new FakeLogger(),
debugHelper = new DebugHelper(fakeLogger);
debugHelper.log("Message");
fakeLogger.logStack[0].should.be.eql("======================================");
fakeLogger.logStack[1].should.be.eql("Message");
fakeLogger.logStack[2].should.be.eql("");
done();
});
it('should correctly log comparison result in case of comparison', function(done) {
var fakeLogger = new FakeLogger(),
debugHelper = new DebugHelper(fakeLogger);
debugHelper.log("Message");
fakeLogger.logStack[0].should.be.eql("======================================");
fakeLogger.logStack[1].should.be.eql("Message");
fakeLogger.logStack[2].should.be.eql("");
done();
});
it('should correctly log nothing if it is not enabled', function(done) {
var fakeLogger = new FakeLogger(),
debugHelper = new DebugHelper(fakeLogger);
debugHelper.shutUp();
debugHelper.simpleLog("Message");
debugHelper.log("Message");
fakeLogger.logStack.length.should.be.eql(0);
done();
});
}); |
/**
* @module express-universal-query-validator/util
* @description Utility functions needed for this module
*/
import url from 'url';
import { attempt, some, reject, isError } from 'lodash';
/**
* Checks if a key=value param can not be
* parsed by global `decodeURIComponent`
* @param {string} query
* @returns {boolean} - did parsing throw?
*/
export function isUnparseableQuery(query = 'key=value') {
return isError(attempt(decodeURIComponent, query));
}
/**
* Are all queries parseable?
* @param {Array} queries
* @returns {boolean}
*/
export function validateQueryParams(queries = []) {
return !some(queries, isUnparseableQuery);
}
/**
* Returns input minus unparseable queries
* @param {Array} queries
* @returns {Array}
*/
export function dropInvalidQueryParams(queries = []) {
return reject(queries, isUnparseableQuery);
}
|
import React from 'react'
import { shallow, mount } from 'enzyme'
import { expect, assert } from 'chai'
import sinon from 'sinon'
import Donation from '../../public/lib/components/Donation'
import Button from '../../public/lib/components/Button'
describe('Donation', () => {
const fetchData = sinon.spy()
it('should have a state of title that is an empty string', () => {
const wrapper = shallow(<Donation/>)
expect(wrapper.state().first).to.deep.equal('');
});
it('should have a state of name that is an empty string', () => {
const wrapper = shallow(<Donation/>)
expect(wrapper.state().last).to.deep.equal('');
});
it('should have a state of location that is an empty string', () => {
const wrapper = shallow(<Donation/>)
expect(wrapper.state().email).to.deep.equal('');
});
it('should have a state of location that is an empty string', () => {
const wrapper = shallow(<Donation/>)
expect(wrapper.state().donation).to.deep.equal('');
});
it('should trigger "click"', () => {
const click = sinon.spy()
const wrapper = mount(<Button handleClick={click} />)
wrapper.simulate('click')
expect(click.calledOnce).to.equal(true)
});
it('should trigger "click"', () => {
const click = sinon.spy()
const wrapper = mount(<Button handleClick={click} />)
wrapper.simulate('click')
expect(click.calledOnce).to.equal(true)
});
});
|
'use strict';
(function() {
var self = this;
var DeathAnimations = function() {
self.deathSprites = [];
self.headSprites = [];
self.bloodEmitters = [];
self.animationDuration = 5000;
self.groundY = 650;
self.bloodParticles = [];
self.bloodTime = 8000;
self.bloodMax = 600;
};
DeathAnimations.prototype = {
update: function(points) {
self.bloodEmitters.forEach(function(emitter) {
var particlesToDestroy = [];
emitter.children.forEach(function(particle) {
if(particle.position.y > globals.ground) {
var bloodparticle = 'blood_particle' + util.randomInt(1, 5);
var blood = game.add.sprite(particle.position.x, particle.position.y, bloodparticle);
blood.timeCreated = Date.now();
self.bloodParticles.push(blood);
particlesToDestroy.push(particle);
}
});
particlesToDestroy.forEach(function(particle) {
var index = emitter.children.indexOf(particle);
emitter.children.splice(index, 1);
particle.kill();
});
if(Date.now() - emitter.emitStartTime > self.animationDuration) {
var index = self.bloodEmitters.indexOf(emitter);
self.bloodEmitters.splice(index, 1);
emitter.destroy();
}
});
var bloodParticlesToDestroy = [];
bloodParticles.forEach(function(bloodParticle) {
if(Date.now() - bloodParticle.timeCreated > self.bloodTime) {
bloodParticlesToDestroy.push(bloodParticle);
}
});
bloodParticlesToDestroy.forEach(function(bloodParticle) {
var index = self.bloodParticles.indexOf(bloodParticle);
self.bloodParticles.splice(index, 1);
bloodParticle.kill();
});
while(bloodParticles.length > self.bloodMax) {
bloodParticles.splice(-50, 50);
}
var headSpritesToKill = [];
self.headSprites.forEach(function(sprite) {
sprite.rotation += sprite.rotationSpeed;
sprite.position = Phaser.Point.add(sprite.position, sprite.velocity);
sprite.velocity = Phaser.Point.add(sprite.velocity, sprite.acceleration);
var textPosition = new Phaser.Point(game.width - 200, 50);
var vectorToText = Phaser.Point.subtract(textPosition, sprite.position);
vectorToText = vectorToText.normalize();
var velocityVector = sprite.velocity.normalize();
var angle = Math.acos(vectorToText.dot(velocityVector));
if(angle < 0.3) {
sprite.acceleration = sprite.velocity.rotate(0, 0, 0.01);
sprite.magnitude += 0.3;
}
else {
sprite.acceleration = sprite.velocity.rotate(0, 0, 0.05);
sprite.magnitude += 0.02;
}
sprite.acceleration.setMagnitude(sprite.magnitude);
if((sprite.position.x > game.width || sprite.position.x < 0) &&
(sprite.position.y > game.height || sprite.position.y < 0)) {
headSpritesToKill.push(sprite);
points.updateMultiplierText();
}
});
headSpritesToKill.forEach(function(sprite) {
var index = self.headSprites.indexOf(sprite);
self.headSprites.splice(index, 1);
sprite.kill();
});
self.deathSprites.forEach(function(sprite) {
if(Date.now() - sprite.startTime > self.animationDuration) {
var index = self.deathSprites.indexOf(sprite);
self.deathSprites.splice(index, 1);
sprite.destroy();
}
else if(Math.abs(sprite.y - self.groundY) <= 20) {
sprite.y = self.groundY;
sprite.body.velocity.x = 0;
sprite.body.velocity.y = 0;
sprite.body.gravity.y = 0;
}
});
},
killChild: function(child, headshot, grenade) {
if(headshot) {
// particle effects
var bloodEmitter = game.add.emitter(child.sprite.x, child.sprite.y - 28, 50);
bloodEmitter.minParticleSpeed.setTo(-50, -100);
bloodEmitter.maxParticleSpeed.setTo(50, -500);
bloodEmitter.makeParticles([
'blood_particle1',
'blood_particle2',
'blood_particle3',
'blood_particle4',
'blood_particle5'
]);
bloodEmitter.gravity = 500;
bloodEmitter.start(true, 0, null, 100);
bloodEmitter.emitStartTime = Date.now();
self.bloodEmitters.push(bloodEmitter);
// head
var headSprite = game.add.sprite(0, 0, 'girl_head');
headSprite.anchor.setTo(0.5, 0.5);
headSprite.x = child.sprite.x;
headSprite.y = child.sprite.y - 68;
if(child.sprite.scale.x < 0) {
headSprite.scale.x = -1;
}
headSprite.rotationSpeed = util.randomFloat(-0.05, 0.05);
var textPosition = new Phaser.Point(game.width - 200, 50);
var vectorToText = Phaser.Point.subtract(textPosition, headSprite.position);
vectorToText = vectorToText.setMagnitude(200);
headSprite.velocity = vectorToText.rotate(0, 0, Math.PI / 2);
headSprite.acceleration = headSprite.velocity.rotate(0, 0, 0.1);
headSprite.magnitude = 8;
headSprite.acceleration.setMagnitude(headSprite.magnitude);
self.headSprites.push(headSprite);
}
// death animation
var sprite = game.add.sprite(child.sprite.x, child.sprite.y, 'girl_death');
if(headshot) {
sprite.animations.add('deathAnimation', [8, 9, 10, 11, 12, 13, 14, 15]);
}
else if(grenade) {
sprite.animations.add('deathAnimation', [16, 17, 18, 19, 20, 21, 22, 23]);
}
else {
sprite.animations.add('deathAnimation', [0, 1, 2, 3, 4, 5, 6, 7]);
}
sprite.anchor.setTo(0.5, 0.5);
sprite.x = child.sprite.x;
sprite.y = child.sprite.y;
game.physics.arcade.enable(sprite);
sprite.body.gravity = child.sprite.body.gravity;
sprite.body.velocity = child.sprite.body.velocity;
if(child.sprite.scale.x < 0) {
sprite.scale.x = -1;
}
sprite.animations.play('deathAnimation', 8, false);
sprite.startTime = Date.now();
self.deathSprites.push(sprite);
}
};
this.DeathAnimations = DeathAnimations;
}).call(self);
|
var {Helper, Operator, Type} = require("@kaoscript/runtime");
module.exports = function() {
let AnimalFlags = Helper.enum(Number, {
None: 0,
HasClaws: 1,
CanFly: 2,
EatsFish: 4,
Endangered: 8
});
function foobar(abilities) {
if(arguments.length < 1) {
throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)");
}
if(abilities === void 0 || abilities === null) {
throw new TypeError("'abilities' is not nullable");
}
else if(!Type.isEnumInstance(abilities, AnimalFlags)) {
throw new TypeError("'abilities' is not of type 'AnimalFlags'");
}
if(Operator.xor((abilities & AnimalFlags.CanFly) !== 0, (abilities & AnimalFlags.EatsFish) !== 0)) {
}
}
}; |
/**
* $list
*/
var $list = (function (module) {
module.hasDuplication = function (list, checkDuplicateItem, comparator) {
for (var i = 0; i < list.length; i++) {
var item = list[i];
if (item != checkDuplicateItem) {
if (comparator.compare(item, checkDuplicateItem) == 0) {
return true;
}
}
}
return false;
};
return module;
}($list || {})
); |
/**
* Constructs a segment <code>[(x_1, y_1), (x_2, y_2)]</code>. Use cases are as follows:
* <ul>
* <li><code>new Malakh.Segment()</code> (gives segment <code>[(0, 0), (0, 0)])</code></li>
* <li><code>new Malakh.Segment({x1: x1, y1: y1, x2: x2, y2: y2})</code></li>
* <li><code>new Malakh.Segment(x1, y1, x2, y2)</code></code></li>
* <li><code>new Malakh.Segment([x1, y1, x2, y2])</code></code></li>
* </ul>
*
* @class <p>Represents a Segment <code>[(x_1, y_1), (x_2, y_2)]</code> on a 2-dimensional plane.
*
* <ul>
* <li>Author: <a href="mailto:michal.golebiowski@laboratorium.ee">Michał Z. Gołębiowski</a>
* <li>Publisher: <a href="http://laboratorium.ee/">Laboratorium EE</a></li>
* <li>License: New BSD (see the license.txt file for copyright information)</li>
* <ul>
*/
Malakh.Segment = function Segment() {
var arguments0 = arguments[0];
if (arguments0 == null) {
/**
* Horizontal start segment parameter.
* @type number
* @default 0
*/
this.x1 = 0;
/**
* Vertical start segment parameter.
* @type number
* @default 0
*/
this.y1 = 0;
/**
* Horizontal end segment parameter.
* @type number
* @default 0
*/
this.x2 = 0;
/**
* Vertical end segment parameter.
* @type number
* @default 0
*/
this.y2 = 0;
} else if (arguments0.x1 == null) {
this.x1 = arguments0[0] || arguments0 || 0;
this.y1 = arguments0[1] || arguments[1] || 0;
this.x2 = arguments0[2] || arguments[2] || 0;
this.y2 = arguments0[3] || arguments[3] || 0;
} else {
this.x1 = arguments0.x1 || 0;
this.y1 = arguments0.y1 || 0;
this.x2 = arguments0.x2 || 0;
this.y2 = arguments0.y2 || 0;
}
};
$.extend(Malakh.Segment.prototype,
/**
* @lends Malakh.Segment.prototype
*/
{
/**
* Checks if another segment is equal to the current one.
*
* @param {Malakh.Segment} segment
* @return {boolean}
*/
equals: function equals(segment) {
return segment instanceof Malakh.Segment &&
this.x1 === segment.x1 && segment.y1 === segment.y1 &&
this.x2 === segment.x2 && segment.y2 === segment.y2;
},
/**
* Returns a <code>string</code> representing the segment.
*
* @return {string}
*/
toString: function toString() {
return '[(' + this.x1 + ', ' + this.y1 + '), ' + '(' + this.x2 + ', ' + this.y2 + ')]';
},
}
);
|
/*jshint node:true*/
module.exports = {
description: 'Generate default configuration for ember-cli-template-lint.',
normalizeEntityName: function() {
// this prevents an error when the entityName is
// not specified (since that doesn't actually matter
// to us
}
};
|
//Copyright 2012 Massachusetts Institute of Technology. All rights reserved.
/**
* @fileoverview Visual blocks editor for App Inventor
* Initialize the blocks editor workspace.
*
* @author sharon@google.com (Sharon Perl)
*/
Blockly.BlocklyEditor = {};
Blockly.BlocklyEditor.startup = function(documentBody, formName) {
Blockly.inject(documentBody);
Blockly.Drawer.createDom();
Blockly.Drawer.init();
Blockly.BlocklyEditor.formName_ = formName;
/* [Added by paulmw in patch 15]
There are three ways that you can change how lexical variables
are handled:
1. Show prefixes to users, and separate namespace in yail
Blockly.showPrefixToUser = true;
Blockly.usePrefixInYail = true;
2. Show prefixes to users, lexical variables share namespace yail
Blockly.showPrefixToUser = true;
Blockly.usePrefixInYail = false;
3. Hide prefixes from users, lexical variables share namespace yail
//The default (as of 12/21/12)
Blockly.showPrefixToUser = false;
Blockly.usePrefixInYail = false;
It is not possible to hide the prefix and have separate namespaces
because Blockly does not allow to items in a list to have the same name
(plus it would be confusing...)
*/
Blockly.showPrefixToUser = false;
Blockly.usePrefixInYail = false;
/******************************************************************************
[lyn, 12/23-27/2012, patch 16]
Prefix labels for parameters, locals, and index variables,
Might want to experiment with different combintations of these. E.g.,
+ maybe all non global parameters have prefix "local" or all have prefix "param".
+ maybe index variables have prefix "index", or maybe instead they are treated as "param"
*/
Blockly.globalNamePrefix = "global"; // For names introduced by global variable declarations
Blockly.procedureParameterPrefix = "parameter"; // For names introduced by procedure/function declarations
Blockly.handlerParameterPrefix = "parameter"; // For names introduced by event handlers
Blockly.localNamePrefix = "local"; // For names introduced by local variable declarations
Blockly.loopParameterPrefix = "index"; // For names introduced by for loops
Blockly.menuSeparator = " "; // Separate prefix from name with this. E.g., space in "param x"
Blockly.yailSeparator = "_"; // Separate prefix from name with this. E.g., underscore "param_ x"
// Curried for convenient use in field_lexical_variable.js
Blockly.possiblyPrefixMenuNameWith = // e.g., "param x" vs "x"
function (prefix) {
return function (name) {
return (Blockly.showPrefixToUser ? (prefix + Blockly.menuSeparator) : "") + name;
}
};
// Curried for convenient use in generators/yail/variables.js
Blockly.possiblyPrefixYailNameWith = // e.g., "param_x" vs "x"
function (prefix) {
return function (name) {
return (Blockly.usePrefixInYail ? (prefix + Blockly.yailSeparator) : "") + name;
}
};
Blockly.prefixGlobalMenuName = function (name) {
return Blockly.globalNamePrefix + Blockly.menuSeparator + name;
};
// Return a list of (1) prefix (if it exists, "" if not) and (2) unprefixed name
Blockly.unprefixName = function (name) {
if (name.indexOf(Blockly.globalNamePrefix + Blockly.menuSeparator) == 0) {
// Globals always have prefix, regardless of flags. Handle these specially
return [Blockly.globalNamePrefix, name.substring(Blockly.globalNamePrefix.length + Blockly.menuSeparator.length)];
} else if (!Blockly.showPrefixToUser) {
return ["", name];
} else {
var prefixes = [Blockly.procedureParameterPrefix,
Blockly.handlerParameterPrefix,
Blockly.localNamePrefix,
Blockly.loopParameterPrefix]
for (i=0; i < prefixes.length; i++) {
if (name.indexOf(prefixes[i]) == 0) {
// name begins with prefix
return [prefixes[i], name.substring(prefixes[i].length + Blockly.menuSeparator.length)]
}
}
// Really an error if get here ...
return ["", name];
}
}
/******************************************************************************/
Blockly.bindEvent_(Blockly.mainWorkspace.getCanvas(), 'blocklyWorkspaceChange', this,
function() {
window.parent.BlocklyPanel_blocklyWorkspaceChanged(Blockly.BlocklyEditor.formName_);
});
};
/**
* Add a "Generate Yail" option to the context menu for every block. The generated yail will go in
* the block's comment (if it has one) for now.
* TODO: eventually create a separate kind of bubble for the generated yail, which can morph into
* the bubble for "do it" output once we hook up to the REPL.
*/
Blockly.Block.prototype.customContextMenu = function(options) {
var yailOption = {enabled: true};
yailOption.text = "Generate Yail";
var myBlock = this;
yailOption.callback = function() {
var yailText;
//Blockly.Yail.blockToCode1 returns a string if the block is a statement
//and an array if the block is a value
var yailTextOrArray = Blockly.Yail.blockToCode1(myBlock);
if(yailTextOrArray instanceof Array){
yailText = yailTextOrArray[0];
} else {
yailText = yailTextOrArray;
}
myBlock.setCommentText(yailText);
};
options.push(yailOption);
var pythonOption = {enabled: true};
pythonOption.text = "Generate Python";
var myBlock = this;
pythonOption.callback = function() {
var pythonText;
//Blockly.Python.blockToCode returns a string if the block is a statement
//and an array if the block is a value
var pythonTextOrArray = Blockly.Python.blockToCode(myBlock);
if(pythonTextOrArray instanceof Array){
pythonText = pythonTextOrArray[0];
} else {
pythonText = pythonTextOrArray;
}
myBlock.setCommentText(pythonText);
};
options.push(pythonOption);
var xmlOption = {enabled: true};
xmlOption.text = "Generate Xml";
var myBlock = this;
xmlOption.callback = function() {
myBlockXml = Blockly.Xml.blockToDom_(myBlock);
myBlockXmlText = Blockly.Xml.domToText(myBlockXml);
myBlock.setCommentText(myBlockXmlText);
};
options.push(xmlOption);
if(myBlock.procCustomContextMenu){
myBlock.procCustomContextMenu(options);
}
};
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'liststyle', 'km', {
armenian: 'លេខអារមេនី',
bulletedTitle: 'លក្ខណៈសម្បត្តិបញ្ជីជាចំណុច',
circle: 'រង្វង់មូល',
decimal: 'លេខទសភាគ (1, 2, 3, ...)',
decimalLeadingZero: 'ទសភាគចាប់ផ្ដើមពីសូន្យ (01, 02, 03, ...)',
disc: 'ថាស',
georgian: 'លេខចចជា (an, ban, gan, ...)',
lowerAlpha: 'ព្យញ្ជនៈតូច (a, b, c, d, e, ...)',
lowerGreek: 'លេខក្រិកតូច (alpha, beta, gamma, ...)',
lowerRoman: 'លេខរ៉ូម៉ាំងតូច (i, ii, iii, iv, v, ...)',
none: 'គ្មាន',
notset: '<not set>',
numberedTitle: 'លក្ខណៈសម្បត្តិបញ្ជីជាលេខ',
square: 'ការេ',
start: 'ចាប់ផ្ដើម',
type: 'ប្រភេទ',
upperAlpha: 'អក្សរធំ (A, B, C, D, E, ...)',
upperRoman: 'លេខរ៉ូម៉ាំងធំ (I, II, III, IV, V, ...)',
validateStartNumber: 'លេខចាប់ផ្ដើមបញ្ជី ត្រូវតែជាតួលេខពិតប្រាកដ។'
} );
|
define(function(require) {
var Core = require('../src/validator'),
$ = require('$');
describe('validator', function() {
test('basic', function() {
});
});
});
|
/**
* Object with data-attributes (HTML5) with a special <markup>
*
* @namespace Lungo
* @class Attributes
*
* @author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi
* @author Guillermo Pascual <pasku@tapquo.com> || @pasku1
*/
Lungo.Attributes = {
count: {
selector: '*',
html: '<span class="tag theme count">{{value}}</span>'
},
pull: {
selector: 'section',
html: '<div class="{{value}}" data-control="pull" data-icon="down" data-loading="black">\
<strong>title</strong>\
</div>'
},
progress: {
selector: '*',
html: '<div class="progress">\
<span class="bar"><span class="value" style="width:{{value}};"></span></span>\
</div>'
},
label: {
selector: '*',
html: '<abbr>{{value}}</abbr>'
},
icon: {
selector: '*',
html: '<span class="icon {{value}}"></span>'
},
image: {
selector: '*',
html: '<img src="{{value}}" class="icon" />'
},
title: {
selector: 'header',
html: '<span class="title centered">{{value}}</span>'
},
loading: {
selector: '*',
html: '<div class="loading {{value}}">\
<span class="top"></span>\
<span class="right"></span>\
<span class="bottom"></span>\
<span class="left"></span>\
</div>'
},
back: {
selector: 'header',
html: '<nav class="left"><a href="#back" data-router="section" class="left"><span class="icon {{value}}"></span></a></nav>'
}
};
|
function clearLog () {
var logArea = document.getElementById("logArea");
logArea.value = "";
}
function addLog (txt) {
var logArea = document.getElementById("logArea");
logArea.value = txt + "\n" + logArea.value;
}
function clearConsole () {
var consoleArea = document.getElementById("consoleArea");
consoleArea.value = "";
}
function addConsole (txt) {
var consoleArea = document.getElementById("consoleArea");
consoleArea.value = txt + "\n" + consoleArea.value;
}
|
var Transform = require('pipestream').Transform;
var util = require('util');
var iconv = require('iconv-lite');
var LT_RE = /^\s*</;
var JSON_RE = /^\s*[\[\{]/;
function WhistleTransform(options) {
Transform.call(this);
options = options || {};
var value = parseInt((options.speed * 1000) / 8);
if (value > 0) {
this._speed = value;
}
if ((value = parseInt(options.delay)) > 0) {
this._delay = value;
}
var charset = options.charset && String(options.charset);
if (!iconv.encodingExists(charset)) {
charset = 'utf8';
}
this._body = getBuffer(options, 'body', charset);
this._top = getBuffer(options, 'top', charset);
this._bottom = getBuffer(options, 'bottom', charset);
if (this._body || this._top || this._bottom) {
if (options.strictHtml) {
this._strictHtml = true;
} else if (options.safeHtml) {
this._safeHtml = true;
}
}
}
function getBuffer(options, name, charset) {
var buf = options[name];
return buf == null || Buffer.isBuffer(buf)
? buf
: iconv.encode(buf + '', charset);
}
util.inherits(WhistleTransform, Transform);
WhistleTransform.prototype.allowInject = function (chunk) {
if (!chunk || (!this._strictHtml && !this._safeHtml)) {
return true;
}
return this._strictHtml
? LT_RE.test(chunk.toString())
: !JSON_RE.test(chunk.toString());
};
WhistleTransform.prototype._transform = function (chunk, encoding, callback) {
var self = this;
var cb = function () {
if (self._allowInject && self._ended && self._bottom) {
chunk = chunk ? Buffer.concat([chunk, self._bottom]) : self._bottom;
self._bottom = null;
}
if (chunk && self._speed) {
setTimeout(function () {
callback(null, chunk);
}, Math.round((chunk.length * 1000) / self._speed));
} else {
callback(null, chunk);
}
};
if (!self._ended) {
self._ended = !chunk;
}
if (!self._inited) {
self._allowInject = self.allowInject(chunk);
self._inited = true;
if (self._allowInject) {
if (self._body) {
self._ended = true;
chunk = self._body;
}
if (self._top) {
chunk = chunk ? Buffer.concat([self._top, chunk]) : self._top;
self._top = null;
}
}
return self._delay ? setTimeout(cb, self._delay) : cb();
}
if (self._ended) {
chunk = null;
}
cb();
};
module.exports = WhistleTransform;
|
const fs = require('fs');
module.exports = async (page, scenario) => {
let cookies = [];
const cookiePath = scenario.cookiePath;
// READ COOKIES FROM FILE IF EXISTS
if (fs.existsSync(cookiePath)) {
cookies = JSON.parse(fs.readFileSync(cookiePath));
}
// // MUNGE COOKIE DOMAIN
// cookies = cookies.map(cookie => {
// cookie.url = 'https://' + cookie.domain;
// delete cookie.domain;
// return cookie;
// });
// SET COOKIES
const setCookies = async () => {
return Promise.all(
cookies.map(async (cookie) => {
await page.setCookie(cookie);
})
);
};
await setCookies();
console.log('Cookie state restored with:', JSON.stringify(cookies, null, 2));
};
|
'use strict';
var path = require('path'),
chai = require('chai');
chai.use(require('sinon-chai'));
chai.use(require('chai-as-promised'));
module.exports = {
expect: chai.expect
};
|
(function() {
var player;
player = new Coke.Character(Coke.settings.grid * 7, Coke.settings.grid * 5, 2, 'down', 'images/player.png');
Coke.updateables.push(player);
}).call(this);
|
var _ = require('lodash')
var chargeServer = require('../lib/server')
var config = require('../lib/config')
var fs = require('fs')
var Handlebars = require('handlebars')
var Hapi = require('hapi')
var path = require('path')
var AMOUNT = _.random(50, 100)
var CARD_CVC = '123'
var CARD_EXP_MONTH = 12
var CARD_EXP_YEAR = new Date().getFullYear() + 1
var CARD_NUMBER = '4242424242424242'
var DESCRIPTION = 'An automated test transaction.'
var METADATA = {
a_string: 'a',
a_number: 1,
}
var PORT = 3001
var TEMPLATE = fs.readFileSync(path.resolve(__dirname, './index.hbs'), 'utf8')
var URL = [
chargeServer.info.uri,
chargeServer.app.PATHNAME,
].join('')
var server = new Hapi.Server()
var template = Handlebars.compile(TEMPLATE)
module.exports = server
_.extend(server.app, {
AMOUNT: AMOUNT,
CARD_CVC: CARD_CVC,
CARD_EMAIL: config.testEmail,
CARD_EXP_MONTH: CARD_EXP_MONTH,
CARD_EXP_YEAR: CARD_EXP_YEAR,
CARD_NUMBER: CARD_NUMBER,
DESCRIPTION: DESCRIPTION,
METADATA: METADATA,
URL: URL,
})
server.connection({
port: PORT,
})
server.route({
path: '/',
method: 'GET',
config: {
handler: function (request, reply) {
return reply(template({
amount: AMOUNT,
description: DESCRIPTION,
metadata: JSON.stringify(METADATA),
stripe_publishable_key: config.stripePublishableKey,
url: URL,
}))
},
},
})
|
var solution = a(1);
alert(solution); // what is the solution?
function a(foo) {
if(foo > 20) return foo;
return b(foo+2);
}
function b(foo) {
return c(foo) + 1;
}
function c(foo) {
return a(foo*2);
}
|
export const battery4 = {"viewBox":"0 0 2304 1792","children":[{"name":"path","attribs":{"d":"M1920 512v768h-1664v-768h1664zM2048 1088h128v-384h-128v-288q0-14-9-23t-23-9h-1856q-14 0-23 9t-9 23v960q0 14 9 23t23 9h1856q14 0 23-9t9-23v-288zM2304 704v384q0 53-37.5 90.5t-90.5 37.5v160q0 66-47 113t-113 47h-1856q-66 0-113-47t-47-113v-960q0-66 47-113t113-47h1856q66 0 113 47t47 113v160q53 0 90.5 37.5t37.5 90.5z"}}]}; |
import app from './app/reducer';
import auth from './auth/reducer';
import config from './config/reducer';
import device from './device/reducer';
import intl from './intl/reducer';
import todos from './todos/reducer';
import ui from './ui/reducer';
import users from './users/reducer';
import messages from './messages/reducer';
import events from './events/reducer';
import bio from './bio/reducer';
import { SIGN_OUT } from './auth/actions';
import { combineReducers } from 'redux';
import { fieldsReducer as fields } from './lib/redux-fields';
import { firebaseReducer as firebase } from './lib/redux-firebase';
import { routerReducer as routing } from 'react-router-redux';
import { updateStateOnStorageLoad } from './configureStorage';
const resetStateOnSignOut = (reducer, initialState) => (state, action) => {
// Reset app state on sign out, stackoverflow.com/q/35622588/233902.
if (action.type === SIGN_OUT) {
// Preserve state without sensitive data.
state = {
app: state.app,
config: initialState.config,
device: initialState.device,
intl: initialState.intl,
routing: state.routing // Routing state has to be reused.
};
}
return reducer(state, action);
};
export default function configureReducer(initialState, platformReducers) {
let reducer = combineReducers({
...platformReducers,
app,
auth,
config,
device,
fields,
firebase,
intl,
routing,
todos,
ui,
users,
messages,
events,
bio
});
// The power of higher-order reducers, http://slides.com/omnidan/hor
reducer = resetStateOnSignOut(reducer, initialState);
reducer = updateStateOnStorageLoad(reducer);
return reducer;
}
|
/**
* @ignore
* dom-attr
* @author yiminghe@gmail.com, lifesinger@gmail.com
*/
KISSY.add('dom/base/attr', function (S, DOM, undefined) {
var doc = S.Env.host.document,
NodeType = DOM.NodeType,
docElement = doc && doc.documentElement,
EMPTY = '',
nodeName = DOM.nodeName,
R_BOOLEAN = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
R_FOCUSABLE = /^(?:button|input|object|select|textarea)$/i,
R_CLICKABLE = /^a(?:rea)?$/i,
R_INVALID_CHAR = /:|^on/,
R_RETURN = /\r/g,
attrFix = {
},
attrFn = {
val: 1,
css: 1,
html: 1,
text: 1,
data: 1,
width: 1,
height: 1,
offset: 1,
scrollTop: 1,
scrollLeft: 1
},
attrHooks = {
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
tabindex: {
get: function (el) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
var attributeNode = el.getAttributeNode('tabindex');
return attributeNode && attributeNode.specified ?
parseInt(attributeNode.value, 10) :
R_FOCUSABLE.test(el.nodeName) ||
R_CLICKABLE.test(el.nodeName) && el.href ?
0 :
undefined;
}
}
},
propFix = {
'hidefocus': 'hideFocus',
tabindex: 'tabIndex',
readonly: 'readOnly',
'for': 'htmlFor',
'class': 'className',
maxlength: 'maxLength',
'cellspacing': 'cellSpacing',
'cellpadding': 'cellPadding',
rowspan: 'rowSpan',
colspan: 'colSpan',
usemap: 'useMap',
'frameborder': 'frameBorder',
'contenteditable': 'contentEditable'
},
// Hook for boolean attributes
// if bool is false
// - standard browser returns null
// - ie<8 return false
// - norm to undefined
boolHook = {
get: function (elem, name) {
// 转发到 prop 方法
return DOM.prop(elem, name) ?
// 根据 w3c attribute , true 时返回属性名字符串
name.toLowerCase() :
undefined;
},
set: function (elem, value, name) {
var propName;
if (value === false) {
// Remove boolean attributes when set to false
DOM.removeAttr(elem, name);
} else {
// 直接设置 true,因为这是 bool 类属性
propName = propFix[ name ] || name;
if (propName in elem) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute(name, name.toLowerCase());
}
return name;
}
},
propHooks = {
},
// get attribute value from attribute node, only for ie
attrNodeHook = {
},
valHooks = {
select: {
// fix for multiple select
get: function (elem) {
var index = elem.selectedIndex,
options = elem.options,
ret,
i,
len,
one = (String(elem.type) === 'select-one');
// Nothing was selected
if (index < 0) {
return null;
} else if (one) {
return DOM.val(options[index]);
}
// Loop through all the selected options
ret = [];
i = 0;
len = options.length;
for (; i < len; ++i) {
if (options[i].selected) {
ret.push(DOM.val(options[i]));
}
}
// Multi-Selects return an array
return ret;
},
set: function (elem, value) {
var values = S.makeArray(value),
opts = elem.options;
S.each(opts, function (opt) {
opt.selected = S.inArray(DOM.val(opt), values);
});
if (!values.length) {
elem.selectedIndex = -1;
}
return values;
}
}
};
// Radios and checkboxes getter/setter
S.each(['radio', 'checkbox'], function (r) {
valHooks[r] = {
get: function (elem) {
// Handle the case where in Webkit '' is returned instead of 'on'
// if a value isn't specified
return elem.getAttribute('value') === null ? 'on' : elem.value;
},
set: function (elem, value) {
if (S.isArray(value)) {
return elem.checked = S.inArray(DOM.val(elem), value);
}
return undefined;
}
};
});
// IE7- 下,需要用 cssText 来获取
// 所有浏览器统一下, attr('style') 标准浏览器也不是 undefined
attrHooks['style'] = {
get: function (el) {
return el.style.cssText;
}
};
function getProp(elem, name) {
name = propFix[name] || name;
var hook = propHooks[name];
if (hook && hook.get) {
return hook.get(elem, name);
} else {
return elem[name];
}
}
S.mix(DOM,
/**
* @override KISSY.DOM
* @class
* @singleton
*/
{
_valHooks: valHooks,
_propFix: propFix,
_attrHooks: attrHooks,
_propHooks: propHooks,
_attrNodeHook: attrNodeHook,
_attrFix: attrFix,
/**
* Get the value of a property for the first element in the set of matched elements.
* or
* Set one or more properties for the set of matched elements.
* @param {HTMLElement[]|String|HTMLElement} selector matched elements
* @param {String|Object} name
* The name of the property to set.
* or
* A map of property-value pairs to set.
* @param [value] A value to set for the property.
* @return {String|undefined|Boolean}
*/
prop: function (selector, name, value) {
var elems = DOM.query(selector),
i,
elem,
hook;
// supports hash
if (S.isPlainObject(name)) {
S.each(name, function (v, k) {
DOM.prop(elems, k, v);
});
return undefined;
}
// Try to normalize/fix the name
name = propFix[ name ] || name;
hook = propHooks[ name ];
if (value !== undefined) {
for (i = elems.length - 1; i >= 0; i--) {
elem = elems[i];
if (hook && hook.set) {
hook.set(elem, value, name);
} else {
elem[ name ] = value;
}
}
} else {
if (elems.length) {
return getProp(elems[0], name);
}
}
return undefined;
},
/**
* Whether one of the matched elements has specified property name
* @param {HTMLElement[]|String|HTMLElement} selector 元素
* @param {String} name The name of property to test
* @return {Boolean}
*/
hasProp: function (selector, name) {
var elems = DOM.query(selector),
i,
len = elems.length,
el;
for (i = 0; i < len; i++) {
el = elems[i];
if (getProp(el, name) !== undefined) {
return true;
}
}
return false;
},
/**
* Remove a property for the set of matched elements.
* @param {HTMLElement[]|String|HTMLElement} selector matched elements
* @param {String} name The name of the property to remove.
*/
removeProp: function (selector, name) {
name = propFix[ name ] || name;
var elems = DOM.query(selector),
i,
el;
for (i = elems.length - 1; i >= 0; i--) {
el = elems[i];
try {
el[ name ] = undefined;
delete el[ name ];
} catch (e) {
// S.log('delete el property error : ');
// S.log(e);
}
}
},
/**
* Get the value of an attribute for the first element in the set of matched elements.
* or
* Set one or more attributes for the set of matched elements.
* @param {HTMLElement[]|HTMLElement|String} selector matched elements
* @param {String|Object} name The name of the attribute to set. or A map of attribute-value pairs to set.
* @param [val] A value to set for the attribute.
* @param [pass] internal use by anim
* @return {String|undefined}
*/
attr: function (selector, name, val, /*internal use by anim/fx*/pass) {
/*
Hazards From Caja Note:
- In IE[67], el.setAttribute doesn't work for attributes like
'class' or 'for'. IE[67] expects you to set 'className' or
'htmlFor'. Caja use setAttributeNode solves this problem.
- In IE[67], <input> elements can shadow attributes. If el is a
form that contains an <input> named x, then el.setAttribute(x, y)
will set x's value rather than setting el's attribute. Using
setAttributeNode solves this problem.
- In IE[67], the style attribute can only be modified by setting
el.style.cssText. Neither setAttribute nor setAttributeNode will
work. el.style.cssText isn't bullet-proof, since it can be
shadowed by <input> elements.
- In IE[67], you can never change the type of an <button> element.
setAttribute('type') silently fails, but setAttributeNode
throws an exception. caja : the silent failure. KISSY throws error.
- In IE[67], you can never change the type of an <input> element.
setAttribute('type') throws an exception. We want the exception.
- In IE[67], setAttribute is case-sensitive, unless you pass 0 as a
3rd argument. setAttributeNode is case-insensitive.
- Trying to set an invalid name like ':' is supposed to throw an
error. In IE[678] and Opera 10, it fails without an error.
*/
var els = DOM.query(selector),
attrNormalizer,
i,
el = els[0],
ret;
// supports hash
if (S.isPlainObject(name)) {
pass = val;
for (var k in name) {
DOM.attr(els, k, name[k], pass);
}
return undefined;
}
// attr functions
if (pass && attrFn[name]) {
return DOM[name](selector, val);
}
// scrollLeft
name = name.toLowerCase();
if (pass && attrFn[name]) {
return DOM[name](selector, val);
}
// custom attrs
name = attrFix[name] || name;
if (R_BOOLEAN.test(name)) {
attrNormalizer = boolHook;
}
// only old ie?
else if (R_INVALID_CHAR.test(name)) {
attrNormalizer = attrNodeHook;
} else {
attrNormalizer = attrHooks[name];
}
if (val === undefined) {
if (el && el.nodeType === NodeType.ELEMENT_NODE) {
// browsers index elements by id/name on forms, give priority to attributes.
if (nodeName(el) == 'form') {
attrNormalizer = attrNodeHook;
}
if (attrNormalizer && attrNormalizer.get) {
return attrNormalizer.get(el, name);
}
ret = el.getAttribute(name);
if (ret === "") {
var attrNode = el.getAttributeNode(name);
if (!attrNode || !attrNode.specified) {
return undefined;
}
}
// standard browser non-existing attribute return null
// ie<8 will return undefined , because it return property
// so norm to undefined
return ret === null ? undefined : ret;
}
} else {
for (i = els.length - 1; i >= 0; i--) {
el = els[i];
if (el && el.nodeType === NodeType.ELEMENT_NODE) {
if (nodeName(el) == 'form') {
attrNormalizer = attrNodeHook;
}
if (attrNormalizer && attrNormalizer.set) {
attrNormalizer.set(el, val, name);
} else {
// convert the value to a string (all browsers do this but IE)
el.setAttribute(name, EMPTY + val);
}
}
}
}
return undefined;
},
/**
* Remove an attribute from each element in the set of matched elements.
* @param {HTMLElement[]|String} selector matched elements
* @param {String} name An attribute to remove
*/
removeAttr: function (selector, name) {
name = name.toLowerCase();
name = attrFix[name] || name;
var els = DOM.query(selector),
propName,
el, i;
for (i = els.length - 1; i >= 0; i--) {
el = els[i];
if (el.nodeType == NodeType.ELEMENT_NODE) {
el.removeAttribute(name);
// Set corresponding property to false for boolean attributes
if (R_BOOLEAN.test(name) && (propName = propFix[ name ] || name) in el) {
el[ propName ] = false;
}
}
}
},
/**
* Whether one of the matched elements has specified attribute
* @method
* @param {HTMLElement[]|String} selector matched elements
* @param {String} name The attribute to be tested
* @return {Boolean}
*/
hasAttr: docElement && !docElement.hasAttribute ?
function (selector, name) {
name = name.toLowerCase();
var elems = DOM.query(selector),
i, el,
attrNode;
// from ppk :http://www.quirksmode.org/dom/w3c_core.html
// IE5-7 doesn't return the value of a style attribute.
// var $attr = el.attributes[name];
for (i = 0; i < elems.length; i++) {
el = elems[i];
attrNode = el.getAttributeNode(name);
if (attrNode && attrNode.specified) {
return true;
}
}
return false;
} :
function (selector, name) {
var elems = DOM.query(selector), i,
len = elems.length;
for (i = 0; i < len; i++) {
//使用原生实现
if (elems[i].hasAttribute(name)) {
return true;
}
}
return false;
},
/**
* Get the current value of the first element in the set of matched elements.
* or
* Set the value of each element in the set of matched elements.
* @param {HTMLElement[]|String} selector matched elements
* @param {String|String[]} [value] A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.
* @return {undefined|String|String[]|Number}
*/
val: function (selector, value) {
var hook, ret, elem, els, i, val;
//getter
if (value === undefined) {
elem = DOM.get(selector);
if (elem) {
hook = valHooks[ nodeName(elem) ] || valHooks[ elem.type ];
if (hook && 'get' in hook &&
(ret = hook.get(elem, 'value')) !== undefined) {
return ret;
}
ret = elem.value;
return typeof ret === 'string' ?
// handle most common string cases
ret.replace(R_RETURN, '') :
// handle cases where value is null/undefined or number
ret == null ? '' : ret;
}
return undefined;
}
els = DOM.query(selector);
for (i = els.length - 1; i >= 0; i--) {
elem = els[i];
if (elem.nodeType !== 1) {
return undefined;
}
val = value;
// Treat null/undefined as ''; convert numbers to string
if (val == null) {
val = '';
} else if (typeof val === 'number') {
val += '';
} else if (S.isArray(val)) {
val = S.map(val, function (value) {
return value == null ? '' : value + '';
});
}
hook = valHooks[ nodeName(elem)] || valHooks[ elem.type ];
// If set returns undefined, fall back to normal setting
if (!hook || !('set' in hook) || hook.set(elem, val, 'value') === undefined) {
elem.value = val;
}
}
return undefined;
},
/**
* Get the combined text contents of each element in the set of matched elements, including their descendants.
* or
* Set the content of each element in the set of matched elements to the specified text.
* @param {HTMLElement[]|HTMLElement|String} selector matched elements
* @param {String} [val] A string of text to set as the content of each matched element.
* @return {String|undefined}
*/
text: function (selector, val) {
var el, els, i, nodeType;
// getter
if (val === undefined) {
// supports css selector/Node/NodeList
el = DOM.get(selector);
return DOM._getText(el);
} else {
els = DOM.query(selector);
for (i = els.length - 1; i >= 0; i--) {
el = els[i];
nodeType = el.nodeType;
if (nodeType == NodeType.ELEMENT_NODE) {
DOM.empty(el);
el.appendChild(el.ownerDocument.createTextNode(val));
}
else if (nodeType == NodeType.TEXT_NODE || nodeType == NodeType.CDATA_SECTION_NODE) {
el.nodeValue = val;
}
}
}
return undefined;
},
_getText: function (el) {
return el.textContent;
}
});
return DOM;
}, {
requires: ['./api']
});
/*
NOTES:
yiminghe@gmail.com: 2013-03-19
- boolean property 和 attribute ie 和其他浏览器不一致,统一为类似 ie8:
- attr('checked',string) == .checked=true setAttribute('checked','checked') // ie8 相同 setAttribute()
- attr('checked',false) == removeAttr('check') // ie8 不同, setAttribute ie8 相当于 .checked=true setAttribute('checked','checked')
- removeAttr('checked') == .checked=false removeAttribute('checked') // ie8 removeAttribute 相同
yiminghe@gmail.com: 2012-11-27
- 拆分 ie attr,条件加载
yiminghe@gmail.com:2011-06-03
- 借鉴 jquery 1.6,理清 attribute 与 property
yiminghe@gmail.com:2011-01-28
- 处理 tabindex,顺便重构
2010.03
- 在 jquery/support.js 中,special attrs 里还有 maxlength, cellspacing,
rowspan, colspan, usemap, frameborder, 但测试发现,在 Grade-A 级浏览器中
并无兼容性问题。
- 当 colspan/rowspan 属性值设置有误时,ie7- 会自动纠正,和 href 一样,需要传递
第 2 个参数来解决。jQuery 未考虑,存在兼容性 bug.
- jQuery 考虑了未显式设定 tabindex 时引发的兼容问题,kissy 里忽略(太不常用了)
- jquery/attributes.js: Safari mis-reports the default selected
property of an option 在 Safari 4 中已修复。
*/ |
module.exports = {
mockery: {
Wrapper: require('./src/mockery/Wrapper.js'),
Schema: require('./src/mockery/Schema.js')
},
Table: require('./src/Table.js'),
table: require('./src/table/index.js'),
object: require('./src/object/index.js'),
Collection: require('./src/Collection.js')
};
|
var routes = {
}; |
// Copyright 2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ----------------
// Check fast objects
var o = { };
assertFalse(0 in o);
assertFalse('x' in o);
assertFalse('y' in o);
assertTrue('toString' in o, "toString");
var o = { x: 12 };
assertFalse(0 in o);
assertTrue('x' in o);
assertFalse('y' in o);
assertTrue('toString' in o, "toString");
var o = { x: 12, y: 15 };
assertFalse(0 in o);
assertTrue('x' in o);
assertTrue('y' in o);
assertTrue('toString' in o, "toString");
// ----------------
// Check dense arrays
var a = [ ];
assertFalse(0 in a);
assertFalse(1 in a);
assertFalse('0' in a);
assertFalse('1' in a);
assertTrue('toString' in a, "toString");
var a = [ 1 ];
assertTrue(0 in a);
assertFalse(1 in a);
assertTrue('0' in a);
assertFalse('1' in a);
assertTrue('toString' in a, "toString");
var a = [ 1, 2 ];
assertTrue(0 in a);
assertTrue(1 in a);
assertTrue('0' in a);
assertTrue('1' in a);
assertTrue('toString' in a, "toString");
var a = [ 1, 2 ];
assertFalse(0.001 in a);
assertTrue(-0 in a);
assertTrue(+0 in a);
assertFalse('0.0' in a);
assertFalse('1.0' in a);
assertFalse(NaN in a);
assertFalse(Infinity in a);
assertFalse(-Infinity in a);
var a = [];
a[1] = 2;
assertFalse(0 in a);
assertTrue(1 in a);
assertFalse(2 in a);
assertFalse('0' in a);
assertTrue('1' in a);
assertFalse('2' in a);
assertTrue('toString' in a, "toString");
// ----------------
// Check dictionary ("normalized") objects
var o = {};
for (var i = 0x0020; i < 0x02ff; i += 2) {
o['char:' + String.fromCharCode(i)] = i;
}
for (var i = 0x0020; i < 0x02ff; i += 2) {
assertTrue('char:' + String.fromCharCode(i) in o);
assertFalse('char:' + String.fromCharCode(i + 1) in o);
}
assertTrue('toString' in o, "toString");
var o = {};
o[Math.pow(2,30)-1] = 0;
o[Math.pow(2,31)-1] = 0;
o[1] = 0;
assertFalse(0 in o);
assertTrue(1 in o);
assertFalse(2 in o);
assertFalse(Math.pow(2,30)-2 in o);
assertTrue(Math.pow(2,30)-1 in o);
assertFalse(Math.pow(2,30)-0 in o);
assertTrue(Math.pow(2,31)-1 in o);
assertFalse(0.001 in o);
assertFalse('0.0' in o);
assertFalse('1.0' in o);
assertFalse(NaN in o);
assertFalse(Infinity in o);
assertFalse(-Infinity in o);
assertFalse(-0 in o);
assertFalse(+0 in o);
assertTrue('toString' in o, "toString");
// ----------------
// Check sparse arrays
var a = [];
a[Math.pow(2,30)-1] = 0;
a[Math.pow(2,31)-1] = 0;
a[1] = 0;
assertFalse(0 in a, "0 in a");
assertTrue(1 in a, "1 in a");
assertFalse(2 in a, "2 in a");
assertFalse(Math.pow(2,30)-2 in a, "Math.pow(2,30)-2 in a");
assertTrue(Math.pow(2,30)-1 in a, "Math.pow(2,30)-1 in a");
assertFalse(Math.pow(2,30)-0 in a, "Math.pow(2,30)-0 in a");
assertTrue(Math.pow(2,31)-1 in a, "Math.pow(2,31)-1 in a");
assertFalse(0.001 in a, "0.001 in a");
assertFalse('0.0' in a,"'0.0' in a");
assertFalse('1.0' in a,"'1.0' in a");
assertFalse(NaN in a,"NaN in a");
assertFalse(Infinity in a,"Infinity in a");
assertFalse(-Infinity in a,"-Infinity in a");
assertFalse(-0 in a,"-0 in a");
assertFalse(+0 in a,"+0 in a");
assertTrue('toString' in a, "toString");
// -------------
// Check negative indices in arrays.
var a = [];
assertFalse(-1 in a);
a[-1] = 43;
assertTrue(-1 in a);
|
/**
* Created by Jamie on 17/03/2017.
*/
var express = require('express');
var pug = require('pug');
var app = express();
// Set the default template engine
app.set('view engine', 'pug');
app.use('/static', express.static('public'));
function setupRoutes() {
// Setup routes
var index = require('./routes/index');
var dashboard = require('./routes/dashboard');
var map = require('./routes/map');
var user = require('./routes/user');
app.use(index);
app.use(dashboard);
app.use(map);
app.use(user);
}
exports.app = app;
exports.setupRoutes = setupRoutes; |
import React from 'react';
const ESCAPE_KEY = 27;
const ENTER_KEY = 13;
class TodoList extends React.Component {
handleKeyDown(event) {
if (event.which !== ENTER_KEY) {
return;
}
event.preventDefault();
let value = this.refs.task.getDOMNode().value.trim();
if (value) {
this.props.handleNewTask(value);
this.refs.task.getDOMNode().value = '';
}
}
render() {
return (
<input className="new-todo"
placeholder="What needs to be done?"
onKeyDown={this.handleKeyDown.bind(this)}
ref="task" />
);
}
}
export default TodoList;
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M19 15l-6 6-1.42-1.42L15.17 16H4V4h2v10h9.17l-3.59-3.58L13 9l6 6z" /></g>
, 'SubdirectoryArrowRight');
|
'use strict';
angular.module('ideaBox.version.interpolate-filter', [])
.filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
};
}]);
|
import React from 'react';
import { getDOMNode } from '@test/testUtils';
import TagGroup from '../TagGroup';
describe('TagGroup', () => {
it('Should output a TagGroup', () => {
const instance = getDOMNode(<TagGroup />);
assert.equal(instance.className, 'rs-tag-group');
});
it('Should have a custom className', () => {
const instance = getDOMNode(<TagGroup className="custom" />);
assert.ok(instance.className.match(/\bcustom\b/));
});
it('Should have a custom style', () => {
const fontSize = '12px';
const instance = getDOMNode(<TagGroup style={{ fontSize }} />);
assert.equal(instance.style.fontSize, fontSize);
});
it('Should have a custom className prefix', () => {
const instance = getDOMNode(<TagGroup classPrefix="custom-prefix" />);
assert.ok(instance.className.match(/\bcustom-prefix\b/));
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.