code
stringlengths 2
1.05M
|
---|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var CommunicationPresentToAll = React.createClass({
displayName: 'CommunicationPresentToAll',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M21 3H3c-1.11 0-2 .89-2 2v14c0 1.11.89 2 2 2h18c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 16.02H3V4.98h18v14.04zM10 12H8l4-4 4 4h-2v4h-4v-4z' })
);
}
});
module.exports = CommunicationPresentToAll;
|
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
///<reference path="typings/babylon.2.2.d.ts" />
///<reference path="typings/jquery/jquery.d.ts" />
///<reference path="IAppView.ts" />
var app3DView = (function () {
function app3DView() {
this.BOX_SIZE = 6;
this.PLANE_SIZE = 600;
this._objects = {};
this.manualMode = false;
this.displayPopup = null;
this.moving = {
down: false,
up: false,
left: false,
right: false,
front: false,
back: false
};
this.rotating = {
down: false,
up: false,
left: false,
right: false
};
this._objects = {};
this._lightPoints = [];
}
app3DView.prototype.navigateToMesh = function (item) {
this.displayPopup(item);
var height = item.height == null ? 0 : item.height;
var position;
var lookAt;
if (item.position2 != null) {
position = new BABYLON.Vector3(item.position2.x, height + 35, item.position2.y - 50);
lookAt = new BABYLON.Vector3(item.position2.x, height, item.position2.y);
}
else {
position = new BABYLON.Vector3(item.points2[0].x, height + 35, item.points2[0].y - 50);
lookAt = new BABYLON.Vector3(item.points2[0].x, height, item.points2[0].y);
}
this.targetPosition = position;
this.targetLookat = lookAt;
this.manualMode = false;
};
app3DView.prototype.click = function (evt) {
this.manualMode = true;
if (this._scene != null) {
var pickResult = this._scene.pick(evt.clientX, evt.clientY);
if (pickResult.hit) {
this.handleObjectClick(pickResult);
}
}
};
app3DView.prototype.keyUp = function (evt) {
switch (evt.keyCode) {
case 37:
this.moving.left = false;
break;
case 38:
this.moving.front = false;
break;
case 39:
this.moving.right = false;
break;
case 40:
this.moving.back = false;
break;
}
};
app3DView.prototype.keyDown = function (evt) {
this.manualMode = true;
switch (evt.keyCode) {
case 37:
this.moving.left = true;
break;
case 38:
this.moving.front = true;
break;
case 39:
this.moving.right = true;
break;
case 40:
this.moving.back = true;
break;
}
};
app3DView.prototype.mouseDown = function (evt) {
this.manualMode = true;
};
app3DView.prototype.pointerDown = function (evt) {
this.manualMode = true;
};
app3DView.prototype.resize = function () {
this._canvas.width = window.innerWidth;
this._canvas.height = window.innerHeight;
if (this._engine != null) {
this._engine.resize();
}
};
app3DView.prototype.createBasePlane = function () {
this._basePlane = BABYLON.Mesh.CreateBox("floor", this.PLANE_SIZE, this._scene);
this._basePlane.scaling.x = 1;
this._basePlane.scaling.z = 1;
this._basePlane.scaling.y = 0.001;
this._basePlane.material = new BABYLON.StandardMaterial("texture1", this._scene);
this._basePlane.material.diffuseColor = new BABYLON.Color3(0, 0, 1);
this._basePlane.material.specularColor = new BABYLON.Color3(0.5, 0.5, 0.5);
this._basePlane.position = new BABYLON.Vector3(-100, 0, 100);
this._basePlane.isPickable = false;
this._basePlane.material.backFaceCulling = false;
};
app3DView.prototype.color3ToHex = function (color) {
var result = "#" + this.rgbToHex(color.r * 255) + this.rgbToHex(color.g * 255) + this.rgbToHex(color.b * 255);
return result;
};
app3DView.prototype.rgbToHex = function (n) {
n = Math.max(0, Math.min(n, 255));
return "0123456789ABCDEF".charAt((n - n % 16) / 16)
+ "0123456789ABCDEF".charAt(n % 16);
};
app3DView.prototype.createBaseBox = function () {
var box = BABYLON.Mesh.CreateBox("box", this.BOX_SIZE, this._scene);
box.scaling.x = 1;
box.scaling.z = 1;
box.scaling.y = 1;
box.position = new BABYLON.Vector3(-100, this.PLANE_SIZE * 0.001 + this.BOX_SIZE / 2, 100);
box.isPickable = false;
return box;
};
app3DView.prototype.createBaseCylinder = function () {
var cylinder = BABYLON.Mesh.CreateCylinder("cylinder", this.BOX_SIZE, this.BOX_SIZE, this.BOX_SIZE, 24, 1, this._scene);
cylinder.scaling.x = 1;
cylinder.scaling.z = 1;
cylinder.scaling.y = 1;
cylinder.position = new BABYLON.Vector3(-100, this.PLANE_SIZE * 0.001 + this.BOX_SIZE / 2, 100);
cylinder.isPickable = false;
return cylinder;
};
app3DView.prototype.setCylinder = function (cylinder, cylinderType, id) {
var data = new CylinderData();
cylinder.isPickable = true;
cylinder.id = id;
switch (cylinderType) {
case CYLINDER_TYPE.AzureCache:
data.Image = "assets/logos/Azure Cache including Redis.png";
break;
case CYLINDER_TYPE.AzureSQL:
data.Image = "assets/logos/Azure SQL Database.png";
break;
case CYLINDER_TYPE.DocumentDB:
data.Image = "assets/logos/DocumentDB.png";
break;
case CYLINDER_TYPE.MySQL:
data.Image = "assets/logos/MySQL database.png";
break;
case CYLINDER_TYPE.SQLDatabase:
data.Image = "assets/logos/SQL Database (generic).png";
break;
case CYLINDER_TYPE.SQLDataSync:
data.Image = "assets/logos/SQL Data Sync.png";
break;
case CYLINDER_TYPE.BlobStorage:
data.Image = "assets/logos/Storage Blob.png";
break;
default:
break;
}
var material0 = new BABYLON.StandardMaterial("mat0", this._scene);
material0.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
material0.specularColor = new BABYLON.Color3(0.4, 0.4, 0.4);
material0.ambientColor = new BABYLON.Color3(0.1, 0.1, 0.1);
material0.emissiveTexture = new BABYLON.Texture(data.Image, this._scene, true, true);
material0.emissiveTexture.uAng = Math.PI;
material0.emissiveTexture.wAng = Math.PI;
// (<BABYLON.Texture>material0.emissiveTexture).vAng = Math.PI;
material0.emissiveTexture.getAlphaFromRGB = true;
material0.emissiveTexture.hasAlpha = true;
material0.emissiveTexture.uScale = 3.5;
material0.emissiveTexture.uOffset = 0.77;
material0.emissiveTexture.vOffset = 0;
material0.emissiveTexture.vScale = 1.1;
material0.useAlphaFromDiffuseTexture = false;
var material1 = new BABYLON.StandardMaterial("mat1", this._scene);
material1.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
material1.specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
var multimat = new BABYLON.MultiMaterial("multi", this._scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
cylinder.rotate(new BABYLON.Vector3(0, 1, 0), Math.PI * 1.75, BABYLON.Space.LOCAL);
cylinder.material = multimat;
cylinder.subMeshes = [];
var verticesCount = cylinder.getTotalVertices();
cylinder.subMeshes.push(new BABYLON.SubMesh(1, 0, verticesCount, 36, 232, cylinder));
cylinder.subMeshes.push(new BABYLON.SubMesh(0, 0, verticesCount, 0, 36, cylinder));
};
app3DView.prototype.createCylinder = function (id, cylinderType, position) {
var cylinder = this.createBaseCylinder();
this.setCylinder(cylinder, cylinderType, id);
cylinder.position.x = position.x;
cylinder.position.z = position.y;
var o = new ObjectData();
o.ID = id;
o.Type = "CYLINDER_TYPE." + CYLINDER_TYPE[cylinderType].toString();
o.Meshes = [cylinder];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
};
app3DView.prototype.createLowBox = function (id, lowboxType, position) {
var box = this.createBaseBox();
this.setLowBox(box, lowboxType, id);
box.scaling.y = 1 / 3;
box.position.y = this.PLANE_SIZE * 0.001 + this.BOX_SIZE / 6;
box.position.x = position.x;
box.position.z = position.y;
var o = new ObjectData();
o.ID = id;
o.Type = "LOWBOX_TYPE." + LOWBOX_TYPE[lowboxType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
};
app3DView.prototype.setLowBox = function (box, lowboxType, id) {
var data = new BoxData();
box.isPickable = true;
box.id = id;
switch (lowboxType) {
case LOWBOX_TYPE.Server:
data.Image = "assets/logos/CustomServer.png";
break;
default:
break;
}
var material0 = new BABYLON.StandardMaterial("mat0", this._scene);
material0.diffuseColor = new BABYLON.Color3(1, 1, 1);
material0.diffuseTexture = new BABYLON.Texture(data.Image, this._scene);
material0.diffuseTexture.wAng = Math.PI;
material0.diffuseTexture.getAlphaFromRGB = true;
material0.diffuseTexture.hasAlpha = true;
material0.diffuseTexture.uScale = 1;
material0.diffuseTexture.vScale = 1;
material0.bumpTexture = new BABYLON.Texture(data.Image, this._scene);
material0.bumpTexture.wAng = Math.PI;
material0.bumpTexture.uScale = 1;
material0.bumpTexture.vScale = 1;
var material1 = new BABYLON.StandardMaterial("mat1", this._scene);
material1.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
var multimat = new BABYLON.MultiMaterial("multi", this._scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
box.rotate(new BABYLON.Vector3(0, 1, 0), Math.PI, BABYLON.Space.LOCAL);
box.material = multimat;
box.subMeshes = [];
var verticesCount = box.getTotalVertices();
box.subMeshes.push(new BABYLON.SubMesh(0, 0, verticesCount, 0, 6, box));
box.subMeshes.push(new BABYLON.SubMesh(1, 0, verticesCount, 6, 30, box));
};
app3DView.prototype.createBox = function (id, boxType, position) {
var box = this.createBaseBox();
this.setBox(box, boxType, id);
box.position.x = position.x;
box.position.z = position.y;
var o = new ObjectData();
o.ID = id;
o.Type = "BOX_TYPE." + BOX_TYPE[boxType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
};
app3DView.prototype.setBox = function (box, boxType, id) {
var data = new BoxData();
box.isPickable = true;
box.id = id;
switch (boxType) {
case BOX_TYPE.VM:
data.Image = "assets/logos/VM symbol only.png";
break;
case BOX_TYPE.WebSite:
data.Image = "assets/logos/Azure Websites.png";
break;
case BOX_TYPE.O365:
data.Image = "assets/logos/Office 365.png";
break;
case BOX_TYPE.GitRepo:
data.Image = "assets/logos/Git repository.png";
break;
case BOX_TYPE.GitHub:
data.Image = "assets/logos/GitHub.png";
break;
case BOX_TYPE.VSO:
data.Image = "assets/logos/Visual Studio Online.png";
break;
case BOX_TYPE.MachineLearning:
data.Image = "assets/logos/Machine Learning.png";
break;
case BOX_TYPE.HDInsight:
data.Image = "assets/logos/HDInsight.png";
break;
case BOX_TYPE.StreamAnalytics:
data.Image = "assets/logos/Stream Analytics.png";
break;
case BOX_TYPE.EventHubs:
data.Image = "assets/logos/Event Hubs.png";
break;
default:
break;
}
var material0 = new BABYLON.StandardMaterial("mat0", this._scene);
material0.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
material0.emissiveTexture = new BABYLON.Texture(data.Image, this._scene);
material0.emissiveTexture.wAng = Math.PI;
material0.emissiveTexture.getAlphaFromRGB = true;
material0.emissiveTexture.hasAlpha = true;
material0.emissiveTexture.uScale = 1;
material0.emissiveTexture.vScale = 1;
material0.useAlphaFromDiffuseTexture = false;
var material1 = new BABYLON.StandardMaterial("mat1", this._scene);
material1.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
var multimat = new BABYLON.MultiMaterial("multi", this._scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
box.rotate(new BABYLON.Vector3(0, 1, 0), Math.PI, BABYLON.Space.LOCAL);
box.material = multimat;
box.subMeshes = [];
var verticesCount = box.getTotalVertices();
box.subMeshes.push(new BABYLON.SubMesh(0, 0, verticesCount, 0, 6, box));
box.subMeshes.push(new BABYLON.SubMesh(1, 0, verticesCount, 6, 30, box));
};
app3DView.prototype.drawArrow = function (id, arrowType, points, color) {
var point1 = points[0];
var meshes = [];
for (var count = 1; count < points.length; count++) {
var backgroundColor = new BABYLON.Color3(color.r, color.g, color.b);
var point2 = points[count];
var point3 = point1.add(point2).multiplyByFloats(0.5, 0.5);
var arrow = BABYLON.Mesh.CreateBox("arrow", this.BOX_SIZE, this._scene);
arrow.scaling.x = point1.subtract(point2).length() / this.BOX_SIZE;
arrow.scaling.z = 0.05;
arrow.scaling.y = 0.001;
var angle = -Math.atan2(point1.y - point2.y, point1.x - point2.x) + Math.PI / 2;
arrow.position = new BABYLON.Vector3(point3.x, this.PLANE_SIZE * 0.001 + 0.11, point3.y);
arrow.rotate(new BABYLON.Vector3(0, 1, 0), -Math.PI / 2 + angle, BABYLON.Space.LOCAL);
arrow.material = new BABYLON.StandardMaterial("texture1", this._scene);
arrow.material.diffuseColor = backgroundColor;
arrow.material.specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
arrow.material.emissiveColor = backgroundColor;
arrow.material.alpha = color.a;
arrow.isPickable = true;
arrow.id = id;
meshes.push(arrow);
//Draw arrow tip?
if (count == points.length - 1 && (arrowType == ARROW_TYPE.ArrowTip || arrowType == ARROW_TYPE.ArrowTipBothEnds)) {
var tip = BABYLON.Mesh.CreateBox("arrow", this.BOX_SIZE, this._scene);
tip.scaling.x = 0.2;
tip.scaling.z = 0.2;
tip.scaling.y = 0.001;
angle = angle + Math.PI / 4;
tip.position = new BABYLON.Vector3(point2.x, this.PLANE_SIZE * 0.001 + 0.11, point2.y);
tip.rotate(new BABYLON.Vector3(0, 1, 0), -Math.PI / 2 + angle, BABYLON.Space.LOCAL);
tip.material = new BABYLON.StandardMaterial("texture1", this._scene);
tip.material.diffuseColor = backgroundColor;
tip.material.specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
tip.material.emissiveColor = new BABYLON.Color3(color.r, color.g, color.b);
tip.material.alpha = color.a;
tip.isPickable = true;
tip.id = id;
meshes.push(tip);
}
//Draw arrow tip at both ends?
if (count == points.length - 1 && arrowType == ARROW_TYPE.ArrowTipBothEnds) {
tip = BABYLON.Mesh.CreateBox("arrow", this.BOX_SIZE, this._scene);
tip.scaling.x = 0.2;
tip.scaling.z = 0.2;
tip.scaling.y = 0.001;
tip.position = new BABYLON.Vector3(point1.x, this.PLANE_SIZE * 0.001 + 0.11, point1.y);
tip.rotate(new BABYLON.Vector3(0, 1, 0), -Math.PI / 2 + angle, BABYLON.Space.LOCAL);
tip.material = new BABYLON.StandardMaterial("texture1", this._scene);
tip.material.diffuseColor = backgroundColor;
tip.material.specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
tip.material.emissiveColor = new BABYLON.Color3(color.r, color.g, color.b);
tip.material.alpha = color.a;
tip.isPickable = true;
tip.id = id;
meshes.push(tip);
}
point1 = point2;
}
var o = new ObjectData();
o.ID = id;
o.Type = "ARROW_TYPE." + ARROW_TYPE[arrowType].toString();
o.Meshes = meshes;
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
};
app3DView.prototype.drawBox2D = function (id, box2DType, points, color) {
switch (box2DType) {
case BOX2D_TYPE.BorderOnly:
var points2 = [];
//Define flat box points
points2.push(new BABYLON.Vector2(points[0].x, points[0].y));
points2.push(new BABYLON.Vector2(points[1].x, points[0].y));
points2.push(new BABYLON.Vector2(points[1].x, points[1].y));
points2.push(new BABYLON.Vector2(points[0].x, points[1].y));
points2.push(new BABYLON.Vector2(points[0].x, points[0].y));
var point1 = points2[0];
var meshes = [];
for (var count = 1; count < points2.length; count++) {
var point2 = points2[count];
var point3 = point1.add(point2).multiplyByFloats(0.5, 0.5);
var line = BABYLON.Mesh.CreateBox("box2d", this.BOX_SIZE, this._scene);
line.scaling.x = point1.subtract(point2).length() / this.BOX_SIZE;
line.scaling.z = 0.05;
line.scaling.y = 0.001;
var angle = -Math.atan2(point1.y - point2.y, point1.x - point2.x) + Math.PI / 2;
line.position = new BABYLON.Vector3(point3.x, this.PLANE_SIZE * 0.001, point3.y);
line.rotate(new BABYLON.Vector3(0, 1, 0), -Math.PI / 2 + angle, BABYLON.Space.LOCAL);
line.material = new BABYLON.StandardMaterial("texture1", this._scene);
line.material.diffuseColor = new BABYLON.Color3(0.7, 0.7, 0.7);
line.material.specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
line.material.emissiveColor = new BABYLON.Color3(color.r, color.g, color.b);
line.material.alpha = color.a;
line.isPickable = true;
line.id = id;
meshes.push(line);
point1 = point2;
}
for (var count = 0; count < 4; count++) {
var corner = BABYLON.Mesh.CreateBox("box2d", this.BOX_SIZE, this._scene);
corner.scaling.x = 0.05;
corner.scaling.z = 0.05;
corner.scaling.y = 0.001;
corner.position = new BABYLON.Vector3(points2[count].x, this.PLANE_SIZE * 0.001, points2[count].y);
corner.material = new BABYLON.StandardMaterial("texture1", this._scene);
corner.material.diffuseColor = new BABYLON.Color3(0.7, 0.7, 0.7);
corner.material.specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
corner.material.emissiveColor = new BABYLON.Color3(color.r, color.g, color.b);
corner.material.alpha = color.a;
corner.isPickable = true;
corner.id = id;
meshes.push(corner);
}
var o = new ObjectData();
o.ID = id;
o.Type = "BOX2D_TYPE." + BOX2D_TYPE[box2DType].toString();
o.Meshes = meshes;
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
case BOX2D_TYPE.Filled:
var backgroundColor = new BABYLON.Color3(color.r, color.g, color.b);
var point = points[0].add(points[1]).multiplyByFloats(0.5, 0.5);
var box = BABYLON.Mesh.CreateBox("box2d", this.BOX_SIZE, this._scene);
box.scaling.x = points[0].subtract(new BABYLON.Vector2(points[1].x, points[0].y)).length() / this.BOX_SIZE;
box.scaling.z = points[0].subtract(new BABYLON.Vector2(points[0].x, points[1].y)).length() / this.BOX_SIZE;
;
box.scaling.y = 0.001;
box.position = new BABYLON.Vector3(point.x, this.PLANE_SIZE * 0.001, point.y);
box.material = new BABYLON.StandardMaterial("texture1", this._scene);
box.material.diffuseColor = backgroundColor;
box.material.specularColor = new BABYLON.Color3(0.7, 0.7, 0.7);
box.material.emissiveColor = backgroundColor;
box.material.alpha = color.a;
box.isPickable = true;
box.id = id;
var o = new ObjectData();
o.ID = id;
o.Type = "BOX2D_TYPE." + BOX2D_TYPE[box2DType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
default:
break;
}
};
app3DView.prototype.drawImage = function (id, imageType, image, position, size, height) {
switch (imageType) {
case IMAGE_TYPE.Flat:
var box = this.createBaseBox();
box.isPickable = true;
box.id = id;
box.position.x = position.x;
box.position.z = position.y;
box.position.y = this.PLANE_SIZE * 0.001;
var material0 = new BABYLON.StandardMaterial("mat0", this._scene);
material0.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
material0.diffuseTexture = new BABYLON.Texture(image, this._scene);
material0.diffuseTexture.wAng = Math.PI;
material0.diffuseTexture.getAlphaFromRGB = true;
material0.diffuseTexture.hasAlpha = true;
material0.diffuseTexture.uScale = 1;
material0.diffuseTexture.vScale = 1;
material0.emissiveTexture = material0.diffuseTexture;
material0.specularTexture = material0.diffuseTexture;
material0.useAlphaFromDiffuseTexture = true;
material0.useSpecularOverAlpha = true;
var material1 = new BABYLON.StandardMaterial("mat1", this._scene);
material1.alpha = 0;
var multimat = new BABYLON.MultiMaterial("multi", this._scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
box.rotate(new BABYLON.Vector3(0, 1, 0), Math.PI, BABYLON.Space.LOCAL);
box.rotate(new BABYLON.Vector3(1, 0, 0), -Math.PI / 2, BABYLON.Space.LOCAL);
box.scaling.z = 0.0001;
box.scaling.x = size / this.BOX_SIZE;
box.scaling.y = size / this.BOX_SIZE;
box.material = multimat;
box.subMeshes = [];
var verticesCount = box.getTotalVertices();
box.subMeshes.push(new BABYLON.SubMesh(0, 0, verticesCount, 0, 6, box));
box.subMeshes.push(new BABYLON.SubMesh(1, 0, verticesCount, 6, 30, box));
var o = new ObjectData();
o.ID = id;
o.Type = "IMAGE_TYPE." + IMAGE_TYPE[imageType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
case IMAGE_TYPE.Floating:
var box = this.createBaseBox();
box.isPickable = true;
box.id = id;
box.position.x = position.x;
box.position.z = position.y;
var material0 = new BABYLON.StandardMaterial("mat0", this._scene);
material0.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
material0.diffuseTexture = new BABYLON.Texture(image, this._scene);
material0.diffuseTexture.wAng = Math.PI;
material0.diffuseTexture.getAlphaFromRGB = true;
material0.diffuseTexture.hasAlpha = true;
material0.diffuseTexture.uScale = 1;
material0.diffuseTexture.vScale = 1;
material0.emissiveTexture = material0.diffuseTexture;
material0.specularTexture = material0.diffuseTexture;
material0.useAlphaFromDiffuseTexture = true;
material0.useSpecularOverAlpha = true;
var material1 = new BABYLON.StandardMaterial("mat1", this._scene);
material1.alpha = 0;
var multimat = new BABYLON.MultiMaterial("multi", this._scene);
multimat.subMaterials.push(material0);
multimat.subMaterials.push(material1);
box.rotate(new BABYLON.Vector3(0, 1, 0), Math.PI, BABYLON.Space.LOCAL);
box.scaling.z = 0.0001;
box.scaling.x = size / this.BOX_SIZE;
box.scaling.y = size / this.BOX_SIZE;
box.position.y = this.PLANE_SIZE * 0.001 + box.scaling.y * this.BOX_SIZE / 2 + height;
box.material = multimat;
box.subMeshes = [];
var verticesCount = box.getTotalVertices();
box.subMeshes.push(new BABYLON.SubMesh(0, 0, verticesCount, 0, 6, box));
box.subMeshes.push(new BABYLON.SubMesh(1, 0, verticesCount, 6, 30, box));
box.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_Y;
var o = new ObjectData();
o.ID = id;
o.Type = "IMAGE_TYPE." + IMAGE_TYPE[imageType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
default:
break;
}
};
app3DView.prototype.drawText = function (id, textType, position, color, fontSize, text, fontName, height, rotate) {
switch (textType) {
case TEXT_TYPE.Flat:
var box = BABYLON.Mesh.CreateBox("textbox2d", this.BOX_SIZE, this._scene);
box.scaling.y = 0.00001;
box.material = new BABYLON.StandardMaterial("texture1", this._scene);
box.isPickable = false;
box.id = id;
var texture = new BABYLON.DynamicTexture("dynamic texture", 512, this._scene, true, BABYLON.Texture.CUBIC_MODE);
texture.hasAlpha = true;
texture.wAng = Math.PI / 2;
var textureContext = texture.getContext();
texture.canRescale = true;
textureContext.font = "bold " + fontSize + "px " + fontName;
var textSize = textureContext.measureText(text);
var width = textSize.width / 80;
if (width > box.scaling.x * this.BOX_SIZE)
box.scaling.x = width / this.BOX_SIZE;
box.position = new BABYLON.Vector3(position.x + (this.BOX_SIZE * box.scaling.x) / 2, this.PLANE_SIZE * 0.001 + 0.2, position.y - (this.BOX_SIZE * box.scaling.z) / 2);
var size = texture.getSize();
textureContext.save();
textureContext.fillStyle = "transparent";
textureContext.fillRect(0, 0, size.width, size.height);
textureContext.fillStyle = this.color3ToHex(new BABYLON.Color3(color.r, color.g, color.b));
textureContext.globalAlpha = color.a;
textureContext.textAlign = "left";
textureContext.fillText(text, 0, 80, size.width);
textureContext.restore();
texture.update();
box.material.diffuseTexture = texture;
box.material.emissiveTexture = texture;
box.material.specularTexture = texture;
box.material.useAlphaFromDiffuseTexture = true;
box.material.useSpecularOverAlpha = true;
var o = new ObjectData();
o.ID = id;
o.Type = "TEXT_TYPE." + TEXT_TYPE[textType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
case TEXT_TYPE.Floating:
var box = BABYLON.Mesh.CreateBox("textbox2d", this.BOX_SIZE, this._scene);
box.scaling.z = 0.00001;
box.material = new BABYLON.StandardMaterial("texture1", this._scene);
box.isPickable = false;
box.id = id;
var texture = new BABYLON.DynamicTexture("dynamic texture", 512, this._scene, true);
texture.hasAlpha = true;
var textureContext = texture.getContext();
textureContext.font = "bold " + fontSize + "px " + fontName;
var size = texture.getSize();
textureContext.save();
textureContext.fillStyle = "transparent";
textureContext.fillRect(0, 0, size.width, size.height);
var textSize = textureContext.measureText(text);
var width = textSize.width / 80;
if (width > box.scaling.x * this.BOX_SIZE)
box.scaling.x = width / this.BOX_SIZE;
box.position = new BABYLON.Vector3(position.x + (this.BOX_SIZE * box.scaling.x) / 2, this.PLANE_SIZE * 0.001 + box.scaling.z / 2 + height, position.y - (this.BOX_SIZE * box.scaling.z) / 2);
textureContext.fillStyle = this.color3ToHex(new BABYLON.Color3(color.r, color.g, color.b));
textureContext.globalAlpha = color.a;
textureContext.textAlign = "left";
textureContext.fillText(text, 0, 80, size.width);
textureContext.restore();
texture.update();
box.material.diffuseTexture = texture;
box.material.emissiveTexture = texture;
box.material.specularTexture = texture;
box.material.useAlphaFromDiffuseTexture = true;
box.material.useSpecularOverAlpha = true;
if (rotate == null)
box.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_Y;
else
box.rotate(new BABYLON.Vector3(0, 1, 0), rotate * Math.PI / 180, BABYLON.Space.LOCAL);
var o = new ObjectData();
o.ID = id;
o.Type = "TEXT_TYPE." + TEXT_TYPE[textType].toString();
o.Meshes = [box];
if (this._objects[id] == null)
this._objects[id] = o;
else
throw "Two objects with the same id '" + id + "' are defined.";
break;
default:
break;
}
};
app3DView.prototype.handleObjectClick = function (pickingInfo) {
var _this = this;
var mesh;
mesh = pickingInfo.pickedMesh;
if (mesh != null) {
this._definition.objects.forEach(function (item) {
if (item.id == mesh.id && (item.position2 != null || item.points2 != null)) {
_this.navigateToMesh(item);
}
});
}
};
app3DView.prototype.destroyScene = function () {
if (this._scene != null) {
this._engine.dispose();
this._scene.dispose();
this._scene = null;
this._definition = null;
this._engine = null;
this._camera = null;
this._cameraHidden = null;
this._basePlane = null;
this._light = null;
this._lightPoints = [];
this._objects = {};
this.targetPosition = null;
this.targetLookat = null;
this.manualMode = false;
}
};
app3DView.prototype.createScene = function (data, canvas) {
var _this = this;
this._definition = data;
this._engine = new BABYLON.Engine(canvas, true);
this._canvas = canvas;
this._scene = new BABYLON.Scene(this._engine);
this._scene.clearColor = new BABYLON.Color3(0, 0, 0);
this._camera = new BABYLON.TouchCamera("Camera", new BABYLON.Vector3(-100, 10, 0), this._scene);
this._camera.attachControl(canvas, true);
this._cameraHidden = new BABYLON.TouchCamera("Camera2", new BABYLON.Vector3(-100, 10, 0), this._scene);
this._cameraHidden.attachControl(canvas, true);
this._scene.setActiveCameraByName("Camera");
//Main light
this._light = new BABYLON.HemisphericLight("hemi", new BABYLON.Vector3(0, 1, 0), this._scene);
this._light.diffuse = new BABYLON.Color3(0.3, 0.3, 0.3);
this._light.specular = new BABYLON.Color3(1, 1, 1);
this._light.groundColor = new BABYLON.Color3(0, 0, 0);
//Point lights
var light0 = new BABYLON.PointLight("lpoint0", new BABYLON.Vector3(300, 40, 300), this._scene);
light0.diffuse = new BABYLON.Color3(0.7, 0.7, 0.7);
light0.specular = new BABYLON.Color3(0.9, 0.9, 0.9);
this._lightPoints.push(light0);
light0 = new BABYLON.PointLight("lpoint1", new BABYLON.Vector3(-500, 40, 300), this._scene);
light0.diffuse = new BABYLON.Color3(0.7, 0.7, 0.7);
light0.specular = new BABYLON.Color3(0.9, 0.9, 0.9);
this._lightPoints.push(light0);
this.createBasePlane();
data.objects.forEach(function (item) {
switch (item.type.split(".")[0]) {
case "CYLINDER_TYPE":
_this.createCylinder(item.id, CYLINDER_TYPE[item.type.split(".")[1]], new BABYLON.Vector2(item.position2.x, item.position2.y));
break;
case "BOX_TYPE":
_this.createBox(item.id, BOX_TYPE[item.type.split(".")[1]], new BABYLON.Vector2(item.position2.x, item.position2.y));
break;
case "LOWBOX_TYPE":
_this.createLowBox(item.id, LOWBOX_TYPE[item.type.split(".")[1]], new BABYLON.Vector2(item.position2.x, item.position2.y));
break;
case "ARROW_TYPE":
var points = [];
item.points2.forEach(function (p) {
points.push(new BABYLON.Vector2(p.x, p.y));
});
var color = new BABYLON.Color4(item.color4[0], item.color4[1], item.color4[2], item.color4[3]);
_this.drawArrow(item.id, ARROW_TYPE[item.type.split(".")[1]], points, color);
break;
case "BOX2D_TYPE":
var points = [];
item.points2.forEach(function (p) {
points.push(new BABYLON.Vector2(p.x, p.y));
});
if (points.length != 2)
throw "2D Boxes require 2 points";
var color = new BABYLON.Color4(item.color4[0], item.color4[1], item.color4[2], item.color4[3]);
_this.drawBox2D(item.id, BOX2D_TYPE[item.type.split(".")[1]], points, color);
break;
case "TEXT_TYPE":
var color = new BABYLON.Color4(item.color4[0], item.color4[1], item.color4[2], item.color4[3]);
var position = new BABYLON.Vector2(item.position2.x, item.position2.y);
_this.drawText(item.id, TEXT_TYPE[item.type.split(".")[1]], position, color, item.fontSize, item.text, item.fontName, item.height, item.rotate);
break;
case "IMAGE_TYPE":
var position = new BABYLON.Vector2(item.position2.x, item.position2.y);
_this.drawImage(item.id, IMAGE_TYPE[item.type.split(".")[1]], item.image, position, item.size, item.height);
break;
default:
break;
}
});
var slide1 = data.objects[0];
var height = slide1.height == null ? 0 : slide1.height;
this.targetPosition = new BABYLON.Vector3(slide1.position2.x, height + 35, slide1.position2.y - 50);
this.targetLookat = new BABYLON.Vector3(slide1.position2.x, height, slide1.position2.y);
this.manualMode = false;
this._engine.runRenderLoop(function () {
_this._scene.render();
if (!_this.manualMode) {
_this._camera.position = _this._camera.position.add(new BABYLON.Vector3((_this.targetPosition.x - _this._camera.position.x) / 50, (_this.targetPosition.y - _this._camera.position.y) / 50, (_this.targetPosition.z - _this._camera.position.z) / 50));
_this._cameraHidden.position = _this._camera.position;
_this._cameraHidden.setTarget(_this.targetLookat);
var desiredRotation = _this._cameraHidden.rotation;
_this._camera.rotation = _this._camera.rotation.add(desiredRotation.subtract(_this._camera.rotation).divide(new BABYLON.Vector3(50, 50, 50)));
var y = _this._camera.rotation.y;
}
if (_this.moving.back) {
var speed = 0.1;
var transformationMatrix = _this._camera.getWorldMatrix();
var direction = new BABYLON.Vector3(0, 0, -speed);
var resultDirection = new BABYLON.Vector3(0, 0, 0);
BABYLON.Vector3.TransformNormalToRef(direction, transformationMatrix, resultDirection);
_this._camera.cameraDirection.addInPlace(resultDirection);
var camera;
camera = _this._camera;
camera._offsetX = 0.000001;
}
else if (_this.moving.front) {
var speed = 0.1;
var transformationMatrix = _this._camera.getWorldMatrix();
var direction = new BABYLON.Vector3(0, 0, speed);
var resultDirection = new BABYLON.Vector3(0, 0, 0);
BABYLON.Vector3.TransformNormalToRef(direction, transformationMatrix, resultDirection);
_this._camera.cameraDirection.addInPlace(resultDirection);
var camera;
camera = _this._camera;
camera._offsetX = 0.000001;
}
if (_this.moving.left) {
var speed = 0.1;
var transformationMatrix = _this._camera.getWorldMatrix();
var direction = new BABYLON.Vector3(-speed, 0, 0);
var resultDirection = new BABYLON.Vector3(0, 0, 0);
BABYLON.Vector3.TransformNormalToRef(direction, transformationMatrix, resultDirection);
_this._camera.cameraDirection.addInPlace(resultDirection);
var camera;
camera = _this._camera;
camera._offsetX = 0.000001;
}
else if (_this.moving.right) {
var speed = 0.1;
var transformationMatrix = _this._camera.getWorldMatrix();
var direction = new BABYLON.Vector3(speed, 0, 0);
var resultDirection = new BABYLON.Vector3(0, 0, 0);
BABYLON.Vector3.TransformNormalToRef(direction, transformationMatrix, resultDirection);
_this._camera.cameraDirection.addInPlace(resultDirection);
var camera;
camera = _this._camera;
camera._offsetX = 0.000001;
}
});
this.resize();
};
return app3DView;
})();
//*********************************************************
//
//AzureLens.Net, https://github.com/matvelloso/azurelens
//
//Copyright (c) Microsoft Corporation
//All rights reserved.
//
// MIT License:
// 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.
//
//*********************************************************
//# sourceMappingURL=app3DView.js.map
|
define({
"page1": {
"selectToolHeader": "Zvolte metodu výběru záznamů k dávkové aktualizaci.",
"selectToolDesc": "Widget podporuje 3 metody generování vybrané sady záznamů k aktualizaci. Můžete zvolit pouze jeden z nich. Potřebujete-li více než jednu metodu, vytvořte novou instanci widgetu.",
"selectByShape": "Výběr podle oblasti",
"selectBySpatQuery": "Výběr podle prvku",
"selectByAttQuery": "Výběr podle prvku a příslušejících prvků",
"selectByQuery": "Výběr podle dotazu",
"toolNotSelected": "Vyberte způsob výběru."
},
"page2": {
"layersToolHeader": "Vyberte vrstvy, které chcete aktualizovat a nastavte volby nástroje výběru.",
"layersToolDesc": "Způsob výběru, který zvolíte na první straně, se použije k výběru a aktualizaci níže zobrazené sady vrstev. Pokud označíte více než jednu vrstvu, bude možné aktualizovat pouze pole, která jsou editovatelná u všech vrstev. V závislosti na zvoleném nástroji výběru mohou být vyžadovány další možnosti.",
"layerTable": {
"colUpdate": "Aktualizovat",
"colLabel": "Vrstva",
"colSelectByLayer": "Výběr podle vrstvy",
"colSelectByField": "Pole dotazu",
"colhighlightSymbol": "Symbol zvýraznění"
},
"toggleLayers": "Při otevření a zavření přepnout viditelnost vrstev",
"noEditableLayers": "Žádné editovatelné vrstvy",
"noLayersSelected": "Nejprve vyberte jednu nebo více vrstev."
},
"page3": {
"commonFieldsHeader": "Vyberte pole, která chcete použít k dávkové aktualizaci.",
"commonFieldsDesc": "Níže se zobrazí pouze pole, která jsou editovatelná u všech vrstev. Vyberte pole, která chcete aktualizovat. Pokud má jedno pole z různých vrstev odlišnou doménu, použije a zobrazí se pouze jedna doména.",
"noCommonFields": "Žádná společná pole",
"fieldTable": {
"colEdit": "Editovatelné",
"colName": "Název",
"colAlias": "Alternativní jméno",
"colAction": "Akce"
}
},
"tabs": {
"selection": "Definujte typ výběru",
"layers": "Definujte vrstvy k aktualizaci",
"fields": "Definujte pole k aktualizaci"
},
"errorOnOk": "Než konfiguraci uložíte, vyplňte všechny parametry.",
"next": "Další",
"back": "Zpět",
"save": "Uložit symbol",
"cancel": "Storno",
"ok": "OK",
"symbolPopup": "Výběr symbolů"
});
|
var _ = require('lodash'),
cheerio = require('cheerio'),
util = require('../../util'),
htmlTag = util.html_tag,
format = util.format;
var metaTag = function(name, content){
var data = {};
switch (name.split(':')[0]){
case 'og':
case 'fb':
data.property = name;
break;
default:
data.name = name;
}
data.content = content;
return htmlTag('meta', data) + '\n';
};
module.exports = function(options){
var page = this.page,
config = this.config || hexo.config,
content = page.content,
images = page.photos || [];
var description = page.description || '';
if (!description){
if (page.excerpt){
description = format.stripHtml(page.excerpt);
} else if (page.content){
description = format.stripHtml(content);
} else if (config.description){
description = config.description;
}
}
description = description.substring(0, 200).replace(/^\s+|\s+$/g, '')
.replace(/\"/g, '\'')
.replace(/\>/g, "&");
if (!images.length && content){
var $ = cheerio.load(content);
$('img').each(function(){
var src = $(this).attr('src');
if (src) images.push(src);
});
}
var data = _.extend({
title: page.title || config.title,
type: this.is_post() ? 'article' : 'website',
url: this.url,
image: images,
site_name: config.title,
description: description,
twitter_card: 'summary',
twitter_id: '',
twitter_site: '',
google_plus: '',
fb_admins: '',
fb_app_id: ''
}, options);
var str = '';
str += metaTag('description', data.description);
str += metaTag('og:type', data.type);
str += metaTag('og:title', data.title);
str += metaTag('og:url', data.url);
str += metaTag('og:site_name', data.site_name);
str += metaTag('og:description', data.description);
images.forEach(function(image){
str += metaTag('og:image', image);
});
str += metaTag('twitter:card', data.twitter_card);
str += metaTag('twitter:title', data.title);
str += metaTag('twitter:description', data.description);
if (data.twitter_id){
var twitterId = data.twitter_id;
if (twitterId[0] !== '@') twitterId = '@' + twitterId;
str += metaTag('twitter:creator', twitterId);
}
if (data.twitter_site){
str += metaTag('twitter:site', data.twitter_site);
}
if (data.google_plus){
str += htmlTag('link', {rel: 'publisher', href: data.google_plus}) + '\n';
}
if (data.fb_admins){
str += metaTag('fb:admins', data.fb_admins);
}
if (data.fb_app_id){
str += metaTag('fb:app_id', data.fb_app_id);
}
return str;
};
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M12 7h8v4h-8z" opacity=".3" /><path d="M8 8H6v7c0 1.1.9 2 2 2h9v-2H8V8z" /><path d="M20 3h-8c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 8h-8V7h8v4zM4 12H2v7c0 1.1.9 2 2 2h9v-2H4v-7z" /></React.Fragment>
, 'DynamicFeedTwoTone');
|
var gulp = require('gulp');
var pandoc = require('gulp-pandoc');
var webserver = require('gulp-webserver');
gulp.task('default', function() {
gulp.src('./index.md')
.pipe(pandoc({
from: 'markdown',
to: 'slidy',
ext: '.html',
args: [
'--standalone',
'--include-in-header=inc/head',
'--include-after-body=inc/end',
'--highlight-style', 'zenburn'
]
}))
.on('error', console.log)
.pipe(gulp.dest('./'));
}
);
var workingFiles = [
'./index.md',
'./scripts/**/*',
'./styles/**/*'
];
gulp.task('dev', ['default', 'webserver'], function() {
gulp.watch(workingFiles, ['default']);
});
gulp.task('webserver', ['default'], function() {
gulp.src('./')
.pipe(webserver({
livereload: false
}));
});
|
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actionCreators from '../actions/index.jsx';
import HostTickets from '../components/Host/HostTickets.jsx';
const mapStateToProps = state => ({
});
const mapDispatchToProps = dispatch => bindActionCreators(actionCreators, dispatch);
const HostTicketsContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(HostTickets);
export default HostTickets;
|
'use strict';
// Last time updated at Sep 07, 2014, 08:32:23
// Latest file can be found here: https://cdn.webrtc-experiment.com/getScreenId.js
// Muaz Khan - www.MuazKhan.com
// MIT License - www.WebRTC-Experiment.com/licence
// Documentation - https://github.com/muaz-khan/WebRTC-Experiment/tree/master/getScreenId.js
// ______________
// getScreenId.js
(function() {
window.getScreenId = function(extensionid,callback) {
this.extensionId = extensionid;
if (!!navigator.mozGetUserMedia) {
callback(null, 'firefox', {
video: {
mozMediaSource: 'window',
mediaSource: 'window'
}
});
return;
}
postMessage();
function onIFrameCallback(event) {
if (!event.data) { return; }
if (event.data.chromeMediaSourceId) {
if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
callback('permission-denied');
} else {
callback(null, event.data.chromeMediaSourceId, getScreenConstraints(null, event.data.chromeMediaSourceId));
}
}
if (event.data.chromeExtensionStatus) {
callback(event.data.chromeExtensionStatus, null, getScreenConstraints(event.data.chromeExtensionStatus));
}
// this event listener is no more needed
window.removeEventListener('message', onIFrameCallback);
}
window.addEventListener('message', onIFrameCallback);
};
var getScreenConstraints = function(error, sourceId) {
var screenConstraints = {
audio: false,
video: {
mandatory: {
chromeMediaSource: error ? 'screen' : 'desktop',
maxWidth: window.screen.width > 1920 ? window.screen.width : 1920,
maxHeight: window.screen.height > 1080 ? window.screen.height : 1080
},
optional: []
}
};
if (sourceId) {
screenConstraints.video.mandatory.chromeMediaSourceId = sourceId;
}
return screenConstraints;
};
var postMessage = function() {
if (!iframe.isLoaded) {
setTimeout(postMessage, 100);
return;
}
iframe.contentWindow.postMessage({/*jshint validthis:true */
captureSourceId: this.extensionId
}, '*');
};
var iframe = document.createElement('iframe');
iframe.onload = function() {
iframe.isLoaded = true;
};
iframe.src = '/desktop_cap.html';
iframe.style.display = 'none';
(document.body || document.documentElement).appendChild(iframe);
})();
|
function NodeUI(parent_node, x, y) {
this.parent_node = parent_node;
this.x = x;
this.y = y;
this.sl = E2.app.scrollOffset[0];
this.st = E2.app.scrollOffset[1];
this.plugin_ui = null;
var nid = 'n' + parent_node.uid, dom = this.dom = make('table');
dom.addClass('plugin');
dom.addClass('graph-node');
dom.attr('id', nid);
dom.mousemove(E2.app.onMouseMoved); // Make sure we don't stall during slot connection, when the mouse enters a node.
dom.addClass('pl_layout');
var h_row = make('tr');
var h_cell = make('td');
var icon = make('span');
var lbl = make('span');
icon.addClass('plugin-icon');
icon.addClass('icon-' + parent_node.plugin.id);
icon.click(function(self) { return function()
{
self.parent_node.open = !self.parent_node.open;
self.content_row.css('display', self.parent_node.open ? 'table-row' : 'none');
self.parent_node.update_connections();
E2.app.updateCanvas(true);
}}(this));
lbl.text(parent_node.get_disp_name());
lbl.addClass('t');
h_cell.attr('colspan', '3');
h_cell.addClass('pl_title');
h_cell.append(icon);
h_cell.append(lbl);
h_row.append(h_cell);
h_row.addClass('pl_header');
h_row.click(E2.app.onNodeHeaderClicked);
h_row.dblclick(E2.app.onNodeHeaderDblClicked(parent_node));
h_row.mouseenter(E2.app.onNodeHeaderEntered(parent_node));
h_row.mouseleave(E2.app.onNodeHeaderExited);
if(parent_node.plugin.desc)
{
// var p_name = E2.app.player.core.plugin_mgr.keybyid[parent_node.plugin.id];
// h_row.attr('alt', '<b>' + p_name + '</b><br/><br/>' + parent_node.plugin.desc);
h_row.attr('alt', '' + parent_node.uid);
h_row.hover(E2.app.onShowTooltip, E2.app.onHideTooltip);
}
dom.append(h_row);
this.header_row = h_row;
var row = this.content_row = make('tr');
row.css('display', parent_node.open ? 'table-row' : 'none');
dom.append(row)
var input_col = make('td');
var content_col = make('td');
var output_col = make('td');
input_col.addClass('ic');
content_col.addClass('pui_col');
content_col.addClass('cc');
output_col.addClass('oc');
if((parent_node.dyn_inputs ? parent_node.dyn_inputs.length : 0) + parent_node.plugin.input_slots.length)
input_col.css('padding-right', '6px');
row.append(input_col)
row.append(content_col)
row.append(output_col)
NodeUI.render_slots(parent_node, nid, input_col, parent_node.plugin.input_slots, E2.slot_type.input);
NodeUI.render_slots(parent_node, nid, output_col, parent_node.plugin.output_slots, E2.slot_type.output);
if(parent_node.dyn_inputs)
NodeUI.render_slots(parent_node, nid, input_col, parent_node.dyn_inputs, E2.slot_type.input);
if(parent_node.dyn_outputs)
NodeUI.render_slots(parent_node, nid, output_col, parent_node.dyn_outputs, E2.slot_type.output);
var plugin = parent_node.plugin;
if(plugin.create_ui)
{
this.plugin_ui = plugin.create_ui();
content_col.append(this.plugin_ui);
}
else
this.plugin_ui = {}; // We must set a dummy object so plugins can tell why they're being called.
make_draggable(dom, E2.app.onNodeDragged(parent_node), E2.app.onNodeDragStopped(parent_node));
var s = dom[0].style;
s.left = '' + x + 'px';
s.top = '' + y + 'px';
E2.dom.canvas_parent.append(dom);
}
NodeUI.create_slot = function(parent_node, nid, col, s, type)
{
var div = make('div');
if(s.uid !== undefined)
div.attr('id', nid + (type === E2.slot_type.input ? 'di' : 'do') + s.uid);
else
div.attr('id', nid + (type === E2.slot_type.input ? 'si' : 'so') + s.index);
div.text(s.name);
div.addClass('pl_slot');
div.definition = s;
div.mouseenter(E2.app.onSlotEntered(parent_node, s, div));
div.mouseleave(E2.app.onSlotExited(parent_node, s, div));
div.mousedown(E2.app.onSlotClicked(parent_node, s, div, type));
var id = '' + parent_node.uid;
id += '_' + (s.uid !== undefined ? 'd' : 's');
id += type === E2.slot_type.input ? 'i' : 'o';
id += '_' + (s.uid !== undefined ? s.uid : s.index);
div.attr('alt', id);
div.hover(E2.app.onShowTooltip, E2.app.onHideTooltip);
col.append(div);
};
NodeUI.render_slots = function(parent_node, nid, col, slots, type)
{
for(var i = 0, len = slots.length; i < len; i++)
NodeUI.create_slot(parent_node, nid, col, slots[i], type);
};
|
import classnames from 'classnames'
import _styles from './styles/_media.scss'
function MediaLeft (props) {
let classNames = classnames(_styles['media-left'], _styles[`media-${props.align}`])
return (
<div style={props.style} className={classNames}>
{props.children}
</div>
)
}
function MediaRight (props) {
let classNames = classnames(_styles['media-right'], _styles[`media-${props.align}`])
return (
<div style={props.style} className={classNames}>
{props.children}
</div>
)
}
function MediaBody (props) {
let classNames = classnames(_styles['media-body'], _styles[`media-${props.align}`])
return (
<div style={props.style} className={classNames}>
{props.children}
</div>
)
}
function MediaHead (props) {
return (
<div style={props.style} className={_styles['media-heading']}>
{props.children}
</div>
)
}
export default function Media (props) {
return (
<div style={props.style} className={_styles.media}>
{props.children}
</div>
)
}
Media.Left = MediaLeft
Media.Body = MediaBody
Media.Head = MediaHead
Media.Right = MediaRight
|
'use strict';
var path = require('path'),
fs = require('fs'),
yaml = require('js-yaml'),
_ = require('lodash'),
GeminiError = require('../errors/gemini-error'),
BrowserConfig = require('./browser-config'),
parseOptions = require('./options');
/**
* @param {Object|String} configData data of the config or path to file
* @param {Object} allowOverrides
* @param {Boolean} allowOverrides.env
* @param {Boolean} allowOverrides.cli
*/
function Config(configData, allowOverrides) {
allowOverrides = _.defaults(allowOverrides || {}, {
env: false,
cli: false
});
var env = allowOverrides.env? process.env : {},
argv = allowOverrides.cli? process.argv : [];
if (_.isString(configData)) {
configData = readConfigData(configData);
}
var parsed = parseOptions({
options: configData,
env: env,
argv: argv
});
this.system = parsed.system;
this.sets = parsed.sets;
this._configs = _.mapValues(parsed.browsers, function(data, id) {
return new BrowserConfig(id, this.system, data);
}.bind(this));
}
Config.prototype.forBrowser = function(id) {
return this._configs[id];
};
Config.prototype.getBrowserIds = function() {
return Object.keys(this._configs);
};
Object.defineProperty(Config.prototype, 'coverageEnabled', {
get: function() {
return this.system.coverage.enabled;
}
});
function readConfigData(filePath) {
var configData = readYAMLFile(filePath),
configDir = path.dirname(filePath);
if (_.has(configData, 'system.projectRoot')) {
configData.system.projectRoot = path.resolve(configDir, configData.system.projectRoot);
} else {
_.set(configData, 'system.projectRoot', configDir);
}
return configData;
}
function readYAMLFile(configPath) {
var text = readFile(configPath);
return parseYAML(text, configPath);
}
function readFile(configPath) {
try {
return fs.readFileSync(configPath, 'utf8');
} catch (e) {
if (e.code === 'ENOENT') {
throw new GeminiError(
'Config file does not exist: ' + configPath,
'Specify config file or configure your project by following\nthe instructions:\n\n' +
'https://github.com/bem/gemini#configuration'
);
}
throw e;
}
}
function parseYAML(source, filename) {
try {
return yaml.safeLoad(source);
} catch (e) {
throw new GeminiError('Error while parsing a config file: ' + filename + '\n' +
e.reason + ' ' + e.mark,
'Gemini config should be valid YAML file.'
);
}
}
module.exports = Config;
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z" /></React.Fragment>
, 'ArrowForward');
|
var searchData=
[
['id_5f',['id_',['../interface_p_b_biometry_user.html#af432918d1b07e1e695e826b397a674ba',1,'PBBiometryUser']]]
];
|
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/* Tabulator v4.7.2 (c) Oliver Folkerd */
var Mutator = function Mutator(table) {
this.table = table; //hold Tabulator object
this.allowedTypes = ["", "data", "edit", "clipboard"]; //list of muatation types
this.enabled = true;
};
//initialize column mutator
Mutator.prototype.initializeColumn = function (column) {
var self = this,
match = false,
config = {};
this.allowedTypes.forEach(function (type) {
var key = "mutator" + (type.charAt(0).toUpperCase() + type.slice(1)),
mutator;
if (column.definition[key]) {
mutator = self.lookupMutator(column.definition[key]);
if (mutator) {
match = true;
config[key] = {
mutator: mutator,
params: column.definition[key + "Params"] || {}
};
}
}
});
if (match) {
column.modules.mutate = config;
}
};
Mutator.prototype.lookupMutator = function (value) {
var mutator = false;
//set column mutator
switch (typeof value === "undefined" ? "undefined" : _typeof(value)) {
case "string":
if (this.mutators[value]) {
mutator = this.mutators[value];
} else {
console.warn("Mutator Error - No such mutator found, ignoring: ", value);
}
break;
case "function":
mutator = value;
break;
}
return mutator;
};
//apply mutator to row
Mutator.prototype.transformRow = function (data, type, updatedData) {
var self = this,
key = "mutator" + (type.charAt(0).toUpperCase() + type.slice(1)),
value;
if (this.enabled) {
self.table.columnManager.traverse(function (column) {
var mutator, params, component;
if (column.modules.mutate) {
mutator = column.modules.mutate[key] || column.modules.mutate.mutator || false;
if (mutator) {
value = column.getFieldValue(typeof updatedData !== "undefined" ? updatedData : data);
if (type == "data" || typeof value !== "undefined") {
component = column.getComponent();
params = typeof mutator.params === "function" ? mutator.params(value, data, type, component) : mutator.params;
column.setFieldValue(data, mutator.mutator(value, data, type, params, component));
}
}
}
});
}
return data;
};
//apply mutator to new cell value
Mutator.prototype.transformCell = function (cell, value) {
var mutator = cell.column.modules.mutate.mutatorEdit || cell.column.modules.mutate.mutator || false,
tempData = {};
if (mutator) {
tempData = Object.assign(tempData, cell.row.getData());
cell.column.setFieldValue(tempData, value);
return mutator.mutator(value, tempData, "edit", mutator.params, cell.getComponent());
} else {
return value;
}
};
Mutator.prototype.enable = function () {
this.enabled = true;
};
Mutator.prototype.disable = function () {
this.enabled = false;
};
//default mutators
Mutator.prototype.mutators = {};
Tabulator.prototype.registerModule("mutator", Mutator);
|
/**
* Created by hen on 3/18/14.
*/
function BrushableScale(ctx, svg, width, updateFunctionNameInCtx, redrawFunctionNameInCtx, scaleNameInCtx, params){
// var svg = d3.select("#vis").append("svg").attr({
// width:800,
// height:800
// })
var offsetX=0,
offsetY=0;
var distanceBetweenAxis = 25; // distance between two scales
var distanceBetweenUpperAndLower = 20 // should be fix !!
// height=20;
var width = width;
var xScale = d3.scale.pow().exponent(2).domain([1,width]).range([0, width])
var xOverViewAxisUpper = d3.svg.axis().scale(xScale);
var xOverViewAxisLower = d3.svg.axis().scale(xScale).orient("top").tickFormat(function(d){return ""});
var xDetailScale = d3.scale.linear().domain([0,width]).range([0,width]).clamp(true)
var xDetailAxisUpper = d3.svg.axis().scale(xDetailScale).ticks(5);
var xDetailAxisLower = d3.svg.axis().scale(xDetailScale).orient("top").tickFormat(function(d){return ""}).ticks(5);
var param = param
var columnLabel ="ABC";
var maxValue = 100;
var labels=[
{name: "largest intersection",id:"I", value:100 },
{name: "largest group",id:"G", value:200 },
{name: "largest set",id:"S", value:300 },
{name: "all items",id:"A", value:400 }
]
var actionsTriggeredByLabelClick=params.actionsTrioggeredByLabelClick;
var connectionAreaData =[
[0,-distanceBetweenAxis],
[100,-distanceBetweenAxis],
[width,0]
]
// add axis
svg.append("g").attr({
"class":"x overviewAxisUpper axis",
"transform":"translate("+offsetX+","+offsetY+")"
}).call(xOverViewAxisUpper)
svg.append("g").attr({
"class":"x overviewAxisLower axis",
"transform":"translate("+offsetX+","+(offsetY+distanceBetweenUpperAndLower)+")"
}).call(xOverViewAxisLower)
svg.append("g").attr({
"class":"x detailAxisUpper axis",
"transform":"translate("+offsetX+","+(offsetY+distanceBetweenAxis+distanceBetweenUpperAndLower)+")"
}).call(xDetailAxisUpper)
svg.append("g").attr({
"class":"x detailAxisLower axis",
"transform":"translate("+offsetX+","+(offsetY+distanceBetweenAxis+2*distanceBetweenUpperAndLower)+")"
}).call(xDetailAxisLower)
// svg.append("path").attr({
// class:"connectionArea",
// "transform":"translate("+offsetX+","+offsetY+")"
// })
var sliders;
var overViewBrushDef;
var overviewBrush;
var redrawFunction = ctx[redrawFunctionNameInCtx];
// brushed function
var brushed = function(){
var endRange = overViewBrushDef.extent()[1];
if (endRange<5){
endRange =5;
overViewBrushDef.extent([0,5]);
}
svg.select(".drawBrush").attr({
width:xScale(endRange)
});
xDetailScale.domain([0,endRange]);
xDetailAxisUpper.scale(xDetailScale);
xDetailAxisLower.scale(xDetailScale);
svg.selectAll(".detailAxisUpper").call(xDetailAxisUpper);
svg.selectAll(".detailAxisLower").call(xDetailAxisLower);
connectionAreaData[1][0]= xScale(endRange);
updateConnectionArea()
if (redrawFunction!=null) redrawFunction();
ctx[scaleNameInCtx] = xDetailScale;
};
var setBrush= function(size){
// var sizeB =xScale(size);
overViewBrushDef.extent([0,size]);
// overviewBrush.select(".e").attr({
// "transform":"translate("+xScale(size)+","+0+")"
// })
overviewBrush.call(overViewBrushDef)
brushed();
}
function updateColumnLabel() {
svg.select(".columnLabelGroup").select("rect").attr({
width:width
})
svg.select(".columnLabelGroup").select("text").attr({
x:width/2
})
}
var update = function(params){
if (params.maxValue !=null) maxValue= params.maxValue;
if (params.labels !=null) labels = params.labels;
if (params.width != null) width = params.width;
updateScales();
updateSliderLabels();
updateColumnLabel();
}
function init(){
if (params.columnLabel != null) columnLabel = params.columnLabel;
// define slider
overViewBrushDef = d3.svg.brush()
.x(xScale)
.extent([0, 100])
.on("brush", brushed)
.on("brushstart", function(){
svg.selectAll(".columnLabelGroup").transition().duration(100).style({
opacity:0
})
svg.selectAll(".connectionArea").transition().duration(100).style({
opacity:.2
})
})
.on("brushend", function(){
svg.selectAll(".columnLabelGroup").transition().duration(500).style({
opacity:1
})
svg.selectAll(".connectionArea").transition().duration(500).style({
opacity:.00001
})
});
sliders = svg.append("g").attr({
class: "sliderGroup",
"transform": "translate(" + offsetX + "," + (offsetY) + ")"
});
sliders.append("path").attr({
class:"connectionArea"
}).style({
opacity:.00001
})
var labelHeight = 20;
var columnLabelGroup = svg.append("g").attr({
class:"columnLabelGroup",
"transform":"translate("+(0)+","+(distanceBetweenUpperAndLower+(distanceBetweenAxis-labelHeight)/2)+")" //Math.floor
})
columnLabelGroup.append("rect").attr({
class:"labelBackground",
x:0,
y:0,
width:width,
height:labelHeight// TODO magic number
}).on({
"click": function(){ actionsTriggeredByLabelClick.forEach(function(d){d();})}
})
columnLabelGroup.append("text").attr({
class:"columnLabel",
"pointer-events":"none",
x:width/2,
y:labelHeight/2
})
// .style({
// "font-size":"1em"
// })
.text(columnLabel);
sliders.append("rect").attr({
class:"drawBrush",
x:0,
y:0,
height:distanceBetweenUpperAndLower,
width:overViewBrushDef.extent()[1]
})
overviewBrush = sliders.append("g").attr({
class:"slider"
}).call(overViewBrushDef)
overviewBrush.selectAll(".w, .extent, .background").remove();
overviewBrush.selectAll("rect").attr({
height:50,
width:20
})
overviewBrush.selectAll(".e")
.append("rect")
.attr({
"class":"handle"
})
overviewBrush.selectAll("rect").attr({
transform:"translate(0,"+(distanceBetweenUpperAndLower/2)+")rotate(45)",
x:-5,
y:-5,
height:10,
width:10
})
sliders.append("g").attr({
class:"labels"
})
}
function updateScales(){
var brushedValue = d3.min([overViewBrushDef.extent()[1], maxValue]);
var optimalExponent = getOptimalExponent(maxValue,width);
xScale.domain([0,maxValue]).range([0, width]).exponent(optimalExponent);
// Heavy label stuff
var formatFunction = null;
var tickValues = xScale.ticks(10);
tickValues.push(maxValue);
var tickValuesReverse = tickValues.reverse();
var drawLabels = {};
var numberWidth = 6/2;// TODO magic Number 6
var maxSpace = width-maxValue.toString(10).length* numberWidth;
drawLabels[maxValue]=true;
tickValuesReverse.forEach(function(label){
if (xScale(label)+label.toString(10).length*numberWidth<maxSpace){
maxSpace = xScale(label)-label.toString(10).length*numberWidth;
drawLabels[label] = true;
}
})
formatFunction = function(d,i){return (d in drawLabels)?d:"";}
// kill last regular tick if too close to maxValue
// if (xScale(tickValuesReverse[0])< width-maxValue.toString(10).length* numberWidth){
// tickValues.slice()
// }
// if (optimalExponent>.8){
// tickValues = xScale.ticks(6);
// formatFunction = function(d,i){return d;}
// //[0,Math.floor(maxValue/3),Math.floor(maxValue*2/3),maxValue]
// }else{
// tickValues = xScale.ticks(8);
// formatFunction = function(d,i){return (i%2==0 || i<4 || i==(tickValues.length-1))?d:"";}
// }
// tickValues.pop();
tickValues.push(maxValue);
xOverViewAxisUpper.scale(xScale).tickValues(tickValues).tickFormat(formatFunction);
xOverViewAxisLower.scale(xScale).tickValues(tickValues);
xDetailScale.range([0,width])
xDetailAxisUpper.scale(xDetailScale);
xDetailAxisLower.scale(xDetailScale);
connectionAreaData[2] = [width,0];
svg.select(".x.overviewAxisUpper.axis").call(xOverViewAxisUpper)
svg.select(".x.overviewAxisLower.axis").call(xOverViewAxisLower)
svg.select(".x.detailAxisUpper.axis").call(xDetailAxisUpper)
svg.select(".x.detailAxisLower.axis").call(xDetailAxisLower)
// do NOT redraw !
overViewBrushDef.x(xScale)
var saveRedraw = redrawFunction;
redrawFunction = null;
setBrush(brushedValue);
redrawFunction = saveRedraw;
}
function updateSliderLabels(){
// slider labels
var sliderLabels = sliders.select(".labels").selectAll(".sliderLabel").data(labels, function(d){return d.name})
sliderLabels.exit().remove();
var sliderLabelsEnter = sliderLabels.enter().append("g").attr({
class:"sliderLabel"
});
sliderLabelsEnter.append("rect").attr({
x:-5,
y:0,
width:10,
height:15
})
.append("svg:title").text( function(d){return d.name})
sliderLabelsEnter.append("line").attr({
x1:0,
x2:0,
y1:15,
y2:20
})
sliderLabelsEnter.append("text").text(function(d){return d.id}).attr({
dy:"1em",
"pointer-events":"none"
})
sliderLabels.attr({
"transform":function(d){return "translate("+xScale(d.value)+","+(-20)+")"}
}).on({
"click":function(d){setBrush(d.value);}
})
}
function getOptimalExponent(maxValue, width){
if (maxValue<=width) return 1;
else{
// ensure that value 5 has at least 5 pixel
var deltaValue = 5;
var deltaPixel = 5;
var optimalExponent = Math.log(deltaPixel/width)/Math.log(deltaValue/maxValue);
return optimalExponent;
}
}
function updateConnectionArea(){
var cAreaNode = svg.selectAll(".connectionArea").data([connectionAreaData])
cAreaNode.exit().remove();
cAreaNode.enter().append("path")
.attr({
class:"connectionArea",
"transform":"translate("+offsetX+","+(offsetY+distanceBetweenUpperAndLower+distanceBetweenAxis)+")"
})
cAreaNode.attr({
"transform":"translate("+offsetX+","+(offsetY+distanceBetweenUpperAndLower+distanceBetweenAxis)+")",
d:d3.svg.area()
})
}
init();
updateSliderLabels();
updateConnectionArea();
// updateScales();
ctx[updateFunctionNameInCtx]=function(d,params){update(params);};
}
|
console.warn("start spec");
describe("less.js main tests", function() {
testLessEqualsInDocument();
it("the global environment", function() {
expect(window.require).toBe(undefined);
});
});
|
$(function () {
$('[data-toggle="popover"]').popover();
$('.popover-dismiss').popover({
trigger: 'focus'
});
});
|
(function(){
var factory = function (exports) {
var lang = {
name : "en",
description : "Open source online Markdown editor.",
tocTitle : "Table of Contents",
toolbar : {
undo : "Undo(Ctrl+Z)",
redo : "Redo(Ctrl+Y)",
bold : "Bold",
del : "Strikethrough",
italic : "Italic",
quote : "Block quote",
ucwords : "Words first letter convert to uppercase",
uppercase : "Selection text convert to uppercase",
lowercase : "Selection text convert to lowercase",
h1 : "Heading 1",
h2 : "Heading 2",
h3 : "Heading 3",
h4 : "Heading 4",
h5 : "Heading 5",
h6 : "Heading 6",
"list-ul" : "Unordered list",
"list-ol" : "Ordered list",
hr : "Horizontal rule",
link : "Link",
"reference-link" : "Reference link",
image : "Image",
code : "Code inline",
"preformatted-text" : "Preformatted text / Code block (Tab indent)",
"code-block" : "Code block (Multi-languages)",
table : "Tables",
datetime : "Datetime",
emoji : "Emoji",
"html-entities" : "HTML Entities",
pagebreak : "Page break",
watch : "Unwatch",
unwatch : "Watch",
preview : "HTML Preview (Press Shift + ESC exit)",
fullscreen : "Fullscreen (Press ESC exit)",
clear : "Clear",
search : "Search",
help : "Help",
info : "About " + exports.title
},
buttons : {
enter : "Enter",
cancel : "Cancel",
close : "Close"
},
dialog : {
link : {
title : "Link",
url : "Address",
urlTitle : "Title",
urlEmpty : "Error: Please fill in the link address."
},
referenceLink : {
title : "Reference link",
name : "Name",
url : "Address",
urlId : "ID",
urlTitle : "Title",
nameEmpty: "Error: Reference name can't be empty.",
idEmpty : "Error: Please fill in reference link id.",
urlEmpty : "Error: Please fill in reference link url address."
},
image : {
title : "Image",
url : "Address",
link : "Link",
alt : "Title",
uploadButton : "Upload",
imageURLEmpty : "Error: picture url address can't be empty.",
uploadFileEmpty : "Error: upload pictures cannot be empty!",
formatNotAllowed : "Error: only allows to upload pictures file, upload allowed image file format:"
},
preformattedText : {
title : "Preformatted text / Codes",
emptyAlert : "Error: Please fill in the Preformatted text or content of the codes.",
placeholder : "coding now...."
},
codeBlock : {
title : "Code block",
selectLabel : "Languages: ",
selectDefaultText : "select a code language...",
otherLanguage : "Other languages",
unselectedLanguageAlert : "Error: Please select the code language.",
codeEmptyAlert : "Error: Please fill in the code content.",
placeholder : "coding now...."
},
htmlEntities : {
title : "HTML Entities"
},
help : {
title : "Help"
}
}
};
exports.defaults.lang = lang;
};
// CommonJS/Node.js
if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
{
module.exports = factory;
}
else if (typeof define === "function") // AMD/CMD/Sea.js
{
if (define.amd) { // for Require.js
define(["editormd"], function(editormd) {
factory(editormd);
});
} else { // for Sea.js
define(function(require) {
var editormd = require("../editormd");
factory(editormd);
});
}
}
else
{
factory(window.editormd);
}
})();
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.1.3.3_A2.2_T1;
* @section: 15.1.3.3;
* @assertion: If string.charAt(k) in [0x0080 - 0x07FF], return 2 octets (00000yyy yyzzzzzz -> 110yyyyy 10zzzzzz);
* @description: Complex tests, use RFC 3629;
*/
errorCount = 0;
count = 0;
var indexP;
var indexO = 0;
l:
for (index = 0x0080; index <= 0x07FF; index++) {
count++;
hex1 = decimalToHexString(0x0080 + (index & 0x003F)).substring(2);
hex2 = decimalToHexString(0x00C0 + (index & 0x07C0) / 0x0040).substring(2);
str = String.fromCharCode(index);
try {
if (encodeURI(str).toUpperCase() === "%" + hex2 + "%" + hex1) continue;
} catch(e) {}
if (indexO === 0) {
indexO = index;
} else {
if ((index - indexP) !== 1) {
if ((indexP - indexO) !== 0) {
var hexP = decimalToHexString(indexP);
var hexO = decimalToHexString(indexO);
$ERROR('#' + hexO + '-' + hexP + ' ');
}
else {
var hexP = decimalToHexString(indexP);
$ERROR('#' + hexP + ' ');
}
indexO = index;
}
}
indexP = index;
errorCount++;
}
if (errorCount > 0) {
if ((indexP - indexO) !== 0) {
var hexP = decimalToHexString(indexP);
var hexO = decimalToHexString(indexO);
$ERROR('#' + hexO + '-' + hexP + ' ');
} else {
var hexP = decimalToHexString(indexP);
$ERROR('#' + hexP + ' ');
}
$ERROR('Total error: ' + errorCount + ' bad Unicode character in ' + count + ' ');
}
function decimalToHexString(n) {
n = Number(n);
var h = "";
for (var i = 3; i >= 0; i--) {
if (n >= Math.pow(16, i)) {
var t = Math.floor(n / Math.pow(16, i));
n -= t * Math.pow(16, i);
if ( t >= 10 ) {
if ( t == 10 ) { h += "A"; }
if ( t == 11 ) { h += "B"; }
if ( t == 12 ) { h += "C"; }
if ( t == 13 ) { h += "D"; }
if ( t == 14 ) { h += "E"; }
if ( t == 15 ) { h += "F"; }
} else {
h += String(t);
}
} else {
h += "0";
}
}
return h;
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:101fe07ed27aef2396a78b39275e437030bf995a8a7a3819339eabfbf08665a0
size 14390
|
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
require('babel/register')({
optional: ['runtime', 'es7.asyncFunctions']
});
process.on('unhandledRejection', function (error) {
console.error('Unhandled Promise Rejection:');
console.error(error && error.stack || error);
});
|
var src = './app/',
dist = './web/';
module.exports = {
server: {
root: dist + '',
watch: dist + '**/*.*'
},
views: {
src: src + 'views/**/*.*',
dist: dist + '',
task: 'pages'
},
scripts: {
src: src + 'assets/scripts/**/*.*',
entry: src + 'assets/scripts/app.js',
dist: dist + 'resources/scripts/',
task: 'scripts'
},
styles: {
src: src + 'assets/styles/**/*.*',
dist: dist + 'resources/styles/',
task: 'styles'
},
images: {
src: src + 'assets/images/**/*.*',
dist: dist + 'resources/images/',
task: 'images'
},
fonts: {
src: src + 'assets/fonts/**/*.*',
dist: dist + 'resources/fonts/',
task: 'fonts'
},
files: {
src: src + 'assets/files/**/*.*',
dist: dist + 'resources/files/',
task: 'files'
}
};
|
/*
* Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* The custom domain assigned to this storage account. This can be set via
* Update.
*
*/
class CustomDomain {
/**
* Create a CustomDomain.
* @member {string} name Gets or sets the custom domain name. Name is the
* CNAME source.
* @member {boolean} [useSubDomain] Indicates whether indirect CName
* validation is enabled. Default value is false. This should only be set on
* updates
*/
constructor() {
}
/**
* Defines the metadata of CustomDomain
*
* @returns {object} metadata of CustomDomain
*
*/
mapper() {
return {
required: false,
serializedName: 'CustomDomain',
type: {
name: 'Composite',
className: 'CustomDomain',
modelProperties: {
name: {
required: true,
serializedName: 'name',
type: {
name: 'String'
}
},
useSubDomain: {
required: false,
serializedName: 'useSubDomain',
type: {
name: 'Boolean'
}
}
}
}
};
}
}
module.exports = CustomDomain;
|
this.asArrowFuncArgList = function(argList) {
var i = 0, list = argList;
while (i < list.length)
this.asArrowFuncArg(list[i++]);
};
this.asArrowFuncArg = function(arg) {
var i = 0, list = null;
if (this.firstNonSimpArg === null && arg.type !== 'Identifier')
this.firstNonSimpArg = arg;
if (arg === this.po)
this.throwTricky('p', this.pt);
switch ( arg.type ) {
case 'Identifier':
if ((this.scopeFlags & SCOPE_FLAG_ALLOW_AWAIT_EXPR) &&
arg.name === 'await')
this.err('arrow.param.is.await.in.an.async',{tn:arg});
// TODO: this can also get checked in the scope manager rather than below
if (this.tight && arguments_or_eval(arg.name))
this.err('binding.to.arguments.or.eval',{tn:arg});
this.declare(arg);
return;
case 'ArrayExpression':
list = arg.elements;
while (i < list.length) {
if (list[i])
this.asArrowFuncArg(list[i]);
i++;
}
arg.type = 'ArrayPattern';
return;
case 'AssignmentExpression':
// if (arg.operator !== '=')
// this.err('complex.assig.not.arg');
this.asArrowFuncArg(arg.left);
delete arg.operator ;
arg.type = 'AssignmentPattern';
return;
case 'ObjectExpression':
list = arg.properties;
while (i < list.length)
this.asArrowFuncArg(list[i++].value );
arg.type = 'ObjectPattern';
return;
case 'AssignmentPattern':
this.asArrowFuncArg(arg.left) ;
return;
case 'ArrayPattern' :
list = arg.elements;
while ( i < list.length ) {
if (list[i])
this.asArrowFuncArg(list[i]);
i++ ;
}
return;
case 'SpreadElement':
if (this.v < 7 && arg.argument.type !== 'Identifier')
this.err('rest.binding.arg.not.id', {tn:arg});
this.asArrowFuncArg(arg.argument);
arg.type = 'RestElement';
return;
case 'RestElement':
if (this.v < 7 && arg.argument.type !== 'Identifier')
this.err('rest.binding.arg.not.id',{tn:arg});
this.asArrowFuncArg(arg.argument);
return;
case 'ObjectPattern':
list = arg.properties;
while (i < list.length)
this.asArrowFuncArg(list[i++].value);
return;
default:
this.err('not.bindable');
}
};
this.parseArrowFunctionExpression = function(arg, context) {
if (this.v <= 5)
this.err('ver.arrow');
var tight = this.tight, async = false;
this.enterFuncScope(false);
this.declMode = DECL_MODE_FUNC_PARAMS;
this.enterComplex();
var scopeFlags = this.scopeFlags;
this.scopeFlags &= INHERITED_SCOPE_FLAGS;
if (this.pt === ERR_ASYNC_NEWLINE_BEFORE_PAREN) {
ASSERT.call(this, arg === this.pe, 'how can an error core not be equal to the erroneous argument?!');
this.err('arrow.newline.before.paren.async');
}
switch ( arg.type ) {
case 'Identifier':
this.firstNonSimpArg = null;
this.asArrowFuncArg(arg);
break;
case PAREN_NODE:
this.firstNonSimpArg = null;
if (arg.expr) {
if (arg.expr.type === 'SequenceExpression')
this.asArrowFuncArgList(arg.expr.expressions);
else
this.asArrowFuncArg(arg.expr);
}
break;
case 'CallExpression':
if (this.v >= 7 && arg.callee.type !== 'Identifier' || arg.callee.name !== 'async')
this.err('not.a.valid.arg.list',{tn:arg});
if (this.parenAsync !== null && arg.callee === this.parenAsync.expr)
this.err('arrow.has.a.paren.async');
// if (this.v < 7)
// this.err('ver.async');
async = true;
this.scopeFlags |= SCOPE_FLAG_ALLOW_AWAIT_EXPR;
this.asArrowFuncArgList(arg.arguments);
break;
case INTERMEDIATE_ASYNC:
async = true;
this.scopeFlags |= SCOPE_FLAG_ALLOW_AWAIT_EXPR;
this.asArrowFuncArg(arg.id);
break;
default:
this.err('not.a.valid.arg.list');
}
this.currentExprIsParams();
if (this.nl)
this.err('arrow.newline');
this.next();
var isExpr = true, nbody = null;
if ( this.lttype === '{' ) {
var prevLabels = this.labels;
this.labels = {};
isExpr = false;
this.scopeFlags |= SCOPE_FLAG_FN;
nbody = this.parseFuncBody(CTX_NONE|CTX_PAT|CTX_NO_SIMPLE_ERR);
this.labels = prevLabels;
}
else
nbody = this. parseNonSeqExpr(PREC_WITH_NO_OP, context|CTX_PAT) ;
this.exitScope();
this.tight = tight;
this.scopeFlags = scopeFlags;
var params = core(arg);
if (params === null)
params = [];
else if (params.type === 'SequenceExpression')
params = params.expressions;
else if (params.type === 'CallExpression')
params = params.arguments;
else {
if (params.type === INTERMEDIATE_ASYNC)
params = params.id;
params = [params];
}
return {
type: 'ArrowFunctionExpression', params: params,
start: arg.start, end: nbody.end,
loc: {
start: arg.loc.start,
end: nbody.loc.end
},
generator: false, expression: isExpr,
body: core(nbody), id : null,
async: async
};
};
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: SPACE (U+0020) between any two tokens is allowed
es5id: 7.2_A1.4_T2
description: Insert real SPACE between tokens of var x=1
---*/
//CHECK#1
eval("\u0020var x\u0020= 1\u0020");
if (x !== 1) {
$ERROR('#1: eval("\\u0020var x\\u0020= 1\\u0020"); x === 1. Actual: ' + (x));
}
//CHECK#2
var x = 1 ;
if (x !== 1) {
$ERROR('#2: var x = 1 ; x === 1. Actual: ' + (x));
}
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM12 3v10l3-3h6V3h-9z" /></React.Fragment>
, 'PermPhoneMsg');
|
/*eslint no-console:0 */
const monk = require('monk');
const fs = require('fs');
const _ = require('underscore');
const CardService = require('../services/CardService.js');
let db = monk('mongodb://127.0.0.1:27017/throneteki');
let cardService = new CardService(db);
let files = fs.readdirSync('thronesdb-json-data/pack');
let totalCards = [];
let packs = JSON.parse(fs.readFileSync('thronesdb-json-data/packs.json'));
let types = JSON.parse(fs.readFileSync('thronesdb-json-data/types.json'));
let factions = JSON.parse(fs.readFileSync('thronesdb-json-data/factions.json'));
_.each(files, file => {
let cards = JSON.parse(fs.readFileSync('thronesdb-json-data/pack/' + file));
totalCards = totalCards.concat(cards);
});
_.each(totalCards, card => {
let cardsByName = _.filter(totalCards, filterCard => {
return filterCard.name === card.name;
});
if(cardsByName.length > 1) {
card.label = card.name + ' (' + card.pack_code + ')';
} else {
card.label = card.name;
}
let faction = _.find(factions, faction => {
return faction.code === card.faction_code;
});
let type = _.find(types, type => {
return type.code === card.type_code;
});
if(faction) {
card.faction_name = faction.name;
} else {
console.info(faction, card.faction_code);
}
if(type) {
card.type_name = type.name;
} else {
console.info(card.type_code);
}
});
let replacePacks = cardService.replacePacks(packs)
.then(packs => {
console.info(packs.length + ' packs imported');
});
let replaceCards = cardService.replaceCards(totalCards)
.then(cards => {
console.info(cards.length + ' cards imported');
});
Promise.all([replacePacks, replaceCards])
.then(() => db.close())
.catch(() => db.close());
|
import d3 from 'd3';
import {identity, noop} from '../../util/fn';
import bucket from './bucket';
export default function() {
var dataBucketer = bucket(),
x = identity,
y = identity;
var largestTriangleOneBucket = function(data) {
if (dataBucketer.bucketSize() >= data.length) {
return data;
}
var pointAreas = calculateAreaOfPoints(data);
var pointAreaBuckets = dataBucketer(pointAreas);
var buckets = dataBucketer(data.slice(1, data.length - 1));
var subsampledData = buckets.map(function(thisBucket, i) {
var pointAreaBucket = pointAreaBuckets[i];
var maxArea = d3.max(pointAreaBucket);
var currentMaxIndex = pointAreaBucket.indexOf(maxArea);
return thisBucket[currentMaxIndex];
});
// First and last data points are their own buckets.
return [].concat(data[0], subsampledData, data[data.length - 1]);
};
function calculateAreaOfPoints(data) {
var xyData = data.map(function(point) {
return [x(point), y(point)];
});
var pointAreas = [];
for (var i = 1; i < xyData.length - 1; i++) {
var lastPoint = xyData[i - 1];
var thisPoint = xyData[i];
var nextPoint = xyData[i + 1];
var base = (lastPoint[0] - nextPoint[0]) * (thisPoint[1] - lastPoint[1]);
var height = (lastPoint[0] - thisPoint[0]) * (nextPoint[1] - lastPoint[1]);
var area = Math.abs(0.5 * base * height);
pointAreas.push(area);
}
return pointAreas;
}
d3.rebind(largestTriangleOneBucket, dataBucketer, 'bucketSize');
largestTriangleOneBucket.x = function(d) {
if (!arguments.length) {
return x;
}
x = d;
return largestTriangleOneBucket;
};
largestTriangleOneBucket.y = function(d) {
if (!arguments.length) {
return y;
}
y = d;
return largestTriangleOneBucket;
};
return largestTriangleOneBucket;
}
|
'use strict';
(function($) {
var throwError = function(msg) {
throw new Error('Sign2Pay: ' + msg);
}
var Sign2Pay = (function () {
/**
* Sign2Pay constructor
*
* @param object settings
*/
function Sign2Pay(settings) {
this.baseUrl = settings.baseUrl || throwError('No base url');
// Remove protocol from base url
this.baseUrl = this.baseUrl.replace(/^http:/, '');
}
/**
* Fetches payment logo
*
* @param function callback
*/
Sign2Pay.prototype.fetchPaymentLogo = function(callback) {
var self = this;
$.ajax(this.baseUrl + 'sign2pay/payment/fetchPaymentLogo', {
type: 'POST',
dataType: 'json',
success: function(options) {
callback(options);
},
error: function(err) {
console.log(err);
throwError('Could not fetch payment options');
}
});
}
/**
* Perform logo update
*/
Sign2Pay.prototype.logoUpdate = function() {
var self = this;
var $mark = $('#sign2pay-mark');
if (!$mark.size()) return;
var callback = function(options) {
$mark.attr('src', options.logo);
}
this.fetchPaymentLogo(callback);
};
/**
* Perform updates
*/
Sign2Pay.prototype.update = function() {
this.logoUpdate();
};
return Sign2Pay;
})();
$(window).load(function() {
window.sign2payPayment = new Sign2Pay(s2pOptions);
});
window.updateSign2pay = function() {
var interval;
interval = setInterval(function() {
if (typeof window.sign2payPayment !== 'object') return;
clearInterval(interval);
// Perform update
window.sign2payPayment.update();
});
};
})(jQuery.noConflict());
|
/* Greek (el) initialisation for the jQuery UI date picker plugin. */
/* Written by Alex Cicovic (http://www.alexcicovic.com) */
(function (factory) {
// AMD. Register as an anonymous module.
module.exports = factory(require('../datepicker'));;
}(function (datepicker) {
datepicker.regional['el'] = {
closeText: '\u039A\u03BB\u03B5\u03AF\u03C3\u03B9\u03BC\u03BF',
prevText: '\u03A0\u03C1\u03BF\u03B7\u03B3\u03BF\u03CD\u03BC\u03B5\u03BD\u03BF\u03C2',
nextText: '\u0395\u03C0\u03CC\u03BC\u03B5\u03BD\u03BF\u03C2',
currentText: '\u03A3\u03AE\u03BC\u03B5\u03C1\u03B1',
monthNames: [
'\u0399\u03B1\u03BD\u03BF\u03C5\u03AC\u03C1\u03B9\u03BF\u03C2',
'\u03A6\u03B5\u03B2\u03C1\u03BF\u03C5\u03AC\u03C1\u03B9\u03BF\u03C2',
'\u039C\u03AC\u03C1\u03C4\u03B9\u03BF\u03C2',
'\u0391\u03C0\u03C1\u03AF\u03BB\u03B9\u03BF\u03C2',
'\u039C\u03AC\u03B9\u03BF\u03C2',
'\u0399\u03BF\u03CD\u03BD\u03B9\u03BF\u03C2',
'\u0399\u03BF\u03CD\u03BB\u03B9\u03BF\u03C2',
'\u0391\u03CD\u03B3\u03BF\u03C5\u03C3\u03C4\u03BF\u03C2',
'\u03A3\u03B5\u03C0\u03C4\u03AD\u03BC\u03B2\u03C1\u03B9\u03BF\u03C2',
'\u039F\u03BA\u03C4\u03CE\u03B2\u03C1\u03B9\u03BF\u03C2',
'\u039D\u03BF\u03AD\u03BC\u03B2\u03C1\u03B9\u03BF\u03C2',
'\u0394\u03B5\u03BA\u03AD\u03BC\u03B2\u03C1\u03B9\u03BF\u03C2'
],
monthNamesShort: [
'\u0399\u03B1\u03BD',
'\u03A6\u03B5\u03B2',
'\u039C\u03B1\u03C1',
'\u0391\u03C0\u03C1',
'\u039C\u03B1\u03B9',
'\u0399\u03BF\u03C5\u03BD',
'\u0399\u03BF\u03C5\u03BB',
'\u0391\u03C5\u03B3',
'\u03A3\u03B5\u03C0',
'\u039F\u03BA\u03C4',
'\u039D\u03BF\u03B5',
'\u0394\u03B5\u03BA'
],
dayNames: [
'\u039A\u03C5\u03C1\u03B9\u03B1\u03BA\u03AE',
'\u0394\u03B5\u03C5\u03C4\u03AD\u03C1\u03B1',
'\u03A4\u03C1\u03AF\u03C4\u03B7',
'\u03A4\u03B5\u03C4\u03AC\u03C1\u03C4\u03B7',
'\u03A0\u03AD\u03BC\u03C0\u03C4\u03B7',
'\u03A0\u03B1\u03C1\u03B1\u03C3\u03BA\u03B5\u03C5\u03AE',
'\u03A3\u03AC\u03B2\u03B2\u03B1\u03C4\u03BF'
],
dayNamesShort: [
'\u039A\u03C5\u03C1',
'\u0394\u03B5\u03C5',
'\u03A4\u03C1\u03B9',
'\u03A4\u03B5\u03C4',
'\u03A0\u03B5\u03BC',
'\u03A0\u03B1\u03C1',
'\u03A3\u03B1\u03B2'
],
dayNamesMin: [
'\u039A\u03C5',
'\u0394\u03B5',
'\u03A4\u03C1',
'\u03A4\u03B5',
'\u03A0\u03B5',
'\u03A0\u03B1',
'\u03A3\u03B1'
],
weekHeader: '\u0395\u03B2\u03B4',
dateFormat: 'dd/mm/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
};
datepicker.setDefaults(datepicker.regional['el']);
return datepicker.regional['el'];
}));
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 (NumminorihSF) Konstantine Petryaev
*
* 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 tail = '';
var parse = function(string){
try{
var res = JSON.parse(string)
}
catch(e){
return null;
}
return res;
};
var w;
if (process.stdin){
process.stdin.setEncoding('utf-8');
var work = function(data){
tail += data.replace(/\r\n[\r\n]+/g, '\r\n');
var array = tail.split('\r\n');
tail = array.pop();
if (array.length) {
var answers = [];
var stringAnswers = [];
for (var i = 0; i < array.length; i++){
var answer = parse(array[i]);
if (answer === null) stringAnswers.push(array[i]);
else answers.push(answer);
}
for(i = 0; i < answers.length; i++){
(function(json){
if (w) {
w.emit('data', json);
if ('ipc' in json) {
json.callback = function(err, res){
process.stdout.write(JSON.stringify({id: json.id, error:err&&err.message, data:res})+'\r\n');
};
w.emit('ipc', json);
}
else w.emit('json', json);
}
else setTimeout(function(){
if (w) {
w.emit('data', json);
if ('ipc' in json) {
json.callback = function(err, res){
process.stdout.write(JSON.stringify({id: json.id, error:err&&err.message, data:res})+'\r\n');
};
w.emit('ipc', json);
}
else w.emit('json', json);
}
}, 500);
})(answers[i]);
}
for(i = 0; i < stringAnswers.length; i++){
(function(string){
if (w) {
w.emit('data', string);
w.emit('string', string);
}
else setTimeout(function(){
if (w) {
w.emit('data', string);
w.emit('string', string);
}
}, 500);
})(stringAnswers[i]);
}
}
};
process.stdin.on('data', work);
process.on('SIGTERM', function(){
process.stdin.removeEventListener('data', work);
});
}
if(module.parent) module.exports = function(worker){w=worker};
else require(process.env.NODE_RUN)(function(worker){
w=worker
});
|
'use strict';
module.exports = {
app: {
title: 'project-x',
description: 'First prototype with Rethinkdb, Express, Angular and Node.js',
keywords: 'Rethinkdb, Express, AngularJS, Node.js'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.css',
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js'
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
};
|
const solid = require('../')
const path = require('path')
solid
.createServer({
webid: true,
sslCert: path.resolve('../test/keys/cert.pem'),
sslKey: path.resolve('../test/keys/key.pem'),
errorHandler: function (err, req, res, next) {
if (err.status !== 200) {
console.log('Oh no! There is an error:' + err.message)
res.status(err.status)
// Now you can send the error how you want
// Maybe you want to render an error page
// res.render('errorPage.ejs', {
// title: err.status + ": This is an error!",
// message: err.message
// })
// Or you want to respond in JSON?
res.json({
title: err.status + ': This is an error!',
message: err.message
})
}
}
})
.listen(3456, function () {
console.log('started ldp with webid on port ' + 3456)
})
|
define(function(require) {
'use strict';
var Backbone = require('backbone');
var AppRouter = Backbone.Router.extend({
routes: {
'': 'MainCtrl',
'hello/:name(/)': 'HelloCtrl',
'devpage': 'DevpageCtrl',
'*actions': 'NotFoundCtrl'
},
MainCtrl: require('controllers/main'),
DevpageCtrl: require('controllers/devpage'),
HelloCtrl: require('controllers/hello'),
NotFoundCtrl: require('controllers/notfound')
});
return new AppRouter ();
});
|
/// <reference path="../extern/three.d.ts"/>
/// <reference path="../src/shortestpaths.ts"/>
/// <reference path="../src/linklengths.ts"/>
/// <reference path="../src/descent.ts"/>
var cola3;
(function (cola3) {
var Graph = (function () {
function Graph(parentObject, n, edges, nodeColour) {
var _this = this;
this.edgeList = [];
this.parentObject = parentObject;
this.rootObject = new THREE.Object3D();
parentObject.add(this.rootObject);
// Create all the node meshes
this.nodeMeshes = Array(n);
for (var i = 0; i < n; ++i) {
var sphere = this.nodeMeshes[i] = new THREE.Mesh(new THREE.SphereGeometry(1, 10, 10), new THREE.MeshLambertMaterial({ color: nodeColour[i] }));
this.rootObject.add(sphere);
}
// Create all the edges
edges.forEach(function (e) {
_this.edgeList.push(new Edge(_this.rootObject, _this.nodeMeshes[e.source].position, _this.nodeMeshes[e.target].position));
});
}
Graph.prototype.setNodePositions = function (colaCoords) {
var x = colaCoords[0], y = colaCoords[1], z = colaCoords[2];
for (var i = 0; i < this.nodeMeshes.length; ++i) {
var p = this.nodeMeshes[i].position;
p.x = x[i];
p.y = y[i];
p.z = z[i];
}
};
Graph.prototype.update = function () {
this.edgeList.forEach(function (e) { return e.update(); });
};
// Remove self from the scene so that the object can be GC'ed
Graph.prototype.destroy = function () {
this.parentObject.remove(this.rootObject);
};
return Graph;
})();
cola3.Graph = Graph;
var Edge = (function () {
function Edge(parentObject, sourcePoint, targetPoint) {
this.parentObject = parentObject;
this.sourcePoint = sourcePoint;
this.targetPoint = targetPoint;
this.shape = this.makeCylinder();
parentObject.add(this.shape);
}
Edge.prototype.makeCylinder = function () {
var n = 12, points = [], cosh = function (v) { return (Math.pow(Math.E, v) + Math.pow(Math.E, -v)) / 2; };
var xmax = 2, m = 2 * cosh(xmax);
for (var i = 0; i < n + 1; i++) {
var x = 2 * xmax * (i - n / 2) / n;
points.push(new THREE.Vector3(cosh(x) / m, 0, (i - n / 2) / n));
}
var material = new THREE.MeshLambertMaterial({ color: 0xcfcfcf }), geometry = new THREE.LatheGeometry(points, 12), cylinder = new THREE.Mesh(geometry, material);
return cylinder;
};
Edge.prototype.update = function () {
var a = this.sourcePoint, b = this.targetPoint;
var m = new THREE.Vector3();
m.addVectors(a, b).divideScalar(2);
this.shape.position = m;
var origVec = new THREE.Vector3(0, 0, 1); //vector of cylinder
var targetVec = new THREE.Vector3();
targetVec.subVectors(b, a);
var l = targetVec.length();
this.shape.scale.set(1, 1, l);
targetVec.normalize();
var angle = Math.acos(origVec.dot(targetVec));
var axis = new THREE.Vector3();
axis.crossVectors(origVec, targetVec);
axis.normalize();
var quaternion = new THREE.Quaternion();
quaternion.setFromAxisAngle(axis, angle);
this.shape.quaternion = quaternion;
};
return Edge;
})();
cola3.Edge = Edge;
})(cola3 || (cola3 = {}));
var LinkAccessor = (function () {
function LinkAccessor() {
}
LinkAccessor.prototype.getSourceIndex = function (e) {
return e.source;
};
LinkAccessor.prototype.getTargetIndex = function (e) {
return e.target;
};
LinkAccessor.prototype.getLength = function (e) {
return e.length;
};
LinkAccessor.prototype.setLength = function (e, l) {
e.length = l;
};
return LinkAccessor;
})();
d3.json("graphdata/miserables.json", function (error, graph) {
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer({ antialias: true });
var sizeRatio = 0.8;
renderer.setSize(window.innerWidth * sizeRatio, window.innerHeight * sizeRatio);
var div = document.getElementById("graphdiv");
div.appendChild(renderer.domElement);
var colaObject = new THREE.Object3D();
colaObject.position = new THREE.Vector3();
scene.add(colaObject);
var ambient = new THREE.AmbientLight(0x1f1f1f);
scene.add(ambient);
var directionalLight = new THREE.DirectionalLight(0xffeedd);
directionalLight.position.set(0, 0, 1);
scene.add(directionalLight);
var n = graph.nodes.length;
var color = d3.scale.category20();
var nodeColourings = graph.nodes.map(function (v) {
var str = color(v.group).replace("#", "0x");
return parseInt(str);
});
var colaGraph = new cola3.Graph(colaObject, n, graph.links, nodeColourings);
var linkAccessor = new LinkAccessor();
cola.jaccardLinkLengths(graph.links, linkAccessor, 1.5);
// Create the distance matrix that Cola needs
var distanceMatrix = (new cola.shortestpaths.Calculator(n, graph.links, linkAccessor.getSourceIndex, linkAccessor.getTargetIndex, linkAccessor.getLength)).DistanceMatrix();
var D = cola.Descent.createSquareMatrix(n, function (i, j) {
return distanceMatrix[i][j] * 7;
});
// G is a square matrix with G[i][j] = 1 iff there exists an edge between node i and node j
// otherwise 2. (
var G = cola.Descent.createSquareMatrix(n, function () {
return 2;
});
graph.links.forEach(function (e) {
var u = linkAccessor.getSourceIndex(e), v = linkAccessor.getTargetIndex(e);
G[u][v] = G[v][u] = 1;
});
// 3d positions vector
var k = 3;
var x = new Array(k);
for (var i = 0; i < k; ++i) {
x[i] = new Array(n);
for (var j = 0; j < n; ++j) {
x[i][j] = 0;
}
}
var descent = new cola.Descent(x, D);
descent.run(10);
descent.G = G;
camera.position.z = 50;
var xAngle = 0;
var yAngle = 0;
document.onmousedown = mousedownhandler;
document.onmouseup = mouseuphandler;
document.onmousemove = mousemovehandler;
var mouse = {
down: false,
x: 0,
y: 0,
dx: 0,
dy: 0
};
function mousedownhandler(e) {
mouse.down = true;
mouse.x = e.clientX;
mouse.y = e.clientY;
}
function mouseuphandler(e) {
mouse.down = false;
}
function mousemovehandler(e) {
if (mouse.down) {
mouse.dx = e.clientX - mouse.x;
mouse.x = e.clientX;
mouse.dy = e.clientY - mouse.y;
mouse.y = e.clientY;
}
}
var delta = Number.POSITIVE_INFINITY;
var converged = false;
var render = function () {
xAngle += mouse.dx / 100;
yAngle += mouse.dy / 100;
colaObject.rotation.set(yAngle, xAngle, 0);
var s = converged ? 0 : descent.rungeKutta();
if (s != 0 && Math.abs(Math.abs(delta / s) - 1) > 1e-7) {
delta = s;
colaGraph.setNodePositions(descent.x);
colaGraph.update(); // Update all the edge positions
}
else {
converged = true;
}
renderer.render(scene, camera);
requestAnimationFrame(render);
};
render();
});
|
{
"translatorID": "631ff0c7-2e64-4279-a9c9-ad9518d40f2b",
"label": "Stuff.co.nz",
"creator": "Sopheak Hean (University of Waikato, Faculty of Education)",
"target": "^https?://(www\\.)?stuff\\.co\\.nz/",
"minVersion": "2.1.9",
"maxVersion": "",
"priority": 100,
"inRepository": true,
"translatorType": 4,
"browserSupport": "gcsibv",
"lastUpdated": "2014-08-23 05:56:33"
}
/*
Stuff.co.nz Translator- Parses Stuff.co.nz articles and creates Zotero-based metadata
Copyright (C) 2010 Sopheak Hean, University of Waikato, Faculty of Education
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Stuff.co.nz does not have an ISSN because it is not a newspaper publisher.
Stuff.co.nz is a collection of newspaper articles from around the country*/
function detectWeb(doc, url) {
var definePath = '//div[@class="blog_content"]';
var XpathObject = doc.evaluate(definePath, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if(XpathObject){
return "blogPost";
} else {
var definePath = '//div[@class="story_landing"]';
var XpathObject = doc.evaluate(definePath, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if (XpathObject){
return "newspaperArticle";
}
}
}
function scrape(doc, url) {
var type = detectWeb(doc, url);
var splitIntoArray;
var fullName="";
var emptyString =" ";
var firstName, lastName;
/*==========================Blog Post===========================*/
if (type =="blogPost"){
var newItem = new Zotero.Item('blogPost');
newItem.url = doc.location.href;
//newItem.title = "No Title Found";
newItem.publicationTitle = "Stuff.co.nz";
newItem.language = "English";
//Get Author
try { /*Try and Catch if encounter erro */
var blogAuthor = "//div[@id='left_col']/span";
var blogAuthorObject = doc.evaluate(blogAuthor, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if (blogAuthorObject) {
if (blogAuthorObject.textContent.replace(/\s*/g,'') ==""){
newItem.creators =blogAuthorObject.textContent.replace(/\s*/g,'');
}
else{
blogAuthorObject = blogAuthorObject.textContent;
if(blogAuthorObject.match(/[\s\n\r\t]+-[\s\n\r\t]+[a-zA-Z\s\n\r\t]*/g)){
blogAuthorObject = blogAuthorObject.replace(/([\s\n\r\t]+-[\s\n\r\t]+[a-zA-Z\s\n\r\t]*)/g, '').replace(/\bBy \b/g,'');
splitIntoArray = blogAuthorObject.split (" ");
for (var i = 0; i < splitIntoArray.length; i++){
firstName = splitIntoArray[i].substring(0,1).toUpperCase();
lastName = splitIntoArray[i].substring(1).toLowerCase();
fullName += firstName + lastName + emptyString;
}
newItem.creators.push(Zotero.Utilities.cleanAuthor(fullName , "author"));
}
else {
splitIntoArray = blogAuthorObject.replace(/\bBy \b/g,'').split (" ");
for (var i = 0; i < splitIntoArray.length; i++){
firstName = splitIntoArray[i].substring(0,1).toUpperCase();
lastName = splitIntoArray[i].substring(1).toLowerCase();
fullName += firstName + lastName + emptyString;
}
newItem.creators.push(Zotero.Utilities.cleanAuthor(fullName , "author")); }
}
}
} catch (err) {
newItem.creators = [];
}
//Blog title
var blogTitle = url.match(/\/blogs\/([^/]+)/);
if (blogTitle){
newItem.blogTitle = ZU.capitalizeTitle(blogTitle[1].replace(/-/g,' '), true);
}
newItem.shortTitle = doShortTitle(doc,url);
newItem.title= doTitle(doc, url);
newItem.date = doDate(doc, url);
newItem.abstractNote = doAbstract(doc, url);
newItem.websiteType = "Newspaper";
newItem.attachments.push({document: doc, title:"Stuff.co.nz Snapshot"});
newItem.complete();
}
/* ======================Newspaper Article========================*/
else if (type =="newspaperArticle"){
var newItem = new Zotero.Item('newspaperArticle');
newItem.url = url;
//newItem.title = "No Title Found";
//Get extended publisher if there is any then replace with stuff.co.nz
var myPublisher = '//span[@class="storycredit"]';
var myPublisherObject = doc.evaluate(myPublisher , doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if (myPublisherObject) {
var realPublisher = myPublisherObject.textContent;
if (realPublisher.match(/\bBy[\s\n\r\t]+[a-zA-Z\s\r\t\n]*-[\s\n\r\t]*/g)){
realPublisher = realPublisher.replace (/\bBy[\s\n\r\t]+[a-zA-Z\s\r\t\n]*-[\s\n\r\t]*/g, '').replace(/^\s*|\s*$/g, '');
newItem.publicationTitle = realPublisher;
} else {
newItem.publicationTitle = "Stuff.co.nz";
}
} else {
newItem.publicationTitle = "Stuff.co.nz";
}
newItem.language = "English";
//Short Title
newItem.shortTitle = doShortTitle(doc,url);
//get Abstract
newItem.abstractNote = doAbstract(doc, url);
var authorXPath = '//span[@class="storycredit"]';
var authorXPathObject = doc.evaluate(authorXPath, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if (authorXPathObject){
var authorArray = new Array("NZPA", "The Press", "The Dominion Post");
authorXPathObject = authorXPathObject.textContent;
if(authorXPathObject.match(/[\s\n\r\t]+-[\s\n\r\t]+\b[a-zA-Z\s\n\r\t]*|^\s+\bBy\s*/g)){
authorXPathObject = authorXPathObject.replace(/([\s\n\r\t]+-[\s\n\r\t]+\b[a-zA-Z\s\n\r\t]*)|\b.co.nz|\b.com|(-[a-zA-Z0-9]*)/g, '');
var authorString = authorXPathObject.replace(/^\s+\bBy\s*|^\s+\bBY\s*/g, '');
if (authorString.match(/\W\band\W+/g)) {
authorTemp = authorString.replace(/\W\band\W+/g, ', ');
authorArray = authorTemp.split(", ");
} else if (!authorString.match(/\W\band\W+/g)) {
authorArray = authorString.toLowerCase();
}
if( authorArray instanceof Array ) {
for (var i in authorArray){
splitIntoArray = authorArray[i].split (" ");
for (var i = 0; i < splitIntoArray.length; i++){
firstName = splitIntoArray[i].substring(0,1).toUpperCase();
lastName = splitIntoArray[i].substring(1).toLowerCase();
fullName += firstChar + lastChar + emptyString;
}
newItem.creators.push(Zotero.Utilities.cleanAuthor(JoinString, "author"));
}
} else {
if (authorString.match(/\W\bof\W+/g)){
authorTemp = authorString.replace (/\W\bof\W(.*)/g, '');
splitIntoArray = authorTemp.split (" ");
for (var i = 0; i < splitIntoArray.length; i++){
firstName = splitIntoArray[i].substring(0,1).toUpperCase();
lastName = splitIntoArray[i].substring(1).toLowerCase();
fullName += firstChar + lastChar + emptyString;
}
newItem.creators.push(Zotero.Utilities.cleanAuthor(JoinString, "author"));
} else {
splitIntoArray = authorArray.split (" ");
for (var i = 0; i < splitIntoArray.length; i++){
firstName = splitIntoArray[i].substring(0,1).toUpperCase();
lastName = splitIntoArray[i].substring(1).toLowerCase();
fullName += firstName+ lastName + emptyString;
}
newItem.creators.push(Zotero.Utilities.cleanAuthor(fullName, "author"));
}
}
} else {
if(authorXPathObject.match(/[\s\n\r]+/g)){
authorXPathObject = ZU.capitalizeTitle( authorXPathObject.trim(), true ); //.replace(/\s+/g, '-');
newItem.creators.push(ZU.cleanAuthor(authorXPathObject, "author"));
} else {
newItem.creators.push(Zotero.Utilities.cleanAuthor(authorXPathObject , "author"));
}
}
} else {
newItem.creators = [];
}
//Title of the Article
newItem.title= doTitle(doc, url);
//Section of the Article
var current = '//li/a[@class="current"]';
var currentObject = doc.evaluate(current, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if (currentObject){
currentObject = currentObject.textContent;
var articleSection = '//li[@class="mid_nav_item"]/a';
var articleSectionObject = doc.evaluate(articleSection , doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if (articleSectionObject){
articleSectionObject = articleSectionObject .textContent;
switch (articleSectionObject){
case "National":
case "Business":
case "Sport":
case "Politics":
newItem.place= "New Zealand";
newItem.section = currentObject;
break;
case "World":
newItem.place= "World";
newItem.section = currentObject; break;
default:
newItem.section = articleSectionObject;break;
}
}
var SectionType = '//li[@class="current_nav_item"]/a';
var SectionTypeObject = doc.evaluate(SectionType, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if (SectionType){
SectionTypeObject = SectionTypeObject.textContent;
switch (SectionTypeObject) {
case "National":
case "Crime":
case "Education":
case "Health":
case "Politics":
case "Environment":
case "Business":
newItem.place= "New Zealand";
newItem.section = currentObject; break;
case "Opinion":
case "Rugby":
case "Soccer":
case "Cricket":
case "Basketball":
case "Fishing":
case "League":
case "Scoreboard":
case "Football":
case "Golf":
case "Motorsport":
case "Netball":
case "Tennis":
newItem.section ="Sport"; break;
default:
newItem.section = SectionTypeObject; break;
}
}
}
else {
var SectionType = '//li[@class="current_nav_item"]/a';
var SectionTypeObject = doc.evaluate(SectionType, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if (SectionType){
SectionTypeObject = SectionTypeObject.textContent;
switch (SectionTypeObject) {
case "National":
case "Crime":
case "Education":
case "Health":
case "Politics":
case "Environment":
case "Business":
newItem.place= "New Zealand";
newItem.section = SectionTypeObject; break;
default:
newItem.section =SectionTypeObject; break;
}
}
}
//Snapshot of the web page.
newItem.attachments.push({document:doc, title:"Stuff.co.nz Snapshot"});
//Call Do date function to make it cleaner in scape. This way things are easier to follow.
newItem.date = doDate(doc,url);
newItem.complete();
}
}
function doShortTitle(doc, url){
var shortTitle="";
var subTitle = '//div[@id="left_col"]/h2';
var subTitleObject = doc.evaluate(subTitle, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if (subTitleObject){
shortTitle= subTitleObject.textContent.replace(/^\s*|\s*$/g, '');
return shortTitle;
} else {
return shortTitle;
}
}
function doAbstract(doc, url){
var abstractString="";
var a= "//meta[@name='description']";
var abs= doc.evaluate(a, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if (abs){
abstractString = abs.content;
return abstractString;
}
return abstractString;
}
function doTitle(doc, url){
var temp="";
var getTitle = '//div[@id="left_col"]//h1';
var getTitleObject = doc.evaluate(getTitle, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
if (getTitleObject) {
var temp=getTitleObject.textContent.replace(/^\s*|\s*$/g, '');
return temp;
}
return temp;
}
function doDate(doc, url){
var dateXpath = "//div[@id='toolbox']/div[3]";
var dateXpathObject = doc.evaluate(dateXpath, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
try {
if (dateXpathObject){
var storeDateValue = dateXpathObject.textContent.replace(/\b(Last updated )\d{0,9}:\d{0,9} /g,'');
var ArrayDate = storeDateValue.split('/');
var emptyString = " ";
var comma = ", ";
var DateString;
var ArrayMonth = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec");
var ArrayNumber = new Array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
for (var i=0; i <ArrayNumber.length; i++){
if(ArrayDate[1] ==ArrayNumber[i]) {
ArrayNumber[i] = ArrayMonth[i];
var month = ArrayNumber[i] + emptyString;
}
DateString = month + ArrayDate[0] + comma + ArrayDate[2];
}
return DateString;
} else {
DateString = "";
return DateString;
}
}catch (err) {
DateString = "";
}
return DateString;
}
function doWeb(doc, url) {
scrape(doc, url);
}
/** BEGIN TEST CASES **/
var testCases = [
{
"type": "web",
"url": "http://www.stuff.co.nz/national/politics/campaign-trail/5967550/Green-party-link-to-billboard-attacks",
"items": [
{
"itemType": "newspaperArticle",
"title": "Green party link to billboard attacks",
"creators": [
{
"firstName": "Danya",
"lastName": "Levy",
"creatorType": "author"
}
],
"date": "Nov 15, 2011",
"abstractNote": "The man who coordinated the vandalism of 700 National billboards says it was an attempt at \"freedom of expression.\"",
"language": "English",
"libraryCatalog": "Stuff.co.nz",
"place": "New Zealand",
"publicationTitle": "Stuff.co.nz",
"section": "Politics",
"url": "http://www.stuff.co.nz/national/politics/campaign-trail/5967550/Green-party-link-to-billboard-attacks",
"attachments": [
{
"title": "Stuff.co.nz Snapshot"
}
],
"tags": [],
"notes": [],
"seeAlso": []
}
]
}
]
/** END TEST CASES **/
|
var GetRight = require('../bounds/GetRight');
var GetTop = require('../bounds/GetTop');
var SetLeft = require('../bounds/SetLeft');
var SetTop = require('../bounds/SetTop');
var ToRightTop = function (gameObject, parent, offsetX, offsetY)
{
if (offsetX === undefined) { offsetX = 0; }
if (offsetY === undefined) { offsetY = 0; }
SetLeft(gameObject, GetRight(parent) + offsetX);
SetTop(gameObject, GetTop(parent) - offsetY);
return gameObject;
};
module.exports = ToRightTop;
|
var data = {
"width": 633,
"height": 506,
"offX": 0,
"offY": 0,
"sourceW": 633,
"sourceH": 506,
"frames": [
{
"file": "keweizhua_0.png"
},
{
"file": "keweizhua_2.png"
},
{
"file": "keweizhua_3.png"
}
],
"animations": {
"diff": [0,1,2]
}
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M15 5H7v5.6c0 .14.64 3.4.64 3.4h8.72s.64-3.26.64-3.4V10h-2V5zm-1 5H8V7h6v3z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M7 20c0 .55.45 1 1 1h8c.55 0 1-.45 1-1v-3H7v3zM18 7c-.55 0-1 .45-1 1V5c0-1.1-.9-2-2-2H7c-1.1 0-2 .9-2 2v5.8c0 .13.01.26.04.39l.8 4c.09.47.5.8.98.8H17c.55 0 1.09-.44 1.2-.98l.77-3.83c.02-.12.03-.25.03-.38V8c0-.55-.45-1-1-1zm-1 3.6c0 .13-.64 3.4-.64 3.4H7.64S7 10.74 7 10.6V5h8v5h2v.6z"
}, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M8 7h6v3H8z"
}, "2")], 'SportsMmaTwoTone');
exports.default = _default;
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "m21.41 11.41-8.83-8.83c-.37-.37-.88-.58-1.41-.58H4c-1.1 0-2 .9-2 2v7.17c0 .53.21 1.04.59 1.41l8.83 8.83c.78.78 2.05.78 2.83 0l7.17-7.17c.78-.78.78-2.04-.01-2.83zM6.5 8C5.67 8 5 7.33 5 6.5S5.67 5 6.5 5 8 5.67 8 6.5 7.33 8 6.5 8z"
}), 'Sell');
|
/* globals Stats, dat, AMI*/
var LoadersVolume = AMI.default.Loaders.Volume;
var CamerasOrthographic = AMI.default.Cameras.Orthographic;
var ControlsOrthographic = AMI.default.Controls.TrackballOrtho;
var HelpersLut = AMI.default.Helpers.Lut;
var HelpersStack = AMI.default.Helpers.Stack;
// Shaders
// Data
var ShadersDataUniforms = AMI.default.Shaders.DataUniform;
var ShadersDataFragment = AMI.default.Shaders.DataFragment;
var ShadersDataVertex = AMI.default.Shaders.DataVertex;
// Layer
var ShadersLayerUniforms = AMI.default.Shaders.LayerUniform;
var ShadersLayerFragment = AMI.default.Shaders.LayerFragment;
var ShadersLayerVertex = AMI.default.Shaders.LayerVertex;
// standard global variables
var controls;
var renderer;
var camera;
var statsyay;
var threeD;
//
var sceneLayer0TextureTarget;
var sceneLayer1TextureTarget;
//
var sceneLayer0;
//
var lutLayer0;
var sceneLayer1;
var meshLayer1;
var uniformsLayer1;
var materialLayer1;
var lutLayer1;
var sceneLayerMix;
var meshLayerMix;
var uniformsLayerMix;
var materialLayerMix;
var layerMix = {
opacity1: 1.0,
};
/**
* Init the scene
*/
function init() {
/**
* Animation loop
*/
function animate() {
// render
controls.update();
// render first layer offscreen
renderer.render(sceneLayer0, camera, sceneLayer0TextureTarget, true);
// render second layer offscreen
renderer.render(sceneLayer1, camera, sceneLayer1TextureTarget, true);
// mix the layers and render it ON screen!
renderer.render(sceneLayerMix, camera);
statsyay.update();
// request new frame
requestAnimationFrame(function() {
animate();
});
}
// renderer
threeD = document.getElementById('container');
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
});
renderer.setSize(threeD.clientWidth, threeD.clientHeight);
renderer.setClearColor(0x607D8B, 1);
threeD.appendChild(renderer.domElement);
// stats
statsyay = new Stats();
threeD.appendChild(statsyay.domElement);
// scene
sceneLayer0 = new THREE.Scene();
sceneLayer1 = new THREE.Scene();
sceneLayerMix = new THREE.Scene();
// render to texture!!!!
sceneLayer0TextureTarget = new THREE.WebGLRenderTarget(
threeD.clientWidth,
threeD.clientHeight,
{minFilter: THREE.LinearFilter,
magFilter: THREE.NearestFilter,
format: THREE.RGBAFormat,
});
sceneLayer1TextureTarget = new THREE.WebGLRenderTarget(
threeD.clientWidth,
threeD.clientHeight,
{minFilter: THREE.LinearFilter,
magFilter: THREE.NearestFilter,
format: THREE.RGBAFormat,
});
// camera
camera = new CamerasOrthographic(
threeD.clientWidth / -2, threeD.clientWidth / 2,
threeD.clientHeight / 2, threeD.clientHeight / -2,
0.1, 10000);
// controls
controls = new ControlsOrthographic(camera, threeD);
controls.staticMoving = true;
controls.noRotate = true;
camera.controls = controls;
animate();
}
// init threeJS...
init();
var data = [
'000183.dcm', '000219.dcm', '000117.dcm',
'000240.dcm', '000033.dcm', '000060.dcm',
'000211.dcm', '000081.dcm', '000054.dcm',
'000090.dcm', '000042.dcm', '000029.dcm',
'000239.dcm', '000226.dcm', '000008.dcm',
'000128.dcm', '000089.dcm', '000254.dcm',
'000208.dcm', '000047.dcm', '000067.dcm',
];
var rawgit =
'https://cdn.rawgit.com/FNNDSC/data/master/dicom/andrei_abdomen/';
var dataFullPath = data.map(function(v) {
return rawgit + 'data/' + v;
});
var labelmap = [
'000000.dcm',
];
var labelmapFullPath = labelmap.map(function(v) {
return rawgit + 'segmentation/' + v;
});
var files = dataFullPath.concat(labelmapFullPath);
// load sequence for each file
// instantiate the loader
// it loads and parses the dicom image
var loader = new LoadersVolume(threeD);
/**
* Build GUI
*/
function buildGUI(stackHelper) {
/**
* Update Layer 1
*/
function updateLayer1() {
// update layer1 geometry...
if (meshLayer1) {
// dispose geometry first
meshLayer1.geometry.dispose();
meshLayer1.geometry = stackHelper.slice.geometry;
meshLayer1.geometry.verticesNeedUpdate = true;
}
}
/**
* Update layer mix
*/
function updateLayerMix() {
// update layer1 geometry...
if (meshLayerMix) {
sceneLayerMix.remove(meshLayerMix);
meshLayerMix.material.dispose();
meshLayerMix.material = null;
meshLayerMix.geometry.dispose();
meshLayerMix.geometry = null;
// add mesh in this scene with right shaders...
meshLayerMix = new THREE.Mesh(
stackHelper.slice.geometry, materialLayerMix);
// go the LPS space
meshLayerMix.applyMatrix(stackHelper.stack._ijk2LPS);
sceneLayerMix.add(meshLayerMix);
}
}
var stack = stackHelper.stack;
var gui = new dat.GUI({
autoPlace: false,
});
var customContainer = document.getElementById('my-gui-container');
customContainer.appendChild(gui.domElement);
var layer0Folder = gui.addFolder('CT');
layer0Folder.add(stackHelper.slice, 'invert');
var lutUpdate = layer0Folder.add(
stackHelper.slice, 'lut', lutLayer0.lutsAvailable());
lutUpdate.onChange(function(value) {
lutLayer0.lut = value;
stackHelper.slice.lutTexture = lutLayer0.texture;
});
var indexUpdate = layer0Folder.add(
stackHelper, 'index', 0, stack.dimensionsIJK.z - 1).step(1).listen();
indexUpdate.onChange(function() {
updateLayer1();
updateLayerMix();
});
layer0Folder.add(
stackHelper.slice, 'interpolation', 0, 1).step(1).listen();
layer0Folder.open();
// layer mix folder
var layerMixFolder = gui.addFolder('Segmentation');
var opacityLayerMix1 = layerMixFolder.add(
layerMix, 'opacity1', 0, 1).step(0.01);
opacityLayerMix1.onChange(function(value) {
uniformsLayerMix.uOpacity1.value = value;
});
layerMixFolder.open();
// hook up callbacks
controls.addEventListener('OnScroll', function(e) {
if (e.delta > 0) {
if (stackHelper.index >= stack.dimensionsIJK.z - 1) {
return false;
}
stackHelper.index += 1;
} else {
if (stackHelper.index <= 0) {
return false;
}
stackHelper.index -= 1;
}
updateLayer1();
updateLayerMix();
});
updateLayer1();
updateLayerMix();
/**
* Handle window resize
*/
function onWindowResize() {
var threeD = document.getElementById('container');
camera.canvas = {
width: threeD.clientWidth,
height: threeD.clientHeight,
};
camera.fitBox(2);
renderer.setSize(threeD.clientWidth, threeD.clientHeight);
}
window.addEventListener('resize', onWindowResize, false);
onWindowResize();
}
/**
* Handle series
*/
function handleSeries() {
//
//
// first stack of first series
var mergedSeries = loader.data[0].mergeSeries(loader.data);
var stack = mergedSeries[0].stack[0];
var stack2 = mergedSeries[1].stack[0];
loader.free();
loader = null;
if(stack.modality === 'SEG') {
stack = mergedSeries[0].stack[0];
stack2 = mergedSeries[1].stack[0];
}
var stackHelper = new HelpersStack(stack);
stackHelper.bbox.visible = false;
stackHelper.border.visible = false;
stackHelper.index = 10;
sceneLayer0.add(stackHelper);
//
//
// create labelmap....
// we only care about the geometry....
// get first stack from series
// prepare it
// * ijk2LPS transforms
// * Z spacing
// * etc.
//
stack2.prepare();
// pixels packing for the fragment shaders now happens there
stack2.pack();
var textures2 = [];
for (var m = 0; m < stack2._rawData.length; m++) {
var tex = new THREE.DataTexture(
stack2.rawData[m],
stack2.textureSize,
stack2.textureSize,
stack2.textureType,
THREE.UnsignedByteType,
THREE.UVMapping,
THREE.ClampToEdgeWrapping,
THREE.ClampToEdgeWrapping,
THREE.NearestFilter,
THREE.NearestFilter);
tex.needsUpdate = true;
tex.flipY = true;
textures2.push(tex);
}
// create material && mesh then add it to sceneLayer1
uniformsLayer1 = ShadersDataUniforms.uniforms();
uniformsLayer1.uTextureSize.value = stack2.textureSize;
uniformsLayer1.uTextureContainer.value = textures2;
uniformsLayer1.uWorldToData.value = stack2.lps2IJK;
uniformsLayer1.uNumberOfChannels.value = stack2.numberOfChannels;
uniformsLayer1.uPixelType.value = stack2.pixelType;
uniformsLayer1.uBitsAllocated.value = stack2.bitsAllocated;
uniformsLayer1.uWindowCenterWidth.value =
[stack2.windowCenter, stack2.windowWidth];
uniformsLayer1.uRescaleSlopeIntercept.value =
[stack2.rescaleSlope, stack2.rescaleIntercept];
uniformsLayer1.uDataDimensions.value = [stack2.dimensionsIJK.x,
stack2.dimensionsIJK.y,
stack2.dimensionsIJK.z];
uniformsLayer1.uInterpolation.value = 0;
// generate shaders on-demand!
var fs = new ShadersDataFragment(uniformsLayer1);
var vs = new ShadersDataVertex();
materialLayer1 = new THREE.ShaderMaterial(
{side: THREE.DoubleSide,
uniforms: uniformsLayer1,
vertexShader: vs.compute(),
fragmentShader: fs.compute(),
});
// add mesh in this scene with right shaders...
meshLayer1 = new THREE.Mesh(stackHelper.slice.geometry, materialLayer1);
// go the LPS space
meshLayer1.applyMatrix(stack._ijk2LPS);
sceneLayer1.add(meshLayer1);
// Create the Mix layer
uniformsLayerMix = ShadersLayerUniforms.uniforms();
uniformsLayerMix.uTextureBackTest0.value = sceneLayer0TextureTarget.texture;
uniformsLayerMix.uTextureBackTest1.value = sceneLayer1TextureTarget.texture;
let fls = new ShadersLayerFragment(uniformsLayerMix);
let vls = new ShadersLayerVertex();
materialLayerMix = new THREE.ShaderMaterial(
{side: THREE.DoubleSide,
uniforms: uniformsLayerMix,
vertexShader: vls.compute(),
fragmentShader: fls.compute(),
transparent: true,
});
// add mesh in this scene with right shaders...
meshLayerMix = new THREE.Mesh(stackHelper.slice.geometry, materialLayer1);
// go the LPS space
meshLayerMix.applyMatrix(stack._ijk2LPS);
sceneLayerMix.add(meshLayerMix);
//
// set camera
var worldbb = stack.worldBoundingBox();
var lpsDims = new THREE.Vector3(
worldbb[1] - worldbb[0],
worldbb[3] - worldbb[2],
worldbb[5] - worldbb[4]
);
// box: {halfDimensions, center}
var box = {
center: stack.worldCenter().clone(),
halfDimensions:
new THREE.Vector3(lpsDims.x + 10, lpsDims.y + 10, lpsDims.z + 10),
};
// init and zoom
var canvas = {
width: threeD.clientWidth,
height: threeD.clientHeight,
};
camera.directions = [stack.xCosine, stack.yCosine, stack.zCosine];
camera.box = box;
camera.canvas = canvas;
camera.update();
camera.fitBox(2);
// CREATE LUT
lutLayer0 = new HelpersLut(
'my-lut-canvases-l0',
'default',
'linear',
[[0, 0, 0, 0], [1, 1, 1, 1]],
[[0, 1], [1, 1]]);
lutLayer0.luts = HelpersLut.presetLuts();
lutLayer1 = new HelpersLut(
'my-lut-canvases-l1',
'default',
'linear',
stack2.segmentationLUT,
stack2.segmentationLUTO,
true);
uniformsLayer1.uLut.value = 1;
uniformsLayer1.uTextureLUT.value = lutLayer1.texture;
buildGUI(stackHelper);
}
loader.load(files)
.then(function() {
handleSeries();
})
.catch(function(error) {
window.console.log('oops... something went wrong...');
window.console.log(error);
});
|
export default {
extensions: ['ts'],
require: ['ts-node/register']
};
|
'use strict';
dragula([single1], { removeOnSpill: true }).on('remove', function (el) {
alert('dropped!');
});
|
/* */
var ElementType = require("domelementtype");
var re_whitespace = /\s+/g;
var NodePrototype = require("./lib/node");
var ElementPrototype = require("./lib/element");
function DomHandler(callback, options, elementCB) {
if (typeof callback === "object") {
elementCB = options;
options = callback;
callback = null;
} else if (typeof options === "function") {
elementCB = options;
options = defaultOpts;
}
this._callback = callback;
this._options = options || defaultOpts;
this._elementCB = elementCB;
this.dom = [];
this._done = false;
this._tagStack = [];
this._parser = this._parser || null;
}
var defaultOpts = {
normalizeWhitespace: false,
withStartIndices: false
};
DomHandler.prototype.onparserinit = function(parser) {
this._parser = parser;
};
DomHandler.prototype.onreset = function() {
DomHandler.call(this, this._callback, this._options, this._elementCB);
};
DomHandler.prototype.onend = function() {
if (this._done)
return;
this._done = true;
this._parser = null;
this._handleCallback(null);
};
DomHandler.prototype._handleCallback = DomHandler.prototype.onerror = function(error) {
if (typeof this._callback === "function") {
this._callback(error, this.dom);
} else {
if (error)
throw error;
}
};
DomHandler.prototype.onclosetag = function() {
var elem = this._tagStack.pop();
if (this._elementCB)
this._elementCB(elem);
};
DomHandler.prototype._addDomElement = function(element) {
var parent = this._tagStack[this._tagStack.length - 1];
var siblings = parent ? parent.children : this.dom;
var previousSibling = siblings[siblings.length - 1];
element.next = null;
if (this._options.withStartIndices) {
element.startIndex = this._parser.startIndex;
}
if (this._options.withDomLvl1) {
element.__proto__ = element.type === "tag" ? ElementPrototype : NodePrototype;
}
if (previousSibling) {
element.prev = previousSibling;
previousSibling.next = element;
} else {
element.prev = null;
}
siblings.push(element);
element.parent = parent || null;
};
DomHandler.prototype.onopentag = function(name, attribs) {
var element = {
type: name === "script" ? ElementType.Script : name === "style" ? ElementType.Style : ElementType.Tag,
name: name,
attribs: attribs,
children: []
};
this._addDomElement(element);
this._tagStack.push(element);
};
DomHandler.prototype.ontext = function(data) {
var normalize = this._options.normalizeWhitespace || this._options.ignoreWhitespace;
var lastTag;
if (!this._tagStack.length && this.dom.length && (lastTag = this.dom[this.dom.length - 1]).type === ElementType.Text) {
if (normalize) {
lastTag.data = (lastTag.data + data).replace(re_whitespace, " ");
} else {
lastTag.data += data;
}
} else {
if (this._tagStack.length && (lastTag = this._tagStack[this._tagStack.length - 1]) && (lastTag = lastTag.children[lastTag.children.length - 1]) && lastTag.type === ElementType.Text) {
if (normalize) {
lastTag.data = (lastTag.data + data).replace(re_whitespace, " ");
} else {
lastTag.data += data;
}
} else {
if (normalize) {
data = data.replace(re_whitespace, " ");
}
this._addDomElement({
data: data,
type: ElementType.Text
});
}
}
};
DomHandler.prototype.oncomment = function(data) {
var lastTag = this._tagStack[this._tagStack.length - 1];
if (lastTag && lastTag.type === ElementType.Comment) {
lastTag.data += data;
return;
}
var element = {
data: data,
type: ElementType.Comment
};
this._addDomElement(element);
this._tagStack.push(element);
};
DomHandler.prototype.oncdatastart = function() {
var element = {
children: [{
data: "",
type: ElementType.Text
}],
type: ElementType.CDATA
};
this._addDomElement(element);
this._tagStack.push(element);
};
DomHandler.prototype.oncommentend = DomHandler.prototype.oncdataend = function() {
this._tagStack.pop();
};
DomHandler.prototype.onprocessinginstruction = function(name, data) {
this._addDomElement({
name: name,
data: data,
type: ElementType.Directive
});
};
module.exports = DomHandler;
|
import defs from '../../_core/defs';
import seempleError from '../../_helpers/seempleerror';
import processPush from './processpush';
import processUnshift from './processunshift';
import processRecreate from './processrecreate';
import processSort from './processsort';
import processRemove from './processremove';
import processRerender from './processrerender';
import processSpliceAdd from './processspliceadd';
// makes possible to render array items based on a name of called method
export default function processRendering({
self,
eventOptions
}) {
const { method, added, removed } = eventOptions;
// nodes object always exist at Seemple instances
const container = self.nodes.container || self.nodes.sandbox;
const selfDef = defs.get(self);
if (!container) {
return;
}
switch (method) {
case 'fill':
case 'copyWithin':
throw seempleError('array:method_compat_renderer', { method });
case 'push':
processPush({
self,
selfDef,
eventOptions,
container
});
break;
case 'unshift':
processUnshift({
self,
selfDef,
eventOptions,
container
});
break;
case 'pull':
case 'pop':
case 'shift':
processRemove({
self,
selfDef,
eventOptions,
container
});
break;
case 'sort':
case 'reverse':
processSort({
self,
selfDef,
eventOptions,
container
});
break;
case 'rerender':
processRerender({
self,
selfDef,
eventOptions,
container
});
break;
case 'recreate':
processRecreate({
self,
selfDef,
eventOptions,
container
});
break;
case 'splice':
if (added.length) {
processSpliceAdd({
self,
selfDef,
eventOptions,
container
});
}
if (removed.length) {
processRemove({
self,
selfDef,
eventOptions,
container
});
}
break;
default:
}
}
|
var cache = {
getUrl: function () {
return false;
}
};
module.exports = cache;
|
import React from 'react'
import Icon from 'react-icon-base'
const MdLocalHotel = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m31.6 11.6c3.7 0 6.8 3.1 6.8 6.8v15h-3.4v-5h-30v5h-3.4v-25h3.4v15h13.4v-11.8h13.2z m-20 10c-2.7 0-5-2.2-5-5s2.3-5 5-5 5 2.3 5 5-2.2 5-5 5z"/></g>
</Icon>
)
export default MdLocalHotel
|
/*
* Copyright (c) 2013-2014 node-coap contributors.
*
* node-coap is licensed under an MIT +no-false-attribs license.
* All rights not explicitly granted in the MIT license are reserved.
* See the included LICENSE file for more details.
*/
var parameters = require('./parameters')
, util = require('util')
, EventEmitter = require('events').EventEmitter
function RetrySend(sock, port, host) {
if (!(this instanceof RetrySend))
return new RetrySend(port, host)
var that = this
this._sock = sock
this._port = port || parameters.coapPort
this._host = host
this._sendAttemp = 0
this._currentTime = parameters.ackTimeout * (1 + (parameters.ackRandomFactor - 1) * Math.random()) * 1000
this._bOff = function() {
that._currentTime = that._currentTime * 2
that._send()
}
}
util.inherits(RetrySend, EventEmitter)
RetrySend.prototype._send = function(avoidBackoff) {
var that = this
this._sock.send(this._message, 0, this._message.length,
this._port, this._host, function(err, bytes) {
that.emit('sent', err, bytes)
if (err) {
that.emit('error', err)
}
})
if (!avoidBackoff && ++this._sendAttemp <= parameters.maxRetransmit)
this._bOffTimer = setTimeout(this._bOff, this._currentTime)
this.emit('sending', this._message)
}
RetrySend.prototype.send = function(message, avoidBackoff) {
var that = this
this._message = message
this._send(avoidBackoff)
if (!avoidBackoff)
this._timer = setTimeout(function() {
var err = new Error('No reply in ' + parameters.exchangeLifetime + 's')
err.retransmitTimeout = parameters.exchangeLifetime;
that.emit('error', err)
}, parameters.exchangeLifetime * 1000)
}
RetrySend.prototype.reset = function() {
clearTimeout(this._timer)
clearTimeout(this._bOffTimer)
}
module.exports = RetrySend
|
;modjewel.define("weinre/target/ElementHighlighter", function(require, exports, module) { // Generated by CoffeeScript 1.3.3
var ElementHighlighter, canvasAvailable, currentHighlighterElement, fromPx, getMetricsForElement, highlighterClass, supportsCanvas;
canvasAvailable = null;
highlighterClass = null;
currentHighlighterElement = null;
module.exports = ElementHighlighter = (function() {
ElementHighlighter.create = function() {
if (highlighterClass == null) {
highlighterClass = require('./ElementHighlighterDivs2');
}
return new highlighterClass();
};
function ElementHighlighter() {
this.hElement = this.createHighlighterElement();
this.hElement.__weinreHighlighter = true;
this.hElement.style.display = "none";
this.hElement.style.zIndex = 10 * 1000 * 1000;
if (currentHighlighterElement) {
document.body.removeChild(currentHighlighterElement);
}
currentHighlighterElement = this.hElement;
document.body.appendChild(this.hElement);
}
ElementHighlighter.prototype.on = function(element) {
if (null === element) {
return;
}
if (element.nodeType !== Node.ELEMENT_NODE) {
return;
}
this.redraw(getMetricsForElement(element));
return this.hElement.style.display = "block";
};
ElementHighlighter.prototype.off = function() {
return this.hElement.style.display = "none";
};
return ElementHighlighter;
})();
getMetricsForElement = function(element) {
var cStyle, el, left, metrics, top;
metrics = {};
left = 0;
top = 0;
el = element;
while (true) {
left += el.offsetLeft;
top += el.offsetTop;
if (!(el = el.offsetParent)) {
break;
}
}
metrics.x = left;
metrics.y = top;
cStyle = document.defaultView.getComputedStyle(element);
metrics.width = element.offsetWidth;
metrics.height = element.offsetHeight;
metrics.marginLeft = fromPx(cStyle["margin-left"] || cStyle["marginLeft"]);
metrics.marginRight = fromPx(cStyle["margin-right"] || cStyle["marginRight"]);
metrics.marginTop = fromPx(cStyle["margin-top"] || cStyle["marginTop"]);
metrics.marginBottom = fromPx(cStyle["margin-bottom"] || cStyle["marginBottom"]);
metrics.borderLeft = fromPx(cStyle["border-left-width"] || cStyle["borderLeftWidth"]);
metrics.borderRight = fromPx(cStyle["border-right-width"] || cStyle["borderRightWidth"]);
metrics.borderTop = fromPx(cStyle["border-top-width"] || cStyle["borderTopWidth"]);
metrics.borderBottom = fromPx(cStyle["border-bottom-width"] || cStyle["borderBottomWidth"]);
metrics.paddingLeft = fromPx(cStyle["padding-left"] || cStyle["paddingLeft"]);
metrics.paddingRight = fromPx(cStyle["padding-right"] || cStyle["paddingRight"]);
metrics.paddingTop = fromPx(cStyle["padding-top"] || cStyle["paddingTop"]);
metrics.paddingBottom = fromPx(cStyle["padding-bottom"] || cStyle["paddingBottom"]);
metrics.x -= metrics.marginLeft;
metrics.y -= metrics.marginTop;
return metrics;
};
fromPx = function(string) {
return parseInt(string.replace(/px$/, ""));
};
supportsCanvas = function() {
var element;
element = document.createElement('canvas');
if (!element.getContext) {
return false;
}
if (element.getContext('2d')) {
return true;
}
return false;
};
require("../common/MethodNamer").setNamesForClass(module.exports);
});
|
import { readFileSync, writeFileSync } from 'fs';
import { join } from 'path';
import glob from 'glob';
import { transformFileSync } from 'babel-core';
const componentFilesPattern = join(
__dirname, '..', '..', 'src', 'frontend', 'bundles', '*', 'components', '*', '*.js'
);
const localeFilesPattern = join(
__dirname, '..', '..', 'src', 'locale', '*.json'
);
const babelOptions = {
stage: 0,
plugins: ['react-intl'],
};
const componentFiles = glob.sync(componentFilesPattern);
const localeFiles = glob.sync(localeFilesPattern);
const messages = componentFiles
.map((file) => ({
file,
babel: transformFileSync(file, babelOptions),
}))
.filter(result => result.babel.metadata['react-intl'])
.reduce((acc, result) => {
result.babel.metadata['react-intl'].messages.forEach((message) => {
if (acc[message.id]) {
throw new Error(`Duplicate message id "${message.id}" in "${result.file}"`);
}
acc[message.id] = message.defaultMessage;
});
return acc;
}, {});
localeFiles.forEach((file) => {
const locale = Object.assign(
{},
messages,
JSON.parse(readFileSync(file).toString())
);
writeFileSync(file, JSON.stringify(locale, null, 2) + '\n');
});
|
'use strict'
|
var chai = require('chai');
var should = chai.should();
var coordinatesRequest = require('../../../lib/model/request/coordinatesRequest');
describe('coordinatesRequest model test', function () {
var lat = 'lat';
var lon = 'lon';
it('should create model', function (done) {
var coordinatesRequestModel = new coordinatesRequest.CoordinatesRequest(
lat,
lon
);
should.exist(coordinatesRequestModel);
coordinatesRequestModel.lat.should.be.equal(lat);
coordinatesRequestModel.lon.should.be.equal(lon);
done();
});
it('should create model by builder', function (done) {
var coordinatesRequestModel = new coordinatesRequest.CoordinatesRequestBuilder()
.withLat(lat)
.withLon(lon)
.build();
should.exist(coordinatesRequestModel);
coordinatesRequestModel.lat.should.be.equal(lat);
coordinatesRequestModel.lon.should.be.equal(lon);
done();
});
});
|
import consoleFunc from './internal/consoleFunc';
/**
* Logs the result of an `async` function to the `console`. Only works in
* Node.js or in browsers that support `console.log` and `console.error` (such
* as FF and Chrome). If multiple arguments are returned from the async
* function, `console.log` is called on each argument in order.
*
* @name log
* @static
* @memberOf module:Utils
* @method
* @category Util
* @param {Function} function - The function you want to eventually apply all
* arguments to.
* @param {...*} arguments... - Any number of arguments to apply to the function.
* @example
*
* // in a module
* var hello = function(name, callback) {
* setTimeout(function() {
* callback(null, 'hello ' + name);
* }, 1000);
* };
*
* // in the node repl
* node> async.log(hello, 'world');
* 'hello world'
*/
export default consoleFunc('log');
|
/**
Copyright 2011 Red Hat, Inc.
This software is licensed to you under the GNU General Public
License as published by the Free Software Foundation; either version
2 of the License (GPLv2) or (at your option) any later version.
There is NO WARRANTY for this software, express or implied,
including the implied warranties of MERCHANTABILITY,
NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
have received a copy of GPLv2 along with this software; if not, see
http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*/
var CUI = CUI ? CUI : {};
CUI.Login = {};
$(document).ready(function() {
CUI.Login.Events.register();
$('#password_link').click(function(e){
e.preventDefault();
$('.card#password_reset').animate({ 'left' : '0px' }, 'slow').css('z-index', 1);
});
$('#username_link').click(function(e){
e.preventDefault();
$('.card#username_recovery').animate({ 'left' : '0px' }, 'slow').css('z-index', 1);
});
$('#password_reset_return_link').click(function(e){
e.preventDefault();
$('.card#password_reset').animate({ 'left' : '-360px' }, 'slow', function(){
$(this).css('z-index', -1);
});
});
$('#username_recovery_return_link').click(function(e){
e.preventDefault();
$('.card#username_recovery').animate({ 'left' : '-360px' }, 'slow', function(){
$(this).css('z-index', -1);
});
});
$('#login_btn').click(function(){
CUI.Login.Actions.toggleSpinner();
});
$(document).bind("ajax:complete",
function(evt, data, status, xhr){
if(status == "success") {
$('form .spinner').fadeOut('fast');
}
}
);
$('#username').focus();
});
CUI.Login.Actions = (function($){
var show_password = function(input_field, input_reveal_field, show){
var password;
if( show ){
password = input_field.val();
input_field.hide();
input_reveal_field.val(password).show();
} else {
password = input_reveal_field.val();
input_reveal_field.hide();
input_field.val(password).show();
}
},
add_hash_input = function(parent){
if (window.location.hash != "") {
$('<input>').attr({
type: 'hidden',
id: 'hash_anchor',
name: 'hash_anchor',
value: window.location.hash
}).appendTo(parent);
}
},
interstitial_switcher_animation = function(num_orgs, redir_path){
if(parseInt(num_orgs, 10) > 1){
$('#interstitial').trigger({type:'login'});
} else if(redir_path){
CUI.Login.Actions.toggleSpinner();
window.location.href = redir_path;
} else {
window.location.reload();
}
},
toggleSpinner = function(){
$('#login_form .spinner').fadeToggle('fast');
},
redirecter = function(url){
if ($.browser.msie){
window.location = url;
} else {
window.location.href = url;
}
};
return {
show_password : show_password,
add_hash_input : add_hash_input,
interstitial_switcher_animation : interstitial_switcher_animation,
redirecter : redirecter,
toggleSpinner : toggleSpinner
};
})(jQuery);
CUI.Login.Events = (function($, actions){
var register = function(){
$('#reveal').change(function(){
actions.show_password($('#password-input'), $('#password-input-reveal'), $(this).is(':checked'));
});
$('#login_form').live('submit', function(e) {
actions.add_hash_input(this);
});
//if you have an #interstitial container for an interstitial, this will function. otherwise it won't.
// this is for alchemy
var interstitial = $('#interstitial');
if (interstitial.length){
$('#interstitial').bind('login', function(event){
CUI.Login.Actions.toggleSpinner();
interstitial.animate({ 'left' : '0px' }, 'slow').css('z-index', 1);
});
}
};
return {
register : register
}
})(jQuery, CUI.Login.Actions);
|
/*global define*/
define(['jquery', 'underscore', 'orotranslation/js/translator', './abstract-action'
], function ($, _, __, AbstractAction) {
'use strict';
/**
* Allows to export grid data
*
* @export orodatagrid/js/datagrid/action/export-action
* @class orodatagrid.datagrid.action.ExportAction
* @extends orodatagrid.datagrid.action.AbstractAction
*/
return AbstractAction.extend({
/** @property oro.PageableCollection */
collection: undefined,
/** @property {orodatagrid.datagrid.ActionLauncher} */
launcher: null,
/**
* {@inheritdoc}
*/
initialize: function (options) {
this.launcherOptions = {
runAction: false
};
this.route = 'oro_datagrid_export_action';
this.route_parameters = {
gridName: options.datagrid.name
};
this.collection = options.datagrid.collection;
AbstractAction.prototype.initialize.apply(this, arguments);
},
/**
* {@inheritdoc}
*/
createLauncher: function (options) {
this.launcher = AbstractAction.prototype.createLauncher.apply(this, arguments);
// update 'href' attribute for each export type
this.listenTo(this.launcher, 'expand', _.bind(function (launcher) {
var fetchData = this.collection.getFetchData();
_.each(launcher.$el.find('.dropdown-menu a'), function (el) {
var $el = $(el);
$el.attr('href', this.getLink(_.extend({format: $el.data('key')}, fetchData)));
}, this);
}, this));
return this.launcher;
}
});
});
|
/*!
* Bootstrap-select v1.7.5 (http://silviomoreto.github.io/bootstrap-select)
*
* Copyright 2013-2015 bootstrap-select
* Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(jQuery);
}
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Nessuna selezione',
noneResultsText: 'Nessun risultato per {0}',
countSelectedText: 'Selezionati {0} di {1}',
maxOptionsText: ['Limite raggiunto ({n} {var} max)', 'Limite del gruppo raggiunto ({n} {var} max)', ['elementi', 'elemento']],
multipleSeparator: ', '
};
})(jQuery);
}));
|
var fnObj = {};
var ACTIONS = axboot.actionExtend(fnObj, {
PAGE_SEARCH: function (caller, act, data) {
axboot.ajax({
type: "GET",
url: ["commonCodes"],
data: caller.searchView.getData(),
callback: function (res) {
caller.gridView01.setData(res);
}
});
return false;
},
PAGE_CLOSE: function (caller, act, data) {
parent.axboot.modal.close();
},
PAGE_SAVE: function (caller, act, data) {
axboot
.call({
type: "PUT",
url: ["commonCodes"],
data: JSON.stringify((function () {
var saveList = [].concat(caller.gridView01.getData("modified"));
saveList = saveList.concat(caller.gridView01.getData("deleted"));
return saveList;
})()),
callback: function (res) {
},
options: {}
})
.done(function () {
parent.axboot.modal.callback("saved");
parent.axToast.push(GROUP_NM + " 정보가 저장되었습니다");
});
},
ITEM_ADD: function (caller, act, data) {
caller.gridView01.addRow();
},
ITEM_DEL: function (caller, act, data) {
caller.gridView01.delRow("selected");
}
});
// fnObj 기본 함수 스타트와 리사이즈
fnObj.pageStart = function () {
this.pageButtonView.initView();
this.searchView.initView();
this.gridView01.initView();
ACTIONS.dispatch(ACTIONS.PAGE_SEARCH);
};
fnObj.pageResize = function () {
};
fnObj.pageButtonView = axboot.viewExtend({
initView: function () {
axboot.buttonClick(this, "data-page-btn", {
"search": function () {
ACTIONS.dispatch(ACTIONS.PAGE_SEARCH);
},
"save": function () {
ACTIONS.dispatch(ACTIONS.PAGE_SAVE);
},
"close": function () {
ACTIONS.dispatch(ACTIONS.PAGE_CLOSE);
},
"add": function () {
ACTIONS.dispatch(ACTIONS.ITEM_ADD);
},
"del": function () {
ACTIONS.dispatch(ACTIONS.ITEM_DEL);
}
});
}
});
//== view 시작
/**
* searchView
*/
fnObj.searchView = axboot.viewExtend(axboot.searchView, {
initView: function () {
},
getData: function () {
return {
pageNumber: this.pageNumber,
pageSize: this.pageSize,
groupCd: GROUP_CD,
useYn: "Y"
}
}
});
/**
* gridView
*/
fnObj.gridView01 = axboot.viewExtend(axboot.gridView, {
initView: function () {
var _this = this;
this.target = axboot.gridBuilder({
showRowSelector: true,
multipleSelect: true,
target: $('[data-ax5grid="grid-view-01"]'),
columns: [
{key: "code", label: "코드", width: 100, align: "center", editor: {type: "text", disabled: "notCreated"}},
{key: "name", label: "코드값", width: 150, align: "left", editor: "text"},
{key: "sort", editor: "number"},
{key: "useYn", editor: "checkYn"}
],
body: {
onClick: function () {
}
}
});
},
getData: function (_type) {
var list = [];
var _list = this.target.getList(_type);
if (_type == "modified" || _type == "deleted") {
list = ax5.util.filter(_list, function () {
return this.code;
});
} else {
list = _list;
}
return list;
},
addRow: function () {
this.target.addRow({__created__: true, groupCd: GROUP_CD, groupNm: GROUP_NM, posUseYn: "N", useYn: "Y"}, "last");
}
});
|
function LoginController(){
$('#login-form #forgot-password').click(function(){
$('#get-credentials').dialog('open');
});
$('#login-form #sign-up').click( function(){
$('#login-container').hide();
$('#account-form-container').show();
});
$('#get-credentials').dialog({
autoOpen: false,
modal: true,
title: "forgot Password",
open: function() {
$('#email-tf').focus();
$('#get-credentials-form').resetForm();
$('#get-credentials .alert').hide();
$(this).show();
},
close: function(){
$('#user-tf').focus();
$(this).hide();
}
});
}
|
import React from 'react';
import {
storiesOf,
action
} from '@storybook/react';
import TextareaBox from './TextareaBox';
import {
wrapComponentWithContainerAndTheme,
colors,
} from "../styles";
function renderChapterWithTheme(theme) {
return {
info: `
Usage
~~~
import React from 'react';
import {TextareaBox} from 'insidesales-components';
~~~
`,
chapters: [
{
sections: [
{
title: 'Example: textarea default empty',
sectionFn: () => wrapComponentWithContainerAndTheme(theme,
<TextareaBox
label="Label"
name="first"
onChange={action('value')}
/>
)
},
{
title: 'Example: textarea with existing text',
sectionFn: () => wrapComponentWithContainerAndTheme(theme,
<TextareaBox
label="Label"
name="firstz"
onChange={action('value')}
value="This text was hardcoded into stories. The structure of this component follows how a `TextareaBox` should look."
/>
)
},
{
title: 'Example: textarea with error text',
sectionFn: () => wrapComponentWithContainerAndTheme(theme,
<TextareaBox
label="Label"
helper="Helper text."
error="Errors will override helper text."
name="third"
onChange={action('value')}
value="This text was hardcoded into stories."
/>
)
},
{
title: 'Example: textarea disabled',
sectionFn: () => wrapComponentWithContainerAndTheme(theme,
<TextareaBox
label="Label"
helper="Helper text."
disabled
name="fourth"
onChange={action('value')}
/>
)
},
{
title: 'Example: textarea disabled with text',
sectionFn: () => wrapComponentWithContainerAndTheme(theme,
<TextareaBox
label="Label"
helper="Helper text."
disabled
name="fifth"
value="this is some example text"
onChange={action('value')}/>
)
},
]
}
]
};
}
storiesOf('Form', module)
.addWithChapters("Default TextareaBox", renderChapterWithTheme({}))
.addWithChapters(
"TextareaBox w/ BlueYellow Theme",
renderChapterWithTheme(colors.blueYellowTheme)
);
|
var test = require('tape');
var db = require('level-test')()('out-of-order');
var fdb = require('../')(db);
var expected = [];
expected.push([
{ type: 'put', key: [ 'key', 'woo' ], value: 0 },
{ type: 'put', key: [ 'hash', 'aaa' ], value: 0 },
{ type: 'put', key: [ 'head', 'woo', 'aaa' ], value: 0 }
]);
expected.push([
{ type: 'put', key: [ 'key', 'woo' ], value: 0 },
{ type: 'put', key: [ 'hash', 'bbb' ], value: 0 },
{ type: 'del', key: [ 'head', 'woo', 'aaa' ], value: 0 },
{ type: 'put', key: [ 'link', 'aaa', 'bbb' ], value: 'woo' },
{ type: 'put', key: [ 'head', 'woo', 'bbb' ], value: 0 }
]);
expected.push([
{ type: 'put', key: [ 'key', 'woo' ], value: 0 },
{ type: 'put', key: [ 'hash', 'ddd' ], value: 0 },
{ type: 'put', key: [ 'dangle', 'woo', 'ccc', 'ddd' ], value: 0 },
{ type: 'put', key: [ 'head', 'woo', 'ddd' ], value: 0 }
]);
expected.push([
{ type: 'put', key: [ 'key', 'woo' ], value: 0 },
{ type: 'put', key: [ 'hash', 'ccc' ], value: 0 },
{ type: 'del', key: [ 'head', 'woo', 'bbb' ], value: 0 },
{ type: 'put', key: [ 'link', 'bbb', 'ccc' ], value: 'woo' },
{ type: 'del', key: [ 'dangle', 'woo', 'ccc', 'ddd' ] },
{ type: 'del', key: [ 'head', 'woo', 'ccc' ] },
{ type: 'put', key: [ 'link', 'ccc', 'ddd' ], value: 'woo' }
]);
var docs = [
{ key: 'woo', hash: 'aaa' },
{ key: 'woo', hash: 'bbb', prev: [ 'aaa' ] },
{ key: 'woo', hash: 'ddd', prev: [ 'ccc' ] },
{ key: 'woo', hash: 'ccc', prev: [ 'bbb' ] }
];
test('out of order', function (t) {
t.plan(expected.length + docs.length);
fdb.on('batch', function (batch) {
t.deepEqual(batch, expected.shift());
});
(function next () {
if (docs.length === 0) return;
var doc = docs.shift();
fdb.create(doc, function (err) {
t.ifError(err);
next();
});
})();
});
|
// Generated by IcedCoffeeScript 1.4.0c
(function() {
var extend, flatten, _ref;
exports.starts = function(string, literal, start) {
return literal === string.substr(start, literal.length);
};
exports.ends = function(string, literal, back) {
var len;
len = literal.length;
return literal === string.substr(string.length - len - (back || 0), len);
};
exports.compact = function(array) {
var item, _i, _len, _results;
_results = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
item = array[_i];
if (item) _results.push(item);
}
return _results;
};
exports.count = function(string, substr) {
var num, pos;
num = pos = 0;
if (!substr.length) return 1 / 0;
while (pos = 1 + string.indexOf(substr, pos)) {
num++;
}
return num;
};
exports.merge = function(options, overrides) {
return extend(extend({}, options), overrides);
};
extend = exports.extend = function(object, properties) {
var key, val;
for (key in properties) {
val = properties[key];
object[key] = val;
}
return object;
};
exports.flatten = flatten = function(array) {
var element, flattened, _i, _len;
flattened = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
element = array[_i];
if (element instanceof Array) {
flattened = flattened.concat(flatten(element));
} else {
flattened.push(element);
}
}
return flattened;
};
exports.del = function(obj, key) {
var val;
val = obj[key];
delete obj[key];
return val;
};
exports.last = function(array, back) {
return array[array.length - (back || 0) - 1];
};
exports.some = (_ref = Array.prototype.some) != null ? _ref : function(fn) {
var e, _i, _len;
for (_i = 0, _len = this.length; _i < _len; _i++) {
e = this[_i];
if (fn(e)) return true;
}
return false;
};
}).call(this);
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.10.6.2_A1_T3;
* @section: 15.10.6.2;
* @assertion: RegExp.prototype.exec(string) Performs a regular expression match of ToString(string) against the regular expression and
* returns an Array object containing the results of the match, or null if the string did not match;
* @description: String is new Object("abcdefghi") and RegExp is /a[a-z]{2,4}/;
*/
__executed = /a[a-z]{2,4}/.exec(new Object("abcdefghi"));
__expected = ["abcde"];
__expected.index=0;
__expected.input="abcdefghi";
//CHECK#0
if ((__executed instanceof Array) !== true) {
$ERROR('#0: __executed = /a[a-z]{2,4}/.exec(new Object("abcdefghi")); (__executed instanceof Array) === true');
}
//CHECK#1
if (__executed.length !== __expected.length) {
$ERROR('#1: __executed = /a[a-z]{2,4}/.exec(new Object("abcdefghi")); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}
//CHECK#2
if (__executed.index !== __expected.index) {
$ERROR('#2: __executed = /a[a-z]{2,4}/.exec(new Object("abcdefghi")); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}
//CHECK#3
if (__executed.input !== __expected.input) {
$ERROR('#3: __executed = /a[a-z]{2,4}/.exec(new Object("abcdefghi")); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}
//CHECK#4
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
$ERROR('#4: __executed = /a[a-z]{2,4}/.exec(new Object("abcdefghi")); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
}
}
|
/*global define,jasmine,describe,it,expect*/
/*jslint white:true,browser:true*/
define([
'common/monoBus'
], function (Bus) {
'use strict';
// Setting a shorter timeout pretty much forces us to set a timeout explicitly
// per async test which falls outside of this reasonable setting for "normal"
// async code. When we simulate async failures, or chained async calls, we
// need to controle the timing expectations within the test itself.
jasmine.DEFAULT_TIMEOUT_INTERVAL = 100;
describe('Bus core functions', function () {
it('Is alive', function () {
var alive;
if (Bus) {
alive = true;
} else {
alive = false;
}
expect(alive).toBeTruthy();
});
it('Send and receive a test based message', function (done) {
var bus = Bus.make();
bus.listen({
test: function (message) {
return (message.type === 'test');
},
handle: function (message) {
expect(message.type).toEqual('test');
done();
}
});
bus.send({
type: 'test'
});
});
it('Send and receive a string key based message', function (done) {
var bus = Bus.make();
bus.listen({
key: 'mykey',
handle: function (message) {
expect(message.prop).toEqual('test2');
done();
}
});
bus.send({prop: 'test2'}, {
key: 'mykey'
});
});
it('Send and receive an object key based message', function (done) {
var bus = Bus.make();
bus.listen({
key: {type: 'test'},
handle: function (message) {
expect(message.prop).toEqual('test2');
done();
}
});
bus.send({prop: 'test2'}, {
key: {type: 'test'}
});
});
it('Request/response', function (done) {
var bus = Bus.make();
bus.respond({
key: {type: 'test'},
handle: function (message) {
return {reply: 'this is my reply'};
}
});
bus.request({}, {
key: {type: 'test'}
})
.then(function (response) {
expect(response.reply).toEqual('this is my reply');
done();
});
});
it('Send and receive a message using the simple api', function (done) {
var bus = Bus.make();
bus.on('test', function (message) {
expect(message.say).toEqual('hi');
done();
});
bus.emit('test', {say: 'hi'});
});
// CHANNELS
it('Send and receive a test based message over a new channel', function (done) {
var bus = Bus.make();
bus.listen({
channel: 'my-test-channel',
test: function (message) {
return (message.type === 'test');
},
handle: function (message) {
expect(message.type).toEqual('test');
done();
}
});
bus.send({
type: 'test'
}, {
channel: 'my-test-channel'
});
});
it('Send and receive a test based message over a new channel with object name', function (done) {
var bus = Bus.make();
bus.listen({
channel: {
name: 'my-test-channel'
},
test: function (message) {
return (message.type === 'test');
},
handle: function (message) {
expect(message.type).toEqual('test');
done();
}
});
bus.send({
type: 'test'
}, {
channel: {
name: 'my-test-channel'
}
});
});
it('Send and receive a test based message over a channel bus', function (done) {
var bus = Bus.make(),
myBus = bus.makeChannelBus();
myBus.on('talk', function (message) {
expect(message.say).toEqual('hello');
done();
});
myBus.emit('talk', {say: 'hello'});
});
it('Send and receive a test based message over a channel bus', function (done) {
var bus = Bus.make(),
myBus = bus.makeChannelBus();
myBus.on('talk', function (message) {
expect(message.say).toEqual('hello');
done();
});
myBus.emit('talk', {say: 'hello'});
});
it('Send and receive a test based message over the main bus from a channel bus', function (done) {
var bus = Bus.make(),
myBus = bus.makeChannelBus();
myBus.bus().on('talk', function (message) {
expect(message.say).toEqual('hello');
done();
});
myBus.bus().emit('talk', {say: 'hello'});
});
it('Send and receive a test based message over the main bus on a new channel from a channel bus', function (done) {
var bus = Bus.make(),
myBus = bus.makeChannelBus();
myBus.bus().listen({
channel: 'my-new-channel',
test: function (message) {
return true;
},
handle: function (message) {
expect(message.test).toEqual('123');
done();
}
});
myBus.bus().send({
test: '123'
},
{
channel: 'my-new-channel'
});
});
it('Send and receive a test based message over a channel bus', function (done) {
var bus = Bus.make(),
myBus = bus.makeChannelBus();
myBus.listen({
test: function (message) {
return (message.language === 'english');
},
handle: function (message) {
expect(message.greeting).toEqual('hello');
done();
}
});
myBus.send({
language: 'english',
greeting: 'hello'
});
});
it('Channel bus Request/response', function (done) {
var bus = Bus.make(),
bus1 = bus.makeChannelBus(),
bus2 = bus.makeChannelBus(),
data = {
key1: 'value1'
};
// responder 1
bus1.respond({
key: {
type: 'get-value'
},
handle: function (message) {
return {
value: data[message.propertyName]
};
}
});
bus1.request({
propertyName: 'key1'
}, {
key: {
type: 'get-value'
}
})
.then(function (response) {
expect(response.value).toEqual('value1');
done();
});
});
it('Nested bus Request/response', function (done) {
var bus = Bus.make(),
bus1 = bus.makeChannelBus(),
bus2 = bus.makeChannelBus(),
data = {
key1: 'value1'
};
// responder 1
bus1.respond({
key: {
type: 'get-value'
},
handle: function (message) {
return {
value: data[message.propertyName]
};
}
});
bus2.respond({
key: {
type: 'get-value'
},
handle: function (message) {
return bus1.request({
propertyName: 'key1'
}, {
key: {
type: 'get-value'
}
});
}
});
bus2.request({
propertyName: 'key1'
}, {
key: {
type: 'get-value'
}
})
.then(function (response) {
expect(response.value).toEqual('value1');
done();
});
});
it('Send and receive a keyed, persistent message over a channel, listen first', function (done) {
var bus = Bus.make();
bus.listen({
channel: 'my-test-channel',
key: 'my-test-key',
handle: function (message) {
expect(message.name).toEqual('Winnie');
done();
}
});
bus.send({
name: 'Winnie'
}, {
channel: 'my-test-channel',
key: 'my-test-key',
persistent: true
});
});
it('Send and receive a keyed, persistent message over a channel, send first', function (done) {
var bus = Bus.make();
bus.set({
name: 'Winnie'
}, {
channel: 'my-test-channel',
key: 'my-test-key'
});
window.setTimeout(function () {
bus.listen({
channel: 'my-test-channel',
key: 'my-test-key',
handle: function (message) {
expect(message.name).toEqual('Winnie');
done();
}
});
}, 1000);
}, 5000);
it('Send and receive a keyed, persistent message over a channel, send first, then update', function (done) {
var bus = Bus.make(),
times = 0;
bus.set({
name: 'Winnie'
}, {
channel: 'my-test-channel',
key: 'my-test-key'
});
window.setTimeout(function () {
bus.listen({
channel: 'my-test-channel',
key: 'my-test-key',
handle: function (message) {
if (times === 0) {
times += 1;
bus.set({
name: 'Tigger'
}, {
channel: 'my-test-channel',
key: 'my-test-key'
});
} else {
expect(message.name).toEqual('Tigger');
done();
}
}
});
}, 1000);
}, 5000);
it('Create a working test based message route, then remove the listener, should fail.', function (done) {
var bus = Bus.make(),
count = 0,
listener = bus.listen({
test: function (message) {
return (message.what === 'test');
},
handle: function (message) {
if (count === 0) {
count += 1;
bus.removeListener(listener);
expect(message.what).toEqual('test');
bus.send({what: 'test'});
window.setTimeout(function () {
expect(count).toEqual(1);
done();
}, 3000);
} else if (count === 1) {
count += 1;
}
}
});
bus.send({
what: 'test'
});
}, 5000);
});
});
|
import {
atRuleParamIndex,
isRangeContextMediaFeature,
isStandardSyntaxMediaFeatureName,
report,
ruleMessages,
validateOptions,
} from "../../utils"
import mediaParser from "postcss-media-query-parser"
export const ruleName = "media-feature-name-case"
export const messages = ruleMessages(ruleName, {
expected: (actual, expected) => `Expected "${actual}" to be "${expected}"`,
})
export default function (expectation) {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: expectation,
possible: [
"lower",
"upper",
],
})
if (!validOptions) { return }
root.walkAtRules(/^media$/i, atRule => {
mediaParser(atRule.params).walk(/^media-feature$/i, mediaFeatureNode => {
const { parent, sourceIndex, value } = mediaFeatureNode
if (isRangeContextMediaFeature(parent.value)) { return }
if (!isStandardSyntaxMediaFeatureName(value)) { return }
const expectedFeatureName = expectation === "lower"
? value.toLowerCase()
: value.toUpperCase()
if (value === expectedFeatureName) { return }
report({
index: atRuleParamIndex(atRule) + sourceIndex,
message: messages.expected(value, expectedFeatureName),
node: atRule,
ruleName,
result,
})
})
})
}
}
|
/* jshint node: true */
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
var app = new EmberAddon({
vendorFiles: {
'handlebars.js': null
}
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
app.import(app.bowerDirectory + '/moment/moment.js');
app.import(app.bowerDirectory + '/pikaday/pikaday.js');
app.import(app.bowerDirectory + '/pikaday/css/pikaday.css');
module.exports = app.toTree();
|
var global_text = {
Ok : "Ok",
header : {
Status : "Status",
Server : "Server",
New : "Add a new server",
Hide: "Hide",
AddServer : "Add a new server",
Connect : "Connect",
Context : "Context",
Index : "Index",
AllIndex : "All Index",
Search : "Search",
AutoRefresh : "AutoRefresh",
Hits : "Hits : ",
Error : "Error",
NoError : "Ok",
Customization : "Customization",
NewServerTitle : "Hide / Show new server form",
ConnectTitle : "Establish the connection with the server",
ServerAndIndexModalTitle : "Change or add new server and choose an alias / index",
navBar : {
Request : "Request",
Keywords : "Keywords",
Templates : "Templates",
}
},
aggregation : {
Aggregations : "Aggregations",
NewAggregation : "New Aggregations"
},
keyword : {
Index : "Index",
Save : "Save",
Add : "Add"
},
request : {
ShowAll : "Show All",
Hide : "Hide",
SimplifiedRequest:"Simplified Request",
ComplexeRequest:"Complexe Request",
ResultPerPage:"Result per page",
Search:"Search",
JsonQuery: "Json Query",
Keywords: "Keywords",
Fields:"Fields",
ShowAllFieldTitle : "Show / Hide all fields",
ShowAllKeywordTitle : "Show / Hide all keywords",
KeywordFromQuery : "Keyword from query",
Name : "Name",
Desc : "Desc",
Save : "Save",
SortBy : "Order by",
Field : "Field",
AddSort : "Add sort"
},
layout : {
DeletePage : "Delete this Page",
Row : "Row",
Col : "Col",
Name : "Name"
},
result : {
request_sub_tab : {
Results : "Results",
Aggregation :"Aggregation",
Template : "Template",
AdvancedRequest : "Advanced Request",
ResultList : "Results list",
JsonResult : "JsonResult",
First: "First",
Csv: "To CSV",
Prev: "Prev",
Next: "Next",
Last: "Last",
Page: "Page",
Go : "Go",
AggregationFilter : "Aggregation Filter",
Or:"Or",
And:"And",
Not:"Not",
}
},
template : {
ResultItems : "Result Items",
Aggregations : "Aggregations",
aggregation_sub_tab :{
Association : "Association",
AggregationType : "Aggregation Type",
Template : "Template",
Default : "Default",
Update : "Update",
Edit: "Edit",
New: "New",
Save: "Save",
Delete: "Delete",
TemplateName : "Template's name"
},
result_items_sub_tab :{
Template : "Template",
New: "New",
Save: "Save",
Delete: "Delete",
TemplateName : "Template's name",
Fields : "Fields"
}
},
csvModal : {
CsvExport : "CSV Export",
Sep : "Sep",
TabSep : "TabSep",
Name : "Name",
Alias : "Alias",
Show : "Show",
Hide : "Hide",
CurrentResult : "CurrentResult",
CurrentResultTitle : "Export current result to csv file",
SomeResult : "Some Result",
SomeResultTitle : "Export some of the result (nb) to csv file",
FullResultTitle : "Export all result to csv File !!! Warning : can take a large ammount of time and ressource if there is a lot of results",
FullResult : "Full Result",
},
context : {
Context : "Context",
UpdateContext : "Update current context",
SaveContext : "Save current context",
NewContext : "New context",
SetAsDefaultContext : "Set as default context",
ContextName : "Context's Name",
Valider : "Validate",
Remove : "Remove current context"
},
log : {
Logs : "Logs",
Hide : "Hide/Show",
Empty : "Empty Logs"
},
moduleManager : {
ModulesManager : "Modules Manager",
Add : "Add",
RestartInterface : "Restart interface",
Lock : "Lock/Unlock interface"
}
}
|
//todo random full lenght top images with scrolling logo and more button
//remove absolute links when moved into trunk remove jquery as a dependency
//var homeBgImg = ["#b6c4d0 url(images/sc9bg1A.jpg) top right fixed", "#b6c4d0 url(images/sc9bg1B.jpg) top right fixed"];
function getRandomArr(arr) {
return Math.floor(Math.random() * arr.length)
}
$.fn.mobileFix = function (options) {
var $parent = $(this),
$fixedElements = $(options.fixedElements);
$(document)
.on('focus', options.inputElements, function(e) {
$parent.addClass(options.addClass);
})
.on('blur', options.inputElements, function(e) {
$parent.removeClass(options.addClass);
// Fix for some scenarios where you need to start scrolling
setTimeout(function() {
$(document).scrollTop($(document).scrollTop())
}, 1);
});
return this; // Allowing chaining
};
function detectmob() {
if( navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
return true;
}
else {
return false;
}
}
$(function() {
_initGlam = function(){
var _bPop;
var _bPopSource;
if(detectmob()){
$('.navbar-collapse').remove();
/* cache dom references */
var $body = jQuery('body');
$(document).on('focus', 'select', function(e) {
$body.addClass('fixfixed');
}).on('blur, change', 'select', function(e) {
$body.removeClass('fixfixed');
});
$(document).on('scrollend', function(e) {
$body.removeClass('fixfixed');
});
}else{
$('#selectmenuContent').hide();
}
scrollToContent = function(loc){
$('html').velocity("scroll", { duration: 1500, easing: "easeInSine", offset: $(loc).offset().top - 55 });
$('#menuContent').collapse('hide');
}
this.compositionComplete = function () { // EXECUTES AFTER DOM UPDATE
holder.run({
domain: "holder.canvas",
use_canvas: false
});
};
$( "#selectmenuContent select" ).change(function(e) {
scrollToContent('#'+$(this).val());
});
$('.nav a').on('click, tap', function(e) {
e.preventDefault();
scrollToContent($(this).attr('href'));
});
$(' .demoLnk').on('click, tap', function(e) {
e.preventDefault();
$('html').velocity("scroll", { duration: 1500, easing: "easeInSine", offset: $($(this).attr('href')).offset().top - 55 });
});
$(".col-md-4 div").velocity("transition.slideUpBigIn", { complete: function(){
$("img").lazyload({effect:'fadeIn'});
} });
$('.thumbnail').on('click, tap', function(e){
currentID = $(this).find('[data-source]');
currentID = $(currentID).data('source');
if(detectmob()){
window.open(
// todo remove this
$(this).find('a').data("url"),
'_blank'
)
}else{
_bPop = $('.popup').bPopup({
fadeSpeed: 'fast',
content:'iframe',
escClose:true,
opacity:0,
position:[20,50],
loadCallback: function() {
$('body').not('iframe body').css('overflow', 'hidden');
$('.popup, .b-iframe').height($(window).height());
$('.popup, .b-iframe').width($(window).width());
$('.popup').append("<div class='closePopUp'>X</div>");
$('.popup').append("<div class='viewSource'>Source</div>");
$('.closePopUp').on('click, tap', function(){
_bPop.close();
});
$('.viewSource').on('click, tap', function(){
_bPop.close();
setTimeout(callSourceHack, 500);
});
},
onClose: function(){
$('body').not('iframe body').css('overflow', 'scroll');
},
// todo remove this
loadUrl: $(this).find('a').data("url")
});
}
});
callSourceHack = function(){
_bPopSource = $('.popup').bPopup({
content:'iframe',
fadeSpeed: 'fast',
escClose:true,
opacity:0,
position:[0,50],
loadCallback: function() {
$('body').not('iframe body').css('overflow', 'hidden');
$('.popup, .b-iframe').height($(window).height());
$('.popup, .b-iframe').width($(window).width());
$('iframe').height(5000);
$('.popup, .b-iframe').css('overflow', 'scroll');
$('body').append("<div class='closePopUp' style='z-index:99999; display:none; ;top:"+($(window).scrollTop() + 70)+"px '>X</div>");
$('.closePopUp').fadeIn('fast');
$('.closePopUp').on('click, tap', function(){
_bPopSource.close();
});
},
onClose:function(){
$('body').not('iframe body').css('overflow', 'scroll');
$('.closePopUp').remove();
},
// todo remove this
loadUrl: 'source.html#' + currentID
});
}
$('[data-url]').on('click', function(e){
currentID = $(this).find('[data-source]');
currentID = $(currentID).data('source');
_bPop = $('.popup').bPopup({
fadeSpeed: 'fast',
content:'iframe',
escClose:true,
opacity:0,
position:[20,50],
loadCallback: function() {
$('body').not('iframe body').css('overflow', 'hidden');
$('.popup, .b-iframe').height($(window).height());
$('.popup, .b-iframe').width($(window).width());
$('.popup').append("<div class='closePopUp'>X</div>");
$('.popup').append("<div class='viewSource'>Source</div>");
$('.closePopUp').on('click, tap', function(){
_bPop.close();
});
$('.viewSource').on('click, tap', function(){
_bPop.close();
setTimeout(callSourceHack, 500);
});
},
onClose: function(){
$('body').not('iframe body').css('overflow', 'scroll');
},
// todo remove this
loadUrl: $(this).data("url")
});
});
}
_initGlam();
});
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['./Binding'],function(B){"use strict";var C=B.extend("sap.ui.model.ContextBinding",{constructor:function(m,p,c,P,e){B.call(this,m,p,c,P,e);this.oElementContext=null;this.bInitial=true;},metadata:{publicMethods:["getElementContext"]}});C.prototype.checkUpdate=function(f){};C.prototype.getBoundContext=function(c){return this.oElementContext;};return C;});
|
'use strict';
const mm = require('egg-mock');
const {
webpackReady,
assertCSR,
assertDevResource,
} = require('../utils/helper');
describe('test/controller/asset.test.js', () => {
let app;
before(async () => {
mm.env('local');
app = mm.app();
await app.ready();
await webpackReady(app);
});
afterEach(mm.restore);
after(() => app.close());
it('should work when simple', async () => {
await app
.httpRequest()
.get('/asset/simple')
.expect(200)
.expect((res) => {
assertCSR(res);
assertDevResource(res, 'asset/simple');
});
});
it('should work when spa', async () => {
await app
.httpRequest()
.get('/asset')
.expect(200)
.expect((res) => {
assertCSR(res);
assertDevResource(res, 'asset/spa');
});
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:36113a1d3807a36d5be72917baad00f596e44c5840a5234266057a794d7ff4b0
size 2246
|
var __ = require('underscore'),
Backbone = require('backbone'),
$ = require('jquery'),
loadTemplate = require('../utils/loadTemplate'),
baseVw = require('./baseVw');
module.exports = baseVw.extend({
className: "flexRow borderBottom",
events: {
},
initialize: function(options){
if (!options.model) {
throw new Error('Please provide a model.');
}
},
render: function(){
var self = this;
loadTemplate('./js/templates/review.html', function(loadedTemplate) {
loadTemplate('./js/templates/ratingStars.html', function(starsTemplate) {
self.$el.html(
loadedTemplate(
__.extend({}, self.model.toJSON(), { starsTmpl: starsTemplate })
)
);
});
});
return this;
}
});
|
// This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.fi');
goog.require('Blockly.Msg');
Blockly.Msg.ADD_COMMENT = "Lisää kommentti";
Blockly.Msg.AUTH = "Valtuuta tämä ohjelma jotta voit tallettaa työsi ja jakaa sen.";
Blockly.Msg.CHANGE_VALUE_TITLE = "Muuta arvoa:";
Blockly.Msg.CHAT = "Keskustele yhteistyökumppanisi kanssa tässä laatikossa!";
Blockly.Msg.COLLAPSE_ALL = "Sulje lohkot";
Blockly.Msg.COLLAPSE_BLOCK = "Sulje lohko";
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "väri 1";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "väri 2";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/"; // untranslated
Blockly.Msg.COLOUR_BLEND_RATIO = "suhde";
Blockly.Msg.COLOUR_BLEND_TITLE = "sekoitus";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "Sekoittaa kaksi väriä keskenään annetussa suhteessa (0.0 - 1.0).";
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://fi.wikipedia.org/wiki/V%C3%A4ri";
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Valitse väri paletista.";
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "satunnainen väri";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Valitse väri sattumanvaraisesti.";
Blockly.Msg.COLOUR_RGB_BLUE = "sininen";
Blockly.Msg.COLOUR_RGB_GREEN = "vihreä";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html";
Blockly.Msg.COLOUR_RGB_RED = "punainen";
Blockly.Msg.COLOUR_RGB_TITLE = "väri, jossa on";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "Luo väri, jossa on tietty määrä punaista, vihreää ja sinistä. Kaikkien arvojen tulee olla välillä 0 - 100.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "poistu silmukasta";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "jatka silmukan seuraavaan toistoon";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Poistu sisemmästä silmukasta.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Ohita loput tästä silmukasta ja siirry seuraavaan toistoon.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Varoitus: Tätä lohkoa voi käyttää vain silmukan sisällä.";
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://github.com/google/blockly/wiki/Loops#for-each for each block"; // untranslated
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST = "listassa";
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST_TAIL = ""; // untranslated
Blockly.Msg.CONTROLS_FOREACH_INPUT_ITEM = "kullekin kohteelle";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Aseta muuttujan %1 arvoksi kukin listan kohde vuorollaan ja suorita joukko lausekkeita.";
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated
Blockly.Msg.CONTROLS_FOR_TITLE = "laske %1 Väli %2-%3 %4:n välein";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "Aseta muuttujaan %1 arvot alkuarvosta loppuarvoon annetun askeleen välein ja suorita joka askeleella annettu koodilohko.";
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "Lisää ehto \"jos\" lohkoon.";
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "Lisää lopullinen \"muuten\" lohko \"jos\" lohkoon.";
Blockly.Msg.CONTROLS_IF_HELPURL = "https://github.com/google/blockly/wiki/IfElse"; // untranslated
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Lisää, poista tai järjestele osioita tässä \"jos\" lohkossa.";
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "muuten";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "muuten jos";
Blockly.Msg.CONTROLS_IF_MSG_IF = "jos";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Jos arvo on tosi, suorita lauseke.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Jos arvo on tosi, suorita ensimmäinen lohko lausekkeita. Muuten suorita toinen lohko lausekkeita.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Jos ensimmäinen arvo on tosi, suorita ensimmäinen lohko lausekkeita. Muuten, jos toinen arvo on tosi, suorita toinen lohko lausekkeita.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Jos ensimmäinen arvo on tosi, suorita ensimmäinen lohko lausekkeita. Muuten, jos toinen arvo on tosi, suorita toinen lohko lausekkeita. Jos mikään arvoista ei ole tosi, suorita viimeinen lohko lausekkeita.";
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://en.wikipedia.org/wiki/For_loop";
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "tee";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "toista %1 kertaa";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Suorita joukko lausekkeita useampi kertaa.";
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "toista kunnes";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "toista niin kauan kuin";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Niin kauan kuin arvo on epätosi, suorita joukko lausekkeita.";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Niin kauan kuin arvo on tosi, suorita joukko lausekkeita.";
Blockly.Msg.DELETE_BLOCK = "Poista lohko";
Blockly.Msg.DELETE_X_BLOCKS = "Poista %1 lohkoa";
Blockly.Msg.DISABLE_BLOCK = "Passivoi lohko";
Blockly.Msg.DUPLICATE_BLOCK = "Kopioi";
Blockly.Msg.ENABLE_BLOCK = "Aktivoi lohko";
Blockly.Msg.EXPAND_ALL = "Laajenna lohkot";
Blockly.Msg.EXPAND_BLOCK = "Laajenna lohko";
Blockly.Msg.EXTERNAL_INPUTS = "Ulkoiset syötteet";
Blockly.Msg.HELP = "Apua";
Blockly.Msg.INLINE_INPUTS = "Tuo syötteet";
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "Luo tyhjä lista";
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Palauta tyhjä lista, pituus 0";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "lista";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Listää, poista tai järjestele uudestaan osioita tässä lohkossa.";
Blockly.Msg.LISTS_CREATE_WITH_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "luo lista";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Lisää kohde listaan.";
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "Luo lista, jossa on mikä tahansa määrä kohteita.";
Blockly.Msg.LISTS_GET_INDEX_FIRST = "ensimmäinen";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "nro (lopusta laskien)";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "nro";
Blockly.Msg.LISTS_GET_INDEX_GET = "hae";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "hae ja poista";
Blockly.Msg.LISTS_GET_INDEX_LAST = "viimeinen";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "satunnainen";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "poista";
Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Palauta ensimmäinen kohde listalta.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = "Palauta kohde annetusta kohdasta listaa. Numero 1 tarkoittaa listan viimeistä kohdetta.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = "Palauta kohde annetusta kohdasta listaa. Numero 1 tarkoittaa listan ensimmäistä kohdetta.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Palauttaa listan viimeisen kohteen.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Palauttaa satunnaisen kohteen listalta.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Poistaa ja palauttaa ensimmäisen kohteen listalta.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = "Poistaa ja palauttaa kohteen annetusta kohden listaa. Nro 1 on ensimmäinen kohde.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = "Poistaa ja palauttaa kohteen annetusta kohden listaa. Nro 1 on ensimmäinen kohde.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Poistaa ja palauttaa viimeisen kohteen listalta.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Poistaa ja palauttaa satunnaisen kohteen listalta.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Poistaa ensimmäisen kohteen listalta.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = "Poistaa kohteen listalta annetusta kohtaa. Nro 1 on viimeinen kohde.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = "Poistaa kohteen listalta annetusta kohtaa. Nro 1 on ensimmäinen kohde.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Poistaa viimeisen kohteen listalta.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Poistaa satunnaisen kohteen listalta.";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "päättyen kohtaan (lopusta laskien)";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "päättyen kohtaan";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "viimeinen";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "hae osalista alkaen alusta";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "hae osalista alkaen kohdasta (lopusta laskien)";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "hae osalista alkaen kohdasta";
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Luo kopio määrätystä kohden listaa.";
Blockly.Msg.LISTS_INDEX_OF_FIRST = "etsi ensimmäinen esiintymä kohteelle";
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated
Blockly.Msg.LISTS_INDEX_OF_LAST = "etsi viimeinen esiintymä kohteelle";
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Palauttaa kohteen ensimmäisen/viimeisen esiintymän kohdan. Palauttaa 0 jos tekstiä ei löydy.";
Blockly.Msg.LISTS_INLIST = "listassa";
Blockly.Msg.LISTS_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated
Blockly.Msg.LISTS_ISEMPTY_TITLE = "%1 on tyhjä";
Blockly.Msg.LISTS_ISEMPTY_TOOLTIP = "Palauttaa tosi, jos lista on tyhjä.";
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated
Blockly.Msg.LISTS_LENGTH_TITLE = "%1:n pituus";
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Palauttaa listan pituuden.";
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_REPEAT_TITLE = "luo lista, jossa kohde %1 toistuu %2 kertaa";
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Luo listan, jossa annettu arvo toistuu määrätyn monta kertaa.";
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "kohteeksi";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "lisää kohtaan";
Blockly.Msg.LISTS_SET_INDEX_SET = "aseta";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Lisää kohteen listan kärkeen.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = "Lisää kohteen annettuun kohtaan listaa. Nro 1 on listan häntä.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = "Lisää kohteen listan annettuun kohtaan. Nro 1 on listan kärki.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Lisää kohteen listan loppuun.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Lisää kohteen satunnaiseen kohtaan listassa.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Asettaa listan ensimmäisen kohteen.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = "Asettaa listan määrätyssä kohtaa olevan kohteen. Nro 1 on listan loppu.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = "Asettaa kohteen määrättyyn kohtaa listassa. Nro 1 on listan alku.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Asettaa listan viimeisen kohteen.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Asettaa satunnaisen kohteen listassa.";
Blockly.Msg.LISTS_SPLIT_HELPURL = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated
Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT = "tee listasta tekstiä";
Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = "tee tekstistä lista";
Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = "Join a list of texts into one text, separated by a delimiter."; // untranslated
Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = "Jaa teksti osiin erotinmerkin perusteella ja järjestä osat listaksi.";
Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = "erottimen kanssa";
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "epätosi";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "Palauttaa joko tosi tai epätosi.";
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "tosi";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://fi.wikipedia.org/wiki/Ep%C3%A4yht%C3%A4l%C3%B6";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Palauta tosi, jos syötteet ovat keskenään samat.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Palauttaa tosi, jos ensimmäinen syöte on suurempi, kuin toinen.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Palauttaa tosi, jos ensimmäinen syöte on suurempi tai yhtä suuri, kuin toinen.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Palauttaa tosi, jos ensimmäinen syöte on pienempi, kuin toinen.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Palauttaa tosi, jos ensimmäinen syöte on pienempi tai yhtä suuri, kuin toinen.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Palauttaa tosi, jos syötteet eivät ole keskenään samoja.";
Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated
Blockly.Msg.LOGIC_NEGATE_TITLE = "ei %1";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Palauttaa tosi, jos syöte on epätosi. Palauttaa epätosi, jos syöte on tosi.";
Blockly.Msg.LOGIC_NULL = "ei mitään";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated
Blockly.Msg.LOGIC_NULL_TOOLTIP = "Palauttaa \"ei mitään\"-arvon.";
Blockly.Msg.LOGIC_OPERATION_AND = "ja";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated
Blockly.Msg.LOGIC_OPERATION_OR = "tai";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Palauttaa tosi, jos kummatkin syötteet ovat tosia.";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Palauttaa tosi, jos ainakin yksi syötteistä on tosi.";
Blockly.Msg.LOGIC_TERNARY_CONDITION = "ehto";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; // untranslated
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "jos epätosi";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "jos tosi";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "Tarkistaa testin ehdon. Jos ehto on tosi, palauttaa \"jos tosi\" arvon, muuten palauttaa \"jos epätosi\" arvon.";
Blockly.Msg.MATH_ADDITION_SYMBOL = "+";
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "http://fi.wikipedia.org/wiki/Aritmetiikka";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "Palauttaa kahden luvun summan.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "Palauttaa jakolaskun osamäärän.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "Palauttaa kahden luvun erotuksen.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "Palauttaa kertolaskun tulon.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Palauttaa ensimmäisen luvun korotettuna toisen luvun potenssiin.";
Blockly.Msg.MATH_CHANGE_HELPURL = "https://fi.wikipedia.org/wiki/Yhteenlasku";
Blockly.Msg.MATH_CHANGE_TITLE = "muuta %1 arvolla %2";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "Lisää arvo muuttujaan '%1'.";
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant";
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Palauttaa jonkin seuraavista vakioista: π (3.141…), e (2.718…), φ (1.618…), neliöjuuri(2) (1.414…), neliöjuuri(½) (0.707…), or ∞ (ääretön).";
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; // untranslated
Blockly.Msg.MATH_CONSTRAIN_TITLE = "rajoita %1 vähintään %2 enintään %3";
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Rajoittaa arvon annetulle suljetulle välille.";
Blockly.Msg.MATH_DIVISION_SYMBOL = "÷";
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "on jaollinen luvulla";
Blockly.Msg.MATH_IS_EVEN = "on parillinen";
Blockly.Msg.MATH_IS_NEGATIVE = "on negatiivinen";
Blockly.Msg.MATH_IS_ODD = "on pariton";
Blockly.Msg.MATH_IS_POSITIVE = "on positiivinen";
Blockly.Msg.MATH_IS_PRIME = "on alkuluku";
Blockly.Msg.MATH_IS_TOOLTIP = "Tarkistaa onko numero parillinen, pariton, alkuluku, kokonaisluku, positiivinen, negatiivinen, tai jos se on jaollinen toisella luvulla. Palauttaa tosi tai epätosi.";
Blockly.Msg.MATH_IS_WHOLE = "on kokonaisluku";
Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation";
Blockly.Msg.MATH_MODULO_TITLE = "%1 ÷ %2 jakojäännös";
Blockly.Msg.MATH_MODULO_TOOLTIP = "Palauttaa jakolaskun jakojäännöksen.";
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "⋅";
Blockly.Msg.MATH_NUMBER_HELPURL = "https://fi.wikipedia.org/wiki/Luku";
Blockly.Msg.MATH_NUMBER_TOOLTIP = "Luku.";
Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "keskiarvo luvuista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "suurin luvuista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "keskiluku luvuista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "pienin luvuista";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "tyyppiarvo luvuista";
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "satunnainen valinta luvuista";
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "keskihajonta luvuista";
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "summa luvuista";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Palauttaa aritmeettisen keskiarvon annetuista luvuista.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Palauttaa suurimman annetuista luvuista.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Palauttaa annettujen lukujen keskiluvun.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Palauttaa pienimmän annetuista luvuista.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Palauttaa luettelon yleisimmistä luvuista annetussa listassa.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Palauttaa satunnaisesti valitun luvun annetuista luvuista.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Palauttaa annettujen lukujen keskihajonnan.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Palauttaa kaikkien annettujen lukujen summan.";
Blockly.Msg.MATH_POWER_SYMBOL = "^";
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://fi.wikipedia.org/wiki/Satunnaisluku";
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "satunnainen murtoluku";
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "Palauttaa satunnaisen luvun oikealta puoliavoimesta välistä [0.0, 1.0).";
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://fi.wikipedia.org/wiki/Satunnaisluku";
Blockly.Msg.MATH_RANDOM_INT_TITLE = "Palauttaa satunnaisen kokonaisluvun väliltä %1-%2";
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Palauttaa satunnaisen kokonaisluvun kahden annetun arvon suljetulta väliltä.";
Blockly.Msg.MATH_ROUND_HELPURL = "https://fi.wikipedia.org/wiki/Py%C3%B6rist%C3%A4minen";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "pyöristä";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "pyöristä alaspäin";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "pyöristä ylöspäin";
Blockly.Msg.MATH_ROUND_TOOLTIP = "Pyöristää luvun ylös- tai alaspäin.";
Blockly.Msg.MATH_SINGLE_HELPURL = "https://fi.wikipedia.org/wiki/Neli%C3%B6juuri";
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "itseisarvo";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "neliöjuuri";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Palauttaa luvun itseisarvon.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "Palauttaa e potenssiin luku.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Palauttaa luvun luonnollisen logaritmin.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Palauttaa luvun kymmenkantaisen logaritmin.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Palauttaa numeron vastaluvun.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "Palauttaa 10 potenssiin luku.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Palauttaa luvun neliöjuuren.";
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-";
Blockly.Msg.MATH_TRIG_ACOS = "acos";
Blockly.Msg.MATH_TRIG_ASIN = "asin";
Blockly.Msg.MATH_TRIG_ATAN = "atan";
Blockly.Msg.MATH_TRIG_COS = "cos";
Blockly.Msg.MATH_TRIG_HELPURL = "https://fi.wikipedia.org/wiki/Trigonometrinen_funktio";
Blockly.Msg.MATH_TRIG_SIN = "sin";
Blockly.Msg.MATH_TRIG_TAN = "tan";
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Palauttaa luvun arkuskosinin.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Palauttaa luvun arkussinin.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Palauttaa luvun arkustangentin.";
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Palauttaa asteluvun (ei radiaanin) kosinin.";
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Palauttaa asteluvun (ei radiaanin) sinin.";
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Palauttaa asteluvun (ei radiaanin) tangentin.";
Blockly.Msg.ME = "Minä";
Blockly.Msg.NEW_VARIABLE = "Uusi muuttuja...";
Blockly.Msg.NEW_VARIABLE_TITLE = "Uuden muuttujan nimi:";
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated
Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "salli kommentit";
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "parametrit:";
Blockly.Msg.PROCEDURES_CALLNORETURN_CALL = ""; // untranslated
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://fi.wikipedia.org/wiki/Aliohjelma";
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Suorittaa käyttäjän määrittelemä funktio '%1'.";
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://fi.wikipedia.org/wiki/Aliohjelma";
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Suorittaa käyttäjän määrittelemän funktion '%1' ja käyttää sen tuotosta.";
Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "parametrit:";
Blockly.Msg.PROCEDURES_CREATE_DO = "Luo '%1'";
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "tee jotain";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "tehdäksesi";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Luo funktio, jolla ei ole tuotosta.";
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "palauta";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Luo funktio, jolla ei ole tuotosta.";
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Varoitus: tällä funktiolla on sama parametri useamman kerran.";
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Korosta funktion määritelmä";
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Jos arvo on tosi, palauta toinen arvo.";
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Varoitus: tätä lohkoa voi käyttää vain funktion määrityksessä.";
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "syötteen nimi:";
Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "Lisää sisääntulon funktioon.";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "syötteet";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "Lisää, poista tai järjestele uudelleen tämän toiminnon tulot.";
Blockly.Msg.REMOVE_COMMENT = "Poista kommentti";
Blockly.Msg.RENAME_VARIABLE = "Nimeä uudelleen muuttuja...";
Blockly.Msg.RENAME_VARIABLE_TITLE = "Nimeä uudelleen kaikki '%1' muuttujaa:";
Blockly.Msg.TEXT_APPEND_APPENDTEXT = "lisää teksti";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_APPEND_TO = "muuttujaan";
Blockly.Msg.TEXT_APPEND_TOOLTIP = "Lisää tekstiä muuttujaan '%1'.";
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "pienet kirjaimet";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "isot alkukirjaimet";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "isot kirjaimet";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Palauttaa kopion tekstistä eri kirjainkoossa.";
Blockly.Msg.TEXT_CHARAT_FIRST = "hae ensimmäinen kirjain";
Blockly.Msg.TEXT_CHARAT_FROM_END = "Hae kirjain nro (lopusta laskien)";
Blockly.Msg.TEXT_CHARAT_FROM_START = "Hae kirjain nro";
Blockly.Msg.TEXT_CHARAT_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated
Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "tekstistä";
Blockly.Msg.TEXT_CHARAT_LAST = "hae viimeinen kirjain";
Blockly.Msg.TEXT_CHARAT_RANDOM = "hae satunnainen kirjain";
Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Palauttaa annetussa kohdassa olevan kirjaimen.";
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Lisää kohteen tekstiin.";
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "liitä";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Lisää, poista tai uudelleen järjestä osioita tässä lohkossa.";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "kirjaimeen nro (lopusta laskien)";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "kirjaimeen nro";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "viimeiseen kirjaimeen";
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "merkkijonosta";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "hae osa alkaen ensimmäisestä kirjaimesta";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "hae osa alkaen kirjaimesta nro (lopusta laskien)";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "hae osa alkaen kirjaimesta nro";
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Palauttaa määrätyn osan tekstistä.";
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated
Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "tekstistä";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "etsi ensimmäinen esiintymä merkkijonolle";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "etsi viimeinen esiintymä merkkijonolle";
Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Palauttaa ensin annetun tekstin ensimmäisen/viimeisen esiintymän osoitteen toisessa tekstissä. Palauttaa osoitteen 0 jos tekstiä ei löytynyt.";
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 on tyhjä";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Palauttaa tosi, jos annettu teksti on tyhjä.";
Blockly.Msg.TEXT_JOIN_HELPURL = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "luo teksti";
Blockly.Msg.TEXT_JOIN_TOOLTIP = "Luo merkkijonon liittämällä yhteen minkä tahansa määrän kohteita.";
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_LENGTH_TITLE = "%1:n pituus";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Palauttaa annetussa tekstissä olevien merkkien määrän (välilyönnit mukaan lukien).";
Blockly.Msg.TEXT_PRINT_HELPURL = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated
Blockly.Msg.TEXT_PRINT_TITLE = "tulosta %1";
Blockly.Msg.TEXT_PRINT_TOOLTIP = "Tulostaa annetun tekstin, numeron tia muun arvon.";
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "Kehottaa käyttäjää syöttämään numeron.";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "Kehottaa käyttäjää syöttämään tekstiä.";
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "käyttäen annettua viestiä, kehottaa syöttämään numeron";
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "käyttäen annettua viestiä, kehottaa syöttämään tekstiä";
Blockly.Msg.TEXT_TEXT_HELPURL = "https://fi.wikipedia.org/wiki/Merkkijono";
Blockly.Msg.TEXT_TEXT_TOOLTIP = "Kirjain, sana tai rivi tekstiä.";
Blockly.Msg.TEXT_TRIM_HELPURL = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "poistaa välilyönnit kummaltakin puolelta";
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "poistaa välilyönnit vasemmalta puolelta";
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "poistaa välilyönnit oikealta puolelta";
Blockly.Msg.TEXT_TRIM_TOOLTIP = "Palauttaa kopion tekstistä siten, että välilyönnit on poistettu yhdestä tai molemmista päistä.";
Blockly.Msg.TODAY = "Tänään";
Blockly.Msg.VARIABLES_DEFAULT_NAME = "kohde";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "Luo 'aseta %1'";
Blockly.Msg.VARIABLES_GET_HELPURL = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "Palauttaa muuttujan arvon.";
Blockly.Msg.VARIABLES_SET = "aseta %1 arvoksi %2";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "Luo 'hae %1'";
Blockly.Msg.VARIABLES_SET_HELPURL = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated
Blockly.Msg.VARIABLES_SET_TOOLTIP = "Asettaa muutujan arvoksi annetun syötteen.";
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE;
Blockly.Msg.PROCEDURES_CALLRETURN_CALL = Blockly.Msg.PROCEDURES_CALLNORETURN_CALL;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
|
$(document).ready(function() {
$(".subCol > a, .imgPane > a").click(function(e) {
e.preventDefault(); //the browser won't open the link
console.log("prevented default");
var href = $(this).attr("href");
console.log('<img src="' + href + '"/>');
/*in case the lightbox already exists (we don't want two elemtns with the same id)*/
if ($('#box').length > 0) {
$('#content').html('<img src="' + href + '" />'); /*replacing image*/
$('#box').show();
}
else {
var box =
'<div id="box">' +
'<div id="content">' +
'<img src="' + href + '"/>' +
'</div>' +
'</div>';
$('body').append(box);
console.log("box added");
$('#box').show();
}
$('#box').on('click', function() {
$('#box').hide();
console.log("box hidden");
});
});
/*http://stackoverflow.com/questions/4753695/disabling-right-click-on-images-using-jquery*/
$('body').on('contextmenu', 'img', function(e) {
return false;
});
});
|
// @flow
const f = require('./function_decl_with_statics');
(f: empty); // err
(f.x: empty); // err
f.missing; // err
|
'use strict';
/**
* Gen 1 mechanics are fairly different to those we know on current gen.
* Therefor we need to make a lot of changes to the battle engine for this game simulation.
* This generation inherits all the changes from older generations, that must be taken into account when editing code.
*/
exports.BattleScripts = {
inherit: 'gen2',
gen: 1,
debug: function (activity) {
if (this.getFormat().debug) {
this.add('debug', activity);
}
},
// Gen 1 stores the last damage dealt by a move in the battle.
// This is used for the move Counter.
lastDamage: 0,
// BattleSide scripts.
// In gen 1, last move information is stored on the side rather than on the active Pokémon.
// This is because there was actually no side, just Battle and active Pokémon effects.
// Side's lastMove is used for Counter and Mirror Move.
side: {
lastMove: '',
},
// BattlePokemon scripts.
pokemon: {
getStat: function (statName, unmodified) {
statName = toId(statName);
if (statName === 'hp') return this.maxhp;
if (unmodified) return this.stats[statName];
return this.modifiedStats[statName];
},
// Gen 1 function to apply a stat modification that is only active until the stat is recalculated or mon switched.
// Modified stats are declared in BattlePokemon object in battle-engine.js in about line 303.
modifyStat: function (stat, modifier) {
if (!(stat in this.stats)) return;
this.modifiedStats[stat] = this.battle.clampIntRange(Math.floor(this.modifiedStats[stat] * modifier), 1, 999);
},
// In generation 1, boosting function increases the stored modified stat and checks for opponent's status.
boostBy: function (boost) {
let changed = false;
for (let i in boost) {
this.boosts[i] += boost[i];
if (this.boosts[i] > 6) {
this.boosts[i] = 6;
}
if (this.boosts[i] < -6) {
this.boosts[i] = -6;
}
if (this.boosts[i]) {
changed = true;
// Recalculate the modified stat
if (this.stats[i]) {
let stat = this.template.baseStats[i];
stat = Math.floor(Math.floor(2 * stat + this.set.ivs[i] + Math.floor(this.set.evs[i] / 4)) * this.level / 100 + 5);
this.modifiedStats[i] = this.stats[i] = Math.floor(stat);
if (this.boosts[i] >= 0) {
this.modifyStat(i, [1, 1.5, 2, 2.5, 3, 3.5, 4][this.boosts[i]]);
} else {
this.modifyStat(i, [100, 66, 50, 40, 33, 28, 25][-this.boosts[i]] / 100);
}
}
}
}
return changed;
},
},
// Battle scripts.
// runMove can be found in scripts.js. This function is the main one when running a move.
// It deals with the beforeMove and AfterMoveSelf events.
// This leads with partial trapping moves shennanigans after the move has been used.
// It also deals with how PP reduction works on gen 1.
runMove: function (move, pokemon, target, sourceEffect) {
move = this.getMove(move);
if (!target) target = this.resolveTarget(pokemon, move);
if (target.subFainted) delete target.subFainted;
this.setActiveMove(move, pokemon, target);
if (pokemon.movedThisTurn || !this.runEvent('BeforeMove', pokemon, target, move)) {
// Prevent invulnerability from persisting until the turn ends.
pokemon.removeVolatile('twoturnmove');
// Rampage moves end without causing confusion
delete pokemon.volatiles['lockedmove'];
this.clearActiveMove(true);
// This is only run for sleep.
this.runEvent('AfterMoveSelf', pokemon, target, move);
return;
}
if (move.beforeMoveCallback) {
if (move.beforeMoveCallback.call(this, pokemon, target, move)) {
this.clearActiveMove(true);
return;
}
}
pokemon.lastDamage = 0;
let lockedMove = this.runEvent('LockMove', pokemon);
if (lockedMove === true) lockedMove = false;
if (!lockedMove && (!pokemon.volatiles['partialtrappinglock'] || pokemon.volatiles['partialtrappinglock'].locked !== target)) {
pokemon.deductPP(move, null, target);
// On gen 1 moves are stored when they are chosen and a PP is deducted.
pokemon.side.lastMove = move.id;
pokemon.lastMove = move.id;
} else {
sourceEffect = move;
}
this.useMove(move, pokemon, target, sourceEffect);
this.singleEvent('AfterMove', move, null, pokemon, target, move);
// If rival fainted
if (target.hp <= 0) {
// We remove recharge
if (pokemon.volatiles['mustrecharge']) pokemon.removeVolatile('mustrecharge');
delete pokemon.volatiles['partialtrappinglock'];
// We remove screens
target.side.removeSideCondition('reflect');
target.side.removeSideCondition('lightscreen');
pokemon.removeVolatile('twoturnmove');
} else {
this.runEvent('AfterMoveSelf', pokemon, target, move);
}
// For partial trapping moves, we are saving the target
if (move.volatileStatus === 'partiallytrapped' && target && target.hp > 0) {
// Let's check if the lock exists
if (pokemon.volatiles['partialtrappinglock'] && target.volatiles['partiallytrapped']) {
// Here the partialtrappinglock volatile has been already applied
if (!pokemon.volatiles['partialtrappinglock'].locked) {
// If it's the first hit, we save the target
pokemon.volatiles['partialtrappinglock'].locked = target;
} else {
if (pokemon.volatiles['partialtrappinglock'].locked !== target && target !== pokemon) {
// The target switched, therefor, we must re-roll the duration, damage, and accuracy.
let duration = [2, 2, 2, 3, 3, 3, 4, 5][this.random(8)];
pokemon.volatiles['partialtrappinglock'].duration = duration;
pokemon.volatiles['partialtrappinglock'].locked = target;
// Duration reset thus partially trapped at 2 always.
target.volatiles['partiallytrapped'].duration = 2;
// We get the move position for the PP change.
let usedMovePos = -1;
for (let m in pokemon.moveset) {
if (pokemon.moveset[m].id === move.id) usedMovePos = m;
}
if (usedMovePos > -1 && pokemon.moveset[usedMovePos].pp === 0) {
// If we were on the middle of the 0 PP sequence, the PPs get reset to 63.
pokemon.moveset[usedMovePos].pp = 63;
pokemon.isStale = 2;
pokemon.isStaleSource = 'ppoverflow';
}
}
}
} // If we move to here, the move failed and there's no partial trapping lock.
}
},
// useMove can be found on scripts.js
// It is the function that actually uses the move, running ModifyMove events.
// It uses the move and then deals with the effects after the move.
useMove: function (move, pokemon, target, sourceEffect) {
if (!sourceEffect && this.effect.id) sourceEffect = this.effect;
move = this.getMove(move);
let baseMove = move;
move = this.getMoveCopy(move);
if (!target) target = this.resolveTarget(pokemon, move);
if (move.target === 'self') {
target = pokemon;
}
if (sourceEffect) move.sourceEffect = sourceEffect.id;
this.setActiveMove(move, pokemon, target);
this.singleEvent('ModifyMove', move, null, pokemon, target, move, move);
if (baseMove.target !== move.target) {
// Target changed in ModifyMove, so we must adjust it here
target = this.resolveTarget(pokemon, move);
}
move = this.runEvent('ModifyMove', pokemon, target, move, move);
if (baseMove.target !== move.target) {
// Check again, this shouldn't ever happen on Gen 1.
target = this.resolveTarget(pokemon, move);
}
if (!move) return false;
let attrs = '';
if (pokemon.fainted) {
// Removing screens upon faint.
pokemon.side.removeSideCondition('reflect');
pokemon.side.removeSideCondition('lightscreen');
return false;
}
if (move.flags['charge'] && !pokemon.volatiles[move.id]) {
attrs = '|[still]'; // Suppress the default move animation
}
if (sourceEffect) attrs += '|[from]' + this.getEffect(sourceEffect);
this.addMove('move', pokemon, move.name, target + attrs);
if (!this.singleEvent('Try', move, null, pokemon, target, move)) {
return true;
}
if (!this.runEvent('TryMove', pokemon, target, move)) {
return true;
}
if (move.ignoreImmunity === undefined) {
move.ignoreImmunity = (move.category === 'Status');
}
let damage = false;
if (target.fainted) {
this.attrLastMove('[notarget]');
this.add('-notarget');
return true;
}
damage = this.tryMoveHit(target, pokemon, move);
// Store 0 damage for last damage if move failed or dealt 0 damage.
// This only happens on moves that don't deal damage but call GetDamageVarsForPlayerAttack (disassembly).
if (!damage && (move.category !== 'Status' || (move.category === 'Status' && !(move.status in {'psn':1, 'tox':1, 'par':1}))) &&
!(move.id in {'conversion':1, 'haze':1, 'mist':1, 'focusenergy':1, 'confuseray':1, 'transform':1, 'lightscreen':1, 'reflect':1, 'substitute':1, 'mimic':1, 'leechseed':1, 'splash':1, 'softboiled':1, 'recover':1, 'rest':1})) {
pokemon.battle.lastDamage = 0;
}
// Go ahead with results of the used move.
if (!damage && damage !== 0) {
this.singleEvent('MoveFail', move, null, target, pokemon, move);
return true;
}
if (!move.negateSecondary) {
this.singleEvent('AfterMoveSecondarySelf', move, null, pokemon, target, move);
this.runEvent('AfterMoveSecondarySelf', pokemon, target, move);
}
return true;
},
// tryMoveHit can be found on scripts.js
// This function attempts a move hit and returns the attempt result before the actual hit happens.
// It deals with partial trapping weirdness and accuracy bugs as well.
tryMoveHit: function (target, pokemon, move, spreadHit) {
let boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
let doSelfDestruct = true;
let damage = 0;
// First, check if the Pokémon is immune to this move.
if (move.ignoreImmunity !== true && !move.ignoreImmunity[move.type] && !target.runImmunity(move.type, true)) {
if (move.selfdestruct) {
this.faint(pokemon, pokemon, move);
}
return false;
}
// Now, let's calculate the accuracy.
let accuracy = move.accuracy;
// Partial trapping moves: true accuracy while it lasts
if (move.volatileStatus === 'partiallytrapped' && pokemon.volatiles['partialtrappinglock'] && target === pokemon.volatiles['partialtrappinglock'].locked) {
accuracy = true;
}
// If a sleep inducing move is used while the user is recharging, the accuracy is true.
if (move.status === 'slp' && target && target.volatiles['mustrecharge']) {
accuracy = true;
}
// OHKO moves only have a chance to hit if the user is at least as fast as the target
if (move.ohko) {
if (target.speed > pokemon.speed) {
this.add('-immune', target, '[ohko]');
return false;
}
}
// Calculate true accuracy for gen 1, which uses 0-255.
if (accuracy !== true) {
accuracy = Math.floor(accuracy * 255 / 100);
// Check also for accuracy modifiers.
if (!move.ignoreAccuracy) {
if (pokemon.boosts.accuracy > 0) {
accuracy *= boostTable[pokemon.boosts.accuracy];
} else {
accuracy = Math.floor(accuracy / boostTable[-pokemon.boosts.accuracy]);
}
}
if (!move.ignoreEvasion) {
if (target.boosts.evasion > 0 && !move.ignorePositiveEvasion) {
accuracy = Math.floor(accuracy / boostTable[target.boosts.evasion]);
} else if (target.boosts.evasion < 0) {
accuracy *= boostTable[-target.boosts.evasion];
}
}
}
accuracy = this.runEvent('Accuracy', target, pokemon, move, accuracy);
// Moves that target the user do not suffer from the 1/256 miss chance.
if (move.target === 'self' && accuracy !== true) accuracy++;
// 1/256 chance of missing always, no matter what. Besides the aforementioned exceptions.
if (accuracy !== true && this.random(256) >= accuracy) {
this.attrLastMove('[miss]');
this.add('-miss', pokemon);
damage = false;
}
// If damage is 0 and not false it means it didn't miss, let's calc.
if (damage !== false) {
pokemon.lastDamage = 0;
if (move.multihit) {
let hits = move.multihit;
if (hits.length) {
// Yes, it's hardcoded... meh
if (hits[0] === 2 && hits[1] === 5) {
hits = [2, 2, 3, 3, 4, 5][this.random(6)];
} else {
hits = this.random(hits[0], hits[1] + 1);
}
}
hits = Math.floor(hits);
// In gen 1, all the hits have the same damage for multihits move
let moveDamage = 0;
let firstDamage;
let i;
for (i = 0; i < hits && target.hp && pokemon.hp; i++) {
if (i === 0) {
// First hit, we calculate
moveDamage = this.moveHit(target, pokemon, move);
firstDamage = moveDamage;
} else {
// We get the previous damage to make it fix damage
move.damage = firstDamage;
moveDamage = this.moveHit(target, pokemon, move);
}
if (moveDamage === false) break;
damage = (moveDamage || 0);
if (target.subFainted) {
i++;
break;
}
}
move.damage = null;
if (i === 0) return true;
this.add('-hitcount', target, i);
} else {
damage = this.moveHit(target, pokemon, move);
}
}
if (move.category !== 'Status') target.gotAttacked(move, damage, pokemon);
// Checking if substitute fainted
if (target.subFainted) doSelfDestruct = false;
if (move.selfdestruct && doSelfDestruct) {
this.faint(pokemon, pokemon, move);
}
// The move missed.
if (!damage && damage !== 0) {
// Delete the partial trap lock if necessary.
delete pokemon.volatiles['partialtrappinglock'];
return false;
}
if (move.ohko) this.add('-ohko');
if (!move.negateSecondary) {
this.singleEvent('AfterMoveSecondary', move, null, target, pokemon, move);
this.runEvent('AfterMoveSecondary', target, pokemon, move);
}
return damage;
},
// move Hit can be found on scripts.js
// It deals with the actual move hit, as the name indicates, dealing damage and/or effects.
// This function also deals with the Gen 1 Substitute behaviour on the hitting process.
moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) {
let damage = 0;
move = this.getMoveCopy(move);
if (!isSecondary && !isSelf) this.setActiveMove(move, pokemon, target);
let hitResult = true;
if (!moveData) moveData = move;
if (move.ignoreImmunity === undefined) {
move.ignoreImmunity = (move.category === 'Status');
}
// We get the sub to the target to see if it existed
let targetSub = (target) ? target.volatiles['substitute'] : false;
let targetHadSub = (targetSub !== null && targetSub !== false && (typeof targetSub !== 'undefined'));
if (target) {
hitResult = this.singleEvent('TryHit', moveData, {}, target, pokemon, move);
// Handle here the applying of partial trapping moves to Pokémon with Substitute
if (targetSub && moveData.volatileStatus && moveData.volatileStatus === 'partiallytrapped') {
target.addVolatile(moveData.volatileStatus, pokemon, move);
}
if (!hitResult) {
if (hitResult === false) this.add('-fail', target);
return false;
}
// Only run the hit events for the hit itself, not the secondary or self hits
if (!isSelf && !isSecondary) {
hitResult = this.runEvent('TryHit', target, pokemon, move);
if (!hitResult) {
if (hitResult === false) this.add('-fail', target);
// Special Substitute hit flag
if (hitResult !== 0) {
return false;
}
}
if (!this.runEvent('TryFieldHit', target, pokemon, move)) {
return false;
}
} else if (isSecondary && !moveData.self) {
hitResult = this.runEvent('TrySecondaryHit', target, pokemon, moveData);
}
if (hitResult === 0) {
target = null;
} else if (!hitResult) {
if (hitResult === false) this.add('-fail', target);
return false;
}
}
if (target) {
let didSomething = false;
damage = this.getDamage(pokemon, target, moveData);
// getDamage has several possible return values:
//
// a number:
// means that much damage is dealt (0 damage still counts as dealing
// damage for the purposes of things like Static)
// false:
// gives error message: "But it failed!" and move ends
// null:
// the move ends, with no message (usually, a custom fail message
// was already output by an event handler)
// undefined:
// means no damage is dealt and the move continues
//
// basically, these values have the same meanings as they do for event
// handlers.
if ((damage || damage === 0) && !target.fainted) {
if (move.noFaint && damage >= target.hp) {
damage = target.hp - 1;
}
damage = this.damage(damage, target, pokemon, move);
if (!(damage || damage === 0)) return false;
didSomething = true;
} else if (damage === false && typeof hitResult === 'undefined') {
this.add('-fail', target);
}
if (damage === false || damage === null) {
return false;
}
if (moveData.boosts && !target.fainted) {
this.boost(moveData.boosts, target, pokemon, move);
// Check the status of the Pokémon whose turn is not.
// When a move that affects stat levels is used, if the Pokémon whose turn it is not right now is paralyzed or
// burned, the correspoding stat penalties will be applied again to that Pokémon.
if (pokemon.side.foe.active[0] && pokemon.side.foe.active[0].status) {
// If it's paralysed, quarter its speed.
if (pokemon.side.foe.active[0].status === 'par') {
pokemon.side.foe.active[0].modifyStat('spe', 0.25);
}
// If it's burned, halve its attack.
if (pokemon.side.foe.active[0].status === 'brn') {
pokemon.side.foe.active[0].modifyStat('atk', 0.5);
}
}
}
if (moveData.heal && !target.fainted) {
let d = target.heal(Math.floor(target.maxhp * moveData.heal[0] / moveData.heal[1]));
if (!d) {
this.add('-fail', target);
return false;
}
this.add('-heal', target, target.getHealth);
didSomething = true;
}
if (moveData.status) {
// Gen 1 bug: If the target has just used hyperbeam and must recharge, its status will be ignored and put to sleep.
// This does NOT revert the paralyse speed drop or the burn attack drop.
if (!target.status || moveData.status === 'slp' && target.volatiles['mustrecharge']) {
if (target.setStatus(moveData.status, pokemon, move)) {
// Gen 1 mechanics: The burn attack drop and the paralyse speed drop are applied here directly on stat modifiers.
if (moveData.status === 'brn') target.modifyStat('atk', 0.5);
if (moveData.status === 'par') target.modifyStat('spe', 0.25);
}
} else if (!isSecondary) {
if (target.status === moveData.status) {
this.add('-fail', target, target.status);
} else {
this.add('-fail', target);
}
}
didSomething = true;
}
if (moveData.forceStatus) {
if (target.setStatus(moveData.forceStatus, pokemon, move)) {
if (moveData.forceStatus === 'brn') target.modifyStat('atk', 0.5);
if (moveData.forceStatus === 'par') target.modifyStat('spe', 0.25);
didSomething = true;
}
}
if (moveData.volatileStatus) {
if (target.addVolatile(moveData.volatileStatus, pokemon, move)) {
didSomething = true;
}
}
if (moveData.sideCondition) {
if (target.side.addSideCondition(moveData.sideCondition, pokemon, move)) {
didSomething = true;
}
}
if (moveData.pseudoWeather) {
if (this.addPseudoWeather(moveData.pseudoWeather, pokemon, move)) {
didSomething = true;
}
}
// Hit events
hitResult = this.singleEvent('Hit', moveData, {}, target, pokemon, move);
if (!isSelf && !isSecondary) {
this.runEvent('Hit', target, pokemon, move);
}
if (!hitResult && !didSomething) {
if (hitResult === false) this.add('-fail', target);
return false;
}
}
let targetHasSub = false;
if (target) {
let targetSub = target.getVolatile('substitute');
if (targetSub !== null) {
targetHasSub = (targetSub.hp > 0);
}
}
// Here's where self effects are applied.
let doSelf = (targetHadSub && targetHasSub) || !targetHadSub;
if (moveData.self && (doSelf || moveData.self.volatileStatus === 'partialtrappinglock')) {
this.moveHit(pokemon, pokemon, move, moveData.self, isSecondary, true);
}
// Now we can save the partial trapping damage.
if (pokemon.volatiles['partialtrappinglock']) {
pokemon.volatiles['partialtrappinglock'].damage = pokemon.lastDamage;
}
// Apply move secondaries.
if (moveData.secondaries) {
for (let i = 0; i < moveData.secondaries.length; i++) {
// We check here whether to negate the probable secondary status if it's para, burn, or freeze.
// In the game, this is checked and if true, the random number generator is not called.
// That means that a move that does not share the type of the target can status it.
// If a move that was not fire-type would exist on Gen 1, it could burn a Pokémon.
if (!(moveData.secondaries[i].status && moveData.secondaries[i].status in {'par':1, 'brn':1, 'frz':1} && target && target.hasType(move.type))) {
let effectChance = Math.floor(moveData.secondaries[i].chance * 255 / 100);
if (typeof moveData.secondaries[i].chance === 'undefined' || this.random(256) < effectChance) {
this.moveHit(target, pokemon, move, moveData.secondaries[i], true, isSelf);
}
}
}
}
if (move.selfSwitch && pokemon.hp) {
pokemon.switchFlag = move.selfSwitch;
}
return damage;
},
// boost can be found on battle-engine.js on Battle object.
// It deals with Pokémon stat boosting, including Gen 1 buggy behaviour with burn and paralyse.
boost: function (boost, target, source, effect) {
if (this.event) {
if (!target) target = this.event.target;
if (!source) source = this.event.source;
if (!effect) effect = this.effect;
}
if (!target || !target.hp) return 0;
effect = this.getEffect(effect);
boost = this.runEvent('Boost', target, source, effect, Object.assign({}, boost));
for (let i in boost) {
let currentBoost = {};
currentBoost[i] = boost[i];
if (boost[i] !== 0 && target.boostBy(currentBoost)) {
let msg = '-boost';
if (boost[i] < 0) {
msg = '-unboost';
boost[i] = -boost[i];
// Re-add attack and speed drops if not present
if (i === 'atk' && target.status === 'brn' && !target.volatiles['brnattackdrop']) {
target.addVolatile('brnattackdrop');
}
if (i === 'spe' && target.status === 'par' && !target.volatiles['parspeeddrop']) {
target.addVolatile('parspeeddrop');
}
} else {
// Check for boost increases deleting attack or speed drops
if (i === 'atk' && target.status === 'brn' && target.volatiles['brnattackdrop']) {
target.removeVolatile('brnattackdrop');
}
if (i === 'spe' && target.status === 'par' && target.volatiles['parspeeddrop']) {
target.removeVolatile('parspeeddrop');
}
}
if (effect.effectType === 'Move') {
this.add(msg, target, i, boost[i]);
} else {
this.add(msg, target, i, boost[i], '[from] ' + effect.fullname);
}
this.runEvent('AfterEachBoost', target, source, effect, currentBoost);
}
}
this.runEvent('AfterBoost', target, source, effect, boost);
},
// damage can be found in battle-engine.js on the Battle object. Not to confuse with BattlePokemon.prototype.damage
// It calculates and executes the damage damage from source to target with effect.
// It also deals with recoil and drains.
damage: function (damage, target, source, effect) {
if (this.event) {
if (!target) target = this.event.target;
if (!source) source = this.event.source;
if (!effect) effect = this.effect;
}
if (!target || !target.hp) return 0;
effect = this.getEffect(effect);
if (!(damage || damage === 0)) return damage;
if (damage !== 0) damage = this.clampIntRange(damage, 1);
if (effect.id !== 'struggle-recoil') { // Struggle recoil is not affected by effects
damage = this.runEvent('Damage', target, source, effect, damage);
if (!(damage || damage === 0)) {
this.debug('damage event failed');
return damage;
}
}
if (damage !== 0) damage = this.clampIntRange(damage, 1);
if (!(effect.id in {'recoil':1, 'drain':1}) && effect.effectType !== 'Status') target.battle.lastDamage = damage;
damage = target.damage(damage, source, effect);
if (source) source.lastDamage = damage;
let name = effect.fullname;
if (name === 'tox') name = 'psn';
switch (effect.id) {
case 'partiallytrapped':
this.add('-damage', target, target.getHealth, '[from] ' + this.effectData.sourceEffect.fullname, '[partiallytrapped]');
break;
default:
if (effect.effectType === 'Move') {
this.add('-damage', target, target.getHealth);
} else if (source && source !== target) {
this.add('-damage', target, target.getHealth, '[from] ' + effect.fullname, '[of] ' + source);
} else {
this.add('-damage', target, target.getHealth, '[from] ' + name);
}
break;
}
if (effect.recoil && source) {
this.damage(this.clampIntRange(Math.floor(damage * effect.recoil[0] / effect.recoil[1]), 1), source, target, 'recoil');
}
if (effect.drain && source) {
this.heal(this.clampIntRange(Math.floor(damage * effect.drain[0] / effect.drain[1]), 1), source, target, 'drain');
}
if (target.fainted || target.hp <= 0) {
this.faint(target);
this.queue = [];
} else {
damage = this.runEvent('AfterDamage', target, source, effect, damage);
}
return damage;
},
// directDamage can be found on battle-engine.js in Battle object
// It deals direct damage damage from source to target with effect.
// It also deals with Gen 1 weird Substitute behaviour.
directDamage: function (damage, target, source, effect) {
if (this.event) {
if (!target) target = this.event.target;
if (!source) source = this.event.source;
if (!effect) effect = this.effect;
}
if (!target || !target.hp) return 0;
if (!damage) return 0;
damage = this.clampIntRange(damage, 1);
// Check here for Substitute on confusion since it's not exactly a move that causes the damage and thus it can't TryMoveHit.
// The hi jump kick recoil also hits the sub.
if (effect.id in {'confusion': 1, 'highjumpkick': 1} && target.volatiles['substitute']) {
target.volatiles['substitute'].hp -= damage;
if (target.volatiles['substitute'].hp <= 0) {
target.removeVolatile('substitute');
target.subFainted = true;
} else {
this.add('-activate', target, 'Substitute', '[damage]');
}
} else {
damage = target.damage(damage, source, effect);
// Now we sent the proper -damage.
switch (effect.id) {
case 'strugglerecoil':
this.add('-damage', target, target.getHealth, '[from] recoil');
break;
case 'confusion':
this.add('-damage', target, target.getHealth, '[from] confusion');
break;
default:
this.add('-damage', target, target.getHealth);
break;
}
if (target.fainted) this.faint(target);
}
return damage;
},
// getDamage can be found on battle-engine.js on the Battle object.
// It calculates the damage pokemon does to target with move.
getDamage: function (pokemon, target, move, suppressMessages) {
// First of all, we get the move.
if (typeof move === 'string') move = this.getMove(move);
if (typeof move === 'number') {
move = {
basePower: move,
type: '???',
category: 'Physical',
flags: {},
};
}
// Let's see if the target is immune to the move.
if (!move.ignoreImmunity || (move.ignoreImmunity !== true && !move.ignoreImmunity[move.type])) {
if (!target.runImmunity(move.type, true)) {
return false;
}
}
// Is it an OHKO move?
if (move.ohko) {
return target.maxhp;
}
// We edit the damage through move's damage callback if necessary.
if (move.damageCallback) {
return move.damageCallback.call(this, pokemon, target);
}
// We take damage from damage=level moves (seismic toss).
if (move.damage === 'level') {
return pokemon.level;
}
// If there's a fix move damage, we return that.
if (move.damage) {
return move.damage;
}
// If it's the first hit on a Normal-type partially trap move, it hits Ghosts anyways but damage is 0.
if (move.volatileStatus === 'partiallytrapped' && move.type === 'Normal' && target.hasType('Ghost')) {
return 0;
}
// Let's check if we are in middle of a partial trap sequence to return the previous damage.
if (pokemon.volatiles['partialtrappinglock'] && (target === pokemon.volatiles['partialtrappinglock'].locked)) {
return pokemon.volatiles['partialtrappinglock'].damage;
}
// We check the category and typing to calculate later on the damage.
if (!move.category) move.category = 'Physical';
if (!move.defensiveCategory) move.defensiveCategory = move.category;
// '???' is typeless damage: used for Struggle and Confusion etc
if (!move.type) move.type = '???';
let type = move.type;
// We get the base power and apply basePowerCallback if necessary.
let basePower = move.basePower;
if (move.basePowerCallback) {
basePower = move.basePowerCallback.call(this, pokemon, target, move);
}
// We check if the base power is proper.
if (!basePower) {
if (basePower === 0) return; // Returning undefined means not dealing damage
return basePower;
}
basePower = this.clampIntRange(basePower, 1);
// Checking for the move's Critical Hit possibility. We check if it's a 100% crit move, otherwise we calculate the chance.
move.crit = move.willCrit || false;
if (!move.crit) {
// In gen 1, the critical chance is based on speed.
// First, we get the base speed, divide it by 2 and floor it. This is our current crit chance.
let critChance = Math.floor(pokemon.template.baseStats['spe'] / 2);
// Now we check for focus energy volatile.
if (pokemon.volatiles['focusenergy']) {
// If it exists, crit chance is divided by 2 again and floored.
critChance = Math.floor(critChance / 2);
} else {
// Normally, without focus energy, crit chance is multiplied by 2 and capped at 255 here.
critChance = this.clampIntRange(critChance * 2, 1, 255);
}
// Now we check for the move's critical hit ratio.
if (move.critRatio === 1) {
// Normal hit ratio, we divide the crit chance by 2 and floor the result again.
critChance = Math.floor(critChance / 2);
} else if (move.critRatio === 2) {
// High crit ratio, we multiply the result so far by 4 and cap it at 255.
critChance = this.clampIntRange(critChance * 4, 1, 255);
}
// Last, we check deppending on ratio if the move critical hits or not.
// We compare our critical hit chance against a random number between 0 and 255.
// If the random number is lower, we get a critical hit. This means there is always a 1/255 chance of not hitting critically.
if (critChance > 0) {
move.crit = (this.random(256) < critChance);
}
}
// Happens after crit calculation.
if (basePower) {
basePower = this.runEvent('BasePower', pokemon, target, move, basePower);
if (move.basePowerModifier) {
basePower *= move.basePowerModifier;
}
}
if (!basePower) return 0;
basePower = this.clampIntRange(basePower, 1);
// We now check attacker's and defender's stats.
let level = pokemon.level;
let attacker = pokemon;
let defender = target;
if (move.useTargetOffensive) attacker = target;
if (move.useSourceDefensive) defender = pokemon;
let atkType = (move.category === 'Physical') ? 'atk' : 'spa';
let defType = (move.defensiveCategory === 'Physical') ? 'def' : 'spd';
let attack = attacker.getStat(atkType);
let defense = defender.getStat(defType);
// In gen 1, screen effect is applied here.
if ((defType === 'def' && defender.volatiles['reflect']) || (defType === 'spd' && defender.volatiles['lightscreen'])) {
this.debug('Screen doubling (Sp)Def');
defense *= 2;
defense = this.clampIntRange(defense, 1, 1998);
}
// In the event of a critical hit, the ofense and defense changes are ignored.
// This includes both boosts and screens.
// Also, level is doubled in damage calculation.
if (move.crit) {
move.ignoreOffensive = true;
move.ignoreDefensive = true;
level *= 2;
if (!suppressMessages) this.add('-crit', target);
}
if (move.ignoreOffensive) {
this.debug('Negating (sp)atk boost/penalty.');
attack = attacker.getStat(atkType, true);
}
if (move.ignoreDefensive) {
this.debug('Negating (sp)def boost/penalty.');
// No screens
defense = target.getStat(defType, true);
}
// When either attack or defense are higher than 256, they are both divided by 4 and moded by 256.
// This is what cuases the roll over bugs.
if (attack >= 256 || defense >= 256) {
attack = this.clampIntRange(Math.floor(attack / 4) % 256, 1);
// Defense isn't checked on the cartridge, but we don't want those / 0 bugs on the sim.
defense = this.clampIntRange(Math.floor(defense / 4) % 256, 1);
}
// Self destruct moves halve defense at this point.
if (move.selfdestruct && defType === 'def') {
defense = this.clampIntRange(Math.floor(defense / 2), 1);
}
// Let's go with the calculation now that we have what we need.
// We do it step by step just like the game does.
let damage = level * 2;
damage = Math.floor(damage / 5);
damage += 2;
damage *= basePower;
damage *= attack;
damage = Math.floor(damage / defense);
damage = this.clampIntRange(Math.floor(damage / 50), 1, 997);
damage += 2;
// STAB damage bonus, the "???" type never gets STAB
if (type !== '???' && pokemon.hasType(type)) {
damage += Math.floor(damage / 2);
}
// Type effectiveness.
// The order here is not correct, must change to check the move versus each type.
let totalTypeMod = this.getEffectiveness(type, target);
// Super effective attack
if (totalTypeMod > 0) {
if (!suppressMessages) this.add('-supereffective', target);
damage *= 20;
damage = Math.floor(damage / 10);
if (totalTypeMod >= 2) {
damage *= 20;
damage = Math.floor(damage / 10);
}
}
if (totalTypeMod < 0) {
if (!suppressMessages) this.add('-resisted', target);
damage *= 5;
damage = Math.floor(damage / 10);
if (totalTypeMod <= -2) {
damage *= 5;
damage = Math.floor(damage / 10);
}
}
// If damage becomes 0, the move is made to miss.
// This occurs when damage was either 2 or 3 prior to applying STAB/Type matchup, and target is 4x resistant to the move.
if (damage === 0) return damage;
// Apply random factor is damage is greater than 1
if (damage > 1) {
damage *= this.random(217, 256);
damage = Math.floor(damage / 255);
if (damage > target.hp && !target.volatiles['substitute']) damage = target.hp;
if (target.volatiles['substitute'] && damage > target.volatiles['substitute'].hp) damage = target.volatiles['substitute'].hp;
}
// And we are done.
return Math.floor(damage);
},
// This is random teams making for gen 1.
// Challenge Cup or CC teams are basically fully random teams.
randomCCTeam: function (side) {
let team = [];
let hasDexNumber = {};
let formes = [[], [], [], [], [], []];
// Pick six random Pokémon, no repeats.
let num;
for (let i = 0; i < 6; i++) {
do {
num = this.random(151) + 1;
} while (num in hasDexNumber);
hasDexNumber[num] = i;
}
let formeCounter = 0;
for (let id in this.data.Pokedex) {
if (!(this.data.Pokedex[id].num in hasDexNumber)) continue;
let template = this.getTemplate(id);
if (!template.learnset || template.forme) continue;
formes[hasDexNumber[template.num]].push(template.species);
if (++formeCounter >= 6) {
// Gen 1 had no alternate formes, so we can break out of the loop already.
break;
}
}
for (let i = 0; i < 6; i++) {
// Choose forme.
let poke = formes[i][this.random(formes[i].length)];
let template = this.getTemplate(poke);
// Level balance: calculate directly from stats rather than using some silly lookup table.
let mbstmin = 1307;
let stats = template.baseStats;
// Modified base stat total assumes 15 DVs, 255 EVs in every stat
let mbst = (stats["hp"] * 2 + 30 + 63 + 100) + 10;
mbst += (stats["atk"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["def"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["spa"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["spd"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["spe"] * 2 + 30 + 63 + 100) + 5;
let level = Math.floor(100 * mbstmin / mbst); // Initial level guess will underestimate
while (level < 100) {
mbst = Math.floor((stats["hp"] * 2 + 30 + 63 + 100) * level / 100 + 10);
mbst += Math.floor(((stats["atk"] * 2 + 30 + 63 + 100) * level / 100 + 5) * level / 100); //since damage is roughly proportional to lvl
mbst += Math.floor((stats["def"] * 2 + 30 + 63 + 100) * level / 100 + 5);
mbst += Math.floor(((stats["spa"] * 2 + 30 + 63 + 100) * level / 100 + 5) * level / 100);
mbst += Math.floor((stats["spd"] * 2 + 30 + 63 + 100) * level / 100 + 5);
mbst += Math.floor((stats["spe"] * 2 + 30 + 63 + 100) * level / 100 + 5);
if (mbst >= mbstmin) break;
level++;
}
// Random DVs.
let ivs = {
hp: this.random(30),
atk: this.random(30),
def: this.random(30),
spa: this.random(30),
spd: this.random(30),
spe: this.random(30),
};
// Maxed EVs.
let evs = {hp: 255, atk: 255, def: 255, spa: 255, spd: 255, spe: 255};
// Four random unique moves from movepool. don't worry about "attacking" or "viable".
// Since Gens 1 and 2 learnsets are shared, we need to weed out Gen 2 moves.
let moves;
let pool = [];
for (let move in template.learnset) {
if (this.getMove(move).gen === 1) pool.push(move);
}
if (pool.length <= 4) {
moves = pool;
} else {
moves = [this.sampleNoReplace(pool), this.sampleNoReplace(pool), this.sampleNoReplace(pool), this.sampleNoReplace(pool)];
}
team.push({
name: poke,
moves: moves,
ability: 'None',
evs: evs,
ivs: ivs,
item: '',
level: level,
happiness: 0,
shiny: false,
nature: 'Serious',
});
}
return team;
},
// Random team generation for Gen 1 Random Battles.
randomTeam: function (side) {
// Get what we need ready.
let pokemonLeft = 0;
let pokemon = [];
let handicapMons = {'magikarp':1, 'weedle':1, 'kakuna':1, 'caterpie':1, 'metapod':1, 'ditto':1};
let nuTiers = {'UU':1, 'BL':1, 'NFE':1, 'LC':1, 'NU':1};
let uuTiers = {'NFE':1, 'UU':1, 'BL':1, 'NU':1};
let n = 1;
let pokemonPool = [];
for (let id in this.data.FormatsData) {
// FIXME: Not ES-compliant
if (n++ > 151 || !this.data.FormatsData[id].randomBattleMoves) continue;
pokemonPool.push(id);
}
// Now let's store what we are getting.
let typeCount = {};
let weaknessCount = {'Electric':0, 'Psychic':0, 'Water':0, 'Ice':0};
let uberCount = 0;
let nuCount = 0;
let hasShitmon = false;
while (pokemonPool.length && pokemonLeft < 6) {
let template = this.getTemplate(this.sampleNoReplace(pokemonPool));
if (!template.exists) continue;
// Bias the tiers so you get less shitmons and only one of the two Ubers.
// If you have a shitmon, you're covered in OUs and Ubers if possible
if ((template.speciesid in handicapMons) && nuCount > 1) continue;
let tier = template.tier;
switch (tier) {
case 'LC':
if (nuCount > 1 || hasShitmon) continue;
break;
case 'Uber':
// Unless you have one of the worst mons, in that case we allow luck to give you all Ubers.
if (uberCount >= 1 && !hasShitmon) continue;
break;
default:
if (uuTiers[tier] && pokemonPool.length > 1 && (hasShitmon || (nuCount > 2 && this.random(2) >= 1))) continue;
}
let skip = false;
// Limit 2 of any type as well. Diversity and minor weakness count.
// The second of a same type has halved chance of being added.
let types = template.types;
for (let t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 || (typeCount[types[t]] === 1 && this.random(2) && pokemonPool.length > 1)) {
skip = true;
break;
}
}
if (skip) continue;
// We need a weakness count of spammable attacks to avoid being swept by those.
// Spammable attacks are: Thunderbolt, Psychic, Surf, Blizzard.
let pokemonWeaknesses = [];
for (let type in weaknessCount) {
let increaseCount = Tools.getImmunity(type, template) && Tools.getEffectiveness(type, template) > 0;
if (!increaseCount) continue;
if (weaknessCount[type] >= 2) {
skip = true;
break;
}
pokemonWeaknesses.push(type);
}
if (skip) continue;
// The set passes the limitations.
let set = this.randomSet(template, pokemon.length);
pokemon.push(set);
// Now let's increase the counters. First, the Pokémon left.
pokemonLeft++;
// Type counter.
for (let t = 0; t < types.length; t++) {
if (typeCount[types[t]]) {
typeCount[types[t]]++;
} else {
typeCount[types[t]] = 1;
}
}
// Weakness counter.
for (let t = 0; t < pokemonWeaknesses.length; t++) {
weaknessCount[pokemonWeaknesses[t]]++;
}
// Increment tier bias counters.
if (tier === 'Uber') {
uberCount++;
} else if (nuTiers[tier]) {
nuCount++;
}
// Is it Magikarp?
if (template.speciesid in handicapMons) hasShitmon = true;
}
return pokemon;
},
init: function () {
this.modData('Learnsets', 'bulbasaur').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'ivysaur').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'venusaur').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'charmander').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'charmeleon').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'charizard').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'squirtle').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'wartortle').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'blastoise').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'butterfree').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'beedrill').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'pidgey').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'pidgeotto').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'pidgeot').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'rattata').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'raticate').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'spearow').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'fearow').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'ekans').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'arbok').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'pikachu').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'raichu').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'sandshrew').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'sandslash').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'nidoranf').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'nidorina').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'nidoqueen').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'nidoranm').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'nidorino').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'nidoking').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'clefairy').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'clefable').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'vulpix').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'ninetales').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'jigglypuff').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'wigglytuff').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'zubat').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'golbat').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'oddish').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'gloom').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'vileplume').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'paras').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'parasect').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'venonat').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'venomoth').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'diglett').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'dugtrio').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'meowth').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'persian').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'psyduck').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'golduck').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'mankey').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'primeape').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'growlithe').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'arcanine').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'poliwag').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'poliwhirl').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'poliwrath').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'abra').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'kadabra').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'alakazam').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'machop').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'machoke').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'machamp').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'bellsprout').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'weepinbell').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'victreebel').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'tentacool').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'tentacruel').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'geodude').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'graveler').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'golem').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'ponyta').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'rapidash').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'slowpoke').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'slowbro').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'magnemite').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'magneton').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'farfetchd').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'doduo').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'dodrio').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'seel').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'dewgong').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'grimer').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'muk').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'shellder').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'cloyster').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'gastly').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'haunter').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'gengar').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'onix').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'drowzee').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'hypno').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'krabby').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'kingler').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'voltorb').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'electrode').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'exeggcute').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'exeggutor').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'cubone').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'marowak').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'hitmonchan').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'hitmonlee').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'lickitung').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'koffing').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'weezing').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'rhyhorn').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'rhydon').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'chansey').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'tangela').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'kangaskhan').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'horsea').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'seadra').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'goldeen').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'seaking').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'staryu').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'starmie').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'mrmime').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'scyther').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'jynx').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'electabuzz').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'magmar').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'pinsir').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'tauros').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'gyarados').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'lapras').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'eevee').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'vaporeon').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'jolteon').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'flareon').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'porygon').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'omanyte').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'omastar').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'kabuto').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'kabutops').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'aerodactyl').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'snorlax').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'articuno').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'zapdos').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'moltres').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'dratini').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'dragonair').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'dragonite').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'mewtwo').learnset.hiddenpower = ['1L1'];
this.modData('Learnsets', 'mew').learnset.hiddenpower = ['1L1'];
},
// Random set generation for Gen 1 Random Battles.
randomSet: function (template, slot) {
if (slot === undefined) slot = 1;
template = this.getTemplate(template);
if (!template.exists) template = this.getTemplate('pikachu'); // Because Gen 1.
let movePool = template.randomBattleMoves.slice();
let moves = [];
let hasType = {};
hasType[template.types[0]] = true;
if (template.types[1]) hasType[template.types[1]] = true;
let hasMove = {};
let counter = {};
let setupType = '';
// Moves that boost Attack:
let PhysicalSetup = {
swordsdance:1, sharpen:1,
};
// Moves which boost Special Attack:
let SpecialSetup = {
amnesia:1, growth:1,
};
// Add the mandatory move
if (template.essentialMove) {
moves.push(template.essentialMove);
}
do {
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length < 4 && movePool.length) {
let moveid = this.sampleNoReplace(movePool);
moves.push(moveid);
}
// Only do move choosing if we have backup moves in the pool...
if (movePool.length) {
hasMove = {};
counter = {Physical: 0, Special: 0, Status: 0, physicalsetup: 0, specialsetup: 0};
for (let k = 0; k < moves.length; k++) {
let move = this.getMove(moves[k]);
let moveid = move.id;
hasMove[moveid] = true;
if (!move.damage && !move.damageCallback) {
counter[move.category]++;
}
if (PhysicalSetup[moveid]) {
counter['physicalsetup']++;
}
if (SpecialSetup[moveid]) {
counter['specialsetup']++;
}
}
if (counter['specialsetup']) {
setupType = 'Special';
} else if (counter['physicalsetup']) {
setupType = 'Physical';
}
for (let k = 0; k < moves.length; k++) {
let moveid = moves[k];
if (moveid === template.essentialMove) continue;
let move = this.getMove(moveid);
let rejected = false;
if (!template.essentialMove || moveid !== template.essentialMove) {
switch (moveid) {
// bad after setup
case 'seismictoss': case 'nightshade':
if (setupType) rejected = true;
break;
// bit redundant to have both
case 'flamethrower':
if (hasMove['fireblast']) rejected = true;
break;
case 'fireblast':
if (hasMove['flamethrower']) rejected = true;
break;
case 'icebeam':
if (hasMove['blizzard']) rejected = true;
break;
// Hydropump and surf are both valid options, just avoid one with eachother.
case 'hydropump':
if (hasMove['surf']) rejected = true;
break;
case 'surf':
if (hasMove['hydropump']) rejected = true;
break;
case 'petaldance': case 'solarbeam':
if (hasMove['megadrain'] || hasMove['razorleaf']) rejected = true;
break;
case 'megadrain':
if (hasMove['razorleaf']) rejected = true;
break;
case 'thunder':
if (hasMove['thunderbolt']) rejected = true;
break;
case 'thunderbolt':
if (hasMove['thunder']) rejected = true;
break;
case 'bonemerang':
if (hasMove['earthquake']) rejected = true;
break;
case 'rest':
if (hasMove['recover'] || hasMove['softboiled']) rejected = true;
break;
case 'softboiled':
if (hasMove['recover']) rejected = true;
break;
case 'sharpen':
case 'swordsdance':
if (counter['Special'] > counter['Physical'] || hasMove['slash'] || !counter['Physical'] || hasMove['growth']) rejected = true;
break;
case 'growth':
if (counter['Special'] < counter['Physical'] || hasMove['swordsdance'] || hasMove['amnesia']) rejected = true;
break;
case 'doubleedge':
if (hasMove['bodyslam']) rejected = true;
break;
case 'mimic':
if (hasMove['mirrormove']) rejected = true;
break;
case 'superfang':
if (hasMove['bodyslam']) rejected = true;
break;
case 'rockslide':
if (hasMove['earthquake'] && hasMove['bodyslam'] && hasMove['hyperbeam']) rejected = true;
break;
case 'bodyslam':
if (hasMove['thunderwave']) rejected = true;
break;
case 'bubblebeam':
if (hasMove['blizzard']) rejected = true;
break;
case 'screech':
if (hasMove['slash']) rejected = true;
break;
case 'slash':
if (hasMove['swordsdance']) rejected = true;
break;
case 'megakick':
if (hasMove['bodyslam']) rejected = true;
break;
case 'eggbomb':
if (hasMove['hyperbeam']) rejected = true;
break;
case 'triattack':
if (hasMove['doubleedge']) rejected = true;
break;
case 'fissure':
if (hasMove['horndrill']) rejected = true;
break;
case 'supersonic':
if (hasMove['confuseray']) rejected = true;
break;
case 'poisonpowder':
if (hasMove['toxic'] || counter['Status'] > 1) rejected = true;
break;
case 'stunspore':
if (hasMove['sleeppowder'] || counter['Status'] > 1) rejected = true;
break;
case 'sleeppowder':
if (hasMove['stunspore'] || counter['Status'] > 2) rejected = true;
break;
case 'toxic':
if (hasMove['sleeppowder'] || hasMove['stunspore'] || counter['Status'] > 1) rejected = true;
break;
} // End of switch for moveid
}
if (rejected) {
moves.splice(k, 1);
break;
}
counter[move.category]++;
} // End of for
} // End of the check for more than 4 moves on moveset.
} while (moves.length < 4 && movePool.length);
let levelScale = {
LC: 96,
NFE: 90,
NU: 90,
UU: 85,
OU: 79,
Uber: 74,
};
// Really bad Pokemon and jokemons, MEWTWO, Pokémon with higher tier in Wrap metas.
let customScale = {
Caterpie: 99, Kakuna: 99, Magikarp: 99, Metapod: 99, Weedle: 99,
Clefairy: 95, "Farfetch'd": 99, Jigglypuff: 99, Ditto: 99, Mewtwo: 70,
Dragonite: 85, Cloyster: 83, Staryu: 90,
};
let level = levelScale[template.tier] || 90;
if (customScale[template.name]) level = customScale[template.name];
if (template.name === 'Mewtwo' && hasMove['amnesia']) level = 68;
return {
name: template.name,
moves: moves,
ability: 'None',
evs: {hp: 255, atk: 255, def: 255, spa: 255, spd: 255, spe: 255},
ivs: {hp: 30, atk: 30, def: 30, spa: 30, spd: 30, spe: 30},
item: '',
level: level,
shiny: false,
gender: false,
};
},
};
|
"use strict";
var core_1 = require('@angular/core');
var common_1 = require('@angular/common');
var ng_table_component_1 = require('./table/ng-table.component');
var ng_table_filtering_directive_1 = require('./table/ng-table-filtering.directive');
var ng_table_paging_directive_1 = require('./table/ng-table-paging.directive');
var ng_table_sorting_directive_1 = require('./table/ng-table-sorting.directive');
var Ng2TableModule = (function () {
function Ng2TableModule() {
}
Ng2TableModule.decorators = [
{ type: core_1.NgModule, args: [{
imports: [common_1.CommonModule],
declarations: [ng_table_component_1.NgTableComponent, ng_table_filtering_directive_1.NgTableFilteringDirective, ng_table_paging_directive_1.NgTablePagingDirective, ng_table_sorting_directive_1.NgTableSortingDirective],
exports: [ng_table_component_1.NgTableComponent, ng_table_filtering_directive_1.NgTableFilteringDirective, ng_table_paging_directive_1.NgTablePagingDirective, ng_table_sorting_directive_1.NgTableSortingDirective]
},] },
];
/** @nocollapse */
Ng2TableModule.ctorParameters = [];
return Ng2TableModule;
}());
exports.Ng2TableModule = Ng2TableModule;
|
import React from 'react'
import invariant from 'invariant'
import { routerShape } from './PropTypes'
import { ContextSubscriber } from './ContextUtils'
const { bool, object, string, func, oneOfType } = React.PropTypes
function isLeftClickEvent(event) {
return event.button === 0
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey)
}
// TODO: De-duplicate against hasAnyProperties in createTransitionManager.
function isEmptyObject(object) {
for (const p in object)
if (Object.prototype.hasOwnProperty.call(object, p))
return false
return true
}
function resolveToLocation(to, router) {
return typeof to === 'function' ? to(router.location) : to
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
const Link = React.createClass({
mixins: [ ContextSubscriber('router') ],
contextTypes: {
router: routerShape
},
propTypes: {
to: oneOfType([ string, object, func ]),
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func,
target: string
},
getDefaultProps() {
return {
onlyActiveOnIndex: false,
style: {}
}
},
handleClick(event) {
if (this.props.onClick)
this.props.onClick(event)
if (event.defaultPrevented)
return
const { router } = this.context
invariant(
router,
'<Link>s rendered outside of a router context cannot navigate.'
)
if (isModifiedEvent(event) || !isLeftClickEvent(event))
return
// If target prop is set (e.g. to "_blank"), let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target)
return
event.preventDefault()
router.push(resolveToLocation(this.props.to, router))
},
render() {
const { to, activeClassName, activeStyle, onlyActiveOnIndex, ...props } = this.props
// Ignore if rendered outside the context of router to simplify unit testing.
const { router } = this.context
if (router) {
// If user does not specify a `to` prop, return an empty anchor tag.
if (!to) { return <a {...props} /> }
const toLocation = resolveToLocation(to, router)
props.href = router.createHref(toLocation)
if (activeClassName || (activeStyle != null && !isEmptyObject(activeStyle))) {
if (router.isActive(toLocation, onlyActiveOnIndex)) {
if (activeClassName) {
if (props.className) {
props.className += ` ${activeClassName}`
} else {
props.className = activeClassName
}
}
if (activeStyle)
props.style = { ...props.style, ...activeStyle }
}
}
}
return <a {...props} onClick={this.handleClick} />
}
})
export default Link
|
import flatMap from 'lodash/flatMap';
import Mediator from '../src/mediator';
import SCORM from '../src/SCORM';
describe('SCORM hashi shim', () => {
let scorm;
let mediator;
beforeEach(() => {
mediator = new Mediator(window);
scorm = new SCORM(mediator);
});
describe('__setData', () => {
it('should set data to the passed in data', () => {
const testData = {
test: 'test',
};
scorm.__setData(testData);
expect(scorm.data).toEqual(testData);
});
it('should set data to an empty state if no data passed in', () => {
scorm.__setData();
expect(scorm.data).toEqual({});
});
});
describe('__setUserData', () => {
it('should set userData to the passed in data', () => {
const testData = {
test: 'test',
};
scorm.__setUserData(testData);
expect(scorm.userData).toEqual(testData);
});
it('should set userData to an empty state if no data passed in', () => {
scorm.__setUserData();
expect(scorm.userData).toEqual({});
});
});
describe('shim management and instance methods', () => {
let shim;
beforeEach(() => {
shim = scorm.__setShimInterface();
scorm.stateUpdated = jest.fn();
});
describe('__setShimInterface method', () => {
it('should set scorm shim property', () => {
expect(scorm.shim).not.toBeUndefined();
});
});
describe('iframeInitialize method', () => {
it('should set API property on object', () => {
const obj = {};
scorm.iframeInitialize(obj);
expect(obj.API).toEqual(scorm.shim);
});
});
describe('LMSInitialize method', () => {
it('should return "true"', () => {
expect(shim.LMSInitialize()).toEqual('true');
});
it('should stateUpdated', () => {
shim.LMSInitialize();
expect(scorm.stateUpdated).toHaveBeenCalled();
});
});
describe('LMSSetValue and LMSGetValue methods', () => {
const types = [
'true-false',
'choice',
'fill-in',
'matching',
'performance',
'sequencing',
'likert',
'numeric',
];
const results = ['correct', 'wrong', 'unanticipated', 'neutral'];
const statuses = ['passed', 'completed', 'failed', 'incomplete', 'browsed', 'not attempted'];
const objectivesValues = flatMap(statuses, (s, i) => [
['cmi.objectives.' + i + '.id', `id${i}`],
['cmi.objectives.' + i + '.score.raw', 1 + i],
['cmi.objectives.' + i + '.score.min', 0],
['cmi.objectives.' + i + '.score.max', 10],
['cmi.objectives.' + i + '.status', s],
]);
const interactionsValues = flatMap(types, (t, i) => [
['cmi.interactions.' + i + '.id', `id${i}`],
]);
const values = [
['cmi.core.lesson_location', 'somewhere'],
['cmi.core.score.raw', 5],
['cmi.core.score.min', 0],
['cmi.core.score.max', 10],
['cmi.suspend_data', 'suspension'],
['cmi.comments', 'learning here'],
...statuses.map(status => ['cmi.core.lesson_status', status]),
...objectivesValues,
...interactionsValues,
];
const writeOnlyInteractionsValues = flatMap(types, (t, i) => [
['cmi.interactions.' + i + '.time', '10:57:54'],
['cmi.interactions.' + i + '.type', t],
['cmi.interactions.' + i + '.weighting', 0.5],
['cmi.interactions.' + i + '.student_response', 3],
...results.map(r => ['cmi.interactions.' + i + '.result', r]),
['cmi.interactions.' + i + '.latency', '9:13:12'],
]);
const notImplementedValues = [
['cmi.student_preference.audio', 3],
['cmi.student_preference.speed', 1],
['cmi.student_preference.text', 1],
];
it.each(values)('should set and get %s properly', (key, value) => {
shim.LMSSetValue(key, value);
expect(shim.LMSGetValue(key)).toEqual(value);
});
it.each(writeOnlyInteractionsValues)(
'should set without errors, but not get %s properly for write only properties',
(key, value) => {
shim.LMSSetValue(key, value);
expect(shim.LMSGetLastError()).toEqual(0);
expect(shim.LMSGetValue(key)).toEqual('');
expect(shim.LMSGetLastError()).toEqual('404');
}
);
it.each(notImplementedValues)(
'should set with errors, and get %s with errors for not implemented properties',
(key, value) => {
shim.LMSSetValue(key, value);
expect(shim.LMSGetLastError()).toEqual('401');
expect(shim.LMSGetValue(key)).toEqual('');
expect(shim.LMSGetLastError()).toEqual('401');
}
);
it('should read language from the userData', () => {
const language = 'fr-fr';
scorm.userData.language = language;
expect(shim.LMSGetValue('cmi.student_preference.language')).toEqual(language);
});
it('should count interactions properly', () => {
interactionsValues.forEach(([k, v]) => shim.LMSSetValue(k, v));
expect(shim.LMSGetValue('cmi.interactions._count')).toEqual(interactionsValues.length);
});
it('should count objectives properly', () => {
statuses.map((s, i) => shim.LMSSetValue('cmi.objectives.' + i + '.id', `id${s}`));
expect(shim.LMSGetValue('cmi.objectives._count')).toEqual(statuses.length);
});
it('should count objectives in an interaction properly', () => {
shim.LMSSetValue('cmi.interactions.0.id', 'test');
statuses.map((s, i) =>
shim.LMSSetValue('cmi.interactions.0.objectives.' + i + '.id', `id${s}`)
);
expect(shim.LMSGetValue('cmi.interactions.0.objectives._count')).toEqual(statuses.length);
});
});
});
});
|
app.controller('NoteCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('js/app/note/notes.json').then(function (resp) {
$scope.notes = resp.data.notes;
// set default note
$scope.note = $scope.notes[0];
$scope.notes[0].selected = true;
});
$scope.colors = ['primary', 'info', 'success', 'warning', 'danger', 'dark'];
$scope.createNote = function(){
var note = {
content: 'New note',
color: $scope.colors[Math.floor((Math.random()*3))],
date: Date.now()
};
$scope.notes.push(note);
$scope.selectNote(note);
}
$scope.deleteNote = function(note){
$scope.notes.splice($scope.notes.indexOf(note), 1);
if(note.selected){
$scope.note = $scope.notes[0];
$scope.notes.length && ($scope.notes[0].selected = true);
}
}
$scope.selectNote = function(note){
angular.forEach($scope.notes, function(note) {
note.selected = false;
});
$scope.note = note;
$scope.note.selected = true;
}
}]);
|
import { PropTypes, Component } from 'react'
export class AddDayForm extends Component {
constructor(props) {
super(props)
this.submit = this.submit.bind(this)
}
submit(e) {
e.preventDefault()
console.log('resort', this.refs.resort.value)
console.log('date', this.refs.date.value)
console.log('powder', this.refs.powder.checked)
console.log('backcountry', this.refs.backcountry.checked)
}
render() {
const { resort, date, powder, backcountry } = this.props
return (
<form onSubmit={this.submit} className="add-day-form">
<label htmlFor="resort">Resort Name</label>
<input id="resort"
type="text"
required
defaultValue={resort}
ref="resort"/>
<label htmlFor="date">Date</label>
<input id="date"
type="date"
required
defaultValue={date}
ref="date"/>
<div>
<input id="powder"
type="checkbox"
defaultChecked={powder}
ref="powder"/>
<label htmlFor="powder">Powder Day</label>
</div>
<div>
<input id="backcountry"
type="checkbox"
defaultChecked={backcountry}
ref="backcountry"/>
<label htmlFor="backcountry">
Backcountry Day
</label>
</div>
<button>Add Day</button>
</form>
)
}
}
AddDayForm.defaultProps = {
resort: "Kirkwood",
date: "2017-02-12",
powder: true,
backcountry: false
}
AddDayForm.propTypes = {
resort: PropTypes.string.isRequired,
date: PropTypes.string.isRequired,
powder: PropTypes.bool.isRequired,
backcountry: PropTypes.bool.isRequired
}
|
export { default, classState } from 'ember-stickler/helpers/class-state';
|
module.exports = {
hiddenFields: {
companiesHouse: {
name: '[data-test="companiesHouseName"]',
number: '[data-test="companiesHouseNumber"]',
address1: '[data-test="companiesHouseAddress1"]',
address2: '[data-test="companiesHouseAddress2"]',
town: '[data-test="companiesHouseAddressTown"]',
county: '[data-test="companiesHouseAddressCounty"]',
postcode: '[data-test="companiesHouseAddressPostcode"]',
country: '[data-test="companiesHouseAddressCountry"]',
},
},
}
|
/**
* @class Core
*/
/**
* A function that does nothing.
*
* @property anim8.noop
*/
function noop() {}
/**
* Returns true if the given variable is defined.
*
* **Examples:**
*
* anim8.isDefined( 0 ); // true
* anim8.isDefined( false ); // true
* anim8.isDefined(); // false
*
* @method anim8.isDefined
* @param {Any} x
* @return {Boolean}
*/
function isDefined(x)
{
return typeof x !== 'undefined';
}
/**
* Returns true if the given variable is a function.
*
* @method anim8.isFunction
* @param {Any} x
* @return {Boolean}
*/
function isFunction(x)
{
return !!(x && x.constructor && x.call && x.apply);
}
/**
* Returns true if the given variable is a number.
*
* **Examples:**
*
* anim8.isNumber( 0 ); // true
* anim8.isNumber( -45.6 ); // true
* anim8.isNumber( true ); // false
* anim8.isNumber( '1' ); // false
* anim8.isNumber(); // false
*
* @method anim8.isNumber
* @param {Any} x
* @return {Boolean}
*/
function isNumber(x)
{
return typeof x === 'number';
}
/**
* Returns true if the given variable is a boolean variable.
*
* **Examples:**
*
* anim8.isBoolean( 0 ); // false
* anim8.isBoolean( -45.6 ); // false
* anim8.isBoolean( true ); // true
* anim8.isBoolean( false ); // true
* anim8.isBoolean( '1' ); // false
* anim8.isBoolean(); // false
*
* @method anim8.isBoolean
* @param {Any} x
* @return {Boolean}
*/
function isBoolean(x)
{
return typeof x === 'boolean';
}
/**
* Returns true if the given variable is a string.
*
* **Examples:**
*
* anim8.isString( '' ); // true
* anim8.isString( '1' ); // true
* anim8.isString( 4.5 ); // false
* anim8.isString(); // false
*
* @method anim8.isString
* @param {Any} x
* @return {Boolean}
*/
function isString(x)
{
return typeof x === 'string';
}
/**
* Returns true if the given variable is an array. This should be checked before
* anim8.isObject since Arrays are objects.
*
* **Examples:**
*
* anim8.isArray( [] ); // true
* anim8.isArray( [4, 5] ); // true
* anim8.isArray( 4.5 ); // false
* anim8.isArray(); // false
*
* @method anim8.isArray
* @param {Any} x
* @return {Boolean}
*/
function isArray(x)
{
return x instanceof Array;
}
/**
* Returns true if the given variable is an object. Arrays are considered
* objects.
*
* **Examples:**
*
* anim8.isObject( {} ); // true
* anim8.isObject( [] ); // true
* anim8.isObject( 4.5 ); // false
* anim8.isObject(); // false
* anim8.isObject( null ); // false
*
* @method anim8.isObject
* @param {Any} x
* @return {Boolean}
*/
function isObject(x)
{
return typeof x === 'object' && x !== null;
}
/**
* Returns the current time in milliseconds.
*
* @method anim8.now
* @return {Number}
*/
var now = (function()
{
return Date.now ? Date.now : function()
{
return new Date().getTime();
};
})();
/**
* Returns the trimmed version of the given string. A trimmed string has no
* whitespace in the beginning or end of it.
*
* **Examples:**
*
* anim8.trim( 'x' ); // 'x'
* anim8.trim( ' x' ); // 'x'
* anim8.trim( 'x ' ); // 'x'
* anim8.trim( ' x ' ); // 'x'
* anim8.trim( ' ' ); // ''
*
* @method anim8.trim
* @param {String} x
* @return {String}
*/
var trim = (function()
{
if (String.prototype.trim) {
return function(x) {
return x.trim();
};
}
return function(x) {
return x.replace(/^([\s]*)|([\s]*)$/g, '');
};
})();
/**
* Determines whether the given variable is empty.
*
* **Examples:**
*
* anim8.isEmpty( '' ); // true
* anim8.isEmpty( 0 ); // true
* anim8.isEmpty( [] ); // true
* anim8.isEmpty( {} ); // true
* anim8.isEmpty( null ); // true
* anim8.isEmpty( true ); // true
* anim8.isEmpty( false ); // true
* anim8.isEmpty( 'x' ); // false
* anim8.isEmpty( 0.3 ); // false
* anim8.isEmpty( [0] ); // false
* anim8.isEmpty( {x:3} ); // false
*
* @method anim8.isEmpty
* @param {Any} x
* @return {Boolean}
*/
function isEmpty(x)
{
if ( isArray( x ) || isString( x ) )
{
return x.length === 0;
}
else if ( x === null )
{
return true;
}
else if ( isObject( x ) )
{
for (var prop in x)
{
return false;
}
}
else if ( isNumber( x ) )
{
return x !== 0.0;
}
return true;
}
/**
* Parses the given input and returns an array.
*
* **Examples:**
*
* anim8.toArray(); // []
* anim8.toArray('a b'); // ['a b']
* anim8.toArray('a b', ' '); // ['a', 'b']
* anim8.toArray({a:0,b:0}); // ['a', 'b']
* anim8.toArray(['a', 'b']); // ['a', 'b']
* anim8.toArray(3.2); // [3.2]
* anim8.toArray(true); // [true]
*
* @param {Any} x
* @param {String} [split]
* @return {Array}
*/
function toArray( x, split )
{
if ( isString( x ) )
{
return split ? x.split( split ) : [ x ];
}
else if ( isArray ( x ) )
{
return x;
}
else if ( isObject( x ) )
{
var props = [];
for ( var prop in x )
{
props.push( prop );
}
return props;
}
else if ( isDefined( x ) )
{
return [ x ];
}
return [];
}
/**
* Performs a deep copy of the given variable. If the variable is an array or
* object a new instance of that type is created where the values are copied as
* well. All other types can't be copied (most likely because they're scalar) so
* they are returned as-is.
*
* @method anim8.copy
* @param {T} x
* @return {T}
*/
function copy(x)
{
if ( isArray(x) )
{
var copied = [];
for (var i = 0; i < x.length; i++)
{
copied.push( copy( x[i] ) );
}
x = copied;
}
else if ( isObject(x) )
{
var copied = {};
for (var p in x)
{
copied[p] = copy( x[p] );
}
x = copied;
}
return x;
}
/**
* Extends the given object by merging the following objects into it, avoiding
* overriding any existing properties.
*
* @method anim8.extend
* @param {Object} out
* @return {Object}
*/
function extend(out)
{
for (var i = 1; i < arguments.length; i++)
{
var o = arguments[ i ];
if ( isObject( o ) )
{
for (var prop in o)
{
if ( !(prop in out) )
{
out[prop] = o[prop];
}
}
}
}
return out;
}
/**
* Returns the first defined variable of a possible 4 variables.
*
* **Examples:**
*
* anim8.coalesce( 1, 2, 3 ); // 1
* anim8.coalesce( undefined, 2, 3 ); // 2
* anim8.coalesce(); // undefined
*
* @method anim8.coalesce
*/
function coalesce(a, b, c, d)
{
if (isDefined(a)) {
return a;
}
if (isDefined(b)) {
return b;
}
if (isDefined(c)) {
return c;
}
return d;
}
/**
* Provides a way to wrap a variable so calculators don't try copying it on parse.
*
* **Examples:**
*
* anim8.constant( 5 ); // function() { return 5; }
*
* @method anim8.constant
* @param {T} variable
* @return {Function}
*/
function constant(variable)
{
return function()
{
return variable;
};
}
/**
* Resolves the given variable. If the variable is a function the result is
* returned.
*
* **Examples:**
*
* anim8.resolve( 5 ); // 5
* anim8.resolve( true ); // true
* anim8.resolve( function(){return 7;} ); // 7
*
* @method anim8.resolve
* @param {Function|E} variable
* @param {Any[]} [args]
* @return {E}
*/
function resolve(variable, args)
{
return isFunction( variable ) ? ( args ? variable.apply(this, args) : variable() ) : variable;
}
/**
* Returns a "unique" identifier.
*
* @method id
* @return {Number}
*/
var id = (function()
{
var _id = 0;
return function() {
return ++_id;
};
})();
|
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('conFusion', ['ionic', 'ngCordova', 'conFusion.controllers', 'conFusion.services'])
.run(function($ionicPlatform, $rootScope, $ionicLoading, $cordovaSplashscreen, $timeout) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
$timeout(function() {
$cordovaSplashscreen.hide();
}, 4000);
});
$rootScope.$on('loading:show', function() {
$ionicLoading.show({
template: '<ion-spinner></ion-spinner> Loading ...'
})
});
$rootScope.$on('loading:hide', function() {
$ionicLoading.hide();
});
$rootScope.$on('$stateChangeStart', function() {
console.log('Loading ...');
$rootScope.$broadcast('loading:show');
});
$rootScope.$on('$stateChangeSuccess', function() {
console.log('done');
$rootScope.$broadcast('loading:hide');
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/sidebar.html',
controller: 'AppCtrl'
})
/*
.state('app.home', {
url: '/home',
views: {
'mainContent': {
templateUrl: 'templates/home.html',
controller: 'IndexController',
resolve: {
dish: ['$stateParams','menuFactory', function($stateParams, menuFactory){
return menuFactory.get({id:0});
}],
leader: ['corporateFactory', function(corporateFactory) {
return corporateFactory.get({id:3});
}],
promotion: ['promotionFactory', function(promotionFactory) {
return promotionFactory.get({id:0});
}]
}
//end Resolve
}
}
})
*/
.state('app.home', {
url: '/home',
views: {
'mainContent': {
templateUrl: 'templates/home.html',
controller: 'IndexController',
resolve: {
menu: ['menuFactory', function(menuFactory) {
return menuFactory.get({
id: 0
});
}],
promotion: ['promotionFactory', function(promotionFactory) {
return promotionFactory.get({
id: 0
});
}],
corporate: ['corporateFactory', function(corporateFactory) {
return corporateFactory.get({
id: 3
});
}]
}
}
}
})
.state('app.aboutus', {
url: '/aboutus',
views: {
'mainContent': {
templateUrl: 'templates/aboutus.html',
controller: 'AboutController',
resolve: {
leaders: ['corporateFactory', function(corporateFactory) {
return corporateFactory.query();
}]
}
}
}
})
.state('app.contactus', {
url: '/contactus',
views: {
'mainContent': {
templateUrl: 'templates/contactus.html'
}
}
})
.state('app.menu', {
url: '/menu',
views: {
'mainContent': {
templateUrl: 'templates/menu.html',
controller: 'MenuController',
resolve: {
dishes: ['menuFactory', function(menuFactory) {
return menuFactory.query();
}]
}
}
}
})
.state('app.favorites', {
url: '/favorites',
views: {
'mainContent': {
templateUrl: 'templates/favorites.html',
controller: 'FavoritesController',
resolve: {
dishes: ['menuFactory', function(menuFactory) {
return menuFactory.query();
}],
favorites: ['favoriteFactory', function(favoriteFactory) {
return favoriteFactory.getFavorites();
}]
}
}
}
})
.state('app.dishdetails', {
url: '/menu/:id',
views: {
'mainContent': {
templateUrl: 'templates/dishdetail.html',
controller: 'DishDetailController',
resolve: {
dish: ['$stateParams', 'menuFactory', function($stateParams, menuFactory) {
return menuFactory.get({
id: parseInt($stateParams.id, 10)
});
}]
}
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/home');
});
|
/**
* jQuery Unveil
* A very lightweight jQuery plugin to lazy load images
* http://luis-almeida.github.com/unveil
*
* Licensed under the MIT license.
* Copyright 2013 Luís Almeida
* https://github.com/luis-almeida
*/
;(function($) {
$.fn.unveil = function(threshold, callback) {
var $w = $(window),
th = threshold || 0,
retina = window.devicePixelRatio > 1,
srcAttrib = retina ? "data-src-retina" : "data-src",
bgiAttrib = retina ? "data-bgi-retina" : "data-bgi",
images = this,
loaded;
this.one("unveil", function() {
if (!handleImg(this)) handleBgi(this);
});
function handleImg(el) {
var source = el.getAttribute(srcAttrib);
source = source || el.getAttribute("data-src");
if (source) {
el.setAttribute("src", source);
if (typeof callback === "function") callback.call(el);
return true;
} else {
return false;
}
}
function handleBgi(el) {
var source = el.getAttribute(bgiAttrib);
source = source || el.getAttribute("data-bgi");
if (source) {
el.style.backgroundImage = "url(" + source + ")";
if (typeof callback === "function") callback.call(el);
return true;
} else {
return false;
}
}
function unveil() {
var inview = images.filter(function() {
var $e = $(this);
if ($e.is(":hidden")) return;
var wt = $w.scrollTop(),
wb = wt + $w.height(),
et = $e.offset().top,
eb = et + $e.height();
return eb >= wt - th && et <= wb + th;
});
loaded = inview.trigger("unveil");
images = images.not(loaded);
}
$w.scroll(unveil);
$w.resize(unveil);
unveil();
return this;
};
})(window.jQuery || window.Zepto);
|
export const selectLibrary = (libraryId) => {
return {
type: 'select_library',
payload: libraryId
};
};
|
/**
* Returns the first string value as a Javascript Number
* @param element - The group/element of the element (e.g. '00200013')
* @param [defaultValue] - The default value to return if the element does not exist
* @returns {*}
*/
DICOMWeb.getNumber = function(element, defaultValue) {
if(!element) {
return defaultValue;
}
// Value is not present if the attribute has a zero length value
if(!element.Value) {
return defaultValue;
}
// Sanity check to make sure we have at least one entry in the array.
if(!element.Value.length) {
return defaultValue;
}
return parseFloat(element.Value[0]);
};
|
// Manipulating JavaScript Objects
// I worked on this challenge: [by myself, with: ]
// There is a section below where you will write your code.
// DO NOT ALTER THIS OBJECT BY ADDING ANYTHING WITHIN THE CURLY BRACES!
var terah = {
name: "Terah",
age: 32,
height: 66,
weight: 130,
hairColor: "brown",
eyeColor: "brown"
}
// __________________________________________
// Write your code below.
var adam = {
name: "Adam"
}
terah['spouse'] = adam;
terah.weight = 125;
// delete terah.eyeColor;
terah.eyeColor = undefined;
adam['spouse'] = terah;
terah.children = {};
var carson = {
name: "Carson"
}
terah.children.carson = carson;
var carter = {
name: "Carter"
}
terah.children.carter = carter;
var colton = {
name: "Colton"
}
terah.children.colton = colton;
adam.children = terah.children;
console.log(terah);
console.log(adam);
// __________________________________________
// Reflection: Use the reflection guidelines
//This wasn't too bad, it took about 15 minutes. It seemed almost exactly like ruby's hash objects where it would have a key value pair and a value associated with the entire thing
// In fact, I think it is the same thing. The period notation vs the bracket notation is interesting and I am unsure of how it turns raw characters into strings and strings into
// what I think are symbols. I guess I will figure that out soon.
//
//
//
//
//
// __________________________________________
// Driver Code: Do not alter code below this line.
function assert(test, message, test_number) {
if (!test) {
console.log(test_number + "false");
throw "ERROR: " + message;
}
console.log(test_number + "true");
return true;
}
assert(
(adam instanceof Object),
"The value of adam should be an Object.",
"1. "
)
assert(
(adam.name === "Adam"),
"The value of the adam name property should be 'Adam'.",
"2. "
)
assert(
terah.spouse === adam,
"terah should have a spouse property with the value of the object adam.",
"3. "
)
assert(
terah.weight === 125,
"The terah weight property should be 125.",
"4. "
)
assert(
terah.eyeColor === undefined || null,
"The terah eyeColor property should be deleted.",
"5. "
)
assert(
terah.spouse.spouse === terah,
"Terah's spouse's spouse property should refer back to the terah object.",
"6. "
)
assert(
(terah.children instanceof Object),
"The value of the terah children property should be defined as an Object.",
"7. "
)
assert(
(terah.children.carson instanceof Object),
"carson should be defined as an object and assigned as a child of Terah",
"8. "
)
assert(
terah.children.carson.name === "Carson",
"Terah's children should include an object called carson which has a name property equal to 'Carson'.",
"9. "
)
assert(
(terah.children.carter instanceof Object),
"carter should be defined as an object and assigned as a child of Terah",
"10. "
)
assert(
terah.children.carter.name === "Carter",
"Terah's children should include an object called carter which has a name property equal to 'Carter'.",
"11. "
)
assert(
(terah.children.colton instanceof Object),
"colton should be defined as an object and assigned as a child of Terah",
"12. "
)
assert(
terah.children.colton.name === "Colton",
"Terah's children should include an object called colton which has a name property equal to 'Colton'.",
"13. "
)
assert(
adam.children === terah.children,
"The value of the adam children property should be equal to the value of the terah children property",
"14. "
)
console.log("\nHere is your final terah object:")
console.log(terah)
|
import { app, BrowserWindow } from 'electron';
export var fileMenuTemplate = {
label: 'File',
submenu: [{
label: "New pad",
accelerator: "CmdOrCtrl+N",
click: function () { app.padController.create() }
},{
type: "separator"
},{
label: "All Quit",
accelerator: "CmdOrCtrl+Shift+Q",
click: function () { app.quit() }
}]
};
|
var user_profile = function(cnf) {
this.id = cnf.id,
this.email = cnf.email,
this.username = cnf.username,
this.picture = cnf.picture,
this.post_count = cnf.post_count,
this.followers = cnf.followers,
this.following = cnf.following
};
module.exports = user_profile;
//Notice that this profile does not contain any password related information
|
cm.model.types = {
"CM_Model_Language": 5,
"CM_Model_Location": 6,
"CM_Model_Splitfeature": 7,
"CM_Model_Splittest": 8,
"CM_Model_SplittestVariation": 9,
"CM_Model_User": 10,
"CM_Model_Splittest_RequestClient": 11,
"CM_Model_Splittest_User": 12,
"CM_Model_Stream_Publish": 13,
"CM_Model_Stream_Subscribe": 14,
"CM_Model_StreamChannel_Message": 15,
"CM_Model_StreamChannel_Message_User": 17,
"Denkmal_Model_Event": 28,
"Denkmal_Model_Song": 31,
"Denkmal_Model_User": 32,
"Denkmal_Model_Venue": 33,
"Denkmal_Model_VenueAlias": 34,
"CM_Model_Location_City": 39,
"CM_Model_Location_Country": 40,
"CM_Model_Location_State": 41,
"CM_Model_Location_Zip": 42,
"CM_Model_LanguageKey": 43,
"Denkmal_Scraper_SourceResult": 51,
"Denkmal_Model_UserInvite": 61,
"Denkmal_Push_Subscription": 63,
"Denkmal_Push_Notification_Message": 64,
"CM_Model_Currency": 65,
"CM_Model_StreamChannel_Media": 70,
"CM_Model_StreamChannelArchive_Media": 71,
"CM_StreamChannel_Thumbnail": 72,
"Denkmal_Model_Region": 77,
"CM_Janus_StreamChannel": 83,
"Denkmal_Model_FacebookPage": 87,
"CM_Migration_Model": 90,
"Denkmal_Model_EventLink": 91,
"Denkmal_Model_EventCategory": 92
};
cm.action.types = {
"CM_Action_Email": 3
};
|
function init(userInfo,callbacks) {
if (!userInfo.appKey || !userInfo.token){
return false;
}
//公有云初始化
RongIMLib.RongIMClient.init(userInfo.appKey);
var instance = RongIMClient.getInstance();
//连接状态监听器
RongIMClient.setConnectionStatusListener({
onChanged: function (status) {
switch (status) {
case RongIMLib.ConnectionStatus.CONNECTED:
console.log("链接成功 ");
callbacks.CONNECTED && callbacks.CONNECTED(instance);
break;
case RongIMLib.ConnectionStatus.CONNECTING:
console.log('正在链接');
break;
case RongIMLib.ConnectionStatus.DISCONNECTED:
console.log('断开连接');
break;
case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
console.log('其他设备登录');
break;
case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
console.log('域名不正确');
break;
case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
console.log('网络不可用');
break;
}
}
});
RongIMClient.setOnReceiveMessageListener({
// 接收到的消息
onReceived: function (message) {
callbacks.Received && callbacks.Received(message);
}
});
//开始链接
RongIMClient.connect(userInfo.token, {
onSuccess: function (id) {
callbacks.Success && callbacks.Success(id);
},
onTokenIncorrect: function () {
console.log('token无效');
},
onError: function (errorCode) {
var info = '';
switch (errorCode) {
case RongIMLib.ErrorCode.TIMEOUT:
info = '超时';
break;
case RongIMLib.ErrorCode.UNKNOWN_ERROR:
info = '未知错误';
break;
case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
info = '不可接受的协议版本';
break;
case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
info = 'appkey不正确';
break;
case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
info = '服务器不可用';
break;
}
console.log(info);
}
});
}
|
for (var i = 0; i < 5; i ++)
console.log ("hello world");
|
"use babel";
// @flow
import type { Range } from "../../LanguageServerProtocolFeature/Types/standard";
import Uri from "vscode-uri";
export type JumpToAction = () => void;
export function jumpTo(
path: string,
range: Range,
pending: boolean,
): JumpToAction | void {
if (path.length > 0) {
let uri = Uri.parse(path);
return () => {
return global.atom.workspace.open(
uri.scheme === "file" ? uri.path : path,
{
initialLine: range.start.line ? range.start.line : 0,
initialColumn: range.start.character ? range.start.character : 0,
pending,
},
);
};
}
}
|
var assert = require('../../../../../double-check').assert;
var func = function() {
console.log("This is a message 2!");
}
assert.pass("dummy2Level1", func);
|
/*
* Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
(function () {
"use strict";
var Raw = function () {};
Raw.prototype.toRaw = function (object, keys) {
var result = {};
keys.forEach(function (key) {
var value = object[key];
if (value === null || value === undefined) {
return;
}
if (typeof value === "object" && value.toRaw) {
result[key] = value.toRaw();
return;
}
result[key] = value;
});
return result;
};
Raw.prototype.assign = function (obj1, obj2) {
Object.keys(obj2).forEach(function (key) {
obj1[key] = obj2[key];
});
};
// Used for debugging to easily diff JSON.
Raw.prototype.sortJSON = function (object) {
var result,
i,
keys,
key,
value;
if (typeof object !== "object" || object === null) {
return object;
}
if (Array.isArray(object)) {
result = [];
for (i = 0; i < object.length; i++) {
result[i] = this.sortJSON(object[i]);
}
return result;
}
result = {};
keys = Object.keys(object).sort();
for (i = 0; i < keys.length; i++) {
key = keys[i];
value = object[key];
result[key] = this.sortJSON(value);
}
return result;
};
module.exports = new Raw();
}());
|
#!/usr/bin/env node
var path = require('path'),
optimist = require('optimist'),
usage = require('./usage'),
commands = require('../lib/commands'),
properties = require('../lib/properties'),
version = require('../package.json').version;
var die = function(msg) {
console.error('\n', msg, '\n');
console.info(usage);
process.exit(1);
}
var argv = optimist
.usage(usage)
.argv;
if (argv.h || argv.help) {
console.info(usage);
return;
}
if (argv.v || argv.version) {
console.info('v' + version);
return;
}
if (argv._.length == 0) {
die('Command argument is required');
}
var commandName = argv._.shift().toLowerCase();
if (!commands[commandName]) {
die('Command ' + commandName + ' is not known to bumm!');
}
try {
var options = properties.parse(argv._);
options.templateDir = path.join(__dirname, '..', 'templates');
if (process.env.BUMM_TEMPLATE_DIR) {
options.templateDir = process.env.BUMM_TEMPLATE_DIR;
}
if (argv.templateDir || argv.t) {
options.templateDir = argv.templateDir || argv.t;
}
// copy switches from argv to options.switches
options.switches = {};
for (var key in argv) {
if (key != '_' && key != '$0' && argv.hasOwnProperty(key)) {
options.switches[key] = argv[key];
}
}
commands[commandName](options);
} catch (e) {
die(e);
}
|
TeX: {
extensions: ["color.js"]
}
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\(','\\)']],
processEscapes: true
}
});
|
//>>built
define({smiley:"\u0e41\u0e17\u0e23\u0e01\u0e44\u0e2d\u0e04\u0e2d\u0e19\u0e41\u0e2a\u0e14\u0e07\u0e2d\u0e32\u0e23\u0e21\u0e13\u0e4c",emoticonSmile:"\u0e22\u0e34\u0e49\u0e21",emoticonLaughing:"\u0e2b\u0e31\u0e27\u0e40\u0e23\u0e32\u0e30",emoticonWink:"\u0e02\u0e22\u0e34\u0e1a\u0e15\u0e32",emoticonGrin:"\u0e22\u0e34\u0e49\u0e21\u0e01\u0e27\u0e49\u0e32\u0e07",emoticonCool:"\u0e40\u0e08\u0e4b\u0e07",emoticonAngry:"\u0e42\u0e01\u0e23\u0e18",emoticonHalf:"\u0e04\u0e23\u0e36\u0e48\u0e07\u0e0b\u0e35\u0e01",
emoticonEyebrow:"\u0e04\u0e34\u0e49\u0e27",emoticonFrown:"\u0e2b\u0e19\u0e49\u0e32\u0e1a\u0e36\u0e49\u0e07",emoticonShy:"\u0e2d\u0e32\u0e22",emoticonGoofy:"\u0e42\u0e07\u0e48",emoticonOops:"\u0e2d\u0e38\u0e4a\u0e1b\u0e2a\u0e4c",emoticonTongue:"\u0e41\u0e25\u0e1a\u0e25\u0e34\u0e49\u0e19",emoticonIdea:"\u0e04\u0e27\u0e32\u0e21\u0e04\u0e34\u0e14",emoticonYes:"\u0e43\u0e0a\u0e48",emoticonNo:"\u0e44\u0e21\u0e48\u0e43\u0e0a\u0e48",emoticonAngel:"\u0e40\u0e17\u0e27\u0e14\u0e32",emoticonCrying:"\u0e23\u0e49\u0e2d\u0e07\u0e44\u0e2b\u0e49",
emoticonHappy:"\u0e21\u0e35\u0e04\u0e27\u0e32\u0e21\u0e2a\u0e38\u0e02"});
|
'use strict';
// 测试环境配置
// ===========================
module.exports = {
mongo: {
uri: 'mongodb://localhost/jackblog-test'
},
redis: {
db: 2
},
port: process.env.PORT || 8080,
seedDB: true
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.