code stringlengths 2 1.05M |
|---|
// Copyright (c) 2011+, HL7, Inc & The MITRE Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of HL7 nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
var mongoose = require('mongoose');
var _ = require('underscore');
var fs = require('fs');
var eco = require('eco');
var async = require('async');
var Immunization = mongoose.model('Immunization');
var ResourceHistory = mongoose.model('ResourceHistory');
var ResponseFormatHelper = require(__dirname + '/../../lib/response_format_helper');
exports.load = function(req, res, id, vid, next) {
if (req.resourceHistory) {
if(vid !== null){
req.resourceHistory.getVersion(vid, function(err, immunization) {
req.immunization = immunization;
next(immunization);
});
} else {
req.resourceHistory.findLatest(function(err, immunization) {
req.immunization = immunization;
next(immunization);
});
}
} else {
ResourceHistory.findOne(id, function(rhErr, resourceHistory) {
if (rhErr) {
next(rhErr);
}
if(resourceHistory !== null) {
req.resourceHistory = resourceHistory;
req.resourceHistory.findLatest(function(err, immunization) {
req.immunization = immunization;
next(immunization);
});
}
});
}
};
exports.show = function(req, res) {
var immunization = req.immunization;
var json = JSON.stringify(immunization);
res.send(json);
};
exports.create = function(req, res) {
var immunization = new Immunization(req.body);
immunization.save(function(err, savedImmunization) {
if(err) {
res.send(500);
} else {
var resourceHistory = new ResourceHistory({resourceType: 'Immunization'});
resourceHistory.addVersion(savedImmunization.id);
resourceHistory.save(function(rhErr, savedResourceHistory){
if (rhErr) {
res.send(500);
} else {
res.set('Location', ("http://localhost:3000/immunization/@" + resourceHistory.id));
res.send(201);
}
});
}
});
};
exports.update = function(req, res) {
var immunization = req.immunization;
immunization = _.extend(immunization, req.body);
immunization.save(function(err, savedimmunization) {
if(err) {
res.send(500);
} else {
var resourceHistory = req.resourceHistory;
resourceHistory.addVersion(savedimmunization);
resourceHistory.save(function(rhErr, savedResourceHistory) {
if (rhErr) {
res.send(500);
} else {
res.send(200);
}
});
}
});
};
exports.destroy = function(req, res) {
var immunization = req.immunization;
immunization.remove(function (err) {
if(err) {
res.send(500);
} else {
res.send(204);
}
});
};
exports.list = function(req, res) {
var content = {
title: "Search results for resource type Immunization",
id: "http://localhost:3000/immunization",
totalResults: 0,
link: {
href: "http://localhost:3000/immunization",
rel: "self"
},
updated: new Date(Date.now()),
entry: []
};
ResourceHistory.find({resourceType:"Immunization"}, function (rhErr, histories) {
if (rhErr) {
return next(rhErr);
}
var counter = 0;
async.forEach(histories, function(history, callback) {
counter++;
content.totalResults = counter;
history.findLatest( function(err, immunization) {
var entrywrapper = {
title: "Immunization " + history.vistaId + " Version " + history.versionCount(),
id: "http://localhost:3000/immunization/@" + history.vistaId,
link: {
href: "http://localhost:3000/immunization/@" + history.vistaId + "/history/@" + history.versionCount(),
rel: "self"
},
updated: history.lastUpdatedAt(),
published: new Date(Date.now()),
content: immunization
};
content.entry.push(entrywrapper);
callback();
});
}, function(err) {
res.send(JSON.stringify(content));
});
});
}; |
//example pather.js
//pather.js
var patherbuilder = function(){
return {pather:{
graph: require('./graphstruct.js').newRGraph(),
getPathCollection: function(routes,stations){
var pathCollection = []
routes.forEach(function(d,i,array){ //for each route
var pathElement = {pathID:d.properties.route_id, stations: []} //create a element for the collection
stations.forEach(function(station,i,array){ //search through the stations
station.properties.routes.forEach(function(route){
if(route == d.properties.route_id) //if one has the same id
pathElement.stations.push(station); //add it to the element list
})
})
pathCollection.push(pathElement); //add the current element to the collection
})
return pathCollection
},
getStops: function(route_id, Routes,pathCollection){
var curRoute;
Routes.forEach(function(route){
if(route.properties.route_id == route_id)
curRoute = route;
})
var stops = [];
pathCollection.forEach(function(path){
if(path.pathID == route_id)
stops = path.stations;
})
curRoute["stops"] = stops;
return curRoute;
},
reverseSegments: function(Segments){
var revsegs = JSON.parse(JSON.stringify(Segments));// make deep copy of segments
revsegs.features.forEach(function(feature){
feature.geometry.coordinates.reverse(); //reverse the ordering of the points
var temp = feature.end;
feature.end = feature.start;
feature.start = temp;
})
return revsegs;
},
setShapes: function(newRoute){
var builder = function(newRoute,range,start,end,graph){
var obj = {
'type':'Feature',
'properties':newRoute.properties,
'geometry':{
'type':'LineString',
'coordinates':range
},
'start':start,
'end':end
};
graph.addEdgeToRoute(newRoute.properties.route_id,
nparse(obj.start.properties.stop_ids[0]),
nparse(obj.end.properties.stop_ids[0])
);
return obj;
}
var nparse = require('./nparse.js').nparse;
var graph = this.graph;
var currentBin,index;
var routeSegments = {
type:'FeatureCollection',
features:[]
};
var splitList = [];
var realStops = getStations(newRoute.stops);
//trueStops = getTrueStops(newRoute.geometry,realStops);
var segmentsArr = getAllLines(newRoute.geometry,realStops);
routeSegments = mergeSegments(segmentsArr);
//plotNewRoute(routeSegments);
return routeSegments;
function mergeSegments(SegmentList){
var mergedFeatureCollection = {
type:'FeatureCollection',
features:[]
};
SegmentList.forEach(function(d){
d.features.forEach(function(feature){
mergedFeatureCollection.features.push(feature);
})
})
return mergedFeatureCollection
}
function getAllLines(MultiLineString,stops){
var LIST = []
MultiLineString.coordinates.forEach(function(d,i){
if(d.length != 0)
LIST.push(getLines(d,stops));
})
//var collection = mergeSegments(LIST);
return LIST;
}
function getStations(stops){
var uniqueStations = [];
var exists = false;
for(var i = 0; i< stops.length; i++){
var station = {'type':'Feature','properties':{'station_name':'' , 'stop_ids':[]}, 'geometry':stops[i].geometry};
for(var j=0; j< uniqueStations.length; j++){
exists = false;
if(nparse(uniqueStations[j].properties.stop_ids[0] ) === nparse(stops[i].properties.stop_id)){
uniqueStations[j].properties.stop_ids.push(stops[i].properties.stop_id)
exists = true;
break;
}
}
if(!exists){
station.properties.station_name = stops[i].properties.stop_name;
station.properties.stop_ids.push(stops[i].properties.stop_id);
uniqueStations.push(station);
}
}
return uniqueStations;
}
function getRange(array,start,stop){
if(start < 0){
start = 0;
}
retArray = [];
//must include endpoints if it needs to interpolate!!!!!!
retArray = array.slice(start,stop+1);
return retArray;
}
function findStop(stopcoor,lineString){
var index = -1;
for(var i =0; i< lineString.length; i++){
var coor = lineString[i];
var d = distance(coor,stopcoor);
if(d === 0){
index = i;
break;
}
}
return index;
}
function findStopsAtPoint(point,stoplist){
var list = [];
stoplist.forEach(function(d,i){
if(distance(d.geometry.coordinates,point)===0)
{
list.push(i);
}
})
return list;
}
function getSet(lineString,realStops){
var listOfStops = [];
realStops.forEach(function(d){
if(findStop(d.geometry.coordinates,lineString) >= 0)
listOfStops.push(d);
})
return listOfStops;
}
function getLines(lineString, realStops,graph){
var trueStops = getSet(lineString,realStops); ///get all stops that lie and the current lineString
var startIndexes = findStopsAtPoint(lineString[0],trueStops); //find all stops that lie and the initial point
var starts = [];
startIndexes.forEach(function(index){
starts.push(trueStops[index]); //for each one push it onto the stack of stops that need to be addressed
})
var routeSegments = {
type:'FeatureCollection',
features:[]
};
var lines = [] //array of linestrings
var lastIndex = 0;
var rcode = newRoute.properties.route_id;
for(var i = 0; i< lineString.length; i++){ //run through every point on the line string;
var tempIndexes; //create temp vars to hold immediately subsequent stops
var temps = [];
if( (tempIndexes = findStopsAtPoint(lineString[i],trueStops)).length !== 0 ){ //find the stops at our current point if they exist
tempIndexes.forEach(function(index){
temps.push(trueStops[index]); //push them on the stack
})
var range;
if(trueStops === [])
range = [];
else
range = getRange(lineString,lastIndex, i);//get the range of points on the lineString that lie between start and end points
lastIndex = i;
if(starts !== []){
starts.forEach(function(start){ //for each stop in the starting points
temps.forEach(function(end){ //for each stop in the ending points ... i.e. cross product
//create a lineString Feature object with the same properties as the route with current start and stop stations.
debugger;
var obj = builder(newRoute,range,start,end,graph);
routeSegments.features.push(obj); //add that path to our list of segments;
})
});
}else{
temps.forEach(function(end){
range = getRange(lineString,0,i)
var start = {
'properties':{
'routes':[rcode],
'stop_code':null,
'stop_ids':[nparse(end.properties.stop_ids[0])+'start'],
'stop_name':'end'},
'geometry':{type:'Point',coordinates:lineString[0]} };
});
var obj = builder(newRoute,range,start,end,graph);
routeSegments.features.push(obj);
}
starts = temps; //set the new starting node
startIndexes = tempIndexes;
}
}
// we have broken out of the loop so if there was a stop at the end
// last index should be the last point in the linestring
if(lastIndex !== lineString.length-1){ // if not
range = getRange(lineString,lastIndex,i);
starts.forEach(function(start){
var end = {
'properties':{
'routes':[rcode],
'stop_code':null,
'stop_ids':[nparse(start.properties.stop_ids[0])+'end'],
'stop_name':'end'
},
'geometry':{
type:'Point',
coordinates:lineString[lineString.length]
}
};
var obj = builder(newRoute,range,start,end,graph);
routeSegments.features.push(obj); //add that path to our list of segments;
})
}
return {'lines':routeSegments,'graph':graph};
}
}//end of setShapes.
}};
}
function distance(a,b){
var d = Math.sqrt( ( a[0] - b[0] ) * ( a[0] - b[0] ) + ( a[1] - b[1] ) * ( a[1] - b[1] ) );
// if(d === 0)
// return d;
// if(d < 0.002){
// console.log("anomoly");
// return 0;
// }
return d;
}
module.exports = {'patherbuilder':patherbuilder}; |
import {Texture2D, ProgramManager} from '@luma.gl/core';
import {AmbientLight} from './ambient-light';
import {DirectionalLight} from './directional-light';
import Effect from '../../lib/effect';
import {Matrix4, Vector3} from 'math.gl';
import ShadowPass from '../../passes/shadow-pass';
import {default as shadow} from '../../shaderlib/shadow/shadow';
const DEFAULT_AMBIENT_LIGHT_PROPS = {color: [255, 255, 255], intensity: 1.0};
const DEFAULT_DIRECTIONAL_LIGHT_PROPS = [
{
color: [255, 255, 255],
intensity: 1.0,
direction: [-1, 3, -1]
},
{
color: [255, 255, 255],
intensity: 0.9,
direction: [1, -8, -2.5]
}
];
const DEFAULT_SHADOW_COLOR = [0, 0, 0, 200 / 255];
// Class to manage ambient, point and directional light sources in deck
export default class LightingEffect extends Effect {
constructor(props) {
super(props);
this.ambientLight = null;
this.directionalLights = [];
this.pointLights = [];
this.shadowColor = DEFAULT_SHADOW_COLOR;
this.shadowPasses = [];
this.shadowMaps = [];
this.dummyShadowMap = null;
this.shadow = false;
this.programManager = null;
for (const key in props) {
const lightSource = props[key];
switch (lightSource.type) {
case 'ambient':
this.ambientLight = lightSource;
break;
case 'directional':
this.directionalLights.push(lightSource);
break;
case 'point':
this.pointLights.push(lightSource);
break;
default:
}
}
this._applyDefaultLights();
this.shadow = this.directionalLights.some(light => light.shadow);
}
preRender(gl, {layers, layerFilter, viewports, onViewportActive, views}) {
if (!this.shadow) return;
// create light matrix every frame to make sure always updated from light source
this.shadowMatrices = this._createLightMatrix();
if (this.shadowPasses.length === 0) {
this._createShadowPasses(gl);
}
if (!this.programManager) {
// TODO - support multiple contexts
this.programManager = ProgramManager.getDefaultProgramManager(gl);
if (shadow) {
this.programManager.addDefaultModule(shadow);
}
}
if (!this.dummyShadowMap) {
this.dummyShadowMap = new Texture2D(gl, {
width: 1,
height: 1
});
}
for (let i = 0; i < this.shadowPasses.length; i++) {
const shadowPass = this.shadowPasses[i];
shadowPass.render({
layers,
layerFilter,
viewports,
onViewportActive,
views,
moduleParameters: {
shadowLightId: i,
dummyShadowMap: this.dummyShadowMap,
shadowMatrices: this.shadowMatrices
}
});
}
}
getModuleParameters(layer) {
const parameters = this.shadow
? {
shadowMaps: this.shadowMaps,
dummyShadowMap: this.dummyShadowMap,
shadowColor: this.shadowColor,
shadowMatrices: this.shadowMatrices
}
: {};
// when not rendering to screen, turn off lighting by adding empty light source object
// lights shader module relies on the `lightSources` to turn on/off lighting
parameters.lightSources = {
ambientLight: this.ambientLight,
directionalLights: this.directionalLights.map(directionalLight =>
directionalLight.getProjectedLight({layer})
),
pointLights: this.pointLights.map(pointLight => pointLight.getProjectedLight({layer}))
};
return parameters;
}
cleanup() {
for (const shadowPass of this.shadowPasses) {
shadowPass.delete();
}
this.shadowPasses.length = 0;
this.shadowMaps.length = 0;
if (this.dummyShadowMap) {
this.dummyShadowMap.delete();
this.dummyShadowMap = null;
}
if (this.shadow && this.programManager) {
this.programManager.removeDefaultModule(shadow);
this.programManager = null;
}
}
_createLightMatrix() {
const lightMatrices = [];
for (const light of this.directionalLights) {
const viewMatrix = new Matrix4().lookAt({
eye: new Vector3(light.direction).negate()
});
lightMatrices.push(viewMatrix);
}
return lightMatrices;
}
_createShadowPasses(gl) {
for (let i = 0; i < this.directionalLights.length; i++) {
const shadowPass = new ShadowPass(gl);
this.shadowPasses[i] = shadowPass;
this.shadowMaps[i] = shadowPass.shadowMap;
}
}
_applyDefaultLights() {
const {ambientLight, pointLights, directionalLights} = this;
if (!ambientLight && pointLights.length === 0 && directionalLights.length === 0) {
this.ambientLight = new AmbientLight(DEFAULT_AMBIENT_LIGHT_PROPS);
this.directionalLights.push(
new DirectionalLight(DEFAULT_DIRECTIONAL_LIGHT_PROPS[0]),
new DirectionalLight(DEFAULT_DIRECTIONAL_LIGHT_PROPS[1])
);
}
}
}
|
require('./ToggleSwitch.less');
var React = require('react');
var ReactDOM = require('react-dom');
module.exports = React.createClass({
displayName:'ToggleSwitch',
getDefaultProps: function (){
return {
className: '',
disabled: false
};
},
__onChange: function (event) {
event.stopPropagation();
this.props.onChange && this.props.onChange(event.target.checked, event);
},
__onInputClick: function (event){
event.stopPropagation();
},
getValue: function () {
return ReactDOM.findDOMNode(this.refs.input).value;
},
setValue: function (value) {
return ReactDOM.findDOMNode(this.refs.input).value = value, this;
},
render: function(){
var _uuid = 'c_toggle_switch_input_' + (new Date()).getTime();
return (
<div className={"zr-toggle-switch " + this.props.className + ' ' + (this.props.disabled?'disabled':'')} data-ts-color={this.props.color||'red'}>
<input ref="input" id={_uuid} disabled={this.props.disabled} type="checkbox" defaultChecked={this.props.value} onClick={this.__onInputClick} onChange={this.__onChange} />
<label htmlFor={_uuid} className="ts-helper"></label>
</div>
);
}
});
|
var knex = require('knex'),
config = require('../../config'),
knexInstance;
function configure(dbConfig) {
var client = dbConfig.client;
dbConfig.debug = dbConfig.debug || false;
if (client==='sqlite3') dbConfig.useNullAsDefault = dbConfig.useNullAsDefault || false;
else if (client==='mysql') {
dbConfig.connection.timezone = 'UTC';
dbConfig.connection.charset = 'utf8mb4';
}
return dbConfig;
}
if (!knexInstance && config.get('database') && config.get('database:client')) knexInstance = knex(configure(config.get('database')));
module.exports = knexInstance; |
//Global Initial Parameters:
const initialPoint = [1, 1];
const layout = {
width: 450, "height": 500,
margin: {l:30, r:30, t:30, b:30},
hovermode: "closest",
showlegend: false,
xaxis: {range: [-7, 7], zeroline: true, title: "x"},
yaxis: {range: [-6, 6], zeroline: true, title: "y"},
aspectratio: {x:1, y:1}
};
var currentPoint = initialPoint;
var defaultHref = window.location.href;
var initX = 0, initY = 0;
var z = numeric.linspace(-2*Math.PI,2*Math.PI,1000);
// 0 is triangular, 1 is square, 2 is sawtooth, 3 is delta's, 4 is parabola, 5 is x, 6 is |x|,
var shape = 6;
var decay = 0.9;
var decay2 = 0.6;
//Plot
/**
* Resets and plots initial area element or basis vectors of 2D Cartesian.
* @param {string} type - basis vectors or area element
*/
function initCarte(type) {
Plotly.purge("graph");
var N = parseFloat(document.getElementById('NController').value);
var L = parseFloat(document.getElementById('LController').value);
var A = parseFloat(document.getElementById('AController').value);
if (type === "#maths"){
Plotly.newPlot("graph", computePlot(z), layout);
} else if (type === "#plot"){
Plotly.newPlot("graph", computePlot(z), layout);
} else if (type ==="#component"){
Plotly.newPlot("graph", computeComponents(z), setLayout());
}
return;
}
/* set the layout of the graph to adjust for different amplitudes and different number of terms involved
it changes the range of the y-axis according to the amplitude and number of therms
*/
function setLayout(){
var N = parseFloat(document.getElementById('NController').value);
var A = parseFloat(document.getElementById('AController').value);
var L = parseFloat(document.getElementById('LController').value);
const new_layout = {
width: 450, "height": 500,
margin: {l:30, r:30, t:30, b:30},
hovermode: "closest",
showlegend: false,
xaxis: {range: [], zeroline: true, title: "x"},
yaxis: {range: [], zeroline: true, title: "y"},
aspectratio: {x:1, y:1}
};
return new_layout;
}
function adding(array){
var result = 0
for(var i =0; i<array.length; ++i){
result+=array[i];
}
return result;
}
function selection(n,A,L,x,type){
if (type===0){
formula = (8*A*1/((2*(n)-1) *Math.PI)**2)*(-1)**(n) * Math.sin(x*(2*n -1) *Math.PI /L);
} else if (type===1){
formula = 2*A/(n*Math.PI) *(1-(-1)**n) *Math.sin(n*Math.PI *x/L);
} else if (type===2){
formula = 2*A*(-1)**(n+1) /(n*Math.PI) * Math.sin(n *Math.PI* x/L);
} else if (type===3){
formula = 1/L * Math.cos(n*Math.PI*x/L);
} else if (type===4){
if (n===0){
formula=(2*L**2)/3;
} else {
formula=A*((4*L**2)/(n*Math.PI)**2)*(-1)**n*Math.cos(n*Math.PI*x/L);
}
} else if (type===5){
formula = A*(2*L/(n*Math.PI)*(-1)**(n+1)*Math.sin(n*Math.PI*x/L));
} else if (type===6){
if (n===0){
formula=A*L;
} else {
formula=(2*A*L/(n*Math.PI)**2)*((-1)**(n) -1)*Math.cos(n*Math.PI*x/L);
}
}
return formula;
}
function summation(x) {
var N = parseFloat(document.getElementById('NController').value);
var L = parseFloat(document.getElementById('LController').value);
var A = parseFloat(document.getElementById('AController').value);
n = numeric.linspace(1,N,N);
var y = [];
for (var i = 0; i < N; ++i){
y.push(selection(n[i],A,L,x,shape));
//y.push((8*A/((2*n[i]-1)*Math.PI)**2)*((-1)**n[i])*Math.sin((2*n[i]-1)*Math.PI*x/L));
}
var sum = adding(y);
return sum;
}
function computePlot(x){
var N = parseFloat(document.getElementById('NController').value);
var L = parseFloat(document.getElementById('LController').value);
var A = parseFloat(document.getElementById('AController').value);
var x_values = [];
var y_values = [];
var y_values_cheat = [];
for (var i = 0; i < x.length ; ++i){
y_values.push(summation(x[i]));
x_values.push(x[i]);
}
for (var i = 0; i< y_values.length; ++i){
y_values_cheat.push(-y_values[y_values.length/2]+y_values[i]);
}
var data=[
{
type:"scatter",
mode:"lines",
x: x_values,
y: y_values_cheat,
line:{color:"rgb(0,225,0)", width:3, dash: "dashed"},
},
];
return data;
}
function odd_selection2(n,A,L,type){
if (type===0){
amplitude = (A*(-1)**n)*(decay)**n; // (8*A*1/((2*(n)-1) *np.pi)**2)*((-1)**(n))
} else if (type===1){
amplitude = (A*(1-(-1)**n))*(decay)**n; // A/(n*np.pi) *(1-(-1)**n)
} else if (type===2){
amplitude = (A*(-1)**(n+1))*(decay)**n; // 2*A*(-1)**(n+1) /(n*np.pi)
} else if (type===3){
amplitude = 1/L;
} else if (type===4){
amplitude = A*((-1)**n)*decay**n; // (((4*L**2)/(n*Math.PI)**2)*(-1)**n)
} else if (type===5){
amplitude = 0.5*A*(2*(-1)**(n+1)*decay**n); //A*(2*L/(n*Math.PI)*(-1)**(n+1)
} else if (type===6){
amplitude = 0;
}
return amplitude;
}
function even_selection2(n,A,L,type){
if (type === 6){
if (n===0){
amplitude2= A*L;
} else {
amplitude2 = 2*A*((-1)**(n)-1);
}
}
else if (type === 0 || type === 1 || type === 2 || type === 3 || type === 4 || type === 5){
amplitude2= 0;}
return amplitude2;
}
function plotSines(n,x,shape){
var N = parseFloat(document.getElementById('NController').value);
var L = parseFloat(document.getElementById('LController').value);
var A = parseFloat(document.getElementById('AController').value);
var x_n = [];
var y_n = [];
var spacing=3*A;
for (var i = 0; i < x.length ; ++i){
x_n.push(x[i]);
y_n.push(((odd_selection2(n,A,L,shape))*Math.sin(n*Math.PI*x[i]/L)+(even_selection2(n,A,L,shape))*Math.cos(n*Math.PI*x[i]/L))+2*spacing*(n));
}
var data=
{
type:"scatter",
mode:"lines",
x: x_n,
y: y_n,
line:{color:"rgb(0,N*10,0)",width:3, dash:"dashed"},
}
;
return data;
}
function computeComponents(x){
var N = parseFloat(document.getElementById('NController').value);
var L = parseFloat(document.getElementById('LController').value);
var A = parseFloat(document.getElementById('AController').value);
var data_value=[];
for (var n=1; n<N+1; ++n){
data_value.push(plotSines(n,z,shape));
}
return data_value;
}
/** updates the plot according to the slider controls. */
function updatePlot() {
var data = [];
// NB: updates according to the active tab
var href = $('ul.tab-nav li a.active.button').attr('href'); // finds out which tab is active
/* ~Jquery
5. Declare and store the floating values from x/y- sliders.
Hint: Same is task 2.
*/
/*
var N = parseFloat(document.getElementById('NController').value);
var A = parseFloat(document.getElementById('AController').value);
var L = parseFloat(document.getElementById('LController').value);
*/
if (href==="#plot"){
data = computePlot(z);
} else if (href==="#component"){
initCarte(href);
data = computeComponents(z);
}
//This is animation bit.
Plotly.animate(
'graph',
{data: data},
{
fromcurrent: true,
transition: {duration: 0,},
frame: {duration: 0, redraw: false,},
mode: "afterall"
}
);
}
function main() {
/*Jquery*/ //NB: Put Jquery stuff in the main not in HTML
$("input[type=range]").each(function () {
/*Allows for live update for display values*/
$(this).on('input', function(){
//Displays: (FLT Value) + (Corresponding Unit(if defined))
$("#"+$(this).attr("id") + "Display").text( $(this).val() + $("#"+$(this).attr("id") + "Display").attr("data-unit"));
//NB: Display values are restricted by their definition in the HTML to always display nice number.
updatePlot(); //Updating the plot is linked with display (Just My preference)
});
});
/*Tabs*/
$(function() {
$('ul.tab-nav li a.button').click(function() {
var href = $(this).attr('href');
$('li a.active.button', $(this).parent().parent()).removeClass('active');
$(this).addClass('active');
$('.tab-pane.active', $(href).parent()).removeClass('active');
$(href).addClass('active');
initCarte(href); //re-initialise when tab is changed
return false;
});
});
$(".rightnav").on('click',function(){
window.location.href =
defaultHref.slice(0,-6)
+(parseInt(defaultHref.slice(-6,-5))+1) + ".html";
});
$(".rightnav").on("mouseenter", function() {
$(".rightnav").css({"color":"#1a0433","font-size":"55px"});
}).on('mouseleave', function(){
$(".rightnav").css({"color":"#330766","font-size":"50px"});
});
$(".leftnav").on('click',function(){
window.location.href =
defaultHref.slice(0,-6)
+(parseInt(defaultHref.slice(-6,-5))-1) + ".html";
});
$(".leftnav").on("mouseenter", function() {
$(".leftnav").css({"color":"#1a0433","font-size":"55px"})
}).on('mouseleave', function(){
$(".leftnav").css({"color":"#330766","font-size":"50px"})
});
//The First Initialisation - I use 's' rather than 'z' :p
initCarte("#maths");
}
$(document).ready(main); //Load main when document is ready. |
/*
* Copyright (c) 2013-2016 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
exports.defineAutoTests = function() {
describe('Badge Plugin (cordova.plugins.notification.badge)', function () {
describe('Plugin availability', function () {
it("should exist", function() {
expect(cordova.plugins.notification.badge).toBeDefined();
});
it("should define clear", function() {
expect(cordova.plugins.notification.badge.clear).toBeDefined();
});
it("should define get", function() {
expect(cordova.plugins.notification.badge.get).toBeDefined();
});
it("should define set", function() {
expect(cordova.plugins.notification.badge.set).toBeDefined();
});
it("should define increase", function() {
expect(cordova.plugins.notification.badge.increase).toBeDefined();
});
it("should define decrease", function() {
expect(cordova.plugins.notification.badge.decrease).toBeDefined();
});
it("should define hasPermission", function() {
expect(cordova.plugins.notification.badge.hasPermission).toBeDefined();
});
it("should define registerPermission", function() {
expect(cordova.plugins.notification.badge.registerPermission).toBeDefined();
});
it("should define configure", function() {
expect(cordova.plugins.notification.badge.configure).toBeDefined();
});
});
describe('API callbacks', function () {
it("clear should invoke callback", function(done) {
cordova.plugins.notification.badge.clear(done);
});
it("get should invoke callback", function(done) {
cordova.plugins.notification.badge.get(done);
});
it("set should invoke callback", function(done) {
cordova.plugins.notification.badge.set(done);
});
it("increase should invoke callback", function(done) {
cordova.plugins.notification.badge.increase(done);
});
it("decrease should invoke callback", function(done) {
cordova.plugins.notification.badge.decrease(done);
});
it("hasPermission should invoke callback", function(done) {
cordova.plugins.notification.badge.hasPermission(done);
});
it("registerPermission should invoke callback", function(done) {
cordova.plugins.notification.badge.registerPermission(done);
});
});
describe('API functions', function () {
it("clear should set badge to 0", function(done) {
cordova.plugins.notification.badge.clear(function (badge) {
expect(badge).toBe(0);
done();
});
});
it("should return badge", function(done) {
cordova.plugins.notification.badge.set(10, function (badge) {
expect(badge).toBe(10);
cordova.plugins.notification.badge.get(function (badge2) {
expect(badge).toBe(badge2);
done();
});
});
});
it("should increase badge", function(done) {
cordova.plugins.notification.badge.set(10, function () {
cordova.plugins.notification.badge.increase(1, function (badge) {
expect(badge).toBe(11);
done();
});
});
});
it("should decrease badge", function(done) {
cordova.plugins.notification.badge.set(10, function () {
cordova.plugins.notification.badge.decrease(1, function (badge) {
expect(badge).toBe(9);
done();
});
});
});
it("hasPermission should return boolean", function(done) {
cordova.plugins.notification.badge.hasPermission(function (has) {
expect(has === true || has === false).toBe(true);
done();
});
});
it("registerPermission should return boolean", function(done) {
cordova.plugins.notification.badge.registerPermission(function (has) {
expect(has === true || has === false).toBe(true);
done();
});
});
});
});
};
|
!function(){const e="boowa-blog-v1";function t(t,n){return new Promise((a,c)=>{if(n)var s=setTimeout(c,n);fetch(t).then(c=>{if(n&&clearTimeout(s),(200===c.status||0===c.status)&&"error"!==c.type){var i=c.clone();caches.open(e).then(e=>{e.put(t,i)})}a(c)},c)})}self.addEventListener("install",e=>{self.skipWaiting()}),self.addEventListener("activate",e=>{e.waitUntil(caches.keys().then(e=>Promise.all(e.map(e=>caches.delete(e)))))}),self.addEventListener("fetch",n=>{var a=n.request.clone();n.respondWith(caches.open(e).then(e=>e.match(a).then(e=>t(a,3e3).catch(async()=>e)).catch(()=>t(a).catch(async e=>e))))})}();
//# sourceMappingURL=bankai-service-worker.js.map |
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var rename = $.rename;
var imagemin = $.imagemin;
var del = require('del');
var exec = require('child_process').exec;
var gutil = require('gulp-util');
var gmux = require('gulp-mux');
var runSequence = require('run-sequence');
var constants = require('../common/constants')();
var helper = require('../common/helper');
var fs = require('fs');
var taskClean = function(constants) {
del([constants.dist.distFolder]);
};
gulp.task('clean', 'Clean distribution folder.', function(done) {
var taskname = 'clean';
gmux.targets.setClientFolder(constants.clientFolder);
if(global.options === null) {
global.options = gmux.targets.askForMultipleTargets(taskname);
}
return gmux.createAndRunTasks(gulp, taskClean, taskname, global.options.target, global.options.mode, constants, done);
});
var taskHtml = function(constants) {
var dest = constants.dist.distFolder;
dest = helper.isMobile(constants) ? dest + '/www' : dest;
gulp.src(constants.html.src)
.pipe(rename('index.html'))
.pipe(gulp.dest(dest));
gulp.src('./' + constants.clientFolder + '/404' + constants.targetSuffix + '.html')
.pipe(rename('404.html'))
.pipe(gulp.dest(dest));
gulp.src('./' + constants.clientFolder + '/favicon' + constants.targetSuffix + '.ico')
.pipe(rename('favicon.ico'))
.pipe(gulp.dest(dest));
gulp.src('./' + constants.clientFolder + '/robots' + constants.targetSuffix + '.txt')
.pipe(rename('robots.txt'))
.pipe(gulp.dest(dest));
gulp.src('./' + constants.clientFolder + '/apple-touch-icon' + constants.targetSuffix + '.png')
.pipe(rename('apple-touch-icon.png'))
.pipe(gulp.dest(dest));
gulp.src('./' + constants.clientFolder + '/config' + constants.targetSuffix + '.xml')
.pipe(rename('config.xml'))
.pipe(gulp.dest(constants.dist.distFolder));
gulp.src(constants.cordova.src + '/hooks/**/*.*')
.pipe(gulp.dest(constants.dist.distFolder + '/hooks'));
};
var taskImage = function(constants) {
var dest = constants.dist.distFolder;
dest = helper.isMobile(constants) ? dest + '/www' : dest;
gulp.src(constants.images.src, {
base: constants.clientFolder
})
.pipe(imagemin())
.pipe(gulp.dest(dest));
};
var taskImageCordova = function(constants) {
if(helper.isMobile(constants)) {
if(fs.existsSync(constants.dist.distFolder + '/platforms/ios')) {
gulp.src(constants.cordova.src + '/resources/ios/icons/**/*')
.pipe(imagemin())
.pipe(gulp.dest(constants.dist.distFolder + '/platforms/ios/' + constants.appname + '/Resources/icons'));
gulp.src(constants.cordova.src + '/resources/ios/splash/**/*')
.pipe(imagemin())
.pipe(gulp.dest(constants.dist.distFolder + '/platforms/ios/' + constants.appname + '/Resources/splash'));
}
if(fs.existsSync(constants.dist.distFolder + '/platforms/android')) {
gulp.src(constants.cordova.src + '/resources/android/**/*')
.pipe(imagemin())
.pipe(gulp.dest(constants.dist.distFolder + '/platforms/android/res'));
}
}
};
gulp.task('html', false, function() {
var taskname = 'html';
gmux.targets.setClientFolder(constants.clientFolder);
if(global.options === null) {
global.options = gmux.targets.askForMultipleTargets(taskname);
}
return gmux.createAndRunTasks(gulp, taskHtml, taskname, global.options.target, global.options.mode, constants);
});
var taskHtmlWatch = function(constants) {
gulp.watch(constants.html.src, ['html']);
};
gulp.task('html:watch', false, function() {
var taskname = 'html:watch';
gmux.targets.setClientFolder(constants.clientFolder);
if(global.options === null) {
global.options = gmux.targets.askForSingleTarget(taskname);
}
gmux.createAndRunTasks(gulp, taskHtmlWatch, taskname, global.options.target, global.options.mode, constants);
});
gulp.task('image', false, ['image:cordova'], function() {
var taskname = 'image';
gmux.targets.setClientFolder(constants.clientFolder);
if(global.options === null) {
global.options = gmux.targets.askForMultipleTargets(taskname);
}
return gmux.createAndRunTasks(gulp, taskImage, taskname, global.options.target, global.options.mode, constants);
});
gulp.task('image:cordova', false, function() {
// this task copy the cordova icons and splashes to dist, but only if the platforms exist
var taskname = 'image:cordova';
gmux.targets.setClientFolder(constants.clientFolder);
if(global.options === null) {
global.options = gmux.targets.askForMultipleTargets(taskname);
}
return gmux.createAndRunTasks(gulp, taskImageCordova, taskname, global.options.target, global.options.mode, constants);
});
var taskCordovaIcon = function(constants) {
if(!helper.isMobile(constants)) {
return;
}
exec('./bin/cordova-generate-icons ' + constants.cordova.icon + ' ' + constants.cordova.src, helper.execHandler);
exec('./bin/cordova-generate-splashes ' + constants.cordova.icon + ' "' + constants.cordova.iconBackground + '" ' + constants.cordova.src, helper.execHandler);
};
gulp.task('cordova:icon', 'Generate the cordova icons and splashes.', function() {
var taskname = 'cordova:icon';
gmux.targets.setClientFolder(constants.clientFolder);
if(global.options === null) {
global.options = gmux.targets.askForMultipleTargets(taskname);
}
return gmux.createAndRunTasks(gulp, taskCordovaIcon, taskname, global.options.target, global.options.mode, constants);
});
gulp.task('dist', 'Distribute the application.', function(done) {
return runSequence('html', 'image', 'browserify', 'style', done);
});
gulp.task('clean:all', 'Clean distribution folder for all targets and modes.', function() {
var taskname = 'clean:all';
gmux.targets.setClientFolder(constants.clientFolder);
var targets = gmux.targets.getAllTargets();
gmux.createAndRunTasks(gulp, taskClean, taskname, targets, 'dev', constants);
gmux.createAndRunTasks(gulp, taskClean, taskname, targets, 'prod', constants);
});
|
"use strict";
//Define the controller module, assign its dependencies, assign the function.
var module = angular.module('MainCtrls', []);
//The actual function that will act as the controller
module.controller('mainCtrl', ['$scope', '$location', '$http', '$cookies', '$mdDialog', 'userSrvc', '$interval',
function indexCtrl($scope, $location, $http, $cookies, $mdDialog, userSrvc, $interval) {
let prom;
function notificationUpdate() {
$http.get("/api/users/notif", {
headers: {
'Authorization': 'Bearer ' + $cookies.get('auth_0')
}
}).then(function success(response) {
$scope.notifications = response.data;
}, function error(error) {
console.log("Failed");
$interval.cancel(prom);
});
}
var activeSendId;
userSrvc.cookieLog(function (error, response) {
if (error) {
$location.url("/");
} else {
$scope.name = response.username;
//update notifications every 2000ms
prom = $interval(notificationUpdate, 4000);
}
});
//Depending on the url show a different partial on the main.html
if ($location.url() == "/main") {
$scope.loc = 'mainFeed';
} else {
$scope.loc = 'profile';
}
$scope.profile_button = function () {
$location.url('/profile');
};
$scope.desafio_button = function () {
$location.url('/main');
};
$scope.logout = function () {
userSrvc.logout(function (err, result) {
if (err) {
window.alert("Something went wrong :/");
} else {
$location.url("/");
}
});
};
//Once search is clicked show the search input
$scope.search = function () {
var element = document.querySelector("#search_box");
document.getElementById("search_bar").style.display = "inline";
element.focus();
//If the search input loses focus collapse it
function focusChangeListener() {
if (document.activeElement === element)
return;
document.getElementById("search_bar").style.display = "none";
document.getElementById("search_button").style.display = "inline";
element.removeEventListener('blur', focusChangeListener, false);
}
element.addEventListener('blur', focusChangeListener, false);
document.getElementById("search_button").style.display = "none";
};
//Show the new challenge dialog
$scope.showNewChallenge = function (ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'partials/dialog1.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
}).then(function (answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function () {
$scope.status = 'You cancelled the dialog.';
});
};
//Show the send challenge dialog
$scope.showSendChallenge = function (ev, id) {
activeSendId = id;
$mdDialog.show({
controller: SendDialogController,
templateUrl: 'partials/send_list.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
}).then(function (answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function () {
$scope.status = 'You cancelled the dialog.';
});
};
let reviewed;
$scope.showReviewGauntlet = function (ev, gauntlet) {
reviewed = gauntlet;
$mdDialog.show({
controller: ReviewGauntletController,
templateUrl: 'partials/reviewDialog.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
}).then(function (answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function () {
$scope.status = 'You cancelled the dialog.';
});
};
function DialogController($scope, $mdDialog) {
$scope.hide = function () {
$mdDialog.hide();
};
$scope.cancel = function () {
$mdDialog.cancel();
};
$scope.answer = function (answer) {
$mdDialog.hide();
$http.post("/api/des/", $scope.challenge, {
headers: {
'Authorization': 'Bearer ' + $cookies.get('auth_0')
}
}).then(function success(response) {
window.alert("Success");
}, function error(error) {
window.alert("Failed");
});
};
}
function SendDialogController($scope, $mdDialog) {
$http.get("/api/users/connect", {
headers: {
'Authorization': 'Bearer ' + $cookies.get('auth_0')
}
}).then(function success(response) {
$scope.data = response.data[0].follower;
}, function error(error) {
window.alert("Failed");
});
$scope.hide = function () {
$mdDialog.hide();
};
$scope.cancel = function () {
$mdDialog.cancel();
};
$scope.answer = function (answer) {
var send = [];
//Iterate over the elements and keep the checked ones
for (var i = 0, j = $scope.data.length; i < j; i++) {
if ($scope.data[i].send)
send.push($scope.data[i]);
}
//Send the checked users and the challenge id to the server
$http.post("/api/des/gauntlet", [send, activeSendId], {
headers: {
'Authorization': 'Bearer ' + $cookies.get('auth_0')
}
}).then(function success(response) {
window.alert("Success");
}, function error(error) {
window.alert("Failed");
});
$mdDialog.hide();
};
}
function ReviewGauntletController($scope, $mdDialog) {
$scope.reviewed = reviewed;
$scope.hide = function () {
$mdDialog.hide();
};
$scope.cancel = function () {
$mdDialog.cancel();
};
$scope.answer = function (answer) {
//Send the checked users and the challenge id to the server
$http.post("/api/des/gauntlet/" + $scope.reviewed._id, {
action: answer
}, {
headers: {
'Authorization': 'Bearer ' + $cookies.get('auth_0')
}
}).then(function success(response) {
window.alert("Success");
}, function error(error) {
window.alert("Failed");
});
$mdDialog.hide();
}
}
}]);
module.controller('SrchCtrl', ['$http', '$cookies', '$q', '$location', SrchCtrl]);
function SrchCtrl($http, $cookies, $q, $location) {
function querySearch(query) {
var defered;
defered = $q.defer();
$http.post("/api/search/", {searchText: query}, {
headers: {
'Authorization': 'Bearer ' + $cookies.get('auth_0'),
'Content-Type': 'application/json'
}
}).then(function success(response) {
defered.resolve(response.data)
}, function error(error) {
//window.alert("Failed");
defered.resolve([]);
});
return defered.promise;
}
var self = this;
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
function searchTextChange(text) {
}
//Go to selected user profile
function selectedItemChange(item) {
if (item.username)
$location.url("/profile/" + item._id);
}
}
|
angular.module('app').factory('AddressService', ['$rootScope', '$q', '$resource', function($rootScope, $q, $resource) {
return {
getCity: function(name){
var api = $resource('/api/address/city/name/:name', {'name': name});
var deferred = $q.defer();
var r = api.get({}, function(){
deferred.resolve(r.data);
}, function(error){
deferred.reject(error);
});
return deferred.promise;
},
getCityNear: function(lat, long){
var api = $resource('/api/address/city/near/lat/:lat/long/:long', {'lat': lat, 'long': long});
var deferred = $q.defer();
var r = api.get({}, function(){
deferred.resolve(r.data);
}, function(error){
deferred.reject(error);
});
return deferred.promise;
},
getCities: function(params){
var api = $resource('/api/address/cities');
var deferred = $q.defer();
var r = api.get({}, function(){
deferred.resolve(r.data);
}, function(error){
deferred.reject(error);
});
return deferred.promise;
}
};
}]); |
/**
* @author f.flore
* created on 16.08.2016
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.settings', [])
.config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('settings', {
url: '/settings',
title: 'Settings',
templateUrl: 'app/pages/settings/settings.html',
controller: 'SettingsPageCtrl',
controllerAs: "settingsCtrl",
});
}
})();
|
import React from 'react';
import ReactDOM from 'react-dom';
import {connect} from 'react-redux';
import {setName} from '../actions';
const mapStateToProps = state => ({
name: state.chat.name
});
const mapDispatchToProps = {
setName
};
const Settings = ({name, setName}) => (
<div>
<label htmlFor="name-input">Name</label>
<input
id="name-input"
type="text"
value={name}
onChange={evt => setName(evt.target.value)}
/>
</div>
);
export default connect(mapStateToProps, mapDispatchToProps)(Settings) |
const CasRequestManager = require("./CasRequestManager");
let CookieRequestManager = function(session, Request) {
CasRequestManager.call(this, session, Request);
this.Requests = new (require("./cookieRequests"))(Request);
}
// heritage from CasRequestManager
CookieRequestManager.prototype = Object.create(CasRequestManager.prototype);
CookieRequestManager.prototype.constructor = CookieRequestManager;
/**
* This is all predefined routines for a request.
* @param {RequestManager} rm
* @param {string} id
* @param {any} arg
* @returns {EventEmitter}
*/
CookieRequestManager.prototype.req = function(rm, id, arg) {
switch(id) {
case "session":
// arg is cookie
return rm.Requests.fetchSession(rm.session, rm.session.space, arg);
break;
default:
return CasRequestManager.prototype.req.call(this, rm, id, arg);
break;
}
}
module.exports = CookieRequestManager; |
const { getGitSha } = require('ci-utils');
const fetch = require('node-fetch');
const https = require('https');
const gitSha = getGitSha(true);
const gitShaLong = getGitSha();
const {
SAUCE_USERNAME,
SAUCE_ACCESS_KEY,
// for push builds, or builds not triggered by a pull request, this is the name of the branch.
// for builds triggered by a pull request this is the name of the branch targeted by the pull request.
// for builds triggered by a tag, this is the same as the name of the tag(TRAVIS_TAG).
TRAVIS_BRANCH,
// if the current job is a pull request, the name of the branch from which the PR originated
// if the current job is a push build, this variable is empty("").
TRAVIS_PULL_REQUEST_BRANCH,
// The pull request number if the current job is a pull request, "false" if it’s not a pull request.
TRAVIS_PULL_REQUEST,
// The slug (in form: owner_name/repo_name) of the repository currently being built.
TRAVIS_REPO_SLUG,
// If the current build is for a git tag, this variable is set to the tag’s name
TRAVIS_TAG,
TRAVIS_BUILD_WEB_URL,
TRAVIS_JOB_NUMBER,
} = process.env;
const auth = Buffer.from(`${SAUCE_USERNAME}:${SAUCE_ACCESS_KEY}`).toString(
'base64',
);
/**
* @param {Object} client - Nightwatch instance @todo add link to API docs
* @param {function} callback
* @returns {void}
*/
async function handleNightwatchResults(client, callback) {
const currentTest = client.currentTest;
const sessionId = client.capabilities['webdriver.remote.sessionid'];
const { username, accessKey } = client.options;
const {
/** @type {string} - Name of test */
name,
/** @type {string} - Name of test file, ie `__tests__/bolt-video.e2e` */
module: testFileName,
/** @type {string} */
group,
/** @type {{ time: string, assertions: array, passed: number, errors: number, failed: number, skipped: number, tests: number, steps: array, timeMs: number}} */
results,
} = currentTest;
if (!client.launch_url.match(/saucelabs/)) {
console.log('Not saucelabs ...');
process.exit(1);
}
if (!username || !accessKey || !sessionId) {
console.log('No username, accessKey or sessionId');
console.log(username);
console.log(accessKey);
console.log(sessionId);
process.exit(1);
}
const passed = results.passed === results.tests - results.skipped;
console.log(`Passed: ${passed ? 'Yes' : 'No'} - ${name}`);
try {
const res = await fetch(
// https://wiki.saucelabs.com/display/DOCS/Job+Methods
`https://saucelabs.com/rest/v1/${SAUCE_USERNAME}/jobs/${sessionId}`,
{
method: 'PUT',
headers: {
Authorization: `Basic ${auth}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
passed,
build: `build-${process.env.TRAVIS_JOB_NUMBER}`,
tags: ['CI'],
'custom-data': {
TRAVIS_JOB_NUMBER,
TRAVIS_BRANCH,
TRAVIS_PULL_REQUEST_BRANCH,
TRAVIS_PULL_REQUEST,
TRAVIS_REPO_SLUG,
TRAVIS_TAG,
TRAVIS_BUILD_WEB_URL,
gitSha,
gitShaLong,
},
}),
},
);
if (res.ok) {
// console.log(`Set SauceLabs details ok`);
} else {
console.log(`Setting SauceLabs details not ok`);
throw new Error(`Set SauceLabs details not ok ${res.statusText}`);
}
const data = JSON.stringify({
passed,
});
const requestPath = `/rest/v1/${username}/jobs/${sessionId}`;
try {
// console.log('Updating Saucelabs', requestPath);
const req = https.request(
{
hostname: 'saucelabs.com',
path: requestPath,
method: 'PUT',
auth: `${username}:${accessKey}`,
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length,
},
},
function(res) {
let results;
res.setEncoding('utf8');
if (res.statusCode !== 200) {
console.log('Failed to updating Saucelabs', requestPath);
console.log(
'Response: ',
res.statusCode,
JSON.stringify(res.headers),
);
}
res.on('data', function onData(chunk) {
// console.log('BODY: ' + chunk);
results = chunk;
});
res.on('end', function onEnd() {
console.info('Finished updating Saucelabs');
callback(results);
});
},
);
req.on('error', function onError(e) {
console.log('problem with request: ' + e.message);
});
req.write(data);
req.end();
} catch (error) {
console.log('Error', error);
callback(error);
}
} catch (err) {
console.log(`Error setting SauceLabs details`, err);
process.exit(1);
}
}
module.exports = {
handleNightwatchResults,
};
|
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
// ideas taken from:
// . The ocean spray in your face [Jeff Lander]
// http://www.double.co.nz/dust/col0798.pdf
// . Building an Advanced Particle System [John van der Burg]
// http://www.gamasutra.com/features/20000623/vanderburg_01.htm
// . LOVE game engine
// http://love2d.org/
//
//
// Radius mode support, from 71 squared
// http://particledesigner.71squared.com/
//
// IMPORTANT: Particle Designer is supported by cocos2d, but
// 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d,
// cocos2d uses a another approach, but the results are almost identical.
//
/**
* Shape Mode of Particle Draw
* @constant
* @type Number
*/
cc.PARTICLE_SHAPE_MODE = 0;
/**
* Texture Mode of Particle Draw
* @constant
* @type Number
*/
cc.PARTICLE_TEXTURE_MODE = 1;
/**
* Star Shape for ShapeMode of Particle
* @constant
* @type Number
*/
cc.PARTICLE_STAR_SHAPE = 0;
/**
* Ball Shape for ShapeMode of Particle
* @constant
* @type Number
*/
cc.PARTICLE_BALL_SHAPE = 1;
/**
* The Particle emitter lives forever
* @constant
* @type Number
*/
cc.PARTICLE_DURATION_INFINITY = -1;
/**
* The starting size of the particle is equal to the ending size
* @constant
* @type Number
*/
cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE = -1;
/**
* The starting radius of the particle is equal to the ending radius
* @constant
* @type Number
*/
cc.PARTICLE_START_RADIUS_EQUAL_TO_END_RADIUS = -1;
/**
* Gravity mode (A mode)
* @constant
* @type Number
*/
cc.PARTICLE_MODE_GRAVITY = 0;
/**
* Radius mode (B mode)
* @constant
* @type Number
*/
cc.PARTICLE_MODE_RADIUS = 1;
// tCCPositionType
// possible types of particle positions
/**
* Living particles are attached to the world and are unaffected by emitter repositioning.
* @constant
* @type Number
*/
cc.PARTICLE_TYPE_FREE = 0;
/**
* Living particles are attached to the world but will follow the emitter repositioning.<br/>
* Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite.
* @constant
* @type Number
*/
cc.PARTICLE_TYPE_RELATIVE = 1;
/**
* Living particles are attached to the emitter and are translated along with it.
* @constant
* @type Number
*/
cc.PARTICLE_TYPE_GROUPED = 2;
/**
* Structure that contains the values of each particle
* @Class
* @Construct
* @param {cc.Point} [pos=cc.PointZero()] Position of particle
* @param {cc.Point} [startPos=cc.PointZero()]
* @param {cc.Color4F} [color= cc.Color4F(0, 0, 0, 1)]
* @param {cc.Color4F} [deltaColor=cc.Color4F(0, 0, 0, 1)]
* @param {cc.Size} [size=0]
* @param {cc.Size} [deltaSize=0]
* @param {Number} [rotation=0]
* @param {Number} [deltaRotation=0]
* @param {Number} [timeToLive=0]
* @param {Number} [atlasIndex=0]
* @param {cc.Particle.ModeA} [modeA=]
* @param {cc.Particle.ModeA} [modeB=]
*/
cc.Particle = function (pos, startPos, color, deltaColor, size, deltaSize, rotation, deltaRotation, timeToLive, atlasIndex, modeA, modeB) {
this.pos = pos ? pos : cc.PointZero();
this.startPos = startPos ? startPos : cc.PointZero();
this.color = color ? color : new cc.Color4F(0, 0, 0, 1);
this.deltaColor = deltaColor ? deltaColor : new cc.Color4F(0, 0, 0, 1);
this.size = size || 0;
this.deltaSize = deltaSize || 0;
this.rotation = rotation || 0;
this.deltaRotation = deltaRotation || 0;
this.timeToLive = timeToLive || 0;
this.atlasIndex = atlasIndex || 0;
this.modeA = modeA ? modeA : new cc.Particle.ModeA();
this.modeB = modeB ? modeB : new cc.Particle.ModeB();
this.isChangeColor = false;
this.drawPos = cc.p(0, 0);
};
/**
* Mode A: gravity, direction, radial accel, tangential accel
* @Class
* @Construct
* @param {cc.Point} dir direction of particle
* @param {Number} radialAccel
* @param {Number} tangentialAccel
*/
cc.Particle.ModeA = function (dir, radialAccel, tangentialAccel) {
this.dir = dir ? dir : cc.PointZero();
this.radialAccel = radialAccel || 0;
this.tangentialAccel = tangentialAccel || 0;
};
/**
* Mode B: radius mode
* @Class
* @Construct
* @param {Number} angle
* @param {Number} degreesPerSecond
* @param {Number} radius
* @param {Number} deltaRadius
*/
cc.Particle.ModeB = function (angle, degreesPerSecond, radius, deltaRadius) {
this.angle = angle || 0;
this.degreesPerSecond = degreesPerSecond || 0;
this.radius = radius || 0;
this.deltaRadius = deltaRadius || 0;
};
/**
* Array of Point instances used to optimize particle updates
*/
cc.Particle.TemporaryPoints = [
cc.p(),
cc.p(),
cc.p(),
cc.p()
];
/**
* <p>
* Particle System base class. <br/>
* Attributes of a Particle System:<br/>
* - emmision rate of the particles<br/>
* - Gravity Mode (Mode A): <br/>
* - gravity <br/>
* - direction <br/>
* - speed +- variance <br/>
* - tangential acceleration +- variance<br/>
* - radial acceleration +- variance<br/>
* - Radius Mode (Mode B): <br/>
* - startRadius +- variance <br/>
* - endRadius +- variance <br/>
* - rotate +- variance <br/>
* - Properties common to all modes: <br/>
* - life +- life variance <br/>
* - start spin +- variance <br/>
* - end spin +- variance <br/>
* - start size +- variance <br/>
* - end size +- variance <br/>
* - start color +- variance <br/>
* - end color +- variance <br/>
* - life +- variance <br/>
* - blending function <br/>
* - texture <br/>
* <br/>
* cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).<br/>
* 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, <br/>
* cocos2d uses a another approach, but the results are almost identical.<br/>
* cocos2d supports all the variables used by Particle Designer plus a bit more: <br/>
* - spinning particles (supported when using ParticleSystem) <br/>
* - tangential acceleration (Gravity mode) <br/>
* - radial acceleration (Gravity mode) <br/>
* - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only) <br/>
* It is possible to customize any of the above mentioned properties in runtime. Example: <br/>
* </p>
* @class
* @extends cc.Node
*
* @example
* emitter.radialAccel = 15;
* emitter.startSpin = 0;
*/
cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
//***********variables*************
_plistFile: "",
//! time elapsed since the start of the system (in seconds)
_elapsed: 0,
_dontTint: false,
// Different modes
//! Mode A:Gravity + Tangential Accel + Radial Accel
modeA: null,
//! Mode B: circular movement (gravity, radial accel and tangential accel don't are not used in this mode)
modeB: null,
//private POINTZERO for ParticleSystem
_pointZeroForParticle: cc.p(0, 0),
//! Array of particles
_particles: null,
// color modulate
// BOOL colorModulate;
//! How many particles can be emitted per second
_emitCounter: 0,
//! particle idx
_particleIdx: 0,
_batchNode: null,
_atlasIndex: 0,
//true if scaled or rotated
_transformSystemDirty: false,
_allocatedParticles: 0,
//drawMode
_drawMode: cc.PARTICLE_SHAPE_MODE,
//shape type
_shapeType: cc.PARTICLE_BALL_SHAPE,
_isActive: false,
_particleCount: 0,
_duration: 0,
_sourcePosition: null,
_posVar: null,
_life: 0,
_lifeVar: 0,
_angle: 0,
_angleVar: 0,
_startSize: 0,
_startSizeVar: 0,
_endSize: 0,
_endSizeVar: 0,
_startColor: null,
_startColorVar: null,
_endColor: null,
_endColorVar: null,
_startSpin: 0,
_startSpinVar: 0,
_endSpin: 0,
_endSpinVar: 0,
_emissionRate: 0,
_totalParticles: 0,
_texture: null,
_blendFunc: null,
_opacityModifyRGB: false,
_positionType: cc.PARTICLE_TYPE_FREE,
_isAutoRemoveOnFinish: false,
_emitterMode: 0,
// quads to be rendered
_quads:null,
// indices
_indices:null,
//_VAOname:0,
//0: vertex 1: indices
_buffersVBO:null,
_pointRect:null,
_textureLoaded: null,
_quadsArrayBuffer:null,
/**
* Constructor
* @override
*/
ctor:function () {
cc.Node.prototype.ctor.call(this);
this._emitterMode = cc.PARTICLE_MODE_GRAVITY;
this.modeA = new cc.ParticleSystem.ModeA();
this.modeB = new cc.ParticleSystem.ModeB();
this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
this._particles = [];
this._sourcePosition = new cc.Point(0, 0);
this._posVar = new cc.Point(0, 0);
this._startColor = new cc.Color4F(1, 1, 1, 1);
this._startColorVar = new cc.Color4F(1, 1, 1, 1);
this._endColor = new cc.Color4F(1, 1, 1, 1);
this._endColorVar = new cc.Color4F(1, 1, 1, 1);
this._plistFile = "";
this._elapsed = 0;
this._dontTint = false;
this._pointZeroForParticle = cc.p(0, 0);
this._emitCounter = 0;
this._particleIdx = 0;
this._batchNode = null;
this._atlasIndex = 0;
this._transformSystemDirty = false;
this._allocatedParticles = 0;
this._drawMode = cc.PARTICLE_SHAPE_MODE;
this._shapeType = cc.PARTICLE_BALL_SHAPE;
this._isActive = false;
this._particleCount = 0;
this._duration = 0;
this._life = 0;
this._lifeVar = 0;
this._angle = 0;
this._angleVar = 0;
this._startSize = 0;
this._startSizeVar = 0;
this._endSize = 0;
this._endSizeVar = 0;
this._startSpin = 0;
this._startSpinVar = 0;
this._endSpin = 0;
this._endSpinVar = 0;
this._emissionRate = 0;
this._totalParticles = 0;
this._texture = null;
this._opacityModifyRGB = false;
this._positionType = cc.PARTICLE_TYPE_FREE;
this._isAutoRemoveOnFinish = false;
this._buffersVBO = [0, 0];
this._quads = [];
this._indices = [];
this._pointRect = cc.RectZero();
this._textureLoaded = true;
if (cc.renderContextType === cc.WEBGL) {
this._quadsArrayBuffer = null;
}
},
/**
* initializes the indices for the vertices
*/
initIndices:function () {
var locIndices = this._indices;
for (var i = 0, len = this._totalParticles; i < len; ++i) {
var i6 = i * 6;
var i4 = i * 4;
locIndices[i6 + 0] = i4 + 0;
locIndices[i6 + 1] = i4 + 1;
locIndices[i6 + 2] = i4 + 2;
locIndices[i6 + 5] = i4 + 1;
locIndices[i6 + 4] = i4 + 2;
locIndices[i6 + 3] = i4 + 3;
}
},
/**
* <p> initializes the texture with a rectangle measured Points<br/>
* pointRect should be in Texture coordinates, not pixel coordinates
* </p>
* @param {cc.Rect} pointRect
*/
initTexCoordsWithRect:function (pointRect) {
var scaleFactor = cc.CONTENT_SCALE_FACTOR();
// convert to pixels coords
var rect = cc.rect(
pointRect.x * scaleFactor,
pointRect.y * scaleFactor,
pointRect.width * scaleFactor,
pointRect.height * scaleFactor);
var wide = pointRect.width;
var high = pointRect.height;
if (this._texture) {
wide = this._texture.getPixelsWide();
high = this._texture.getPixelsHigh();
}
if(cc.renderContextType === cc.CANVAS)
return;
var left, bottom, right, top;
if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) {
left = (rect.x * 2 + 1) / (wide * 2);
bottom = (rect.y * 2 + 1) / (high * 2);
right = left + (rect.width * 2 - 2) / (wide * 2);
top = bottom + (rect.height * 2 - 2) / (high * 2);
} else {
left = rect.x / wide;
bottom = rect.y / high;
right = left + rect.width / wide;
top = bottom + rect.height / high;
}
// Important. Texture in cocos2d are inverted, so the Y component should be inverted
var temp = top;
top = bottom;
bottom = temp;
var quads;
var start = 0, end = 0;
if (this._batchNode) {
quads = this._batchNode.getTextureAtlas().getQuads();
start = this._atlasIndex;
end = this._atlasIndex + this._totalParticles;
} else {
quads = this._quads;
start = 0;
end = this._totalParticles;
}
for (var i = start; i < end; i++) {
if (!quads[i])
quads[i] = cc.V3F_C4B_T2F_QuadZero();
// bottom-left vertex:
var selQuad = quads[i];
selQuad.bl.texCoords.u = left;
selQuad.bl.texCoords.v = bottom;
// bottom-right vertex:
selQuad.br.texCoords.u = right;
selQuad.br.texCoords.v = bottom;
// top-left vertex:
selQuad.tl.texCoords.u = left;
selQuad.tl.texCoords.v = top;
// top-right vertex:
selQuad.tr.texCoords.u = right;
selQuad.tr.texCoords.v = top;
}
},
/**
* return weak reference to the cc.SpriteBatchNode that renders the cc.Sprite
* @return {cc.ParticleBatchNode}
*/
getBatchNode:function () {
return this._batchNode;
},
/**
* set weak reference to the cc.SpriteBatchNode that renders the cc.Sprite
* @param {cc.ParticleBatchNode} batchNode
*/
setBatchNode:function (batchNode) {
if (this._batchNode != batchNode) {
var oldBatch = this._batchNode;
this._batchNode = batchNode; //weak reference
if (batchNode) {
var locParticles = this._particles;
for (var i = 0; i < this._totalParticles; i++)
locParticles[i].atlasIndex = i;
}
// NEW: is self render ?
if (!batchNode) {
this._allocMemory();
this.initIndices();
this.setTexture(oldBatch.getTexture());
//if (cc.TEXTURE_ATLAS_USE_VAO)
// this._setupVBOandVAO();
//else
this._setupVBO();
} else if (!oldBatch) {
// OLD: was it self render cleanup ?
// copy current state to batch
this._batchNode.getTextureAtlas()._copyQuadsToTextureAtlas(this._quads, this._atlasIndex);
//delete buffer
cc.renderContext.deleteBuffer(this._buffersVBO[1]); //where is re-bindBuffer code?
//if (cc.TEXTURE_ATLAS_USE_VAO)
// glDeleteVertexArrays(1, this._VAOname);
}
}
},
/**
* return index of system in batch node array
* @return {Number}
*/
getAtlasIndex:function () {
return this._atlasIndex;
},
/**
* set index of system in batch node array
* @param {Number} atlasIndex
*/
setAtlasIndex:function (atlasIndex) {
this._atlasIndex = atlasIndex;
},
/**
* Return DrawMode of ParticleSystem
* @return {Number}
*/
getDrawMode:function () {
return this._drawMode;
},
/**
* DrawMode of ParticleSystem setter
* @param {Number} drawMode
*/
setDrawMode:function (drawMode) {
this._drawMode = drawMode;
},
/**
* Return ShapeType of ParticleSystem
* @return {Number}
*/
getShapeType:function () {
return this._shapeType;
},
/**
* ShapeType of ParticleSystem setter
* @param {Number} shapeType
*/
setShapeType:function (shapeType) {
this._shapeType = shapeType;
},
/**
* Return ParticleSystem is active
* @return {Boolean}
*/
isActive:function () {
return this._isActive;
},
/**
* Quantity of particles that are being simulated at the moment
* @return {Number}
*/
getParticleCount:function () {
return this._particleCount;
},
/**
* Quantity of particles setter
* @param {Number} particleCount
*/
setParticleCount:function (particleCount) {
this._particleCount = particleCount;
},
/**
* How many seconds the emitter wil run. -1 means 'forever'
* @return {Number}
*/
getDuration:function () {
return this._duration;
},
/**
* set run seconds of the emitter
* @param {Number} duration
*/
setDuration:function (duration) {
this._duration = duration;
},
/**
* Return sourcePosition of the emitter
* @return {cc.Point | Object}
*/
getSourcePosition:function () {
return {x:this._sourcePosition.x, y:this._sourcePosition.y};
},
/**
* sourcePosition of the emitter setter
* @param sourcePosition
*/
setSourcePosition:function (sourcePosition) {
this._sourcePosition = sourcePosition;
},
/**
* Return Position variance of the emitter
* @return {cc.Point | Object}
*/
getPosVar:function () {
return {x: this._posVar.x, y: this._posVar.y};
},
/**
* Position variance of the emitter setter
* @param {cc.Point} posVar
*/
setPosVar:function (posVar) {
this._posVar = posVar;
},
/**
* Return life of each particle
* @return {Number}
*/
getLife:function () {
return this._life;
},
/**
* life of each particle setter
* @param {Number} life
*/
setLife:function (life) {
this._life = life;
},
/**
* Return life variance of each particle
* @return {Number}
*/
getLifeVar:function () {
return this._lifeVar;
},
/**
* life variance of each particle setter
* @param {Number} lifeVar
*/
setLifeVar:function (lifeVar) {
this._lifeVar = lifeVar;
},
/**
* Return angle of each particle
* @return {Number}
*/
getAngle:function () {
return this._angle;
},
/**
* angle of each particle setter
* @param {Number} angle
*/
setAngle:function (angle) {
this._angle = angle;
},
/**
* Return angle variance of each particle
* @return {Number}
*/
getAngleVar:function () {
return this._angleVar;
},
/**
* angle variance of each particle setter
* @param angleVar
*/
setAngleVar:function (angleVar) {
this._angleVar = angleVar;
},
// mode A
/**
* Return Gravity of emitter
* @return {cc.Point}
*/
getGravity:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getGravity() : Particle Mode should be Gravity");
var locGravity = this.modeA.gravity;
return cc.p(locGravity.x, locGravity.y);
},
/**
* Gravity of emitter setter
* @param {cc.Point} gravity
*/
setGravity:function (gravity) {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setGravity() : Particle Mode should be Gravity");
this.modeA.gravity = gravity;
},
/**
* Return Speed of each particle
* @return {Number}
*/
getSpeed:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getSpeed() : Particle Mode should be Gravity");
return this.modeA.speed;
},
/**
* Speed of each particle setter
* @param {Number} speed
*/
setSpeed:function (speed) {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setSpeed() : Particle Mode should be Gravity");
this.modeA.speed = speed;
},
/**
* return speed variance of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
getSpeedVar:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getSpeedVar() : Particle Mode should be Gravity");
return this.modeA.speedVar;
},
/**
* speed variance of each particle setter. Only available in 'Gravity' mode.
* @param {Number} speedVar
*/
setSpeedVar:function (speedVar) {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setSpeedVar() : Particle Mode should be Gravity");
this.modeA.speedVar = speedVar;
},
/**
* Return tangential acceleration of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
getTangentialAccel:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getTangentialAccel() : Particle Mode should be Gravity");
return this.modeA.tangentialAccel;
},
/**
* Tangential acceleration of each particle setter. Only available in 'Gravity' mode.
* @param {Number} tangentialAccel
*/
setTangentialAccel:function (tangentialAccel) {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setTangentialAccel() : Particle Mode should be Gravity");
this.modeA.tangentialAccel = tangentialAccel;
},
/**
* Return tangential acceleration variance of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
getTangentialAccelVar:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getTangentialAccelVar() : Particle Mode should be Gravity");
return this.modeA.tangentialAccelVar;
},
/**
* tangential acceleration variance of each particle setter. Only available in 'Gravity' mode.
* @param {Number} tangentialAccelVar
*/
setTangentialAccelVar:function (tangentialAccelVar) {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setTangentialAccelVar() : Particle Mode should be Gravity");
this.modeA.tangentialAccelVar = tangentialAccelVar;
},
/**
* Return radial acceleration of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
getRadialAccel:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getRadialAccel() : Particle Mode should be Gravity");
return this.modeA.radialAccel;
},
/**
* radial acceleration of each particle setter. Only available in 'Gravity' mode.
* @param {Number} radialAccel
*/
setRadialAccel:function (radialAccel) {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setRadialAccel() : Particle Mode should be Gravity");
this.modeA.radialAccel = radialAccel;
},
/**
* Return radial acceleration variance of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
getRadialAccelVar:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getRadialAccelVar() : Particle Mode should be Gravity");
return this.modeA.radialAccelVar;
},
/**
* radial acceleration variance of each particle setter. Only available in 'Gravity' mode.
* @param {Number} radialAccelVar
*/
setRadialAccelVar:function (radialAccelVar) {
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setRadialAccelVar() : Particle Mode should be Gravity");
this.modeA.radialAccelVar = radialAccelVar;
},
/**
* get the rotation of each particle to its direction Only available in 'Gravity' mode.
* @returns {boolean}
*/
getRotationIsDir: function(){
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getRotationIsDir() : Particle Mode should be Gravity");
return this.modeA.rotationIsDir;
},
/**
* set the rotation of each particle to its direction Only available in 'Gravity' mode.
* @param {boolean} t
*/
setRotationIsDir: function(t){
if(this._emitterMode !== cc.PARTICLE_MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setRotationIsDir() : Particle Mode should be Gravity");
this.modeA.rotationIsDir = t;
},
// mode B
/**
* Return starting radius of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
getStartRadius:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getStartRadius() : Particle Mode should be Radius");
return this.modeB.startRadius;
},
/**
* starting radius of the particles setter. Only available in 'Radius' mode.
* @param {Number} startRadius
*/
setStartRadius:function (startRadius) {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setStartRadius() : Particle Mode should be Radius");
this.modeB.startRadius = startRadius;
},
/**
* Return starting radius variance of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
getStartRadiusVar:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getStartRadiusVar() : Particle Mode should be Radius");
return this.modeB.startRadiusVar;
},
/**
* starting radius variance of the particles setter. Only available in 'Radius' mode.
* @param {Number} startRadiusVar
*/
setStartRadiusVar:function (startRadiusVar) {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setStartRadiusVar() : Particle Mode should be Radius");
this.modeB.startRadiusVar = startRadiusVar;
},
/**
* Return ending radius of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
getEndRadius:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getEndRadius() : Particle Mode should be Radius");
return this.modeB.endRadius;
},
/**
* ending radius of the particles setter. Only available in 'Radius' mode.
* @param {Number} endRadius
*/
setEndRadius:function (endRadius) {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setEndRadius() : Particle Mode should be Radius");
this.modeB.endRadius = endRadius;
},
/**
* Return ending radius variance of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
getEndRadiusVar:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getEndRadiusVar() : Particle Mode should be Radius");
return this.modeB.endRadiusVar;
},
/**
* ending radius variance of the particles setter. Only available in 'Radius' mode.
* @param endRadiusVar
*/
setEndRadiusVar:function (endRadiusVar) {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setEndRadiusVar() : Particle Mode should be Radius");
this.modeB.endRadiusVar = endRadiusVar;
},
/**
* get Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode.
* @return {Number}
*/
getRotatePerSecond:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getRotatePerSecond() : Particle Mode should be Radius");
return this.modeB.rotatePerSecond;
},
/**
* set Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode.
* @param {Number} degrees
*/
setRotatePerSecond:function (degrees) {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setRotatePerSecond() : Particle Mode should be Radius");
this.modeB.rotatePerSecond = degrees;
},
/**
* Return Variance in degrees for rotatePerSecond. Only available in 'Radius' mode.
* @return {Number}
*/
getRotatePerSecondVar:function () {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getRotatePerSecondVar() : Particle Mode should be Radius");
return this.modeB.rotatePerSecondVar;
},
/**
* Variance in degrees for rotatePerSecond setter. Only available in 'Radius' mode.
* @param degrees
*/
setRotatePerSecondVar:function (degrees) {
if(this._emitterMode !== cc.PARTICLE_MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setRotatePerSecondVar() : Particle Mode should be Radius");
this.modeB.rotatePerSecondVar = degrees;
},
//////////////////////////////////////////////////////////////////////////
//don't use a transform matrix, this is faster
setScale:function (scale, scaleY) {
this._transformSystemDirty = true;
cc.Node.prototype.setScale.call(this, scale, scaleY);
},
setRotation:function (newRotation) {
this._transformSystemDirty = true;
cc.Node.prototype.setRotation.call(this, newRotation);
},
setScaleX:function (newScaleX) {
this._transformSystemDirty = true;
cc.Node.prototype.setScaleX.call(this, newScaleX);
},
setScaleY:function (newScaleY) {
this._transformSystemDirty = true;
cc.Node.prototype.setScaleY.call(this, newScaleY);
},
/**
* get start size in pixels of each particle
* @return {Number}
*/
getStartSize:function () {
return this._startSize;
},
/**
* set start size in pixels of each particle
* @param {Number} startSize
*/
setStartSize:function (startSize) {
this._startSize = startSize;
},
/**
* get size variance in pixels of each particle
* @return {Number}
*/
getStartSizeVar:function () {
return this._startSizeVar;
},
/**
* set size variance in pixels of each particle
* @param {Number} startSizeVar
*/
setStartSizeVar:function (startSizeVar) {
this._startSizeVar = startSizeVar;
},
/**
* get end size in pixels of each particle
* @return {Number}
*/
getEndSize:function () {
return this._endSize;
},
/**
* set end size in pixels of each particle
* @param endSize
*/
setEndSize:function (endSize) {
this._endSize = endSize;
},
/**
* get end size variance in pixels of each particle
* @return {Number}
*/
getEndSizeVar:function () {
return this._endSizeVar;
},
/**
* set end size variance in pixels of each particle
* @param {Number} endSizeVar
*/
setEndSizeVar:function (endSizeVar) {
this._endSizeVar = endSizeVar;
},
/**
* set start color of each particle
* @return {cc.Color4F}
*/
getStartColor:function () {
return this._startColor;
},
/**
* get start color of each particle
* @param {cc.Color4F} startColor
*/
setStartColor:function (startColor) {
if (startColor instanceof cc.Color3B)
startColor = cc.c4FFromccc3B(startColor);
this._startColor = startColor;
},
/**
* get start color variance of each particle
* @return {cc.Color4F}
*/
getStartColorVar:function () {
return this._startColorVar;
},
/**
* set start color variance of each particle
* @param {cc.Color4F} startColorVar
*/
setStartColorVar:function (startColorVar) {
if (startColorVar instanceof cc.Color3B)
startColorVar = cc.c4FFromccc3B(startColorVar);
this._startColorVar = startColorVar;
},
/**
* get end color and end color variation of each particle
* @return {cc.Color4F}
*/
getEndColor:function () {
return this._endColor;
},
/**
* set end color and end color variation of each particle
* @param {cc.Color4F} endColor
*/
setEndColor:function (endColor) {
if (endColor instanceof cc.Color3B)
endColor = cc.c4FFromccc3B(endColor);
this._endColor = endColor;
},
/**
* get end color variance of each particle
* @return {cc.Color4F}
*/
getEndColorVar:function () {
return this._endColorVar;
},
/**
* set end color variance of each particle
* @param {cc.Color4F} endColorVar
*/
setEndColorVar:function (endColorVar) {
if (endColorVar instanceof cc.Color3B)
endColorVar = cc.c4FFromccc3B(endColorVar);
this._endColorVar = endColorVar;
},
/**
* get initial angle of each particle
* @return {Number}
*/
getStartSpin:function () {
return this._startSpin;
},
/**
* set initial angle of each particle
* @param {Number} startSpin
*/
setStartSpin:function (startSpin) {
this._startSpin = startSpin;
},
/**
* get initial angle variance of each particle
* @return {Number}
*/
getStartSpinVar:function () {
return this._startSpinVar;
},
/**
* set initial angle variance of each particle
* @param {Number} startSpinVar
*/
setStartSpinVar:function (startSpinVar) {
this._startSpinVar = startSpinVar;
},
/**
* get end angle of each particle
* @return {Number}
*/
getEndSpin:function () {
return this._endSpin;
},
/**
* set end angle of each particle
* @param {Number} endSpin
*/
setEndSpin:function (endSpin) {
this._endSpin = endSpin;
},
/**
* get end angle variance of each particle
* @return {Number}
*/
getEndSpinVar:function () {
return this._endSpinVar;
},
/**
* set end angle variance of each particle
* @param {Number} endSpinVar
*/
setEndSpinVar:function (endSpinVar) {
this._endSpinVar = endSpinVar;
},
/**
* get emission rate of the particles
* @return {Number}
*/
getEmissionRate:function () {
return this._emissionRate;
},
/**
* set emission rate of the particles
* @param {Number} emissionRate
*/
setEmissionRate:function (emissionRate) {
this._emissionRate = emissionRate;
},
/**
* get maximum particles of the system
* @return {Number}
*/
getTotalParticles:function () {
return this._totalParticles;
},
/**
* set maximum particles of the system
* @param {Number} tp totalParticles
*/
setTotalParticles:function (tp) {
//cc.Assert(tp <= this._allocatedParticles, "Particle: resizing particle array only supported for quads");
if (cc.renderContextType === cc.CANVAS){
this._totalParticles = (tp < 200) ? tp : 200;
return;
}
// If we are setting the total numer of particles to a number higher
// than what is allocated, we need to allocate new arrays
if (tp > this._allocatedParticles) {
var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
// Allocate new memory
this._indices = new Uint16Array(tp * 6);
var locQuadsArrayBuffer = new ArrayBuffer(tp * quadSize);
//TODO need fix
// Assign pointers
var locParticles = this._particles;
locParticles.length = 0;
var locQuads = this._quads;
locQuads.length = 0;
for (var j = 0; j < tp; j++) {
locParticles[j] = new cc.Particle();
locQuads[j] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, locQuadsArrayBuffer, j * quadSize);
}
this._allocatedParticles = tp;
this._totalParticles = tp;
// Init particles
if (this._batchNode) {
for (var i = 0; i < tp; i++)
locParticles[i].atlasIndex = i;
}
this._quadsArrayBuffer = locQuadsArrayBuffer;
this.initIndices();
//if (cc.TEXTURE_ATLAS_USE_VAO)
// this._setupVBOandVAO();
//else
this._setupVBO();
//set the texture coord
if(this._texture){
var size = this._texture.getContentSize();
this.initTexCoordsWithRect(cc.rect(0, 0, size.width, size.height));
}
} else
this._totalParticles = tp;
this.resetSystem();
},
/**
* get Texture of Particle System
* @return {cc.Texture2D}
*/
getTexture:function () {
return this._texture;
},
/**
* set Texture of Particle System
* @param {cc.Texture2D } texture
*/
setTexture:function (texture) {
if(texture.isLoaded()){
var size = texture.getContentSize();
this.setTextureWithRect(texture, cc.rect(0, 0, size.width, size.height));
} else {
this._textureLoaded = false;
texture.addLoadedEventListener(function(sender){
this._textureLoaded = true;
var size = sender.getContentSize();
this.setTextureWithRect(sender, cc.rect(0, 0, size.width, size.height));
}, this);
}
},
/** conforms to CocosNodeTexture protocol */
/**
* get BlendFunc of Particle System
* @return {cc.BlendFunc}
*/
getBlendFunc:function () {
return this._blendFunc;
},
/**
* set BlendFunc of Particle System
* @param {Number} src
* @param {Number} dst
*/
setBlendFunc:function (src, dst) {
if (arguments.length == 1) {
if (this._blendFunc != src) {
this._blendFunc = src;
this._updateBlendFunc();
}
} else {
if (this._blendFunc.src != src || this._blendFunc.dst != dst) {
this._blendFunc = {src:src, dst:dst};
this._updateBlendFunc();
}
}
},
/**
* does the alpha value modify color getter
* @return {Boolean}
*/
getOpacityModifyRGB:function () {
return this._opacityModifyRGB;
},
/**
* does the alpha value modify color setter
* @param newValue
*/
setOpacityModifyRGB:function (newValue) {
this._opacityModifyRGB = newValue;
},
/**
* <p>whether or not the particles are using blend additive.<br/>
* If enabled, the following blending function will be used.<br/>
* </p>
* @return {Boolean}
* @example
* source blend function = GL_SRC_ALPHA;
* dest blend function = GL_ONE;
*/
isBlendAdditive:function () {
return (( this._blendFunc.src == gl.SRC_ALPHA && this._blendFunc.dst == gl.ONE) || (this._blendFunc.src == gl.ONE && this._blendFunc.dst == gl.ONE));
},
/**
* <p>whether or not the particles are using blend additive.<br/>
* If enabled, the following blending function will be used.<br/>
* </p>
* @param {Boolean} isBlendAdditive
*/
setBlendAdditive:function (isBlendAdditive) {
var locBlendFunc = this._blendFunc;
if (isBlendAdditive) {
locBlendFunc.src = gl.SRC_ALPHA;
locBlendFunc.dst = gl.ONE;
} else {
if (cc.renderContextType === cc.WEBGL) {
if (this._texture && !this._texture.hasPremultipliedAlpha()) {
locBlendFunc.src = gl.SRC_ALPHA;
locBlendFunc.dst = gl.ONE_MINUS_SRC_ALPHA;
} else {
locBlendFunc.src = cc.BLEND_SRC;
locBlendFunc.dst = cc.BLEND_DST;
}
} else {
locBlendFunc.src = cc.BLEND_SRC;
locBlendFunc.dst = cc.BLEND_DST;
}
}
},
/**
* get particles movement type: Free or Grouped
* @return {Number}
*/
getPositionType:function () {
return this._positionType;
},
/**
* set particles movement type: Free or Grouped
* @param {Number} positionType
*/
setPositionType:function (positionType) {
this._positionType = positionType;
},
/**
* <p> return whether or not the node will be auto-removed when it has no particles left.<br/>
* By default it is false.<br/>
* </p>
* @return {Boolean}
*/
isAutoRemoveOnFinish:function () {
return this._isAutoRemoveOnFinish;
},
/**
* <p> set whether or not the node will be auto-removed when it has no particles left.<br/>
* By default it is false.<br/>
* </p>
* @param {Boolean} isAutoRemoveOnFinish
*/
setAutoRemoveOnFinish:function (isAutoRemoveOnFinish) {
this._isAutoRemoveOnFinish = isAutoRemoveOnFinish;
},
/**
* return kind of emitter modes
* @return {Number}
*/
getEmitterMode:function () {
return this._emitterMode;
},
/**
* <p>Switch between different kind of emitter modes:<br/>
* - CCPARTICLE_MODE_GRAVITY: uses gravity, speed, radial and tangential acceleration<br/>
* - CCPARTICLE_MODE_RADIUS: uses radius movement + rotation <br/>
* </p>
* @param {Number} emitterMode
*/
setEmitterMode:function (emitterMode) {
this._emitterMode = emitterMode;
},
/**
* initializes a cc.ParticleSystem
*/
init:function () {
return this.initWithTotalParticles(150);
},
/**
* <p>
* initializes a CCParticleSystem from a plist file. <br/>
* This plist files can be creted manually or with Particle Designer:<br/>
* http://particledesigner.71squared.com/
* </p>
* @param {String} plistFile
* @return {boolean}
*/
initWithFile:function (plistFile) {
this._plistFile = plistFile;
var fileUtils = cc.FileUtils.getInstance();
var fullPath = fileUtils.fullPathForFilename(plistFile);
var dict = fileUtils.dictionaryWithContentsOfFileThreadSafe(fullPath);
if(!dict){
cc.log("cc.ParticleSystem.initWithFile(): Particles: file not found");
return false;
}
// XXX compute path from a path, should define a function somewhere to do it
return this.initWithDictionary(dict, "");
},
/**
* return bounding box of particle system in world space
* @return {cc.Rect}
*/
getBoundingBoxToWorld:function () {
return cc.rect(0, 0, cc.canvas.width, cc.canvas.height);
},
/**
* initializes a particle system from a NSDictionary and the path from where to load the png
* @param {object} dictionary
* @param {String} dirname
* @return {Boolean}
*/
initWithDictionary:function (dictionary, dirname) {
var ret = false;
var buffer = null;
var image = null;
var locValueForKey = this._valueForKey;
var maxParticles = parseInt(locValueForKey("maxParticles", dictionary));
// self, not super
if (this.initWithTotalParticles(maxParticles)) {
// angle
this._angle = parseFloat(locValueForKey("angle", dictionary));
this._angleVar = parseFloat(locValueForKey("angleVariance", dictionary));
// duration
this._duration = parseFloat(locValueForKey("duration", dictionary));
// blend function
this._blendFunc.src = parseInt(locValueForKey("blendFuncSource", dictionary));
this._blendFunc.dst = parseInt(locValueForKey("blendFuncDestination", dictionary));
// color
var locStartColor = this._startColor;
locStartColor.r = parseFloat(locValueForKey("startColorRed", dictionary));
locStartColor.g = parseFloat(locValueForKey("startColorGreen", dictionary));
locStartColor.b = parseFloat(locValueForKey("startColorBlue", dictionary));
locStartColor.a = parseFloat(locValueForKey("startColorAlpha", dictionary));
var locStartColorVar = this._startColorVar;
locStartColorVar.r = parseFloat(locValueForKey("startColorVarianceRed", dictionary));
locStartColorVar.g = parseFloat(locValueForKey("startColorVarianceGreen", dictionary));
locStartColorVar.b = parseFloat(locValueForKey("startColorVarianceBlue", dictionary));
locStartColorVar.a = parseFloat(locValueForKey("startColorVarianceAlpha", dictionary));
var locEndColor = this._endColor;
locEndColor.r = parseFloat(locValueForKey("finishColorRed", dictionary));
locEndColor.g = parseFloat(locValueForKey("finishColorGreen", dictionary));
locEndColor.b = parseFloat(locValueForKey("finishColorBlue", dictionary));
locEndColor.a = parseFloat(locValueForKey("finishColorAlpha", dictionary));
var locEndColorVar = this._endColorVar;
locEndColorVar.r = parseFloat(locValueForKey("finishColorVarianceRed", dictionary));
locEndColorVar.g = parseFloat(locValueForKey("finishColorVarianceGreen", dictionary));
locEndColorVar.b = parseFloat(locValueForKey("finishColorVarianceBlue", dictionary));
locEndColorVar.a = parseFloat(locValueForKey("finishColorVarianceAlpha", dictionary));
// particle size
this._startSize = parseFloat(locValueForKey("startParticleSize", dictionary));
this._startSizeVar = parseFloat(locValueForKey("startParticleSizeVariance", dictionary));
this._endSize = parseFloat(locValueForKey("finishParticleSize", dictionary));
this._endSizeVar = parseFloat(locValueForKey("finishParticleSizeVariance", dictionary));
// position
var x = parseFloat(locValueForKey("sourcePositionx", dictionary));
var y = parseFloat(locValueForKey("sourcePositiony", dictionary));
this.setPosition(x, y);
this._posVar.x = parseFloat(locValueForKey("sourcePositionVariancex", dictionary));
this._posVar.y = parseFloat(locValueForKey("sourcePositionVariancey", dictionary));
// Spinning
this._startSpin = parseFloat(locValueForKey("rotationStart", dictionary));
this._startSpinVar = parseFloat(locValueForKey("rotationStartVariance", dictionary));
this._endSpin = parseFloat(locValueForKey("rotationEnd", dictionary));
this._endSpinVar = parseFloat(locValueForKey("rotationEndVariance", dictionary));
this._emitterMode = parseInt(locValueForKey("emitterType", dictionary));
// Mode A: Gravity + tangential accel + radial accel
if (this._emitterMode == cc.PARTICLE_MODE_GRAVITY) {
var locModeA = this.modeA;
// gravity
locModeA.gravity.x = parseFloat(locValueForKey("gravityx", dictionary));
locModeA.gravity.y = parseFloat(locValueForKey("gravityy", dictionary));
// speed
locModeA.speed = parseFloat(locValueForKey("speed", dictionary));
locModeA.speedVar = parseFloat(locValueForKey("speedVariance", dictionary));
// radial acceleration
var pszTmp = locValueForKey("radialAcceleration", dictionary);
locModeA.radialAccel = (pszTmp) ? parseFloat(pszTmp) : 0;
pszTmp = locValueForKey("radialAccelVariance", dictionary);
locModeA.radialAccelVar = (pszTmp) ? parseFloat(pszTmp) : 0;
// tangential acceleration
pszTmp = locValueForKey("tangentialAcceleration", dictionary);
locModeA.tangentialAccel = (pszTmp) ? parseFloat(pszTmp) : 0;
pszTmp = locValueForKey("tangentialAccelVariance", dictionary);
locModeA.tangentialAccelVar = (pszTmp) ? parseFloat(pszTmp) : 0;
// rotation is dir
var locRotationIsDir = locValueForKey("rotationIsDir", dictionary).toLowerCase();
locModeA.rotationIsDir = (locRotationIsDir != null && (locRotationIsDir === "true" || locRotationIsDir === "1"));
} else if (this._emitterMode == cc.PARTICLE_MODE_RADIUS) {
// or Mode B: radius movement
var locModeB = this.modeB;
locModeB.startRadius = parseFloat(locValueForKey("maxRadius", dictionary));
locModeB.startRadiusVar = parseFloat(locValueForKey("maxRadiusVariance", dictionary));
locModeB.endRadius = parseFloat(locValueForKey("minRadius", dictionary));
locModeB.endRadiusVar = 0;
locModeB.rotatePerSecond = parseFloat(locValueForKey("rotatePerSecond", dictionary));
locModeB.rotatePerSecondVar = parseFloat(locValueForKey("rotatePerSecondVariance", dictionary));
} else {
cc.log("cc.ParticleSystem.initWithDictionary(): Invalid emitterType in config file");
return false;
}
// life span
this._life = parseFloat(locValueForKey("particleLifespan", dictionary));
this._lifeVar = parseFloat(locValueForKey("particleLifespanVariance", dictionary));
// emission Rate
this._emissionRate = this._totalParticles / this._life;
//don't get the internal texture if a batchNode is used
if (!this._batchNode) {
// Set a compatible default for the alpha transfer
this._opacityModifyRGB = false;
// texture
// Try to get the texture from the cache
var textureName = locValueForKey("textureFileName", dictionary);
var fileUtils = cc.FileUtils.getInstance();
var imgPath = fileUtils.fullPathFromRelativeFile(textureName, this._plistFile);
var tex = cc.TextureCache.getInstance().textureForKey(imgPath);
if (tex) {
this.setTexture(tex);
} else {
var textureData = locValueForKey("textureImageData", dictionary);
if (textureData && textureData.length == 0) {
tex = cc.TextureCache.getInstance().addImage(imgPath);
if (!tex)
return false;
this.setTexture(tex);
} else {
buffer = cc.unzipBase64AsArray(textureData, 1);
if (!buffer) {
cc.log("cc.ParticleSystem: error decoding or ungzipping textureImageData");
return false;
}
var imageFormat = cc.getImageFormatByData(buffer);
if(imageFormat !== cc.FMT_TIFF && imageFormat !== cc.FMT_PNG){
cc.log("cc.ParticleSystem: unknown image format with Data");
return false;
}
var canvasObj = document.createElement("canvas");
if(imageFormat === cc.FMT_PNG){
var myPngObj = new cc.PNGReader(buffer);
myPngObj.render(canvasObj);
} else {
var myTIFFObj = cc.TIFFReader.getInstance();
myTIFFObj.parseTIFF(buffer,canvasObj);
}
var imgFullPath = fileUtils.fullPathForFilename(imgPath);
cc.TextureCache.getInstance().cacheImage(imgFullPath, canvasObj);
var addTexture = cc.TextureCache.getInstance().textureForKey(imgPath);
if(!addTexture)
cc.log("cc.ParticleSystem.initWithDictionary() : error loading the texture");
this.setTexture(addTexture);
}
}
}
ret = true;
}
return ret;
},
/**
* Initializes a system with a fixed number of particles
* @param {Number} numberOfParticles
* @return {Boolean}
*/
initWithTotalParticles:function (numberOfParticles) {
this._totalParticles = numberOfParticles;
var i, locParticles = this._particles;
locParticles.length = 0;
for(i = 0; i< numberOfParticles; i++){
locParticles[i] = new cc.Particle();
}
if (!locParticles) {
cc.log("Particle system: not enough memory");
return false;
}
this._allocatedParticles = numberOfParticles;
if (this._batchNode)
for (i = 0; i < this._totalParticles; i++)
locParticles[i].atlasIndex = i;
// default, active
this._isActive = true;
// default blend function
this._blendFunc.src = cc.BLEND_SRC;
this._blendFunc.dst = cc.BLEND_DST;
// default movement type;
this._positionType = cc.PARTICLE_TYPE_FREE;
// by default be in mode A:
this._emitterMode = cc.PARTICLE_MODE_GRAVITY;
// default: modulate
// XXX: not used
// colorModulate = YES;
this._isAutoRemoveOnFinish = false;
//for batchNode
this._transformSystemDirty = false;
// udpate after action in run!
this.scheduleUpdateWithPriority(1);
if(cc.renderContextType === cc.WEBGL){
// allocating data space
if (!this._allocMemory())
return false;
this.initIndices();
//if (cc.TEXTURE_ATLAS_USE_VAO)
// this._setupVBOandVAO();
//else
this._setupVBO();
this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURECOLOR));
}
return true;
},
destroyParticleSystem:function () {
this.unscheduleUpdate();
},
/**
* Add a particle to the emitter
* @return {Boolean}
*/
addParticle: function () {
if (this.isFull())
return false;
var particle, particles = this._particles;
if (cc.renderContextType === cc.CANVAS) {
if (this._particleCount < particles.length) {
particle = particles[this._particleCount];
} else {
particle = new cc.Particle();
particles.push(particle);
}
} else {
particle = particles[this._particleCount];
}
this.initParticle(particle);
++this._particleCount;
return true;
},
/**
* Initializes a particle
* @param {cc.Particle} particle
*/
initParticle:function (particle) {
var locRandomMinus11 = cc.RANDOM_MINUS1_1;
// timeToLive
// no negative life. prevent division by 0
particle.timeToLive = this._life + this._lifeVar * locRandomMinus11();
particle.timeToLive = Math.max(0, particle.timeToLive);
// position
particle.pos.x = this._sourcePosition.x + this._posVar.x * locRandomMinus11();
particle.pos.y = this._sourcePosition.y + this._posVar.y * locRandomMinus11();
// Color
var start, end;
var locStartColor = this._startColor, locStartColorVar = this._startColorVar;
var locEndColor = this._endColor, locEndColorVar = this._endColorVar;
if (cc.renderContextType === cc.CANVAS) {
start = new cc.Color4F(
cc.clampf(locStartColor.r + locStartColorVar.r * locRandomMinus11(), 0, 1),
cc.clampf(locStartColor.g + locStartColorVar.g * locRandomMinus11(), 0, 1),
cc.clampf(locStartColor.b + locStartColorVar.b * locRandomMinus11(), 0, 1),
cc.clampf(locStartColor.a + locStartColorVar.a * locRandomMinus11(), 0, 1)
);
end = new cc.Color4F(
cc.clampf(locEndColor.r + locEndColorVar.r * locRandomMinus11(), 0, 1),
cc.clampf(locEndColor.g + locEndColorVar.g * locRandomMinus11(), 0, 1),
cc.clampf(locEndColor.b + locEndColorVar.b * locRandomMinus11(), 0, 1),
cc.clampf(locEndColor.a + locEndColorVar.a * locRandomMinus11(), 0, 1)
);
} else {
start = {
r: cc.clampf(locStartColor.r + locStartColorVar.r * locRandomMinus11(), 0, 1),
g: cc.clampf(locStartColor.g + locStartColorVar.g * locRandomMinus11(), 0, 1),
b: cc.clampf(locStartColor.b + locStartColorVar.b * locRandomMinus11(), 0, 1),
a: cc.clampf(locStartColor.a + locStartColorVar.a * locRandomMinus11(), 0, 1)
};
end = {
r: cc.clampf(locEndColor.r + locEndColorVar.r * locRandomMinus11(), 0, 1),
g: cc.clampf(locEndColor.g + locEndColorVar.g * locRandomMinus11(), 0, 1),
b: cc.clampf(locEndColor.b + locEndColorVar.b * locRandomMinus11(), 0, 1),
a: cc.clampf(locEndColor.a + locEndColorVar.a * locRandomMinus11(), 0, 1)
};
}
particle.color = start;
var locParticleDeltaColor = particle.deltaColor, locParticleTimeToLive = particle.timeToLive;
locParticleDeltaColor.r = (end.r - start.r) / locParticleTimeToLive;
locParticleDeltaColor.g = (end.g - start.g) / locParticleTimeToLive;
locParticleDeltaColor.b = (end.b - start.b) / locParticleTimeToLive;
locParticleDeltaColor.a = (end.a - start.a) / locParticleTimeToLive;
// size
var startS = this._startSize + this._startSizeVar * locRandomMinus11();
startS = Math.max(0, startS); // No negative value
particle.size = startS;
if (this._endSize === cc.PARTICLE_START_SIZE_EQUAL_TO_END_SIZE) {
particle.deltaSize = 0;
} else {
var endS = this._endSize + this._endSizeVar * locRandomMinus11();
endS = Math.max(0, endS); // No negative values
particle.deltaSize = (endS - startS) / locParticleTimeToLive;
}
// rotation
var startA = this._startSpin + this._startSpinVar * locRandomMinus11();
var endA = this._endSpin + this._endSpinVar * locRandomMinus11();
particle.rotation = startA;
particle.deltaRotation = (endA - startA) / locParticleTimeToLive;
// position
if (this._positionType == cc.PARTICLE_TYPE_FREE)
particle.startPos = this.convertToWorldSpace(this._pointZeroForParticle);
else if (this._positionType == cc.PARTICLE_TYPE_RELATIVE){
particle.startPos.x = this._position.x;
particle.startPos.y = this._position.y;
}
// direction
var a = cc.DEGREES_TO_RADIANS(this._angle + this._angleVar * locRandomMinus11());
// Mode Gravity: A
if (this._emitterMode === cc.PARTICLE_MODE_GRAVITY) {
var locModeA = this.modeA, locParticleModeA = particle.modeA;
var s = locModeA.speed + locModeA.speedVar * locRandomMinus11();
// direction
locParticleModeA.dir.x = Math.cos(a);
locParticleModeA.dir.y = Math.sin(a);
cc.pMultIn(locParticleModeA.dir, s);
// radial accel
locParticleModeA.radialAccel = locModeA.radialAccel + locModeA.radialAccelVar * locRandomMinus11();
// tangential accel
locParticleModeA.tangentialAccel = locModeA.tangentialAccel + locModeA.tangentialAccelVar * locRandomMinus11();
// rotation is dir
if(locModeA.rotationIsDir)
particle.rotation = -cc.RADIANS_TO_DEGREES(cc.pToAngle(locParticleModeA.dir));
} else {
// Mode Radius: B
var locModeB = this.modeB, locParitlceModeB = particle.modeB;
// Set the default diameter of the particle from the source position
var startRadius = locModeB.startRadius + locModeB.startRadiusVar * locRandomMinus11();
var endRadius = locModeB.endRadius + locModeB.endRadiusVar * locRandomMinus11();
locParitlceModeB.radius = startRadius;
locParitlceModeB.deltaRadius = (locModeB.endRadius === cc.PARTICLE_START_RADIUS_EQUAL_TO_END_RADIUS) ? 0 : (endRadius - startRadius) / locParticleTimeToLive;
locParitlceModeB.angle = a;
locParitlceModeB.degreesPerSecond = cc.DEGREES_TO_RADIANS(locModeB.rotatePerSecond + locModeB.rotatePerSecondVar * locRandomMinus11());
}
},
/**
* stop emitting particles. Running particles will continue to run until they die
*/
stopSystem:function () {
this._isActive = false;
this._elapsed = this._duration;
this._emitCounter = 0;
},
/**
* Kill all living particles.
*/
resetSystem:function () {
this._isActive = true;
this._elapsed = 0;
var locParticles = this._particles;
for (this._particleIdx = 0; this._particleIdx < this._particleCount; ++this._particleIdx)
locParticles[this._particleIdx].timeToLive = 0 ;
},
/**
* whether or not the system is full
* @return {Boolean}
*/
isFull:function () {
return (this._particleCount >= this._totalParticles);
},
/**
* should be overridden by subclasses
* @param {cc.Particle} particle
* @param {cc.Point} newPosition
*/
updateQuadWithParticle:function (particle, newPosition) {
var quad = null;
if (this._batchNode) {
var batchQuads = this._batchNode.getTextureAtlas().getQuads();
quad = batchQuads[this._atlasIndex + particle.atlasIndex];
this._batchNode.getTextureAtlas()._dirty = true;
} else
quad = this._quads[this._particleIdx];
var r, g, b, a;
if(this._opacityModifyRGB){
r = 0 | (particle.color.r * particle.color.a * 255);
g = 0 | (particle.color.g * particle.color.a * 255);
b = 0 | (particle.color.b * particle.color.a * 255);
a = 0 | (particle.color.a * 255);
}else{
r = 0 | (particle.color.r * 255);
g = 0 | (particle.color.g * 255);
b = 0 | (particle.color.b * 255);
a = 0 | (particle.color.a * 255);
}
var locColors = quad.bl.colors;
locColors.r = r;
locColors.g = g;
locColors.b = b;
locColors.a = a;
locColors = quad.br.colors;
locColors.r = r;
locColors.g = g;
locColors.b = b;
locColors.a = a;
locColors = quad.tl.colors;
locColors.r = r;
locColors.g = g;
locColors.b = b;
locColors.a = a;
locColors = quad.tr.colors;
locColors.r = r;
locColors.g = g;
locColors.b = b;
locColors.a = a;
// vertices
var size_2 = particle.size / 2;
if (particle.rotation) {
var x1 = -size_2;
var y1 = -size_2;
var x2 = size_2;
var y2 = size_2;
var x = newPosition.x;
var y = newPosition.y;
var rad = -cc.DEGREES_TO_RADIANS(particle.rotation);
var cr = Math.cos(rad);
var sr = Math.sin(rad);
var ax = x1 * cr - y1 * sr + x;
var ay = x1 * sr + y1 * cr + y;
var bx = x2 * cr - y1 * sr + x;
var by = x2 * sr + y1 * cr + y;
var cx = x2 * cr - y2 * sr + x;
var cy = x2 * sr + y2 * cr + y;
var dx = x1 * cr - y2 * sr + x;
var dy = x1 * sr + y2 * cr + y;
// bottom-left
quad.bl.vertices.x = ax;
quad.bl.vertices.y = ay;
// bottom-right vertex:
quad.br.vertices.x = bx;
quad.br.vertices.y = by;
// top-left vertex:
quad.tl.vertices.x = dx;
quad.tl.vertices.y = dy;
// top-right vertex:
quad.tr.vertices.x = cx;
quad.tr.vertices.y = cy;
} else {
// bottom-left vertex:
quad.bl.vertices.x = newPosition.x - size_2;
quad.bl.vertices.y = newPosition.y - size_2;
// bottom-right vertex:
quad.br.vertices.x = newPosition.x + size_2;
quad.br.vertices.y = newPosition.y - size_2;
// top-left vertex:
quad.tl.vertices.x = newPosition.x - size_2;
quad.tl.vertices.y = newPosition.y + size_2;
// top-right vertex:
quad.tr.vertices.x = newPosition.x + size_2;
quad.tr.vertices.y = newPosition.y + size_2;
}
},
/**
* should be overridden by subclasses
*/
postStep:function () {
if (cc.renderContextType === cc.WEBGL) {
var gl = cc.renderContext;
gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]);
gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW);
// Option 2: Data
// glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * particleCount, quads_, GL_DYNAMIC_DRAW);
// Option 3: Orphaning + glMapBuffer
// glBufferData(GL_ARRAY_BUFFER, sizeof(m_pQuads[0])*m_uTotalParticles, NULL, GL_STREAM_DRAW);
// void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
// memcpy(buf, m_pQuads, sizeof(m_pQuads[0])*m_uTotalParticles);
// glUnmapBuffer(GL_ARRAY_BUFFER);
//cc.CHECK_GL_ERROR_DEBUG();
}
},
/**
* update emitter's status
* @override
* @param {Number} dt delta time
*/
update:function (dt) {
if (this._isActive && this._emissionRate) {
var rate = 1.0 / this._emissionRate;
//issue #1201, prevent bursts of particles, due to too high emitCounter
if (this._particleCount < this._totalParticles)
this._emitCounter += dt;
while ((this._particleCount < this._totalParticles) && (this._emitCounter > rate)) {
this.addParticle();
this._emitCounter -= rate;
}
this._elapsed += dt;
if (this._duration != -1 && this._duration < this._elapsed)
this.stopSystem();
}
this._particleIdx = 0;
var currentPosition = cc.Particle.TemporaryPoints[0];
if (this._positionType == cc.PARTICLE_TYPE_FREE) {
cc.pIn(currentPosition, this.convertToWorldSpace(this._pointZeroForParticle));
} else if (this._positionType == cc.PARTICLE_TYPE_RELATIVE) {
currentPosition.x = this._position.x;
currentPosition.y = this._position.y;
}
if (this._visible) {
// Used to reduce memory allocation / creation within the loop
var tpa = cc.Particle.TemporaryPoints[1],
tpb = cc.Particle.TemporaryPoints[2],
tpc = cc.Particle.TemporaryPoints[3];
var locParticles = this._particles;
while (this._particleIdx < this._particleCount) {
// Reset the working particles
cc.pZeroIn(tpa);
cc.pZeroIn(tpb);
cc.pZeroIn(tpc);
var selParticle = locParticles[this._particleIdx];
// life
selParticle.timeToLive -= dt;
if (selParticle.timeToLive > 0) {
// Mode A: gravity, direction, tangential accel & radial accel
if (this._emitterMode == cc.PARTICLE_MODE_GRAVITY) {
var tmp = tpc, radial = tpa, tangential = tpb;
// radial acceleration
if (selParticle.pos.x || selParticle.pos.y) {
cc.pIn(radial, selParticle.pos);
cc.pNormalizeIn(radial);
} else {
cc.pZeroIn(radial);
}
cc.pIn(tangential, radial);
cc.pMultIn(radial, selParticle.modeA.radialAccel);
// tangential acceleration
var newy = tangential.x;
tangential.x = -tangential.y;
tangential.y = newy;
cc.pMultIn(tangential, selParticle.modeA.tangentialAccel);
cc.pIn(tmp, radial);
cc.pAddIn(tmp, tangential);
cc.pAddIn(tmp, this.modeA.gravity);
cc.pMultIn(tmp, dt);
cc.pAddIn(selParticle.modeA.dir, tmp);
cc.pIn(tmp, selParticle.modeA.dir);
cc.pMultIn(tmp, dt);
cc.pAddIn(selParticle.pos, tmp);
} else {
// Mode B: radius movement
var selModeB = selParticle.modeB;
// Update the angle and radius of the particle.
selModeB.angle += selModeB.degreesPerSecond * dt;
selModeB.radius += selModeB.deltaRadius * dt;
selParticle.pos.x = -Math.cos(selModeB.angle) * selModeB.radius;
selParticle.pos.y = -Math.sin(selModeB.angle) * selModeB.radius;
}
// color
if (!this._dontTint) {
selParticle.color.r += (selParticle.deltaColor.r * dt);
selParticle.color.g += (selParticle.deltaColor.g * dt);
selParticle.color.b += (selParticle.deltaColor.b * dt);
selParticle.color.a += (selParticle.deltaColor.a * dt);
selParticle.isChangeColor = true;
}
// size
selParticle.size += (selParticle.deltaSize * dt);
selParticle.size = Math.max(0, selParticle.size);
// angle
selParticle.rotation += (selParticle.deltaRotation * dt);
//
// update values in quad
//
var newPos = tpa;
if (this._positionType == cc.PARTICLE_TYPE_FREE || this._positionType == cc.PARTICLE_TYPE_RELATIVE) {
var diff = tpb;
cc.pIn(diff, currentPosition);
cc.pSubIn(diff, selParticle.startPos);
cc.pIn(newPos, selParticle.pos);
cc.pSubIn(newPos, diff);
} else {
cc.pIn(newPos, selParticle.pos);
}
// translate newPos to correct position, since matrix transform isn't performed in batchnode
// don't update the particle with the new position information, it will interfere with the radius and tangential calculations
if (this._batchNode) {
newPos.x += this._position._x;
newPos.y += this._position._y;
}
if (cc.renderContextType == cc.WEBGL) {
// IMPORTANT: newPos may not be used as a reference here! (as it is just the temporary tpa point)
// the implementation of updateQuadWithParticle must use
// the x and y values directly
this.updateQuadWithParticle(selParticle, newPos);
} else {
cc.pIn(selParticle.drawPos, newPos);
}
//updateParticleImp(self, updateParticleSel, p, newPos);
// update particle counter
++this._particleIdx;
} else {
// life < 0
var currentIndex = selParticle.atlasIndex;
if(this._particleIdx !== this._particleCount -1){
var deadParticle = locParticles[this._particleIdx];
locParticles[this._particleIdx] = locParticles[this._particleCount -1];
locParticles[this._particleCount -1] = deadParticle;
}
if (this._batchNode) {
//disable the switched particle
this._batchNode.disableParticle(this._atlasIndex + currentIndex);
//switch indexes
locParticles[this._particleCount - 1].atlasIndex = currentIndex;
}
--this._particleCount;
if (this._particleCount == 0 && this._isAutoRemoveOnFinish) {
this.unscheduleUpdate();
this._parent.removeChild(this, true);
return;
}
}
}
this._transformSystemDirty = false;
}
if (!this._batchNode)
this.postStep();
},
updateWithNoTime:function () {
this.update(0);
},
/**
* return the string found by key in dict.
* @param {string} key
* @param {object} dict
* @return {String} "" if not found; return the string if found.
* @private
*/
_valueForKey:function (key, dict) {
if (dict) {
var pString = dict[key];
return pString != null ? pString : "";
}
return "";
},
_updateBlendFunc:function () {
if(this._batchNode){
cc.log("Can't change blending functions when the particle is being batched");
return;
}
var locTexture = this._texture;
if (locTexture && locTexture instanceof cc.Texture2D) {
this._opacityModifyRGB = false;
var locBlendFunc = this._blendFunc;
if (locBlendFunc.src == cc.BLEND_SRC && locBlendFunc.dst == cc.BLEND_DST) {
if (locTexture.hasPremultipliedAlpha()) {
this._opacityModifyRGB = true;
} else {
locBlendFunc.src = gl.SRC_ALPHA;
locBlendFunc.dst = gl.ONE_MINUS_SRC_ALPHA;
}
}
}
},
clone:function () {
var retParticle = new cc.ParticleSystem();
// self, not super
if (retParticle.initWithTotalParticles(this._totalParticles)) {
// angle
retParticle._angle = this._angle;
retParticle._angleVar = this._angleVar;
// duration
retParticle._duration = this._duration;
// blend function
retParticle._blendFunc.src = this._blendFunc.src;
retParticle._blendFunc.dst = this._blendFunc.dst;
// color
var particleStartColor = retParticle._startColor, locStartColor = this._startColor;
particleStartColor.r = locStartColor.r;
particleStartColor.g = locStartColor.g;
particleStartColor.b = locStartColor.b;
particleStartColor.a = locStartColor.a;
var particleStartColorVar = retParticle._startColorVar, locStartColorVar = this._startColorVar;
particleStartColorVar.r = locStartColorVar.r;
particleStartColorVar.g = locStartColorVar.g;
particleStartColorVar.b = locStartColorVar.b;
particleStartColorVar.a = locStartColorVar.a;
var particleEndColor = retParticle._endColor, locEndColor = this._endColor;
particleEndColor.r = locEndColor.r;
particleEndColor.g = locEndColor.g;
particleEndColor.b = locEndColor.b;
particleEndColor.a = locEndColor.a;
var particleEndColorVar = retParticle._endColorVar, locEndColorVar = this._endColorVar;
particleEndColorVar.r = locEndColorVar.r;
particleEndColorVar.g = locEndColorVar.g;
particleEndColorVar.b = locEndColorVar.b;
particleEndColorVar.a = locEndColorVar.a;
// particle size
retParticle._startSize = this._startSize;
retParticle._startSizeVar = this._startSizeVar;
retParticle._endSize = this._endSize;
retParticle._endSizeVar = this._endSizeVar;
// position
retParticle.setPosition(this._position._x, this._position._y);
retParticle._posVar.x = this._posVar.x;
retParticle._posVar.y = this._posVar.y;
// Spinning
retParticle._startSpin = this._startSpin;
retParticle._startSpinVar = this._startSpinVar;
retParticle._endSpin = this._endSpin;
retParticle._endSpinVar = this._endSpinVar;
retParticle._emitterMode = this._emitterMode;
// Mode A: Gravity + tangential accel + radial accel
if (this._emitterMode == cc.PARTICLE_MODE_GRAVITY) {
var particleModeA = retParticle.modeA, locModeA = this.modeA;
// gravity
particleModeA.gravity.x = locModeA.gravity.x;
particleModeA.gravity.y = locModeA.gravity.y;
// speed
particleModeA.speed = locModeA.speed;
particleModeA.speedVar = locModeA.speedVar;
// radial acceleration
particleModeA.radialAccel = locModeA.radialAccel;
particleModeA.radialAccelVar = locModeA.radialAccelVar;
// tangential acceleration
particleModeA.tangentialAccel = locModeA.tangentialAccel;
particleModeA.tangentialAccelVar = locModeA.tangentialAccelVar;
} else if (this._emitterMode == cc.PARTICLE_MODE_RADIUS) {
var particleModeB = retParticle.modeB, locModeB = this.modeB;
// or Mode B: radius movement
particleModeB.startRadius = locModeB.startRadius;
particleModeB.startRadiusVar = locModeB.startRadiusVar;
particleModeB.endRadius = locModeB.endRadius;
particleModeB.endRadiusVar = locModeB.endRadiusVar;
particleModeB.rotatePerSecond = locModeB.rotatePerSecond;
particleModeB.rotatePerSecondVar = locModeB.rotatePerSecondVar;
}
// life span
retParticle._life = this._life;
retParticle._lifeVar = this._lifeVar;
// emission Rate
retParticle._emissionRate = this._emissionRate;
//don't get the internal texture if a batchNode is used
if (!this._batchNode) {
// Set a compatible default for the alpha transfer
retParticle._opacityModifyRGB = this._opacityModifyRGB;
// texture
retParticle._texture = this._texture;
}
}
return retParticle;
},
/**
* <p> Sets a new CCSpriteFrame as particle.</br>
* WARNING: this method is experimental. Use setTextureWithRect instead.
* </p>
* @param {cc.SpriteFrame} spriteFrame
*/
setDisplayFrame:function (spriteFrame) {
var locOffset = spriteFrame.getOffsetInPixels();
if(locOffset.x != 0 || locOffset.y != 0)
cc.log("cc.ParticleSystem.setDisplayFrame(): QuadParticle only supports SpriteFrames with no offsets");
// update texture before updating texture rect
if (cc.renderContextType === cc.WEBGL)
if (!this._texture || spriteFrame.getTexture()._webTextureObj != this._texture._webTextureObj)
this.setTexture(spriteFrame.getTexture());
},
/**
* Sets a new texture with a rect. The rect is in Points.
* @param {cc.Texture2D} texture
* @param {cc.Rect} rect
*/
setTextureWithRect:function (texture, rect) {
var locTexture = this._texture;
if (cc.renderContextType === cc.WEBGL) {
// Only update the texture if is different from the current one
if ((!locTexture || texture._webTextureObj != locTexture._webTextureObj) && (locTexture != texture)) {
this._texture = texture;
this._updateBlendFunc();
}
} else {
if ((!locTexture || texture != locTexture) && (locTexture != texture)) {
this._texture = texture;
this._updateBlendFunc();
}
}
this._pointRect = rect;
this.initTexCoordsWithRect(rect);
},
/**
* draw particle
* @param {CanvasRenderingContext2D} ctx CanvasContext
* @override
*/
draw:function (ctx) {
if(!this._textureLoaded || this._batchNode) // draw should not be called when added to a particleBatchNode
return;
if (cc.renderContextType === cc.CANVAS)
this._drawForCanvas(ctx);
else
this._drawForWebGL(ctx);
cc.g_NumberOfDraws++;
},
_drawForCanvas:function (ctx) {
var context = ctx || cc.renderContext;
context.save();
if (this.isBlendAdditive())
context.globalCompositeOperation = 'lighter';
else
context.globalCompositeOperation = 'source-over';
for (var i = 0; i < this._particleCount; i++) {
var particle = this._particles[i];
var lpx = (0 | (particle.size * 0.5));
if (this._drawMode == cc.PARTICLE_TEXTURE_MODE) {
var element = this._texture.getHtmlElementObj();
// Delay drawing until the texture is fully loaded by the browser
if (!element.width || !element.height)
continue;
context.save();
context.globalAlpha = particle.color.a;
context.translate((0 | particle.drawPos.x), -(0 | particle.drawPos.y));
var size = Math.floor(particle.size / 4) * 4;
var w = this._pointRect.width;
var h = this._pointRect.height;
context.scale(
Math.max((1 / w) * size, 0.000001),
Math.max((1 / h) * size, 0.000001)
);
if (particle.rotation)
context.rotate(cc.DEGREES_TO_RADIANS(particle.rotation));
context.translate(-(0 | (w / 2)), -(0 | (h / 2)));
if (particle.isChangeColor) {
var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(element);
if (cacheTextureForColor) {
// Create another cache for the tinted version
// This speeds up things by a fair bit
if (!cacheTextureForColor.tintCache) {
cacheTextureForColor.tintCache = document.createElement('canvas');
cacheTextureForColor.tintCache.width = element.width;
cacheTextureForColor.tintCache.height = element.height;
}
cc.generateTintImage(element, cacheTextureForColor, particle.color, this._pointRect, cacheTextureForColor.tintCache);
element = cacheTextureForColor.tintCache;
}
}
context.drawImage(element, 0, 0);
context.restore();
} else {
context.save();
context.globalAlpha = particle.color.a;
context.translate(0 | particle.drawPos.x, -(0 | particle.drawPos.y));
if (this._shapeType == cc.PARTICLE_STAR_SHAPE) {
if (particle.rotation)
context.rotate(cc.DEGREES_TO_RADIANS(particle.rotation));
cc.drawingUtil.drawStar(context, lpx, particle.color);
} else
cc.drawingUtil.drawColorBall(context, lpx, particle.color);
context.restore();
}
}
context.restore();
},
_drawForWebGL:function (ctx) {
if(!this._texture)
return;
var gl = ctx || cc.renderContext;
this._shaderProgram.use();
this._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4();
cc.glBindTexture2D(this._texture);
cc.glBlendFuncForParticle(this._blendFunc.src, this._blendFunc.dst);
//cc.Assert(this._particleIdx == this._particleCount, "Abnormal error in particle quad");
//
// Using VBO without VAO
//
cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSCOLORTEX);
gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]);
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]);
gl.drawElements(gl.TRIANGLES, this._particleIdx * 6, gl.UNSIGNED_SHORT, 0);
},
/**
* listen the event that coming to foreground on Android
* @param {cc.Class} obj
*/
listenBackToForeground:function (obj) {
if (cc.TEXTURE_ATLAS_USE_VAO)
this._setupVBOandVAO();
else
this._setupVBO();
},
_setupVBOandVAO:function () {
//Not support on WebGL
/*if (cc.renderContextType == cc.CANVAS) {
return;
}*/
//NOT SUPPORTED
/*glGenVertexArrays(1, this._VAOname);
glBindVertexArray(this._VAOname);
var kQuadSize = sizeof(m_pQuads[0].bl);
glGenBuffers(2, this._buffersVBO[0]);
glBindBuffer(GL_ARRAY_BUFFER, this._buffersVBO[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(this._quads[0]) * this._totalParticles, this._quads, GL_DYNAMIC_DRAW);
// vertices
glEnableVertexAttribArray(kCCVertexAttrib_Position);
glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, kQuadSize, offsetof(ccV3F_C4B_T2F, vertices));
// colors
glEnableVertexAttribArray(kCCVertexAttrib_Color);
glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, offsetof(ccV3F_C4B_T2F, colors));
// tex coords
glEnableVertexAttribArray(kCCVertexAttrib_TexCoords);
glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, offsetof(ccV3F_C4B_T2F, texCoords));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(m_pIndices[0]) * m_uTotalParticles * 6, m_pIndices, GL_STATIC_DRAW);
glBindVertexArray(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
CHECK_GL_ERROR_DEBUG();*/
},
_setupVBO:function () {
if (cc.renderContextType == cc.CANVAS)
return;
var gl = cc.renderContext;
//gl.deleteBuffer(this._buffersVBO[0]);
this._buffersVBO[0] = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]);
gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW);
this._buffersVBO[1] = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW);
//cc.CHECK_GL_ERROR_DEBUG();
},
_allocMemory:function () {
if (cc.renderContextType === cc.CANVAS)
return true;
//cc.Assert((!this._quads && !this._indices), "Memory already allocated");
if(this._batchNode){
cc.log("cc.ParticleSystem._allocMemory(): Memory should not be allocated when not using batchNode");
return false;
}
var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
var totalParticles = this._totalParticles;
var locQuads = this._quads;
locQuads.length = 0;
this._indices = new Uint16Array(totalParticles * 6);
var locQuadsArrayBuffer = new ArrayBuffer(quadSize * totalParticles);
for (var i = 0; i < totalParticles; i++)
locQuads[i] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, locQuadsArrayBuffer, i * quadSize);
if (!locQuads || !this._indices) {
cc.log("cocos2d: Particle system: not enough memory");
return false;
}
this._quadsArrayBuffer = locQuadsArrayBuffer;
return true;
}
});
/**
* <p> return the string found by key in dict. <br/>
* This plist files can be create manually or with Particle Designer:<br/>
* http://particledesigner.71squared.com/<br/>
* </p>
* @param {String} plistFile
* @return {cc.ParticleSystem}
*/
cc.ParticleSystem.create = function (plistFile) {
var ret = new cc.ParticleSystem();
if (!plistFile || typeof(plistFile) === "number") {
var ton = plistFile || 100;
ret.setDrawMode(cc.PARTICLE_TEXTURE_MODE);
ret.initWithTotalParticles(ton);
return ret;
}
if (ret && ret.initWithFile(plistFile))
return ret;
return null;
};
/**
* create a system with a fixed number of particles
* @param {Number} number_of_particles
* @return {cc.ParticleSystem}
*/
cc.ParticleSystem.createWithTotalParticles = function (number_of_particles) {
//emitter.initWithTotalParticles(number_of_particles);
var particle = new cc.ParticleSystem();
if (particle && particle.initWithTotalParticles(number_of_particles))
return particle;
return null;
};
// Different modes
/**
* Mode A:Gravity + Tangential Accel + Radial Accel
* @Class
* @Construct
* @param {cc.Point} [gravity=] Gravity value.
* @param {Number} [speed=0] speed of each particle.
* @param {Number} [speedVar=0] speed variance of each particle.
* @param {Number} [tangentialAccel=0] tangential acceleration of each particle.
* @param {Number} [tangentialAccelVar=0] tangential acceleration variance of each particle.
* @param {Number} [radialAccel=0] radial acceleration of each particle.
* @param {Number} [radialAccelVar=0] radial acceleration variance of each particle.
* @param {boolean} [rotationIsDir=false]
*/
cc.ParticleSystem.ModeA = function (gravity, speed, speedVar, tangentialAccel, tangentialAccelVar, radialAccel, radialAccelVar, rotationIsDir) {
/** Gravity value. Only available in 'Gravity' mode. */
this.gravity = gravity ? gravity : cc.PointZero();
/** speed of each particle. Only available in 'Gravity' mode. */
this.speed = speed || 0;
/** speed variance of each particle. Only available in 'Gravity' mode. */
this.speedVar = speedVar || 0;
/** tangential acceleration of each particle. Only available in 'Gravity' mode. */
this.tangentialAccel = tangentialAccel || 0;
/** tangential acceleration variance of each particle. Only available in 'Gravity' mode. */
this.tangentialAccelVar = tangentialAccelVar || 0;
/** radial acceleration of each particle. Only available in 'Gravity' mode. */
this.radialAccel = radialAccel || 0;
/** radial acceleration variance of each particle. Only available in 'Gravity' mode. */
this.radialAccelVar = radialAccelVar || 0;
/** set the rotation of each particle to its direction Only available in 'Gravity' mode. */
this.rotationIsDir = rotationIsDir || false;
};
/**
* Mode B: circular movement (gravity, radial accel and tangential accel don't are not used in this mode)
* @Class
* @Construct
* @param {Number} startRadius The starting radius of the particles.
* @param {Number} startRadiusVar The starting radius variance of the particles.
* @param {Number} endRadius The ending radius of the particles.
* @param {Number} endRadiusVar The ending radius variance of the particles.
* @param {Number} rotatePerSecond Number of degress to rotate a particle around the source pos per second.
* @param {Number} rotatePerSecondVar Variance in degrees for rotatePerSecond.
*/
cc.ParticleSystem.ModeB = function (startRadius, startRadiusVar, endRadius, endRadiusVar, rotatePerSecond, rotatePerSecondVar) {
/** The starting radius of the particles. Only available in 'Radius' mode. */
this.startRadius = startRadius || 0;
/** The starting radius variance of the particles. Only available in 'Radius' mode. */
this.startRadiusVar = startRadiusVar || 0;
/** The ending radius of the particles. Only available in 'Radius' mode. */
this.endRadius = endRadius || 0;
/** The ending radius variance of the particles. Only available in 'Radius' mode. */
this.endRadiusVar = endRadiusVar || 0;
/** Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. */
this.rotatePerSecond = rotatePerSecond || 0;
/** Variance in degrees for rotatePerSecond. Only available in 'Radius' mode. */
this.rotatePerSecondVar = rotatePerSecondVar || 0;
};
|
/*
* 1.7 Given an image represented by an NxN matrix
* where each pixel in the image is 4 bytes,
* write a method to rotate the image by 90 degrees.
* Can you do this in place?
*/
// Layer rotation strategy:
//
// function rotateMatrix(matrix) {
// for (var layer = 0; layer < matrix.length / 2; layer++) {
// var first = layer;
// var last = matrix.length - 1 - layer;
// for (var i = first; i < last; i++) {
// // save top
// var top = matrix[first][i]
// // move left -> top
// matrix[first][i] = matrix[last-i-first][first];
// // move bottom -> left
// matrix[last-i-first][first] = matrix[last][last-i-first];
// // move right -> bottom
// matrix[last][last-i -first] = matrix[i][last];
// // move top(temp) -> right
// matrix[i][last] = top;
// }
// }
// return matrix;
// }
// Helpers
var deepCopy = require('../../various/deepCopy/deepCopy').deepCopy;
function transpose(matrix) {
var output = deepCopy(matrix);
for (var y = 0; y < matrix.length - 1; y++) {
for (var x = y + 1; x < matrix.length; x++) {
output[x][y] = matrix[y][x];
output[y][x] = matrix[x][y];
}
}
return output;
}
function flipVertical(matrix) {
var output = deepCopy(matrix);
for (var y = 0; y < (output.length - 1)/ 2; y++) {
for (var x = 0; x < output.length; x++) {
output[y][x] = matrix[matrix.length-1-y][x];
output[output.length-1-y][x] = matrix[y][x];
}
}
return output;
}
function flipHorizontal(matrix) {
var output = deepCopy(matrix);
for (var y = 0; y < matrix.length; y++) {
for (var x = 0; x < (matrix.length - 1)/2; x++) {
output[y][x] = matrix[y][matrix.length - 1 - x];
output[y][matrix.length - 1 - x] = matrix[y][x];
}
}
return output;
}
// test > 1.7 rotateMatrix
// # rotateMatrix(file.matrix) === [[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]] (rotate 90 degree cw the matrix as default)
// # rotateMatrix(file.matrix, 90) === [[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]] (rotate 90 degree cw the matrix)
// # rotateMatrix(file.matrix, -90) === [[4,8,12,16],[3,7,11,15],[2,6,10,14],[1,5,9,13]] (rotate 90 degree ccw the matrix)
// # rotateMatrix(file.matrix, 180) === [[16,15,14,13],[12,11,10,9],[8,7,6,5],[4,3,2,1]] (rotate 180 degree cw the matrix)
// # rotateMatrix(file.matrix, 270) === [[4,8,12,16],[3,7,11,15],[2,6,10,14],[1,5,9,13]] (rotate 270 degree cw the matrix)
// # rotateMatrix(file.matrix, -270) === [[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]] (rotate 270 degree ccw the matrix)
exports.rotateMatrix = function(matrix, deg) {
deg = deg || 90;
switch (deg) {
case 90:
return flipHorizontal(transpose(matrix));
case -90:
return flipVertical(transpose(matrix));
case 180:
return flipVertical(flipHorizontal(matrix));
case 270:
return flipVertical(transpose(matrix));
case -270:
return flipHorizontal(transpose(matrix));
}
};
exports.matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
// ====================================================================
// ####################################################################
// ====================================================================
// In-place
function transposeInPlace(matrix) {
for (var y = 0; y < matrix.length - 1; y++) {
for (var x = y + 1; x < matrix.length; x++) {
var temp = matrix[x][y];
matrix[x][y] = matrix[y][x];
matrix[y][x] = temp;
}
}
return matrix;
}
function flipVerticalInPlace(matrix) {
for (var y = 0; y < (matrix.length - 1)/ 2; y++) {
for (var x = 0; x < matrix.length; x++) {
var temp = matrix[y][x];
matrix[y][x] = matrix[matrix.length-1-y][x];
matrix[matrix.length-1-y][x] = temp;
}
}
return matrix;
}
function flipHorizontalInPlace(matrix) {
for (var y = 0; y < matrix.length; y++) {
for (var x = 0; x < (matrix.length - 1)/2; x++) {
var temp = matrix[y][x];
matrix[y][x] = matrix[y][matrix.length - 1 - x];
matrix[y][matrix.length - 1 - x] = temp;
}
}
return matrix;
}
// test > 1.7b rotateMatrixInPlace
// # rotateMatrixInPlace(file.matrix) === [[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]] (rotate 90 degree cw the matrix as default)
// # rotateMatrixInPlace(file.matrix, 90) === [[16,15,14,13],[12,11,10,9],[8,7,6,5],[4,3,2,1]] (rotate 90 degree cw the matrix)
// # rotateMatrixInPlace(file.matrix, -90) === [[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]] (rotate 90 degree ccw the matrix)
// # rotateMatrixInPlace(file.matrix, 180) === [[4,8,12,16],[3,7,11,15],[2,6,10,14],[1,5,9,13]] (rotate 180 degree cw the matrix)
// # rotateMatrixInPlace(file.matrix, 270) === [[16,15,14,13],[12,11,10,9],[8,7,6,5],[4,3,2,1]] (rotate 270 degree cw the matrix)
// # rotateMatrixInPlace(file.matrix, -270) === [[4,8,12,16],[3,7,11,15],[2,6,10,14],[1,5,9,13]] (rotate 270 degree ccw the matrix)
exports.rotateMatrixInPlace = function(matrix, deg) {
deg = deg || 90;
switch (deg) {
case 90:
return flipHorizontalInPlace(transposeInPlace(matrix));
case -90:
return flipVerticalInPlace(transposeInPlace(matrix));
case 180:
return flipVerticalInPlace(flipHorizontalInPlace(matrix));
case 270:
return flipVerticalInPlace(transposeInPlace(matrix));
case -270:
return flipHorizontalInPlace(transposeInPlace(matrix));
}
};
|
module.exports = function (sequelize, DataTypes) {
var configModel = sequelize.define("config", {
name: {
type: DataTypes.STRING,
validate: {
notEmpty: true
}
},
protocol: {
type: DataTypes.STRING,
defaultValue: 'HTTPS',
validate: {
notEmpty: true
}
},
uri: {
type: DataTypes.STRING,
validate: {
isUrl: true,
notEmpty: true
}
},
port: {
type: DataTypes.INTEGER,
validate: {
isNumeric: true
}
},
path: {
type: DataTypes.STRING,
validate: {}
},
enabled: {
type: DataTypes.BOOLEAN,
defaultValue: 1,
},
pollFrequencyInSeconds: {
type: DataTypes.INTEGER,
defaultValue: 3600,
validate: {
isNumeric: true
}
},
degradedResponseTimeMS: {
type: DataTypes.INTEGER,
defaultValue: 950,
validate: {
isNumeric: true
}
},
failedResponseTimeMS: {
type: DataTypes.INTEGER,
defaultValue: 1500,
validate: {
isNumeric: true
}
},
expectedResponseCode: {
type: DataTypes.STRING,
defaultValue: '2XX',
validate: {
notEmpty: true
}
}
}, {
classMethods: {
associate: function (models) {
var tenantIDOptions = {
foreignKey: 'tenantID'
};
configModel.belongsTo(models.tenant, tenantIDOptions);
}
}
});
return configModel;
};
|
var TelegramBot = require('node-telegram-bot-api');
var TELEGRAM_TOKEN = process.env.TELEGRAM_TOKEN;
if (TELEGRAM_TOKEN === undefined) {
console.error("Undefined TELEGRAM_TOKEN enviroment variable");
process.exit();
}
// Setup polling way
var bot = new TelegramBot(TELEGRAM_TOKEN, {polling: true});
/* Commands spanish descriptions:
start - presenta al bot.
location - muestra la localización del evento.
cat - manda una foto de un gatito.
*/
// Start message
bot.onText(/^\/start$/, function (msg) {
var fromId = msg.from.id;
bot.sendMessage(fromId, "Hola, soy el bot del frontFest! Estaré encantado de responder tus preguntas sobre el evento.");
});
//Ask for event location
bot.onText(/^\/location$/, function (msg) {
var chatId = msg.chat.id;
latitude = '40.412664';
longitude = '-3.718301';
title = 'frontFest (Google Campus)';
address = 'Calle Moreno Nieto, 2, 28005 Madrid, Spain';
bot.sendVenue(chatId, latitude, longitude, title, address);
bot.sendMessage(chatId, '(se accede por la entrada del auditorio)');
});
// Matches /cat
bot.onText(/^\/cat$/, function (msg) {
var chatId = msg.chat.id;
var width = getRandomInt(100, 500);
var height = getRandomInt(100, 500);
var photo = `http://placekitten.com/${width}/${height}`;
bot.sendPhoto(chatId, photo, {caption: 'meow!'});
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// server to keep alive on heroku
var http = require('http');
var server = http.createServer(function(request, response) {
response.end("Hi there! :)");
});
server.listen(process.env.PORT || 8080); |
'use strict';
define([
'jquery', 'underscore', 'backbone', 'backbone.radio', 'marionette',
'routers/sketch', 'collections/sketch'
], function (
$, _, Backbone, Radio, Marionette,
SketchRouter, SketchCollection
) {
var SketchComponent = Backbone.Model.extend({
defaults: {
name: 'Sketch',
slug: 'sketch',
router: false,
dataCollection: false,
channel: false
},
readAll: function () {
var coll,
deferred = $.Deferred();
coll = this.get('dataCollection');
//console.log('read the collection: ');
//console.log(coll);
deferred.resolve(coll);
return deferred.promise();
},
readAllFromLocalForage: function () {
var coll,
deferred = $.Deferred();
coll = this.get('dataCollection');
coll.fetch({
success: function(collected) {
//console.log('read from localForage: ');
//console.log(collected);
deferred.resolve(collected);
}
});
return deferred.promise();
},
readModel: function (id) {
var coll,
deferred = $.Deferred();
coll = this.get('dataCollection');
//console.log('read the collection: ');
//console.log(coll);
deferred.resolve(coll.get(id));
return deferred.promise();
},
readFromLocalForage: function (id) {
var coll,
deferred = $.Deferred();
coll = this.get('dataCollection');
coll.get(id).fetch({
success: function(collected) {
//console.log('read from localForage: ');
//console.log(collected);
deferred.resolve(collected);
}
});
return deferred.promise();
},
createToLocalForage: function (val) {
var coll,
deferred = $.Deferred();
coll = this.get('dataCollection');
coll.create(val, {
success: function(model) {
//console.log('created to localForage: ');
//console.log(model);
deferred.resolve(model);
}
});
return deferred.promise();
},
deleteFromLocalForage: function (id) {
var coll,
deferred = $.Deferred();
coll = this.get('dataCollection');
coll.get(id).destroy({
success: function(collected) {
//console.log('deleted from localForage: ');
//console.log(collected);
deferred.resolve(collected);
}
});
return deferred.promise();
},
updateLocalForage: function (id, val) {
var coll,
deferred = $.Deferred();
coll = this.get('dataCollection');
//console.log(coll.get(id));
coll.get(id).save(val, {
success: function(model) {
//console.log('updated localForage: ');
//console.log(model);
deferred.resolve(model);
}
});
return deferred.promise();
},
initialize: function () {
this.set({channel: Radio.channel('sketch')});
this.set({dataCollection: new SketchCollection()});
var self = this;
this.get('channel').reply('read-all', function () {
return self.readAll();
});
this.get('channel').reply('read-all:localforage', function () {
return self.readAllFromLocalForage();
});
this.get('channel').reply('read', function (id) {
return self.readModel(id);
});
this.get('channel').reply('read:localforage', function (id) {
return self.readFromLocalForage(id);
});
this.get('channel').reply('create:localforage', function (val) {
return self.createToLocalForage(val);
});
this.get('channel').reply('delete:localforage', function (id) {
return self.deleteFromLocalForage(id);
});
this.get('channel').reply('update:localforage', function (id, val) {
return self.updateLocalForage(id, val);
});
},
initRouter: function () {
this.set({router: new SketchRouter()});
return this;
}
});
return SketchComponent;
});
|
import { UIKitIncomingInteractionContainerType } from '@rocket.chat/apps-engine/definition/uikit/UIKitIncomingInteractionContainer';
import { Modal, AnimatedVisibility, ButtonGroup, Button, Box } from '@rocket.chat/fuselage';
import { useMutableCallback, useUniqueId } from '@rocket.chat/fuselage-hooks';
import { kitContext, UiKitComponent, UiKitModal, modalParser } from '@rocket.chat/fuselage-ui-kit';
import { uiKitText } from '@rocket.chat/ui-kit';
import React, { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';
import RawText from '../../../../client/components/basic/RawText';
import { renderMessageBody } from '../../../ui-utils/client';
import { getURL } from '../../../utils/lib/getURL';
import * as ActionManager from '../ActionManager';
// TODO: move this to fuselage-ui-kit itself
modalParser.text = ({ text, type } = {}) => {
if (type !== 'mrkdwn') {
return text;
}
return <RawText>{renderMessageBody({ msg: text })}</RawText>;
};
const textParser = uiKitText({
plain_text: ({ text }) => text,
text: ({ text }) => text,
});
const focusableElementsString = `
a[href]:not([tabindex="-1"]),
area[href]:not([tabindex="-1"]),
input:not([disabled]):not([tabindex="-1"]),
select:not([disabled]):not([tabindex="-1"]),
textarea:not([disabled]):not([tabindex="-1"]),
button:not([disabled]):not([tabindex="-1"]),
iframe,
object,
embed,
[tabindex]:not([tabindex="-1"]),
[contenteditable]`;
const focusableElementsStringInvalid = `
a[href]:not([tabindex="-1"]):invalid,
area[href]:not([tabindex="-1"]):invalid,
input:not([disabled]):not([tabindex="-1"]):invalid,
select:not([disabled]):not([tabindex="-1"]):invalid,
textarea:not([disabled]):not([tabindex="-1"]):invalid,
button:not([disabled]):not([tabindex="-1"]):invalid,
iframe:invalid,
object:invalid,
embed:invalid,
[tabindex]:not([tabindex="-1"]):invalid,
[contenteditable]:invalid`;
export function ModalBlock({
view,
errors,
appId,
onSubmit,
onClose,
onCancel,
}) {
const id = `modal_id_${ useUniqueId() }`;
const ref = useRef();
// Auto focus
useEffect(() => {
if (!ref.current) {
return;
}
if (errors && Object.keys(errors).length) {
const element = ref.current.querySelector(focusableElementsStringInvalid);
element && element.focus();
} else {
const element = ref.current.querySelector(focusableElementsString);
element && element.focus();
}
}, [ref.current, errors]);
// save focus to restore after close
const previousFocus = useMemo(() => document.activeElement, []);
// restore the focus after the component unmount
useEffect(() => () => previousFocus && previousFocus.focus(), []);
// Handle Tab, Shift + Tab, Enter and Escape
const handleKeyDown = useCallback((event) => {
if (event.keyCode === 13) { // ENTER
return onSubmit(event);
}
if (event.keyCode === 27) { // ESC
event.stopPropagation();
event.preventDefault();
onClose();
return false;
}
if (event.keyCode === 9) { // TAB
const elements = Array.from(ref.current.querySelectorAll(focusableElementsString));
const [first] = elements;
const last = elements.pop();
if (!ref.current.contains(document.activeElement)) {
return first.focus();
}
if (event.shiftKey) {
if (!first || first === document.activeElement) {
last.focus();
event.stopPropagation();
event.preventDefault();
}
return;
}
if (!last || last === document.activeElement) {
first.focus();
event.stopPropagation();
event.preventDefault();
}
}
}, [onSubmit]);
// Clean the events
useEffect(() => {
const element = document.querySelector('.rc-modal-wrapper');
const container = element.querySelector('.rcx-modal__content');
const close = (e) => {
if (e.target !== element) {
return;
}
e.preventDefault();
e.stopPropagation();
onClose();
return false;
};
const ignoreIfnotContains = (e) => {
if (!container.contains(e.target)) {
return;
}
return handleKeyDown(e);
};
document.addEventListener('keydown', ignoreIfnotContains);
element.addEventListener('click', close);
return () => {
document.removeEventListener('keydown', ignoreIfnotContains);
element.removeEventListener('click', close);
};
}, handleKeyDown);
return (
<AnimatedVisibility visibility={AnimatedVisibility.UNHIDING}>
<Modal open id={id} ref={ref}>
<Modal.Header>
<Modal.Thumb url={getURL(`/api/apps/${ appId }/icon`)} />
<Modal.Title>{textParser([view.title])}</Modal.Title>
<Modal.Close tabIndex={-1} onClick={onClose} />
</Modal.Header>
<Modal.Content>
<Box
is='form'
method='post'
action='#'
onSubmit={onSubmit}
>
<UiKitComponent render={UiKitModal} blocks={view.blocks} />
</Box>
</Modal.Content>
<Modal.Footer>
<ButtonGroup align='end'>
{view.close && <Button onClick={onCancel}>{textParser([view.close.text])}</Button>}
{view.submit && <Button primary onClick={onSubmit}>{textParser([view.submit.text])}</Button>}
</ButtonGroup>
</Modal.Footer>
</Modal>
</AnimatedVisibility>
);
}
const useActionManagerState = (initialState) => {
const [state, setState] = useState(initialState);
const { viewId } = state;
useEffect(() => {
const handleUpdate = ({ type, ...data }) => {
if (type === 'errors') {
const { errors } = data;
setState({ ...state, errors });
return;
}
setState(data);
};
ActionManager.on(viewId, handleUpdate);
return () => {
ActionManager.off(viewId, handleUpdate);
};
}, [viewId]);
return state;
};
const useValues = (view) => {
const reducer = useMutableCallback((values, { actionId, payload }) => ({
...values,
[actionId]: payload,
}));
const initializer = useMutableCallback(() => {
const filterInputFields = ({ element, elements = [] }) => {
if (element && element.initialValue) {
return true;
}
if (elements.length && elements.map((element) => ({ element })).filter(filterInputFields).length) {
return true;
}
};
const mapElementToState = ({ element, blockId, elements = [] }) => {
if (elements.length) {
return elements.map((element) => ({ element, blockId })).filter(filterInputFields).map(mapElementToState);
}
return [element.actionId, { value: element.initialValue, blockId }];
};
return view.blocks
.filter(filterInputFields)
.map(mapElementToState)
.reduce((obj, el) => {
if (Array.isArray(el[0])) {
return { ...obj, ...Object.fromEntries(el) };
}
const [key, value] = el;
return { ...obj, [key]: value };
}, {});
});
return useReducer(reducer, null, initializer);
};
function ConnectedModalBlock(props) {
const state = useActionManagerState(props);
const {
appId,
viewId,
mid: _mid,
errors,
view,
} = state;
const [values, updateValues] = useValues(view);
const groupStateByBlockId = (obj) => Object.entries(obj).reduce((obj, [key, { blockId, value }]) => {
obj[blockId] = obj[blockId] || {};
obj[blockId][key] = value;
return obj;
}, {});
const prevent = (e) => {
if (e) {
(e.nativeEvent || e).stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
}
};
const context = {
action: ({ actionId, appId, value, blockId, mid = _mid }) => ActionManager.triggerBlockAction({
container: {
type: UIKitIncomingInteractionContainerType.VIEW,
id: viewId,
},
actionId,
appId,
value,
blockId,
mid,
}),
state: ({ actionId, value, /* ,appId, */ blockId = 'default' }) => {
updateValues({
actionId,
payload: {
blockId,
value,
},
});
},
...state,
values,
};
const handleSubmit = useMutableCallback((e) => {
prevent(e);
ActionManager.triggerSubmitView({
viewId,
appId,
payload: {
view: {
...view,
id: viewId,
state: groupStateByBlockId(values),
},
},
});
});
const handleCancel = useMutableCallback((e) => {
prevent(e);
return ActionManager.triggerCancel({
appId,
viewId,
view: {
...view,
id: viewId,
state: groupStateByBlockId(values),
},
});
});
const handleClose = useMutableCallback((e) => {
prevent(e);
return ActionManager.triggerCancel({
appId,
viewId,
view: {
...view,
id: viewId,
state: groupStateByBlockId(values),
},
isCleared: true,
});
});
return <kitContext.Provider value={context}>
<ModalBlock
view={view}
errors={errors}
appId={appId}
onSubmit={handleSubmit}
onCancel={handleCancel}
onClose={handleClose}
/>
</kitContext.Provider>;
}
export default ConnectedModalBlock;
|
const gulp = require('gulp');
const babel = require('gulp-babel');
const concat = require('gulp-concat');
gulp.task('babel', () => {
return gulp.src('src/t-infinity/app/static/src/js/**/*.js')
.pipe(babel({
presets: ['es2015']
}))
.pipe(concat('all.js'))
.pipe(gulp.dest('src/t-infinity/app/static/js/'));
}); |
window.onload = function(){
const Items = document.getElementsByClassName('item');
for (var i = 0; i < Items.length; i++) {
var newClassName = 'color_' + (i + 1);
Items[i].classList.add(newClassName);
}
}
function colorChange(event){
const toChangeColorClassName = event.classList.item(1);
const TextNumber = event.textContent;
const big_item = document.getElementById('big_item');
big_item.className = '';
big_item.className = 'big_item ' + toChangeColorClassName;
const RadiusNumber = (parseInt(TextNumber) * 10);
big_item.textContent = "Border-Radius: " + RadiusNumber + 'px';
big_item.style.borderRadius = RadiusNumber + 'px';
}
/*
გვერდზე არის რაიმე ფორმის 4კუთხედი ჩაწერილი რამე ტექსტით.
1) ღილაკით ხდება ფონტის შევცლა. // Dancing Script-ზე
2) ტექსტის ზომის გაორმაგება.
3) ტექსტის ზომის შემცირება 5-ით
4) ფონის შეცვლა.
5) ჩარჩოს გამოჩენა რომელიც იქნება dotted ტიპის. ზომა 4px, ფერი თქვენი სურვილით.
6) რადიუსი 20px მინიჭება.
P.S
ყველა ღილაკზე მეორჯერ დაჭერის შემთხვევაში უნდა მოხდეს შსაბამისი თვისების მოცილება.
*/ |
module("jquery/view")
test("multipel template types work", function(){
$.each(["micro","ejs","jaml", "tmpl"], function(){
$("#qunit-test-area").html("");
ok($("#qunit-test-area").children().length == 0,this+ ": Empty To Start")
$("#qunit-test-area").html("//jquery/view/test/qunit/template."+this,{"message" :"helloworld"})
ok($("#qunit-test-area").find('h3').length, this+": h3 written for ")
ok( /helloworld\s*/.test( $("#qunit-test-area").text()), this+": hello world present for ")
})
})
test("plugin in ejs", function(){
$("#qunit-test-area").html("");
$("#qunit-test-area").html("//jquery/view/test/qunit/plugin.ejs",{})
ok(/something/.test( $("#something").text()),"something has something");
$("#qunit-test-area").html("");
})
test("nested plugins", function(){
$("#qunit-test-area").html("");
$("#qunit-test-area").html("//jquery/view/test/qunit/nested_plugin.ejs",{})
ok(/something/.test( $("#something").text()),"something has something");
})
test("async templates, and caching work", function(){
$("#qunit-test-area").html("");
stop();
var i = 0;
$("#qunit-test-area").html("//jquery/view/test/qunit/temp.ejs",{"message" :"helloworld"}, function(text){
ok( /helloworld\s*/.test( $("#qunit-test-area").text()))
ok(/helloworld\s*/.test(text), "we got a rendered template");
i++;
equals(i, 2, "Ajax is not synchronous");
equals(this.attr("id"), "qunit-test-area" )
start();
});
i++;
equals(i, 1, "Ajax is not synchronous")
})
test("caching works", function(){
// this basically does a large ajax request and makes sure
// that the second time is always faster
$("#qunit-test-area").html("");
stop();
var startT = new Date(),
first;
$("#qunit-test-area").html("//jquery/view/test/qunit/large.ejs",{"message" :"helloworld"}, function(text){
first = new Date();
ok(text, "we got a rendered template");
$("#qunit-test-area").html("");
$("#qunit-test-area").html("//jquery/view/test/qunit/large.ejs",{"message" :"helloworld"}, function(text){
var lap2 = new Date - first ,
lap1 = first-startT;
ok(lap2 < lap1, "faster this time "+(lap1 - lap2) )
start();
$("#qunit-test-area").html("");
})
})
})
test("hookup", function(){
$("#qunit-test-area").html("");
$("#qunit-test-area").html("//jquery/view/test/qunit/hookup.ejs",{}); //makes sure no error happens
})
|
import _ from 'lodash';
// default config
const defaultConfig = {
defaultValue: true,
omitPathsOnly: false
};
/**
* building default config and overwriting with passed config
*
* @private
* @param {Object} passedConfig Config options to overwrite base config
* @returns {Object} Returns config with overwritten properties
*/
function buildConfig(passedConfig) {
if (!passedConfig) {
return defaultConfig;
}
return Object.assign({}, defaultConfig, passedConfig);
}
/**
* returns true if any of the paths given are different between
* first object and second object given
*
* @param {Object} passedPaths Array of string paths to props
* @param {Object} firstObject
* @param {Object} secondObject
* @param {Object} passedConfig Object of config overwrites
* @returns {boolean} Returns whether paths in object are different
*/
export default function arePathsDiff(passedPaths, firstObject, secondObject, passedConfig) {
const config = buildConfig(passedConfig);
// if empty paths, return defaultValue from config
if (!Array.isArray(passedPaths) || passedPaths.length === 0) {
return config.defaultValue;
}
// if omit paths only flag was passed then check all props except paths passed
if (config.omitPathsOnly) {
return !_.isEqual(
_.omit(firstObject, passedPaths),
_.omit(secondObject, passedPaths)
);
}
return !passedPaths.every((passedPath) => {
let path = passedPath;
let omit = null;
if (typeof path === 'object' && path.hasOwnProperty('path')) {
if (path.omit) {
omit = path.omit;
}
path = path.path;
}
let current = _.get(firstObject, path, {});
if (omit !== null) {
current = _.omit(current, omit);
}
let next = _.get(secondObject, path, {});
if (omit !== null) {
next = _.omit(next, omit);
}
return _.isEqual(current, next);
});
}
|
const assert = require('chai').assert;
const World = require('../lib/world');
const Paddle = require('../lib/paddle');
const Ball = require('../lib/ball');
describe('World', function() {
it('should be a function', function() {
assert.isFunction(World);
});
it('should instanitate an object', function() {
var world = new World();
assert.isObject(world);
});
it('should take the first argument as the "width" of the instantiated world', function() {
var world = new World(50, 250);
assert.equal(world.width, 50);
});
it('should take the second argument as the "height" of the instantiated world', function() {
var world = new World(50, 250);
assert.equal(world.height, 250);
});
it('should have a "court" array which starts out as an empty array', function() {
var world = new World(50, 250);
assert.deepEqual(world.court, []);
});
it('should have a "paddle" object', function() {
var paddle = new Paddle({});
var ball = new Ball({});
var world = new World(500, 500, paddle, ball);
assert.isObject(world.paddle);
});
it('should have a "ball" object', function() {
var paddle = new Paddle({});
var ball = new Ball({});
var world = new World(500, 500, paddle, ball);
assert.isObject(world.ball);
});
});
|
var player; //created
var hp = 5; //created
var orihp = hp;
var lvl1hearts;
var invulnerable = 2; //invulnerable for 2 seconds
var isinvul = false;
var bullet; //created
var bulletdmg = 1;
var hombullet;
var homdmg = 0.5;
var homstart = 90; //original is 30
var laser; //dont forget to add blink before attack launches
var laserDamage = 2;
var laserStrt = 8000; //start after how many miliseconds
var laserDur = 2000; //lasts for 2 seconds
var dmg;
var progressbar;
var progresscrop;
var lvl1timer = 90; //90 seconds
var oritimer = lvl1timer;
var pause_label;
var lvlstarttime;
var i;
//^^ required Elements so far
var text1; //temporary
var text2; //temporary
var playlvl1State = {
init: function(){
bgmusic.pause();
lvl1mus.play();
lvl1mus.loopFull(0.6);
},
create: function(){
lvlstarttime = game.time.now;
var bg = game.add.tileSprite(0,0,450,750,'bg3');
this.game.world.setBounds(0,0,450,750);
bg.alpha = 0.4;
//background
this.bullet = game.add.group();
this.bullet.enableBody = true;
game.physics.arcade.enable(this.bullet);
this.bullet.createMultiple(999, 'bullet');
game.time.events.loop(500, this.addbullet, this);
//normal bullet
this.hombullet = game.add.group();
this.hombullet.enableBody = true;
game.physics.arcade.enable(this.hombullet);
game.time.events.add((oritimer - homstart) * 1000, function(){
this.hombullet.createMultiple(999, 'hombullet',0);
game.time.events.loop(1500, this.addhombullet, this);
},this);
this.laser = game.add.group();
this.laser.enableBody = true;
game.physics.arcade.enable(this.laser);
game.time.events.add(laserStrt, function(){
this.laser.createMultiple(1,'laser',this);
game.time.events.loop(laserStrt, this.addlaser, this);
},this);
pause_label = game.add.text(415, game.height/45, 'II', { font: '36px Arial', fill: '#ffffff' });
pause_label.inputEnabled = true;
pause_label.events.onInputUp.add(function(){
game.paused = true;
//container size is 237 by 80
exittomenu = game.add.sprite(game.width/2, 280,'exittomenu');
exittomenu.anchor.setTo(0.5);
resume = game.add.sprite(game.width/2, 400, 'resume');
resume.anchor.setTo(0.5);
paused_label = game.add.text(game.width/2, game.height/8, 'Paused', { font: '48px Arial', fill: '#ffffff' });
paused_label.anchor.setTo(0.5);
bg.tint = 0xf05239;
});
game.input.onDown.add( function(event){
if(game.paused){
//x1 x2 y1 y2 for exittomenu border;
var x1 = game.width/2 - 118;
var x2 = game.width/2 + 118;
var y1 = 280 - 40;
var y2 = 280 + 40;
//y3 y4 for resume border;
var y3 = 400 - 40;
var y4 = 400 + 40;
if(event.x > x1 && event.x < x2 && event.y > y1 && event.y < y2 ){
game.paused = false;
game.state.start('menu');
lvl1timer = oritimer;
hp = orihp;
lvl1mus.stop();
bgmusic.resume(0.6);
bg.tint = 0xffffff;
isinvul = false;
} else if(event.x > x1 && event.x < x2 && event.y > y3 && event.y < y4){
bg.tint = 0xffffff;
game.paused = false;
paused_label.destroy();
exittomenu.destroy();
resume.destroy();
}
else{
}
}
}, self);
//pause state
progressbar = game.add.sprite(50, 50,'lvlprogress');
progressbar.anchor.setTo(0);
progresscrop = new Phaser.Rectangle(progressbar.positionX, progressbar.positionY, progressbar.width, progressbar.height);
var progtween = game.add.tween(progresscrop).to( { width: 0 }, lvl1timer * 1000, null, false, 0, 0, false);
progressbar.crop(progresscrop);
progtween.start();
//progress bar
this.player = game.add.sprite(game.width/2, 550, 'player');
this.player.anchor.setTo(0.5);
this.player.animations.add('playermove',[0,1,2,3,4,5,6,7]);
this.player.animations.play('playermove',12,true);
this.player.enableBody = true;
game.physics.arcade.enable(this.player);
this.player.body.enable = true;
this.player.body.collideWorldBounds = true;
//player
this.cursor = game.input.keyboard.createCursorKeys();
//controls
text1 = game.add.text(game.width/2, game.height/5,hp,{font: '84px Arial', fill: '#fff000'});
text1.anchor.setTo(0.5);
text1.visible = false;
text2 = game.add.text(370, 50,lvl1timer,{font: '40px Arial', fill: '#ffffff'});
text2.anchor.setTo(0.5);
text2.visible = false;
//rendering OR fix
var statsbar = game.add.sprite(game.width/2, 700, 'container2');
statsbar.anchor.setTo(0.5,0.5);
//bottom stats bar
lvl1hearts = game.add.group();
for(i = 0; i< 5; i++){
var hearts = game.add.sprite(75 * (i+1),700,'hearts');
hearts.anchor.setTo(0.5,0.5);
hearts.animations.add('full',[0]);
hearts.animations.add('fulltohalf',[0,1,0,1,0,1,0,1,0,1]);
hearts.animations.add('half',[1]);
hearts.animations.add('halftonone',[1,2,1,2,1,2,1,2,1,2]);
hearts.animations.add('none',[2]);
hearts.animations.add('fulltonone',[0,2,0,2,0,2,0,2,0,2]);
hearts.animations.play('full',1,true);
lvl1hearts.add(hearts);
}
//hearts
game.time.events.loop(1000, this.lvl1timer, this);
//timer decreasing
},
update: function() {
this.movePlayer();
game.physics.arcade.overlap(this.player, this.bullet,this.damaged, this.addDmg1,null, this);
game.physics.arcade.overlap(this.player, this.hombullet, this.damaged,this.addDmg2, null, this);
game.physics.arcade.overlap(this.player, this.laser, this.damaged,this.addDmg3, null, this);
game.physics.arcade.overlap(this.laser, this.hombullet, this.killHombullet, null, this);
game.physics.arcade.overlap(this.laser, this.bullet, this.killBullet, null, this);
progressbar.updateCrop();
//prog crop updating
if(lvl1timer <= 0 || hp<=0){
this.levelreset();
}
}, killBullet: function(laser,bullet){
bullet.kill();
}, killHombullet: function(laser,hombullet){
hombullet.kill();
},
addDmg1: function(){
dmg = bulletdmg;
},
addDmg2: function(){
dmg = homdmg;
},
addDmg3: function(){
dmg = laserDamage;
},
levelreset: function(){
lvl1timer = oritimer;
hp = orihp;
lvl1mus.stop();
bgmusic.resume(0.6);
isinvul = false;
game.state.start('menu');
},
lvl1timer: function() {
lvl1timer -= 1;
text2.text -= 1;
},
addbullet: function() {
var bullet = this.bullet.getFirstDead();
if(!bullet) {
return;
}
bullet.anchor.setTo(0.5);
bullet.reset(game.rnd.integerInRange(10,440) , 0);
bullet.body.velocity.y = 200;
bullet.checkWorldBounds = true;
bullet.outOfBoundsKill = true;
},
addhombullet: function(){
var hombullet = this.hombullet.getFirstDead();
if(!hombullet) {
return;
}
hombullet.anchor.setTo(0.5);
hombullet.reset(this.player.x , 0);
hombullet.animations.add('homMove',[0,1,2]);
hombullet.animations.play('homMove',3,true);
hombullet.body.velocity.y = 250;
hombullet.checkWorldBounds = true;
hombullet.outOfBoundsKill = true;
},
addlaser: function(){
var laser = this.laser.getFirstDead();
if(!laser){
return;
}
var rndX = game.rnd.pick([45,135,225,315,405])
var laserAlrt = game.add.sprite(rndX,0,'alert');
laserAlrt.enableBody = false;
laserAlrt.alpha = 0.0;
laserAlrt.anchor.setTo(0.5,0);
var Ltween = game.add.tween(laserAlrt).to({alpha: 1.0},250, Phaser.Easing.Linear.None, true, 0, 3, true);
Ltween.onComplete.add(function(){
laserAlrt.kill();
laser.reset(rndX,650);
laserEff.play();
laser.anchor.setTo(0.5,1);
game.time.events.add(laserDur,function(){
laser.kill();
laserEff.stop();
},this);
},this);
},
noBody: function(){
this.player.enableBody = false;
},
okBody: function(){
this.player.alpha = 1.0;
this.player.enableBody = true;
isinvul = false;
},
movePlayer: function(){
if (this.cursor.left.isDown){
this.player.body.velocity.x = -300;
} else if (this.cursor.right.isDown){
this.player.body.velocity.x = 300;
} else {
this.player.body.velocity.x = 0;
}
},
damaged: function(player,bullet){
bullet.kill();
var LheartsArr = [];
var Lhearts = 0;
var preHP = hp;
var exception = 0;
hp -= dmg;
if(hp <= 0){
return;
}
switch (true){
//we compare hp and dmg for %1==0 or not
case (preHP%1 == 0 && dmg%1 == 0): //5 -- 2 //fulltonone
for(Lhearts = 0; Lhearts<dmg; Lhearts++){
LheartsArr[Lhearts] = lvl1hearts.getAt(preHP-1);
LheartsArr[Lhearts].animations.play('fulltonone',5,false);
preHP -= 1;
}
break;
case (preHP%1 == 0 && dmg%1 != 0): //5 -- 2.5 OR 5 -- 0.5 //fulltonone + fulltohalf
for(Lhearts = 0; Lhearts<dmg; Lhearts++){
LheartsArr[Lhearts] = lvl1hearts.getAt(preHP-1);
preHP -= 1;
if(preHP <= hp){
LheartsArr[Lhearts].animations.play('fulltohalf',5,false);
} else{
LheartsArr[Lhearts].animations.play('fulltonone',5,false);
}
}
break;
case (preHP%1 != 0 && dmg%1 == 0):// 4.5 -- 2 OR 3.5 -- 1 //halftonone + fulltonone + fulltohalf
for(Lhearts = 0; Lhearts<dmg+1 ; Lhearts++){
LheartsArr[Lhearts] = lvl1hearts.getAt(Math.round(preHP)-1);
preHP -= 1;
if(exception == 0){
LheartsArr[Lhearts].animations.play('halftonone',5,false);
if(dmg > 1){
exception = 1;
} else{
exception = 2;
}
} else if(exception == 1){
LheartsArr[Lhearts].animations.play('fulltonone',5,false);
} else if(exception == 2){
LheartsArr[Lhearts].animations.play('fulltohalf',5,false);
}
}
break;
case (preHP%1 != 0 && dmg%1 != 0)://3.5 -- 1.5 OR 4.5 -- 2.5 //halftonone + fulltonone
for(Lhearts = 0; Lhearts<dmg+1 ; Lhearts++){
LheartsArr[Lhearts] = lvl1hearts.getAt(Math.round(preHP)-1);
preHP -= 1;
if(exception == 0){
LheartsArr[Lhearts].animations.play('halftonone',5,false);
exception = 1;
} else if(exception == 1){
LheartsArr[Lhearts].animations.play('fulltonone',5,false);
}
if(preHP<=hp){
break;
}
}
break;
default:
break;
}
},
} |
/*global define*/
define(
function () {
// http://stackoverflow.com/a/11646945
var MediaStream = window.MediaStream;
if ( typeof MediaStream === 'undefined' && typeof webkitMediaStream !== 'undefined' ) {
MediaStream = webkitMediaStream;
}
/*global MediaStream:true */
if ( typeof MediaStream !== 'undefined' && !( 'stop' in MediaStream.prototype ) ) {
MediaStream.prototype.stop = function () {
this.getAudioTracks().forEach( function ( track ) {
track.stop();
} );
this.getVideoTracks().forEach( function ( track ) {
track.stop();
} );
};
}
}
) |
var shared = require('./shared.karma.conf');
module.exports = function(config) {
shared(config);
config.files = config.files.concat([
// test helpers
'src/bower_components/angular-mocks/angular-mocks.js',
// unit testing
'test/unit/**/*.js'
]);
};
|
import React, { Component, PropTypes } from 'react'
import Colors from '../Theme/Colors'
const Styles = {
container: {
},
row: {
display: 'flex',
flexDirection: 'row'
},
button: {
height: 30,
width: 75,
fontSize: 13,
marginRight: 4,
backgroundColor: Colors.subtleLine,
borderRadius: 2,
border: `1px solid ${Colors.backgroundSubtleDark}`,
cursor: 'pointer',
color: Colors.foregroundDark
},
buttonActive: {
color: Colors.bold
}
}
class NativeOverlayLayoutType extends Component {
static propTypes = {
layoutType: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired
}
render () {
const { onChange, layoutType } = this.props
const makeHandler = newlayoutType => event => {
event.stopPropagation()
event.preventDefault()
onChange(newlayoutType)
return false
}
const makeButtonStyle = value =>
layoutType === value ? { ...Styles.button, ...Styles.buttonActive } : Styles.button
return (
<div style={Styles.container}>
<div style={Styles.row}>
<button style={makeButtonStyle('image')} onClick={makeHandler('image')}>Image</button>
<button style={makeButtonStyle('screen')} onClick={makeHandler('screen')}>Screen</button>
</div>
</div>
)
}
}
export default NativeOverlayLayoutType
|
function readJS (content, funcname) {
if (typeof content !== 'string') return [];
if (typeof funcname !== 'string') funcname = undefined;
funcname = funcname || 'tr';
var start = -1;
var end = -1;
var exprs = [];
while (
(start = content.indexOf(funcname)) > -1 &&
(end = content.indexOf('(', start)) > -1
) {
var func = content.substring(start, end);
var isTR = 1;
if (start > 0) {
var prev = content.substring(start - 1, start);
if (/[a-zA-Z0-9$_.]/.test(prev)) {
isTR = 0;
} else if (prev.charCodeAt(0) > 127) {
func = prev + func;
}
}
if (isTR == 1) {
try {
if (func.indexOf('.') > -1) {
var parts = func.split('.');
var parts2 = funcname.split('.');
var test = 'var ';
var test2 = '';
var exp = [];
for (var i = 0; i < parts.length; i++) {
var part = parts[i].trim();
exp.push(part);
test2 += JSON.stringify(part) + ' == ' +
JSON.stringify(parts2[i].trim()) + ' && ';
if (i == parts.length -1) {
test += exp.join('.') + ' = function () {}; ';
} else {
test += exp.join('.') + ' = {}; ';
}
}
test += 'return ' + test2 + 'typeof ' + exp.join('.') +
' == "function"';
var isTR = new Function(test)() ? 1 : 0;
} else {
var name = new Function('return function ' + func + ' () {}.name')();
if (name != funcname) {
isTR = 0;
}
}
} catch(e) {
isTR = 0;
}
}
if (isTR == 0) {
content = content.substring(start + funcname.length);
continue;
}
content = content.substring(end + 1);
var pa = 0; // parenthesis
var sq = 0; // single-quote
var dq = 0; // double-quote
var bs = 0; // backslash
var expr = '';
var closed = 0;
while (content.length) {
var cur = content.substring(0, 1);
if (bs % 2 == 0) {
if (dq == 0) {
if (sq == 0 && cur == "'") {
sq = 1;
} else if (sq == 1 && cur == "'") {
sq = 0;
}
}
if (sq == 0) {
if (dq == 0 && cur == '"') {
dq = 1;
} else if (dq == 1 && cur == '"') {
dq = 0;
}
}
}
if (sq == 0 && dq == 0) {
if (pa == 0 && (cur == ')' || cur == ',')) {
// finish if we have first argument
closed = 1;
break;
}
}
if (cur == '(') {
pa++;
}
if (cur == ')') {
pa--;
if (pa < 0) pa = 0;
}
if (cur == '\\') {
bs++;
} else {
bs = 0;
}
expr += cur;
content = content.substring(1);
}
if (closed == 1) {
exprs.push(expr);
content = content.substring(1);
}
}
if (exprs.length == 0) return [];
var strings = exprs.map(function (expr) {
try {
return new Function('return ' + expr.trim())() || '';
} catch (e) {
return '';
}
});
strings = strings.map(function (string) {
return String(string);
}).filter(function (string) {
return string.length;
});
return strings;
}
module.exports = readJS;
|
describe('Plane', function(){
var plane;
var airport;
beforeEach(function(){
plane = new Plane();
airport = jasmine.createSpyObj('airport',['clearForLanding', 'clearForTakeoff', 'isStormy']);
});
it('can land at an airport', function(){
plane.land(airport);
expect(airport.clearForLanding).toHaveBeenCalledWith(plane);
});
it('can take off from an airport', function() {
plane.land(airport);
plane.takeoff();
expect(airport.clearForTakeoff).toHaveBeenCalled();
});
});
|
import EventEmitter from 'events'
import fetch from 'node-fetch'
import { Dropbox } from 'dropbox/lib'
import delay from '@zap/utils/delay'
import * as api from './dbApi'
/**
* createConnection - Creates dropbox api connection.
*
* @param {*} { clientId, authRedirectUrl, tokens }
* @returns {object} returns {client, accessTokens} object. `client` represents dropbox api instance
*/
async function createConnection({ clientId, authRedirectUrl, tokens }) {
const accessTokens = tokens || (await api.createAuthWindow(clientId, authRedirectUrl))
const client = new Dropbox({ clientId, accessToken: accessTokens.access_token, fetch })
return { client, accessTokens }
}
/**
* createClient - Creates dropbox api client.
*
* @param {object} params - client params
* @param {string} params.clientId - dropbox client ID. Obtained through developer console
* @param {string} params.authRedirectUrl - authorized callback URL
* @param {string} params.tokens - existing tokens. If omitted authentication process will start on creation
* @returns {object} - dropbox client
*/
async function createClient({ clientId, authRedirectUrl, tokens }) {
// provides access to basic event emitter functionality
const emitter = new EventEmitter()
/**
* postTokensReceived - Emit `tokensReceived` after tokens have been received.
*
* @param {object} tokensReceived Tokens
*/
async function postTokensReceived(tokensReceived) {
// schedule event posting for the next event loop iteration
// to give listeners chance to subscribe before the first update
await delay(0)
emitter.emit('tokensReceived', tokensReceived)
}
let { client, accessTokens } = await createConnection({ clientId, authRedirectUrl, tokens })
postTokensReceived(accessTokens)
/**
* refreshAuth - Attempts to re-create connection to get new access tokens.
*/
async function refreshAuth() {
;({ client, accessTokens } = await createConnection({
clientId,
authRedirectUrl,
}))
postTokensReceived(accessTokens)
}
/**
* testConnection - Checks if connection is healthy and client is ready to process requests.
*
* @returns {boolean} `true` if client is ready to interact with API `false` otherwise
*/
async function testConnection() {
try {
await api.listFiles(client, { limit: 1 })
return true
} catch (e) {
return false
}
}
/**
* apiCall - Wrap api calls to catch errors that are potentially caused with expired/incorrect tokens.
*
* @param {Function} method Method to call
* @param {...object} args Additional arguments to pass to call the method with
* @returns {any} Result of calling the api method
*/
function apiCall(method, ...args) {
try {
return method.call(null, client, ...args)
} catch (e) {
// try re-initializing connection
// TODO: continue call exec ?
refreshAuth()
return null
}
}
return {
getTokens: () => accessTokens,
refreshAuth,
testConnection,
downloadToBuffer: apiCall.bind(this, api.downloadToBuffer),
uploadFromBuffer: apiCall.bind(this, api.uploadFromBuffer),
getFileInfo: apiCall.bind(this, api.getFileInfo),
listFiles: apiCall.bind(this, api.listFiles),
on: emitter.on.bind(emitter),
off: emitter.off.bind(emitter),
removeAllListeners: emitter.removeAllListeners.bind(emitter),
}
}
export default createClient
|
(function () {
angular.module('servicios').service('maestrosService', maestrosService);
function maestrosService($http) {
// Retornamos una promesa
this.gettingCategorias = $http.get('/maestros');
}
}());
|
const path = require('path');
const webpack = require('webpack');
const ENTRY_POINTS = [ './client/src/index' ];
const DEV_ENTRY_POINTS = ENTRY_POINTS.concat( [ 'webpack-hot-middleware/client' ] );
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: process.NODE_ENV === 'production' ? ENTRY_POINTS : DEV_ENTRY_POINTS,
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
],
module: {
loaders: [
{ test: /\.html$/, loaders: ['react-hot', 'file-loader?name=[name].[ext]'], include: path.join(__dirname, 'client', 'src') },
{ test: /\.js$/, loaders: ['react-hot', 'babel'], include: path.join(__dirname, 'client', 'src') },
{ test: /\.css$/, loaders: ['react-hot', 'style-loader', 'css-loader'] },
{ test: /\.png$/, loader: 'url-loader?limit=100000' },
{ test: /\.jpg$/, loader: 'file-loader?name=/images/[name].[ext]' },
{ test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader: 'file?name=/fonts/[name].[ext]&limit=10000&mimetype=application/font-woff' }, //
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'file?name=/fonts/[name].[ext]&limit=10000&mimetype=application/octet-stream' },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file?name=/fonts/[name].[ext]' }, //
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'file?name=/fonts/[name].[ext]&limit=10000&mimetype=image/svg+xml'}//
]
},
devServer: {
proxy: {
'/api':{
target: 'http://localhost:8080'
}
}
}
};
|
'use strict'
const db = require('APP/db')
, {User, Season, Glasses, Order, Review, Promise, GlassesOrders} = db
, {mapValues} = require('lodash')
function seedEverything() {
const seeded = {
users: users(),
seasons: seasons(),
glasses: glasses()
}
seeded.orders = orders(seeded)
seeded.reviews = reviews(seeded)
seeded.GlassesOrders = glassesOrdersTable(seeded)
return Promise.props(seeded)
}
const users = seed(User, {
danny: {
email: 'danny@email.com',
name: 'Danny',
password: 'test',
isAdmin: true
},
marcos: {
email: 'marcos@email.com',
name: 'Marcos',
password: 'test',
isAdmin: true
},
natasha: {
email: 'natasha@email.com',
name: 'Natasha',
password: 'test',
isAdmin: true
},
pim: {
email: 'pim@email.com',
name: 'Pim',
password: 'test',
isAdmin: true
},
user: {
email: 'user@email.com',
name: 'User',
password: 'test',
isAdmin: false
}
})
const seasons = seed(Season, {
winter: {
season: 'winter'
},
spring: {
season: 'spring'
},
summer: {
season: 'summer'
},
fall: {
season: 'fall'
}
})
const glasses = seed(Glasses, {
daniel: {
name: 'Daniel',
color: 'black',
material: 'metal',
price: 10000,
description: `You'll look totally scholarly in these specs.`,
image: 'http://i.imgur.com/3NOvG4t.png',
quantity: 17,
season_id: 1
},
marcos: {
name: 'Marcos',
color: 'blue',
material: 'metal',
price: 25000,
description: `You'll look totally fancy in these specs.`,
image: 'http://i.imgur.com/EsO3iMd.jpg',
quantity: 4,
season_id: 1
},
natasha: {
name: 'Natasha',
color: 'blue',
material: 'acetate',
price: 17500,
description: `You'll look totally rad in these specs.`,
image: 'http://i.imgur.com/xIOvGWa.png',
quantity: 59,
season_id: 1
},
pim: {
name: 'Pim',
color: 'multi',
material: 'acetate',
price: 15000,
description: `You'll look totally librarian in these specs.`,
image: 'http://i.imgur.com/XOqM5AE.png',
quantity: 31,
season_id: 2
},
omri: {
name: 'Omri',
color: 'pink',
material: 'acetate',
price: 21000,
description: `You'll look totally heroic in these specs.`,
image: 'http://i.imgur.com/u9I91HD.png',
quantity: 31,
season_id: 2
},
john: {
name: 'John',
color: 'red',
material: 'acetate',
price: 10000,
description: `You'll look totally British in these specs.`,
image: 'http://i.imgur.com/dHxKtyq.png',
quantity: 84,
season_id: 2
},
sam: {
name: 'Sam',
color: 'multi',
material: 'acetate',
price: 26000,
description: `You'll look totally spiffy in these specs.`,
image: 'http://i.imgur.com/kNe7EV8.png',
quantity: 12,
season_id: 3
},
ian: {
name: 'Ian',
color: 'gold',
material: 'metal',
price: 16500,
description: `You'll look totally fresh in these specs.`,
image: 'http://i.imgur.com/tcvgy5p.png',
quantity: 31,
season_id: 3
},
lisa: {
name: 'Lisa',
color: 'brown',
material: 'mixed',
price: 12500,
description: `You'll look totally retro in these specs.`,
image: 'http://i.imgur.com/Icvi1y4.png',
quantity: 106,
season_id: 3
},
yoonah: {
name: 'Yoo-Nah',
color: 'brown',
material: 'acetate',
price: 19500,
description: `You'll look totally Harry-Potter-ish in these specs.`,
image: 'http://i.imgur.com/MQ2Tv9C.png',
quantity: 8,
season_id: 4
},
robbyn: {
name: 'Robbyn',
color: 'blue',
material: 'acetate',
price: 23500,
description: `You'll look totally smart in these specs.`,
image: 'http://i.imgur.com/GVwBDLx.png',
quantity: 76,
season_id: 4
},
damon: {
name: 'Damon',
color: 'multi',
material: 'mixed',
price: 20500,
description: `You'll look totally vogue in these specs.`,
image: 'http://i.imgur.com/NHnYUPc.png',
quantity: 49,
season_id: 4
}
})
const orders = seed(Order,
({users}) => ({
order1: {
status: 'in-progress',
user_id: users.marcos.id
},
order2: {
status: 'shipped',
user_id: users.user.id
}
})
)
const reviews = seed(Review,
({users, glasses}) => ({
review1: {
text: 'Awful',
rating: 5,
user_id: users.natasha.id,
glass_id: glasses.natasha.id
},
review2: {
text: 'INCREDIBLE',
rating: 3,
user_id: users.pim.id,
glass_id: glasses.omri.id
},
review3: {
text: 'Recommended!',
rating: 4,
user_id: users.user.id,
glass_id: glasses.damon.id
}
})
)
const glassesOrdersTable = seed(GlassesOrders,
({orders, glasses}) => ({
association1: {
order_id: orders.order1.id,
glass_id: glasses.omri.id
},
association2: {
order_id: orders.order1.id,
glass_id: glasses.sam.id
},
association3: {
order_id: orders.order2.id,
glass_id: glasses.john.id
},
association4: {
order_id: orders.order1.id,
glass_id: glasses.daniel.id
},
association5: {
order_id: orders.order1.id,
glass_id: glasses.pim.id
}
})
)
if (module === require.main) {
db.didSync
.then(() => db.sync({force: true}))
.then(seedEverything)
.finally(() => process.exit(0))
}
class BadRow extends Error {
constructor(key, row, error) {
super(error)
this.cause = error
this.row = row
this.key = key
}
toString() {
return `[${this.key}] ${this.cause} while creating ${JSON.stringify(this.row, 0, 2)}`
}
}
// seed(Model: Sequelize.Model, rows: Function|Object) ->
// (others?: {...Function|Object}) -> Promise<Seeded>
//
// Takes a model and either an Object describing rows to insert,
// or a function that when called, returns rows to insert. returns
// a function that will seed the DB when called and resolve with
// a Promise of the object of all seeded rows.
//
// The function form can be used to initialize rows that reference
// other models.
function seed(Model, rows) {
return (others={}) => {
if (typeof rows === 'function') {
rows = Promise.props(
mapValues(others,
other =>
// Is other a function? If so, call it. Otherwise, leave it alone.
typeof other === 'function' ? other() : other)
).then(rows)
}
return Promise.resolve(rows)
.then(rows => Promise.props(
Object.keys(rows)
.map(key => {
const row = rows[key]
return {
key,
value: Promise.props(row)
.then(row => Model.create(row)
.catch(error => { throw new BadRow(key, row, error) })
)
}
}).reduce(
(all, one) => Object.assign({}, all, {[one.key]: one.value}),
{}
)
)
)
.then(seeded => {
console.log(`Seeded ${Object.keys(seeded).length} ${Model.name} OK`)
return seeded
}).catch(error => {
console.error(`Error seeding ${Model.name}: ${error} \n${error.stack}`)
})
}
}
module.exports = Object.assign(seed, {users, seasons, glasses, orders, reviews})
|
/// <reference path="../../typings/mocha/mocha.d.ts" />
/// <reference path="../../typings/chai/chai.d.ts" />
var chai = require('chai');
var assert = chai.assert;
var IsNumber = require('../../src/validators/isNumber');
describe('isNumber', function () {
it('should get a template message', function () {
var validator = new IsNumber([], []);
assert.equal(validator.getTemplateMessage(), '%s deve conter numeros');
});
it('should invalid', function () {
var validatorNotValid = new IsNumber([], ['123a']);
assert.equal(validatorNotValid.isValid(), false);
});
it('should valid', function () {
var validatorNotValid = new IsNumber([], ['12123']);
assert.equal(validatorNotValid.isValid(), true);
});
});
|
import Ember from 'ember';
import EmberValidations from 'ember-validations';
export default Ember.Controller.extend( EmberValidations.Mixin,
{
validations: {
"model.def": {
generic: true,
definitionlike: true,
},
"model.example": {
generic: true,
nongendered: true,
sentencelike: true,
}
},
actions: {
submitProposal: function() {
this.send("log", "proposal", "new meaning");
this.get("proposalTarget");
var _this = this;
this.get("model").save().then(
function(model) {
_this.transitionToRoute("proposal", model);
},
function() {
// apparently, just defining this function
// makes everything work. weird.
}
);
},
}
});
|
(function() {
const a= document.querySelector("#demo");
const b= document.querySelector("#n");
const c= document.querySelector("#u");
let numbers ={one: 1, two: 2, three: 3};
a.innerText = JSON.stringify(numbers);
//underscore js
function Stooge(name) {
this.name = name;
}
Stooge.prototype.silly = true;
const no = _.allKeys(new Stooge("moe"));
c.innerText = JSON.stringify(no);
//normal js
b.innerText = JSON.stringify(numb);
}()) |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Sound = mongoose.model('Sound'),
_ = require('lodash');
/**
* Find sound by id
*/
exports.sound = function(req, res, next, id) {
Sound.load(id, function(err, sound) {
if (err) return next(err);
if (!sound) return next(new Error('Failed to load sound ' + id));
req.sound = sound;
next();
});
};
/**
* Create a sound
*/
exports.create = function(req, res) {
var sound = new Sound(req.body);
sound.user = req.user;
sound.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
sound: sound
});
} else {
res.jsonp(sound);
}
});
};
/**
* Update a sound
*/
exports.update = function(req, res) {
var sound = req.sound;
sound = _.extend(sound, req.body);
sound.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
sound: sound
});
} else {
res.jsonp(sound);
}
});
};
/**
* Delete a sound
*/
exports.destroy = function(req, res) {
var sound = req.sound;
sound.remove(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
sound: sound
});
} else {
res.jsonp(sound);
}
});
};
/**
* Show a sound
*/
exports.show = function(req, res) {
res.jsonp(req.sound);
};
/**
* List of sounds
*/
exports.all = function(req, res) {
Sound.find().sort('-created').populate('user', 'name username').exec(function(err, sounds) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(sounds);
}
});
};
|
/* jslint node:true */
/* global Promise: true, indexedDB: true */
'use strict';
var Schema = require('./schema/schema');
var QueryWrapper = require('./querywrapper');
var TransactionWrapper = require('./transactionwrapper');
var removeListeners = require('./helpers/removelisteners');
/**
* Constructor for IDB-wrapper
* @param {String} database The database to open
* @param {Integer} version The database version
*/
var IDBWrapper = function IDBWrapper(database, version) {
this._databaseName = database;
this._version = version;
this._availableStores = [];
Object.defineProperty(this, 'schema', {
get: function () {
if (!this._schema) {
this._schema = new Schema(this);
}
return this._schema;
}
});
this.open();
};
/**
* Opens or closes and re-opens a database connection
* @param {Boolean} closeAndReopen Should the current connection be closed and re-opened?
* @return {Object} A promise
*/
IDBWrapper.prototype.open = function (closeAndReopen) {
if (this._connectionPromise && !closeAndReopen) {
return this._connectionPromise;
}
if (this._database) {
this._database.close();
}
this._connectionPromise = new Promise(function (resolve, reject) {
var initialReq = indexedDB.open(this._databaseName, this._version);
initialReq.onsuccess = function (e) {
this._database = e.target.result;
this._defineStoreAccessors(this._database);
resolve(this);
removeListeners(e.target);
}.bind(this);
initialReq.onerror = function (e) {
reject(new Error(e.target.error.message));
removeListeners(e.target);
};
initialReq.onupgradeneeded = this._onUpgradeNeeded.bind(this);
}.bind(this));
return this._connectionPromise;
};
/**
* Performs a transaction
* @param {Function} callback A callback performing the actions
* @return {Object} A promise
*/
IDBWrapper.prototype.transaction = function (stores,callback) {
var transactionStores;
var options = {};
if (typeof stores !== 'function') {
if (!Array.isArray(stores)) {
throw new Error('Expecting an array of stores for the transaction');
}
transactionStores = stores.filter(function (store) {
return this._availableStores.indexOf(store) !== -1;
}, this);
if (!transactionStores.length) {
throw new Error('No valid stores specified');
}
} else {
// no stores have been specified, so we should auto detect them
options.autoDetectUsedStores = true;
transactionStores = this._availableStores;
// only a callback was passed in, reassign variable
callback = stores;
}
var wrapper = new TransactionWrapper(transactionStores, callback, this._database, options);
return wrapper.performTransaction();
};
/**
* Defines store accessors on the IDB instance
* @param {IDBDatabase} db The database object
*/
IDBWrapper.prototype._defineStoreAccessors = function (db) {
var existingStores = db.objectStoreNames;
for (var i = 0, ii = existingStores.length; i< ii; i++) {
var store = existingStores[i];
this._availableStores.push(store);
// these accessors will be only available AFTER connecting
Object.defineProperty(this, store, {
enumerable: true,
configurable: true,
get: (function (store) {
return function () {
return new QueryWrapper(store, this._connectionPromise);
};
}(store))
});
}
};
/**
* Handles onupgradeneeded event
* @param {Object} e The event
*/
IDBWrapper.prototype._onUpgradeNeeded = function (e) {
var db = e.target.result;
var transaction = e.target.transaction;
this.schema.runDDLStatements(db, transaction, e.oldVersion, e.newVersion);
// TODO: clear schema ddl statements here?
};
/**
* Adds data to the store
* @param {String} store The store name
* @param {Array} values An array of values to insert
* @return {Object} A promise
*/
IDBWrapper.prototype.insert = function (store, values) {
var q = new QueryWrapper(store, this._connectionPromise);
return q.insert(values);
};
/**
* Either inserts or updates the passed in values
* @param {String} store The store name
* @param {Array} values And array of values to upsert
* @return {Object} A promise
*/
IDBWrapper.prototype.upsert = function (store, values) {
var q = new QueryWrapper(store, this._connectionPromise);
return q.upsert(values);
};
/**
* Find a single value from a store by key
* @param {String} store The store name
* @param {Mixed} key The key value
* @param {Boolean} required Whether the promise will be rejected for an empty result
* @return {Promise} A promise
*/
IDBWrapper.prototype.findByKey = function (store, key, required) {
var q = new QueryWrapper(store, this._connectionPromise);
return q.find(key, required);
};
/**
* Exports the selected stores as a nested javascript object
* @param {Array} stores The stores to export, optional
* @return {Object} A promise which resolves with a javascript object holding the exported data
*/
IDBWrapper.prototype.export = function (stores) {
stores = stores || this._availableStores;
var selects = stores.map(function (store) {
return this[store].findAll();
}.bind(this));
return Promise
.all(selects)
.then(function (results) {
return stores.reduce(function (finalResult, store, index) {
finalResult[store] = results[index];
return finalResult;
}, {});
});
};
/**
* Imports data from a javascript object or json string
* @param {Mixed} data A javascript object or JSON string
* @return {Object} A promise
*/
IDBWrapper.prototype.import = function (data) {
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) {
return Promise.reject(e);
}
}
var stores = Object.keys(data);
if (!stores.every(function (store) {
return this._availableStores.indexOf(store) !== -1;
}.bind(this))) {
return Promise.reject(new Error('Import data contains data for non-existing stores'));
}
// TODO: handle all inserts in a single transaction
// to prevent partial imports
var upserts = stores.map(function (store) {
return this[store].upsert(data[store]);
}.bind(this));
return Promise.all(upserts);
};
/**
* Convenience method to construct a new instance
* @param {String} database The database to open
* @param {Integer} version The database version
* @return {Object} A new instance
*/
IDBWrapper.initialize = function (database, version) {
return new IDBWrapper(database, version);
};
module.exports = IDBWrapper;
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Users = new Schema({
username: { type: String, required: true }, // twitter id
created_at: { type: Date, default: Date.now, required: true },
updated_at: { type: Date, default: Date.now, required: true },
last_loggedin_at: { type: Date, default: Date.now, required: true }
});
/**
* ログイン処理
* 指定されたusernameが存在しなければ作成する
*/
Users.static('login', function (username, callback) {
var that = this;
callback = callback || function () {};
that.findOne({ username: username }, function (err, user) {
if (err) {
callback(err);
} else if (user) {
// 既にユーザが作成されている
user.last_loggedin_at = Date.now();
user.save(function (err) {
if (err) { callback(err); }
else { callback(null, user); }
});
} else {
// ユーザの新規作成
var newUser = new that({ username: username });
newUser.save(function (err) {
if (err) { callback(err); }
else { callback(null, newUser); }
});
}
});
});
module.exports = mongoose.model('User', Users);
|
/**
* Module dependencies.
*/
var express = require('express'),
routes = require('./routes'),
user = require('./routes/user'),
http = require('http'),
path = require('path'),
cons = require('consolidate'),
uuid = require('node-uuid'),
socketConnection = require('./sockets'),
stylus = require('stylus'),
nib = require('nib');
var app = express()
app.engine('dust', cons.dust)
app.configure(function() {
app.set('port', process.env.PORT || 3000)
app.set('views', __dirname + '/views')
app.set('view engine', 'dust') //dust.js default
app.set('view options', {
layout: false
}); //disable layout default
app.locals({
layout: false
})
app.use(express.logger('dev'))
app.use(stylus.middleware({
src: __dirname + '/public',
compile: compile
}))
app.use(express.bodyParser())
app.use(express.methodOverride())
app.use(app.router)
app.use(express.static(path.join(__dirname, 'public')))
})
app.configure('development', function() {
app.use(express.errorHandler())
})
app.get('/', routes.index)
app.get('/test', function(req, res) {
var q = req.param('q', "")
var uuid = uuid.v4()
pub.write(JSON.stringify({
uuid: uuid,
req: "test"
}), 'utf8')
queue[uuid] = function(data) {
res.render('index', {
q: data
})
}
})
var queue = {}
function respQueue(uuid, data) {
if (queue[uuid]) {
queue[uuid](data)
queue[uuid] = undefined
}
}
function compile(str, path) {
console.log("COMPILE")
console.log(path)
return stylus(str)
.set('filename', path)
.use(nib())
}
var server = http.createServer(app)
var io = require('socket.io').listen(server)
io.sockets.on('connection', socketConnection)
server.listen(app.get('port'), function() {
console.log("Express server listening on port " + app.get('port'))
})
|
const HTMLWebackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const SkuWebpackPlugin = require('../../../../webpack-plugin');
module.exports = {
entry: './main.js',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
babelrc: false,
presets: [['@babel/preset-react', { runtime: 'automatic' }]],
},
},
],
},
],
},
plugins: [
new HTMLWebackPlugin(),
new SkuWebpackPlugin({
target: 'browser',
MiniCssExtractPlugin,
}),
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
devServer: {
port: 9876,
},
};
|
'use strict';
var dbgsrc = {
properties : {
type : 'debugnode',
prmname : 'DBUGSRC',
description : 'Dummy source node to test infeasibilities',
hobbes : {
debug: true,
id : 'DBUGSRC',
type : 'node'
}
}
};
var dbgsinks = {
properties : {
type : 'debugnode',
prmname : 'DBUGSNK',
description : 'Dummy source node to test infeasibilities',
hobbes : {
debug: true,
id : 'DBUGSNK',
type : 'node'
}
}
};
var sinkLink = {
properties : {
type : 'Diversion',
prmname : 'DBUGSNK-SINK',
description : 'Debug link from DBUGSINK to SINK with high unit cost.',
hobbes : {
debug: true,
id : 'DBUGSNK-SINK',
origin: 'DBUGSNK',
terminus : 'SINK',
type : 'link'
},
costs : {
type : 'Constant'
}
}
};
var sourceLink = {
properties : {
type : 'Diversion',
prmname : 'SOURCE-DBUGSRC',
origin : 'SOURCE',
terminus : 'DBUGSRC',
description : 'Debug link from source to DBUGSOURCE with high unit cost.',
hobbes : {
debug: true,
id : 'SOURCE-DBUGSRC',
origin: 'SOURCE',
terminus : 'DBUGSRC',
type : 'link'
},
costs : {
type : 'Constant'
}
}
};
module.exports = function(nodes) {
var config = require('../config').get();
var cost = parseInt(config.debugCost) || 2000000;
var all = false, matches = [];
if( config.debug === '*' || config.debug.toLowerCase() === 'all' ) {
all = true;
} else {
matches = config.debug.toLowerCase().split(',');
}
var newList = [], np;
for( var i = 0; i < nodes.length; i++ ) {
np = nodes[i].properties.hobbes;
if( np.type === 'node' &&
(all || matches.indexOf(np.id.toLowerCase()) > -1 )) {
newList.push({
properties : {
type : 'Diversion',
prmname : np.id+'-DBUGSNK',
hobbes : {
debug: true,
id : np.id+'-DBUGSNK',
type : 'link',
origin : np.id,
terminus : 'DBUGSNK',
},
costs : {}
}
});
newList.push({
properties : {
type : 'Diversion',
prmname : 'DBUGSRC-'+np.id,
hobbes : {
debug: true,
id : 'DBUGSRC-'+np.id,
type : 'link',
origin : 'DBUGSRC',
terminus : np.id,
},
costs : {}
}
});
}
// Push this regardless
newList.push(nodes[i]);
}
sinkLink.properties.costs.cost = cost;
sourceLink.properties.costs.cost = cost;
newList.push(sinkLink);
newList.push(sourceLink);
newList.push(dbgsinks);
newList.push(dbgsrc);
return newList;
};
|
import React from 'react';
const AboutPage2 = () => {
return (
<div className='subpage-about'>
<h3>my skills</h3>
<p>
At the bginning of May 2016 I started learning how to develop for the web. Since then I have focussed my efforts towards learning the following skills:
</p>
<ul>
<li>JavaScript ES6</li>
<li>Babel & ESLint</li>
<li>CSS/CSS3, Sass, and SVG</li>
<li>React</li>
<li>Redux</li>
<li>Webpack</li>
<li>Node.js</li>
<li>Ajax</li>
<li>Git & GitHub</li>
<li>Browser dev tools (Chrome/React/Redux)</li>
<li>Responsive & mobile first design</li>
</ul>
</div>
);
}
export default AboutPage2;
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2007, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
/**
* XFormItem class: "acl (composite item)
* this item is used in the Admin UI to display SambaAcctFlags
* D - Account is disabled
* H - a home directory required
* I - an inter-domain trust account
* L - Account has been auto-blocked
* M - an MNS logon account
* N - Password not required
* S - a server trust account
* T - temporary duplicate account entry
* U - a normal user account
* W - a workstation trust account
* X - Password does not expire
* @class ZaSambaAcFlagsXFormItem
* @constructor ZaSambaAcFlagsXFormItem
* @author Greg Solovyev
**/
function ZaSambaAcFlagsXFormItem() {}
XFormItemFactory.createItemType("_SAMBAACFLAGS_", "sambaacflags", ZaSambaAcFlagsXFormItem, Composite_XFormItem);
ZaSambaAcFlagsXFormItem.prototype.numCols = 2;
ZaSambaAcFlagsXFormItem.prototype.nowrap = true;
ZaSambaAcFlagsXFormItem.prototype.initializeItems =
function () {
this.items = [];
//U
this.items.push(
{type:_CHECKBOX_,width:"40px",containerCssStyle:"width:40px", forceUpdate:true, ref:".",
labelLocation:_RIGHT_, label:"Normal user account", relevantBehavior:_PARENT_,
getDisplayValue:function (itemval) {
return (itemval && itemval.indexOf("U")>0);
},
elementChanged:function(isChecked, instanceValue, event) {
var U,D, H, I, L, M, N, S, T, W, X;
if(instanceValue) {
D = instanceValue.indexOf("D") > 0;
H = instanceValue.indexOf("H") > 0;
I = instanceValue.indexOf("I") > 0;
L = instanceValue.indexOf("L") > 0;
M = instanceValue.indexOf("M") > 0;
N = instanceValue.indexOf("N") > 0;
S = instanceValue.indexOf("S") > 0;
T = instanceValue.indexOf("T") > 0;
W = instanceValue.indexOf("W") > 0;
X = instanceValue.indexOf("X") > 0;
}
U = isChecked;
var newVal = "[";
if(D) newVal += "D";
if(H) newVal += "H";
if(I) newVal += "I";
if(L) newVal += "L";
if(M) newVal += "M";
if(N) newVal += "N";
if(S) newVal += "S";
if(T) newVal += "T";
if(U) newVal += "U";
if(W) newVal += "W";
if(X) newVal += "X";
newVal += "]";
this.getForm().itemChanged(this.getParentItem(), newVal, event);
}
});
//X
this.items.push(
{type:_CHECKBOX_,width:"40px",containerCssStyle:"width:40px", forceUpdate:true, ref:".",
labelLocation:_RIGHT_, label:"Password does not expire", relevantBehavior:_PARENT_,
getDisplayValue:function (itemval) {
return (itemval && itemval.indexOf("X")>0);
},
elementChanged:function(isChecked, instanceValue, event) {
var U, D, H, I, L, M, N, S, T, W, X;
if(instanceValue) {
U = instanceValue.indexOf("U") > 0;
D = instanceValue.indexOf("D") > 0;
H = instanceValue.indexOf("H") > 0;
I = instanceValue.indexOf("I") > 0;
L = instanceValue.indexOf("L") > 0;
M = instanceValue.indexOf("M") > 0;
N = instanceValue.indexOf("N") > 0;
S = instanceValue.indexOf("S") > 0;
T = instanceValue.indexOf("T") > 0;
W = instanceValue.indexOf("W") > 0;
}
X = isChecked;
var newVal = "[";
if(D) newVal += "D";
if(H) newVal += "H";
if(I) newVal += "I";
if(L) newVal += "L";
if(M) newVal += "M";
if(N) newVal += "N";
if(S) newVal += "S";
if(T) newVal += "T";
if(U) newVal += "U";
if(W) newVal += "W";
if(X) newVal += "X";
newVal += "]";
this.getForm().itemChanged(this.getParentItem(), newVal, event);
}
});
//D
this.items.push(
{type:_CHECKBOX_,width:"40px",containerCssStyle:"width:40px", forceUpdate:true, ref:".",
labelLocation:_RIGHT_, label:"Account is disabled", relevantBehavior:_PARENT_,
getDisplayValue:function (itemval) {
return (itemval && itemval.indexOf("D")>0);
},
elementChanged:function(isChecked, instanceValue, event) {
var U,D, H, I, L, M, N, S, T, W, X;
if(instanceValue) {
U = instanceValue.indexOf("U") > 0;
H = instanceValue.indexOf("H") > 0;
I = instanceValue.indexOf("I") > 0;
L = instanceValue.indexOf("L") > 0;
M = instanceValue.indexOf("M") > 0;
N = instanceValue.indexOf("N") > 0;
S = instanceValue.indexOf("S") > 0;
T = instanceValue.indexOf("T") > 0;
W = instanceValue.indexOf("W") > 0;
X = instanceValue.indexOf("X") > 0;
}
D = isChecked;
var newVal = "[";
if(D) newVal += "D";
if(H) newVal += "H";
if(I) newVal += "I";
if(L) newVal += "L";
if(M) newVal += "M";
if(N) newVal += "N";
if(S) newVal += "S";
if(T) newVal += "T";
if(U) newVal += "U";
if(W) newVal += "W";
if(X) newVal += "X";
newVal += "]";
this.getForm().itemChanged(this.getParentItem(), newVal, event);
}
});
//H
this.items.push(
{type:_CHECKBOX_,width:"40px",containerCssStyle:"width:40px", forceUpdate:true, ref:".",
labelLocation:_RIGHT_, label:"Home directory required", relevantBehavior:_PARENT_,
getDisplayValue:function (itemval) {
return (itemval && itemval.indexOf("H")>0);
},
elementChanged:function(isChecked, instanceValue, event) {
var U, D, H, I, L, M, N, S, T, W, X;
if(instanceValue) {
U = instanceValue.indexOf("U") > 0;
D = instanceValue.indexOf("D") > 0;
I = instanceValue.indexOf("I") > 0;
L = instanceValue.indexOf("L") > 0;
M = instanceValue.indexOf("M") > 0;
N = instanceValue.indexOf("N") > 0;
S = instanceValue.indexOf("S") > 0;
T = instanceValue.indexOf("T") > 0;
W = instanceValue.indexOf("W") > 0;
X = instanceValue.indexOf("X") > 0;
}
H = isChecked;
var newVal = "[";
if(D) newVal += "D";
if(H) newVal += "H";
if(I) newVal += "I";
if(L) newVal += "L";
if(M) newVal += "M";
if(N) newVal += "N";
if(S) newVal += "S";
if(T) newVal += "T";
if(U) newVal += "U";
if(W) newVal += "W";
if(X) newVal += "X";
newVal += "]";
this.getForm().itemChanged(this.getParentItem(), newVal, event);
}
});
//I
this.items.push(
{type:_CHECKBOX_,width:"40px",containerCssStyle:"width:40px", forceUpdate:true, ref:".",
labelLocation:_RIGHT_, label:"Inter-domain trust account", relevantBehavior:_PARENT_,
getDisplayValue:function (itemval) {
return (itemval && itemval.indexOf("I")>0);
},
elementChanged:function(isChecked, instanceValue, event) {
var U, D, H, I, L, M, N, S, T, W, X;
if(instanceValue) {
U = instanceValue.indexOf("U") > 0;
D = instanceValue.indexOf("D") > 0;
H = instanceValue.indexOf("H") > 0;
L = instanceValue.indexOf("L") > 0;
M = instanceValue.indexOf("M") > 0;
N = instanceValue.indexOf("N") > 0;
S = instanceValue.indexOf("S") > 0;
T = instanceValue.indexOf("T") > 0;
W = instanceValue.indexOf("W") > 0;
X = instanceValue.indexOf("X") > 0;
}
I = isChecked;
var newVal = "[";
if(D) newVal += "D";
if(H) newVal += "H";
if(I) newVal += "I";
if(L) newVal += "L";
if(M) newVal += "M";
if(N) newVal += "N";
if(S) newVal += "S";
if(T) newVal += "T";
if(U) newVal += "U";
if(W) newVal += "W";
if(X) newVal += "X";
newVal += "]";
this.getForm().itemChanged(this.getParentItem(), newVal, event);
}
});
//L
this.items.push(
{type:_CHECKBOX_,width:"40px",containerCssStyle:"width:40px", forceUpdate:true, ref:".",
labelLocation:_RIGHT_, label:"Account has been auto-blocked", relevantBehavior:_PARENT_,
getDisplayValue:function (itemval) {
return (itemval && itemval.indexOf("L")>0);
},
elementChanged:function(isChecked, instanceValue, event) {
var U, D, H, I, L, M, N, S, T, W, X;
if(instanceValue) {
U = instanceValue.indexOf("U") > 0;
D = instanceValue.indexOf("D") > 0;
H = instanceValue.indexOf("H") > 0;
I = instanceValue.indexOf("I") > 0;
M = instanceValue.indexOf("M") > 0;
N = instanceValue.indexOf("N") > 0;
S = instanceValue.indexOf("S") > 0;
T = instanceValue.indexOf("T") > 0;
W = instanceValue.indexOf("W") > 0;
X = instanceValue.indexOf("X") > 0;
}
L = isChecked;
var newVal = "[";
if(D) newVal += "D";
if(H) newVal += "H";
if(I) newVal += "I";
if(L) newVal += "L";
if(M) newVal += "M";
if(N) newVal += "N";
if(S) newVal += "S";
if(T) newVal += "T";
if(U) newVal += "U";
if(W) newVal += "W";
if(X) newVal += "X";
newVal += "]";
this.getForm().itemChanged(this.getParentItem(), newVal, event);
}
});
//M
this.items.push(
{type:_CHECKBOX_,width:"40px",containerCssStyle:"width:40px", forceUpdate:true, ref:".",
labelLocation:_RIGHT_, label:"MNS logon account", relevantBehavior:_PARENT_,
getDisplayValue:function (itemval) {
return (itemval && itemval.indexOf("M")>0);
},
elementChanged:function(isChecked, instanceValue, event) {
var U, D, H, I, L, M, N, S, T, W, X;
if(instanceValue) {
U = instanceValue.indexOf("U") > 0;
D = instanceValue.indexOf("D") > 0;
H = instanceValue.indexOf("H") > 0;
I = instanceValue.indexOf("I") > 0;
L = instanceValue.indexOf("L") > 0;
N = instanceValue.indexOf("N") > 0;
S = instanceValue.indexOf("S") > 0;
T = instanceValue.indexOf("T") > 0;
W = instanceValue.indexOf("W") > 0;
X = instanceValue.indexOf("X") > 0;
}
M = isChecked;
var newVal = "[";
if(D) newVal += "D";
if(H) newVal += "H";
if(I) newVal += "I";
if(L) newVal += "L";
if(M) newVal += "M";
if(N) newVal += "N";
if(S) newVal += "S";
if(T) newVal += "T";
if(U) newVal += "U";
if(W) newVal += "W";
if(X) newVal += "X";
newVal += "]";
this.getForm().itemChanged(this.getParentItem(), newVal, event);
}
});
//N
this.items.push(
{type:_CHECKBOX_,width:"40px",containerCssStyle:"width:40px", forceUpdate:true, ref:".",
labelLocation:_RIGHT_, label:"Password not required", relevantBehavior:_PARENT_,
getDisplayValue:function (itemval) {
return (itemval && itemval.indexOf("N")>0);
},
elementChanged:function(isChecked, instanceValue, event) {
var U, D, H, I, L, M, N, S, T, W, X;
if(instanceValue) {
U = instanceValue.indexOf("U") > 0;
D = instanceValue.indexOf("D") > 0;
H = instanceValue.indexOf("H") > 0;
I = instanceValue.indexOf("I") > 0;
L = instanceValue.indexOf("L") > 0;
M = instanceValue.indexOf("M") > 0;
S = instanceValue.indexOf("S") > 0;
T = instanceValue.indexOf("T") > 0;
W = instanceValue.indexOf("W") > 0;
X = instanceValue.indexOf("X") > 0;
}
N = isChecked;
var newVal = "[";
if(D) newVal += "D";
if(H) newVal += "H";
if(I) newVal += "I";
if(L) newVal += "L";
if(M) newVal += "M";
if(N) newVal += "N";
if(S) newVal += "S";
if(T) newVal += "T";
if(U) newVal += "U";
if(W) newVal += "W";
if(X) newVal += "X";
newVal += "]";
this.getForm().itemChanged(this.getParentItem(), newVal, event);
}
});
//S
this.items.push(
{type:_CHECKBOX_,width:"40px",containerCssStyle:"width:40px", forceUpdate:true, ref:".",
labelLocation:_RIGHT_, label:"Server trust account", relevantBehavior:_PARENT_,
getDisplayValue:function (itemval) {
return (itemval && itemval.indexOf("S")>0);
},
elementChanged:function(isChecked, instanceValue, event) {
var U, D, H, I, L, M, N, S, T, W, X;
if(instanceValue) {
U = instanceValue.indexOf("U") > 0;
D = instanceValue.indexOf("D") > 0;
H = instanceValue.indexOf("H") > 0;
I = instanceValue.indexOf("I") > 0;
L = instanceValue.indexOf("L") > 0;
M = instanceValue.indexOf("M") > 0;
N = instanceValue.indexOf("N") > 0;
T = instanceValue.indexOf("T") > 0;
W = instanceValue.indexOf("W") > 0;
X = instanceValue.indexOf("X") > 0;
}
S = isChecked;
var newVal = "[";
if(D) newVal += "D";
if(H) newVal += "H";
if(I) newVal += "I";
if(L) newVal += "L";
if(M) newVal += "M";
if(N) newVal += "N";
if(S) newVal += "S";
if(T) newVal += "T";
if(U) newVal += "U";
if(W) newVal += "W";
if(X) newVal += "X";
newVal += "]";
this.getForm().itemChanged(this.getParentItem(), newVal, event);
}
});
//T
this.items.push(
{type:_CHECKBOX_,width:"40px",containerCssStyle:"width:40px", forceUpdate:true, ref:".",
labelLocation:_RIGHT_, label:"Temporary duplicate account", relevantBehavior:_PARENT_,
getDisplayValue:function (itemval) {
return (itemval && itemval.indexOf("T")>0);
},
elementChanged:function(isChecked, instanceValue, event) {
var U, D, H, I, L, M, N, S, T, W, X;
if(instanceValue) {
U = instanceValue.indexOf("U") > 0;
D = instanceValue.indexOf("D") > 0;
H = instanceValue.indexOf("H") > 0;
I = instanceValue.indexOf("I") > 0;
L = instanceValue.indexOf("L") > 0;
M = instanceValue.indexOf("M") > 0;
N = instanceValue.indexOf("N") > 0;
S = instanceValue.indexOf("S") > 0;
W = instanceValue.indexOf("W") > 0;
X = instanceValue.indexOf("X") > 0;
}
T = isChecked;
var newVal = "[";
if(D) newVal += "D";
if(H) newVal += "H";
if(I) newVal += "I";
if(L) newVal += "L";
if(M) newVal += "M";
if(N) newVal += "N";
if(S) newVal += "S";
if(T) newVal += "T";
if(U) newVal += "U";
if(W) newVal += "W";
if(X) newVal += "X";
newVal += "]";
this.getForm().itemChanged(this.getParentItem(), newVal, event);
}
});
//W
this.items.push(
{type:_CHECKBOX_,width:"40px",containerCssStyle:"width:40px", forceUpdate:true, ref:".",
labelLocation:_RIGHT_, label:"Workstation trust account", relevantBehavior:_PARENT_,
getDisplayValue:function (itemval) {
return (itemval && itemval.indexOf("W")>0);
},
elementChanged:function(isChecked, instanceValue, event) {
var U, D, H, I, L, M, N, S, T, W, X;
if(instanceValue) {
U = instanceValue.indexOf("U") > 0;
D = instanceValue.indexOf("D") > 0;
H = instanceValue.indexOf("H") > 0;
I = instanceValue.indexOf("I") > 0;
L = instanceValue.indexOf("L") > 0;
M = instanceValue.indexOf("M") > 0;
N = instanceValue.indexOf("N") > 0;
S = instanceValue.indexOf("S") > 0;
T = instanceValue.indexOf("T") > 0;
X = instanceValue.indexOf("X") > 0;
}
W = isChecked;
var newVal = "[";
if(D) newVal += "D";
if(H) newVal += "H";
if(I) newVal += "I";
if(L) newVal += "L";
if(M) newVal += "M";
if(N) newVal += "N";
if(S) newVal += "S";
if(T) newVal += "T";
if(U) newVal += "U";
if(W) newVal += "W";
if(X) newVal += "X";
newVal += "]";
this.getForm().itemChanged(this.getParentItem(), newVal, event);
}
});
Composite_XFormItem.prototype.initializeItems.call(this);
};
ZaSambaAcFlagsXFormItem.prototype.items = [];
|
const EC = protractor.ExpectedConditions;
class BasicPage {
constructor() {
this.colHeaderList = null;
}
get() {
browser.get('/basic.html');
browser.wait(EC.presenceOf($('.dt-body')), 5000);
}
getColHeaderIcon(index) {
if (!this.colHeaderList) {
this.loadColHeaderList();
}
return element(this.colHeaderList.row(index)).element(by.css('.sort-btn'));
}
isColSortedAsc(index) {
if (!this.colHeaderList) {
this.loadColHeaderList();
}
return this.getColHeaderIcon(index).getAttribute('class').then(classes => (
classes.split(' ').indexOf('sort-asc') !== -1
));
}
isColSortedDesc(index) {
if (!this.colHeaderList) {
this.loadColHeaderList();
}
return this.getColHeaderIcon(index).getAttribute('class').then(classes => (
classes.split(' ').indexOf('sort-desc') !== -1
));
}
isColSorted(index) {
if (!this.colHeaderList) {
this.loadColHeaderList();
}
return this.getColHeaderIcon(index).getAttribute('class').then((classes) => {
const splits = classes.split(' ');
for (let i = 0; i < splits.length; ++i) {
if (splits[i] === 'sort-asc' || splits[i] === 'sort-desc') {
return true;
}
}
return false;
});
}
loadColHeaderList() {
this.colHeaderList = by.repeater('column in header.columns[\'center\'] track by column.$id');
}
}
module.exports = BasicPage;
|
'use strict';
const jayson = require('jayson');
const server = new jayson.server({
add: function(params, callback) {
callback(null, params.a + params.b);
}
});
server.http().listen(3000);
|
var searchData=
[
['size',['SIZE',['../dc/dbb/ncd__global_8h.html#a70ed59adcb4159ac551058053e649640',1,'ncd_global.h']]]
];
|
import React, {PropTypes, Component} from 'react';
export default class ToolTip extends Component {
static propTypes = {
tooltip: PropTypes.object
}
render() {
let visibility='hidden';
let transform='';
let x=0;
let y=0;
let width=150,height=70;
let transformText='translate('+width/2+','+(height/2-5)+')';
let transformArrow='';
if(this.props.tooltip.display === true){
let position = this.props.tooltip.pos;
x= position.x;
y= position.y;
visibility='visible';
if(y>height){
transform='translate(' + (x-width/2) + ',' + (y-height-20) + ')';
transformArrow='translate('+(width/2-20)+','+(height-2)+')';
}else if(y<height){
transform='translate(' + (x-width/2) + ',' + (Math.round(y)+20) + ')';
transformArrow='translate('+(width/2-20)+','+0+') rotate(180,20,0)';
}
}else{
visibility='hidden'
}
return (
<g transform={transform}>
<rect class="shadow" is width={width} height={height} rx="5" ry="5" visibility={visibility} fill="#6391da" opacity=".9"/>
<polygon class="shadow" is points="10,0 30,0 20,10" transform={transformArrow}
fill="#6391da" opacity=".9" visibility={visibility}/>
<text is visibility={visibility} transform={transformText}>
<tspan is x="0" text-anchor="middle" font-size="15px" fill="#ffffff">{this.props.tooltip.data.key}</tspan>
<tspan is x="0" text-anchor="middle" dy="25" font-size="20px" fill="#a9f3ff">{this.props.tooltip.data.value+' visits'}</tspan>
</text>
</g>
);
}
}
|
(function (globals) {
var ASM = function (stdlib, ffi, heap) {
'use asm';
function f_ping() {
return;
}
return { f_ping: f_ping };
};
var asm = ASM(globals);
var adaptors = { ping: asm.f_ping };
globals.ASM = adaptors;
}(this));
|
'use strict';
const Firebase = require('firebase');
const BaseFirebaseService = require('./baseFirebaseService');
class AuthFirebaseService extends BaseFirebaseService {
constructor() {
super();
this.authRef = new Firebase(super.getBaseRefURL());
}
authUserWithGoogle(user, callback) {
console.log('attempting Firebase login...', user.idToken);
this.authRef.authWithOAuthToken('google', user.idToken, function(error, authData) {
if (error) {
console.log('Login Failed!', error);
} else {
console.log('Authenticated successfully with payload:', authData);
callback(authData);
}
});
}
authWithPassword(credentials) {
console.log('attempting user/pass Firebase login... ', credentials);
return this.authRef.authWithPassword(credentials).then((authData) => {
console.log('Authenticated successfully with payload:', authData);
return authData;
}).catch((error) => {
console.log('Login error: ', error);
return Promise.reject(error);
});
}
authWithToken(token) {
if(token) {
console.log('attempting token Firebase login... ', token);
return this.authRef.authWithCustomToken(token).then((authData) => {
console.log('Authenticated successfully with payload:', authData);
return authData;
}).catch((error) => {
console.log('Login error: ', error);
return Promise.reject(error);
});
} else {
return null;
}
}
logout() {
this.authRef.unauth();
}
}
module.exports = AuthFirebaseService;
|
/**
* express-file-autorouter
* Copyright(c) 2017 Perez Yuan <yzmspirit@gmail.com>
* version 1.0.1
* MIT Licensed
*/
'use strict';
const fs = require('fs');
const path = require('path');
function AutoRouter(options) {
this.options = Object.assign({
//routers path
routerPath: null,
// the express app object
app: null,
//routers alias
alias: {}
}, options)
this.allRouters = {};
this.init();
}
AutoRouter.prototype = {
init() {
let me = this;
let options = me.options;
if (!options.routerPath) {
throw new Error('Must need routerPath');
} else {
me.getFiles(me.options.routerPath);
}
},
getFiles(routerPath) {
let me = this;
let files = fs.readdirSync(routerPath);
me.createRouter(routerPath, files);
},
createRouter(routerPath, files) {
let me = this;
let app = me.options.app;
files.forEach((file) => {
let filePath = me.sepChange(path.join(routerPath, file));
if (fs.statSync(filePath).isDirectory()) {
me.getFiles(filePath)
} else {
// remove rootPath and suffix
let routerName = filePath.substring(
me.options.routerPath.length,
filePath.lastIndexOf('.')
);
let router = require(filePath);
if (me.isRouter(router)) {
routerName = me.options.alias[me.sepChange(routerName)] || routerName;
if (app) {
app.use(routerName, router);
} else {
console.log('No app!Please useing getRouters() method')
}
me.allRouters[routerName] = router;
}
}
});
},
sepChange(str) {
return str.split(path.sep).join('/');
},
isRouter(router) {
return typeof router.route === 'function';
},
getRouters() {
for(let key in this.allRouters) {
return this.allRouters;
}
return null;
// return {};
}
}
module.exports = AutoRouter; |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'liststyle', 'ka', {
armenian: 'სომხური გადანომრვა',
bulletedTitle: 'ღილებიანი სიის პარამეტრები',
circle: 'წრეწირი',
decimal: 'რიცხვებით (1, 2, 3, ..)',
decimalLeadingZero: 'ნულით დაწყებული რიცხვებით (01, 02, 03, ..)',
disc: 'წრე',
georgian: 'ქართული გადანომრვა (ან, ბან, გან, ..)',
lowerAlpha: 'პატარა ლათინური ასოებით (a, b, c, d, e, ..)',
lowerGreek: 'პატარა ბერძნული ასოებით (ალფა, ბეტა, გამა, ..)',
lowerRoman: 'რომაული გადანომრვცა პატარა ციფრებით (i, ii, iii, iv, v, ..)',
none: 'არაფერი',
notset: '<არაფერი>',
numberedTitle: 'გადანომრილი სიის პარამეტრები',
square: 'კვადრატი',
start: 'საწყისი',
type: 'ტიპი',
upperAlpha: 'დიდი ლათინური ასოებით (A, B, C, D, E, ..)',
upperRoman: 'რომაული გადანომრვა დიდი ციფრებით (I, II, III, IV, V, etc.)',
validateStartNumber: 'სიის საწყისი მთელი რიცხვი უნდა იყოს.'
} );
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import './style/lib/animate.css';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import reducer from './reducer';
import CRouter from './routes';
// redux 注入操作
const middleware = [thunk];
const store = createStore(reducer, applyMiddleware(...middleware));
console.log(store.getState());
ReactDOM.render(
<Provider store={store}>
<CRouter store={store} />
</Provider>
,
document.getElementById('root')
);
registerServiceWorker(); |
var Client = require('node-rest-client').Client;
var client = new Client();
var async = require('async');
var http = require('http');
var account = "Julie";
var apiKey = "41e8f9cd109d6c7a0ec679df2ccf50318ab2d053";
var publicApiKey = "80e5642726c76dd0390fdfa015c4fd17c0d00a1e";
// We'll use 10 concurrent HTTP clients
var socketsCountToUse = 10;
http.globalAgent.maxSockets = socketsCountToUse;
/*
* This parameters are used to control the experiments and specify how much data we want to create.
*/
var numberOfGivePointsRequests = 500;
// Initial participation counter
var initialCounter;
/*
* This function returns a function that we can use with the async.js library.
*/
function getTransactionPOSTRequestFunction() {
return function(callback) {
var requestData = {
headers:{
"Content-Type": "application/json"
},
data: {
},
requestConfig:{
'timeout' : 5000,
keepAlive: false
},
responseConfig:{
'timeout' : 5000
}
};
console.log("PUT /users/" + account + "/counters/appreciation/1");
var req = client.put("http://127.0.0.1:8080/gamification/api/v1/apps/" + apiKey + "/users/" + account + "/counters/participation/1", requestData, function(data, response) {
var error = null;
var result = {
requestData: requestData,
data: data,
response: response
};
callback(error, result);
});
req.on('error', function(err){
console.error("Network error: " + err);
});
req.on('requestTimeout',function(req){
console.log('request has expired');
req.abort();
});
req.on('responseTimeout',function(res){
console.log('response has expired');
});
}
}
/*
* Prepare an array of HTTP request functions. We will pass these to async.parallel
*/
var requests = [];
for (var i=0; i<numberOfGivePointsRequests; i++) {
requests.push(
getTransactionPOSTRequestFunction()
);
};
// Will retrieve the initial counter value
function retrieveInitialCounterValue(callback) {
var requestData = {
headers:{
"Accept": "application/json"
}
};
client.get("http://127.0.0.1:8080/gamification/api/v1/apps/" + publicApiKey + "/users/" + account + "/performance", requestData, function(data, response) {
initialCounter = data.counters.participation;
callback(null, "Done");
});
};
/*
* POST transaction requests in parallel
*/
function postTransactionRequestsInParallel(callback) {
console.log("\n\n==========================================");
console.log("Getting transaction requests in parallel");
console.log("------------------------------------------");
var numberOfUnsuccessfulResponses = 0;
async.parallel(requests, function(err, results) {
for (var i=0; i<results.length; i++) {
if (results[i].response.statusCode < 200 || results[i].response.statusCode >= 300) {
console.log("Result " + i + ": " + results[i].response.statusCode);
numberOfUnsuccessfulResponses++;
} else {
console.log("OK: Got " + results[i].response.statusCode);
}
}
callback(null, results.length + " transaction POSTs have been sent. " + numberOfUnsuccessfulResponses + " have failed.");
});
}
/*
* Comparing the performance counter on the server to what it should be
*/
function checkValues(callback) {
console.log("\n\n==========================================");
console.log("Comparing client-side and server-side stats");
console.log("------------------------------------------");
var requestData = {
headers:{
"Accept": "application/json"
}
};
client.get("http://127.0.0.1:8080/gamification/api/v1/apps/" + publicApiKey + "/users/" + account + "/performance", requestData, function(data, response) {
if (data.badges.length != 1) {
console.log("Number of badges is invalid. Should be 1. Test failed.");
} else {
console.log("Badge obtained. Pass.");
}
var counterValueNow = data.counters.participation;
var expectedCounterValue = initialCounter + numberOfGivePointsRequests;
console.log("Participation counter before test: " + initialCounter);
console.log("Participation counter now: " + counterValueNow);
if (counterValueNow !== expectedCounterValue) {
console.log("Participation counter error: should be " + expectedCounterValue + ", is " + counterValueNow + ". Test failed.");
} else {
console.log("All points have been registered. Pass.");
}
callback(null, "Done");
});
}
async.series([
retrieveInitialCounterValue,
postTransactionRequestsInParallel,
checkValues
], function(err, results) {
console.log("\n\n==========================================");
console.log("Summary");
console.log("------------------------------------------");
//console.log(err);
console.log(results);
});
|
export { default } from 'rsg-components/Argument/ArgumentRenderer';
|
/*
Copyright (c) 2013
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";
angular.module(
'pot',
[
'ui.bootstrap',
'ngTable',
'pot.services',
'pot.filters',
'pot.directives',
'pot.controllers'
]
)
.run(function ($rootScope, food, recipes) {
angular.forEach(food, function(item, id) {
// add an img property (URL) to each food item
// pointing to the food icon
item.id = id;
item.img = 'static/img/food/' + id + '.png';
if (!item.hasOwnProperty('health')) item.health = 0;
if (!item.hasOwnProperty('hunger')) item.hunger = 0;
if (!item.hasOwnProperty('sanity')) item.sanity = 0;
if (!item.hasOwnProperty('perish')) item.perish = 0;
});
angular.forEach(recipes, function(recipe, id) {
// add an img property (URL) to each recipe
// pointing to the recipe icon
recipe.id = id;
recipe.img = 'static/img/recipes/' + id + '.png';
});
});
}());
|
"use strict";
define(
function ()
{
var module = {
color:null,
scheme:"lightly"
};
module.CHANGE = 'onBackgroundChange'
return module;
});
|
let emoticons,
codesMap = {},
primaryCodesMap = {},
regexp,
metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g,
entityMap;
entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
let definition = {
"smile": {"title": "Smile", "codes": [":)", ":=)", ":-)"]},
"sad-smile": {"title": "Sad Smile", "codes": [":(", ":=(", ":-("]},
"big-smile": {"title": "Big Smile", "codes": [":D", ":=D", ":-D", ":d", ":=d", ":-d"]}
};
function escape(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
export class EmoticonsParser {
constructor() {
"use strict";
this.define(definition);
}
/**
* Define emoticons set.
*
* @param {Object} data
*/
define(data) {
var name, i, codes, code,
patterns = [];
for (name in data) {
codes = data[name].codes;
for (i in codes) {
code = codes[i];
codesMap[code] = name;
// Create escaped variants, because mostly you want to parse escaped
// user text.
codesMap[escape(code)] = name;
if (i == 0) {
primaryCodesMap[code] = name;
}
}
}
for (code in codesMap) {
patterns.push('(' + code.replace(metachars, "\\$&") + ')');
}
regexp = new RegExp(patterns.join('|'), 'g');
emoticons = data;
}
/**
* Replace emoticons in text.
*
* @param {String} text
* @param {Function} [fn] optional template builder function.
*/
replace(text, fn) {
return text.replace(regexp, (code)=> {
var name = codesMap[code];
return (fn || this.tpl)(name, code, emoticons[name].title);
});
}
/**
* Get primary emoticons as html string in order to display them later as overview.
*
* @param {Function} [fn] optional template builder function.
* @return {String}
*/
toString(fn) {
var code,
str = '',
name;
for (code in primaryCodesMap) {
name = primaryCodesMap[code];
str += (fn || this.tpl)(name, code, emoticons[name].title);
}
return str;
}
/**
* Build html string for emoticons.
*
* @param {String} name
* @param {String} code
* @param {String} title
* @return {String}
*/
tpl(name, code, title) {
return '<span class="emoticon emoticon-' + name + '" title="' + title + '">' +
code + '</span>';
}
}
|
/**
* Tasks that run during "build" plus WATCH task;
*/
module.exports = function (grunt) {
grunt.registerTask('default', [
'build'
]);
};
|
'use strict';
var fs = require('fs');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var readFile = require("html-wiring")
module.exports = yeoman.generators.Base.extend({
constructor: function() {
yeoman.generators.Base.apply(this, arguments);
this.option('skip-welcome-message', {
desc: 'Skips the welcome message',
type: Boolean
});
this.option('skip-install', {
desc: 'Skips the installation of dependencies',
type: Boolean
});
this.option('skip-install-message', {
desc: 'Skips the message after the installation of dependencies',
type: Boolean
});
},
initializing: function() {
this.pkg = require('../../package.json');
},
prompting: function() {
var done = this.async();
if (!this.options['skip-welcome-message']) {
this.log(yosay('Out of the box I include Express,mongoose,Node.js,AngularJS,jQuery,HTML5 Boilerplate and Bootstrap.'));
}
var prompts = [{
type: 'checkbox',
name: 'mainframeworks',
message: 'Would you like to use mongoose ?',
choices: [{
name: 'mongoose',
value: 'includeMongooes',
}]
}, {
type: 'list',
name: 'bootstapSelect',
message: 'Would you like Bootstrap or Sass - Bootstrap ?',
choices: [{
name: 'Sass',
value: 'includeSass',
}, {
name: 'Bootstrap',
value: 'includeBootstrap',
}]
}, {
type: 'checkbox',
name: 'lib',
message: 'What more lib would you like ?',
choices: [{
name: 'Moment',
value: 'includeMoment',
checked: true
}, {
name: 'Underscore',
value: 'includeUnderscore',
checked: true
}, {
name: 'Angular UI Bootstrap',
value: 'includeABootstrap',
checked: true
}]
}
];
this.prompt(prompts, function(answers) {
var mainframeworks = answers.mainframeworks;
var lib = answers.lib;
var bootstrap = answers.bootstapSelect;
var hasMainframeworks = function(mainframework) {
return mainframeworks.indexOf(mainframework) !== -1;
};
var hasLib = function(libs) {
return lib.indexOf(libs) !== -1;
};
var hasBootstrap = function(boot) {
return bootstrap.indexOf(boot) !== -1;
};
// manually deal with the response, get back and store the results.
// we change a bit this way of doing to automatically do this in the self.prompt() method.
this.includeMongooes = hasMainframeworks('includeMongooes');
this.includeABootstrap = hasLib('includeABootstrap');
this.includeUnderscore = hasLib('includeUnderscore');
this.includeMoment = hasLib('includeMoment');
this.includeJQuery = true //hasLib('includeJQuery');
this.includeSass = hasBootstrap('includeSass');
this.includeBootstrap = hasBootstrap('includeBootstrap');
done();
}.bind(this));
},
writing: {
/* packageJSON: function() {
//this.template('_package.json', 'package.json');
//this.copy('_package.json', 'package.json');
},*/
bower: function() {
var bower = {
name: this.appname,
private: true,
dependencies: {},
exportsOverride: {}
};
var bs = 'bootstrap' + (this.includeSass ? '-sass' : '');
bower.dependencies[bs] = 'latest';
bower.dependencies.angular = 'latest';
bower.dependencies['angular-resource'] = '1.4.8';
bower.dependencies['angular-cookies'] = '1.4.8';
bower.dependencies['angular-route'] = '1.4.8';
bower.dependencies['angular-ui-router'] = '1.4.8';
bower.dependencies['angular-mocks'] = '1.4.8';
bower.dependencies['angular-cookies'] = '1.4.8';
bower.dependencies['angular-sanitize'] = '1.4.8';
if (this.includeABootstrap) {
bower.dependencies['angular-bootstrap'] = 'latest';
}
if (this.includeUnderscore) {
bower.dependencies['underscore'] = 'latest';
}
if (this.includeMoment) {
bower.dependencies['moment'] = 'latest';
}
if (this.includeJQuery) {
bower.dependencies.jquery = 'latest';
}
this.fs.copy(
this.templatePath('bowerrc'),
this.destinationPath('.bowerrc')
);
this.write('bower.json', JSON.stringify(bower, null, 2));
},
jshint: function() {
this.fs.copy(
this.templatePath('jshintrc'),
this.destinationPath('.jshintrc')
);
},
mainStylesheet: function() {},
app: function() {
//JS
this.copy('angular/js/controllers/user/user_controller.js', 'public/js/controllers/user/user_controller.js');
this.copy('angular/js/directives/global/global_directive.js', 'public/js/directives/global/global_directive.js');
this.copy('angular/js/services/user/user_service.js', 'public/js/services/user/user_service.js');
this.copy('angular/js/app.js', 'public/js/app.js');
this.copy('angular/js/config.js', 'public/js/config.js');
this.copy('angular/js/init.js', 'public/js/init.js');
//css
this.copy('angular/styles/style.css', 'public/styles/style.css');
this.copy('angular/styles/style_mobile.css', 'public/styles/style_mobile.css');
this.copy('angular/styles/animate.css', 'public/styles/animate.css');
//view
this.copy('angular/views/header.html', 'public/views/header.html');
this.copy('angular/views/footer.html', 'public/views/footer.html');
this.copy('angular/views/index.html', 'public/views/index.html');
this.copy('angular/views/user/user.html', 'public/views/user/user.html');
this.copy('angular/images/banner.png', 'public/images/banner.png');
//
this.copy('angular/humans.txt', 'public/humans.txt');
this.copy('angular/robots.txt', 'public/robots.txt');
//Controller
this.copy('app/controllers/index.js', 'app/controllers/index.js');
/* this.copy('app/views/includes/head.jade', 'app/views/includes/head.jade')
this.copy('app/views/includes/foot.jade', 'app/views/includes/foot.jade');*/
if (this.includeMongooes) {
//Mongooes model
this.copy('app/models/list.js', 'app/models/list.js');
this.copy('config/query/query.js', 'app/query/query.js');
} else {
this.copy('app/models/list.js', 'app/models/list.js');
}
if (this.includeSass) {
this.copy('app/styles/_customVariables.scss', 'app/styles/_customVariables.scss');
this.copy('app/styles/app.scss', 'app/styles/app.scss');
}
//JADE
this.copy('app/views/layouts/default.jade', 'app/views/layouts/default.jade');
this.copy('app/views/404.jade', 'app/views/404.jade');
this.copy('app/views/500.jade', 'app/views/500.jade');
this.copy('app/views/index.jade', 'app/views/index.jade');
//Config Env
this.copy('config/env/all.js', 'config/env/all.js');
this.copy('config/env/development.json', 'config/env/development.json');
this.copy('config/env/production.json', 'config/env/production.json');
this.copy('config/env/test.json', 'config/env/test.json');
this.copy('config/env/travis.json', 'config/env/travis.json');
//config
this.copy('config/config.js', 'config/config.js');
if (this.includeMongooes && this.includeSass) {
this.copy('config/express_mongooes_sass.js', 'config/express.js');
} else if (this.includeSass) {
this.copy('config/express_sass.js', 'config/express.js');
} else if (this.includeMongooes) {
this.copy('config/express_mongooes.js', 'config/express.js');
} else {
this.copy('config/express.js', 'config/express.js');
}
this.copy('config/routes.js', 'config/routes.js');
this.copy('server.js', 'server.js');
var projectDir = this.sourceRoot() //process.cwd();
var footPath = projectDir + "/app/views/includes/foot.jade",
footFile = readFile.readFileAsString(footPath);
var headPath = projectDir + "/app/views/includes/head.jade",
headFile = readFile.readFileAsString(headPath);
var pakagePath = projectDir + "/_package.json",
pakageFile = readFile.readFileAsString(pakagePath);
var pakage = JSON.parse(pakageFile);
if (this.includeUnderscore && footFile) {
footFile += "\n script(type = 'text/javascript', src = '/lib/underscore/underscore.js')";
}
if (this.includeMoment && footFile) {
footFile += "\n script(type = 'text/javascript', src = '/lib/moment/moment.js')";
}
if (this.includeBootstrap && footFile) {
footFile += "\n link(rel='stylesheet', href='/lib/bootstrap/dist/css/bootstrap.min.css')";
footFile += "\n script(type = 'text/javascript', src = '/lib/bootstrap/dist/js/bootstrap.min.js')";
}
if (this.includeSass && footFile) {
footFile += "\n script(type = 'text/javascript', src = '/lib/bootstrap-sass/assets/javascripts/bootstrap.min.js')";
}
if (this.includeSass && headFile) {
headFile += "\n link(rel='stylesheet', href='/styles/app.css')";
}
if (pakage.dependencies) {
if (this.includeMongooes) {
pakage.dependencies['mongoose'] = 'latest';
pakage.dependencies['connect-mongo'] = '0.8.2';
pakage.dependencies['express-session'] = 'latest';
}
if (this.includeMongoosastic) {
pakage.dependencies['mongoosastic'] = 'latest';
}
if (this.includeSass) {
pakage.dependencies['node-sass-middleware'] = 'latest';
}
}
this.write('package.json', JSON.stringify(pakage, null, 2));
this.write('app/views/includes/foot.jade', footFile);
this.write('app/views/includes/head.jade', headFile);
//this.copy('app/views/includes/head.jade', 'app/views/includes/head.jade')
//this.copy('app/views/includes/foot.jade', 'app/views/includes/foot.jade');
}
},
install: function() {
var howToInstall =
'\nAfter running ' +
chalk.yellow.bold('npm install & bower install') + '.';
if (this.options['skip-install']) {
this.log(howToInstall);
return;
}
this.installDependencies({
skipMessage: this.options['skip-install-message'],
skipInstall: this.options['skip-install'],
callback: function() {
}.bind(this)
});
this.on('end', function() {
console.log("Happy Coding !!!");
console.log(this.sourceRoot())
}.bind(this));
}
});
|
/*!
* jQuery tinySwitch Plugin v0.2
* Copyright 2013 darkfe(i@darkfe.com)
* Released under the MIT license
* Date: 2013/7/21
*/
(function($){
var FLAG = 'tinySwitch_' +new Date();
/*
解析 data-tinySwitch 属性里的规则
语法:
checked ? action1 : action2 next~#container
value==1 ? action1 : action2 next~#container
*/
var parseRule = function(rule){
var exprPattern = /(\w+)(?:([=><!$*^~]{1,2})((?:&?(?:\d+|'(?:\\'|[^'])+'))+))?/;
var mutipleValue = /(?:\d+|'(?:\\'|[^'])+')/g;
var rulePattern = /(?:;\s*)?(?:@(\w+)\s)?((?:(?:value|index)[=><!$*^~]{1,2}(?:\d+|'(?:\\'|[^'])+')(?:&(?:\d+|'(?:\\'|[^'])+'))*)|(?:checked|selected))\s\?\s(\S+)(?:\s\:\s(\S+))?\s(?:((?:\w+\.)*\w+)~)?((?:[^;']+|'(?:\\'|[^'])+')+)/ig;
var current = null;
var ruleList = [];
while(current = rulePattern.exec(rule)){
var expr = current[2].match(exprPattern);
ruleList.push({
group : current[1],
expr : {
keyword : expr[1],
operator : expr[2],
value : $.map((expr[3] || '').match(mutipleValue) || [], function(value, index){
if(value.indexOf('\'')===0){
return value.slice(1,-1);
}else{
return value;
}
}).sort()
},
ifDo : (current[3]||'').split('&'),
elseDo : (current[4]||'').split('&'),
pos : (current[5]||'') ? (current[5]||'').split('.') : [],
selector : current[6],
rule : rule
});
}
return ruleList;
}
var runSwitch = function(rule, sender){
var ruleActions = parseRule(rule);
var groupName = sender.attr('name');
var selectedControls = groupName ?
(
sender.is(':radio') ?
sender :
$('[name="' + groupName + '"]')
) : sender;
var value =
(sender.is('select') ? sender.find(':selected') : selectedControls.filter(':checked'))
.map(function(){
return $(this).val();
}).get().sort();
$.each(ruleActions, function(index, ruleItem){
var result = false;
var target = $(document);
var tempTarget = sender;
var tempLevel;
var elements = null;
var loopTimes = 0;
var compare = function(valueA, operator, valueB){
var result = true;
if($.type(valueA) == 'array' && $.type(valueB) == 'array'){
if(valueA.length != valueB.length){
return false;
}
$.each(valueA,function(index, value){
if(compare(value, operator, valueB[index]) === false){
return result = false;
}
});
return result;
}
var intValueA = parseInt(valueA,10)||0;
var intValueB = parseInt(valueB,10)||0;
var strValueA = valueA+'';
switch(operator){
case '==':
return valueA == valueB;
case '!=':
return valueA != valueB;
case '>':
return intValueA > intValueB;
case '<':
return intValueA < intValueB;
//case '*=':
//return strValueA.indexOf(valueB) != -1;
//case '$=':
//return strValueA.lastIndexOf(valueB) === strValueA.length - 1;
//case '^=':
//return strValueA.indexOf(valueB) === 0;
case '~' :
return new RegExp(valueB).test(strValueA);
case '!~' :
return !(new RegExp(valueB).test(strValueA));
}
}
switch(ruleItem.expr.keyword){
case 'selected' :
result = true;
break;
case 'checked':
result = sender.is(':checked');
break;
case 'value':
result = compare(value, ruleItem.expr.operator, ruleItem.expr.value);
break;
}
while(ruleItem.pos.length){
tempLevel = ruleItem.pos.shift().match(/^(\d*)([a-zA-Z]+)$/);
loopTimes = !tempLevel[1] ? 1 : (parseInt(tempLevel[1],10) || 0);
if(tempTarget[tempLevel = tempLevel[2]]){
while(loopTimes){
tempTarget = tempTarget[tempLevel]();
loopTimes--;
}
}
target = tempTarget;
}
elements = $(target).find(ruleItem.selector).add($(target).filter(ruleItem.selector));
$.each(ruleItem[(result && ruleItem.ifDo.length) ? 'ifDo' : 'elseDo'],function(index, item){
if(ACTIONS[item]){
ACTIONS[item].call(elements, elements, sender)
}
});
});
}
/*
tinySwitch
*/
var tinySwitch = function(elements){
return $(elements).each(function(){
var target = $(this);
//保证不重复绑定
if(target.data(FLAG)){
return;
}
target
//添加上标记
.data(FLAG,'1')
.on(tinySwitch.eventSwitching,function(){
var that = $(this);
var groupName = that.attr('name');
var rule =
that.find(':selected').attr(tinySwitch.propRule) ||
that.attr(tinySwitch.propRule);
if(groupName && GROUP[groupName]){
rule = GROUP[groupName];
}
runSwitch(rule, that);
})
.on(target.is('select') ? 'change' : 'click',function(){
var th = 'triggerHandler', that = $(this);
//如果beforeswitch返回false, 停止switch执行
if(that[th](tinySwitch.eventBeforeSwitch) === false){
return;
}
that[th](tinySwitch.eventSwitching);
that[th](tinySwitch.eventAfterSwitch);
})
.filter('select, :checkbox, :radio:checked')
.triggerHandler(tinySwitch.eventSwitching);
});
}
var CONTROLS = 'input,select,textarea';
/*
默认支持的四个规则
*/
var ACTIONS = {
'show' : function(elements){
elements.show();
},
'hide' : function(elements){
elements.hide();
},
'enabled' : function(elements){
elements.filter(CONTROLS).add(elements.find(CONTROLS)).attr('disabled', false);
},
'disabled' : function(elements){
elements.filter(CONTROLS).add(elements.find(CONTROLS)).attr('disabled', true);
},
'focus' : function(elements){
elements.eq(0).focus();
}
};
/*
Group rules
*/
var GROUP = {};
$.extend(tinySwitch,{
propRule : 'data-tsrule',
eventSwitching : 'switching',
eventBeforeSwitch : 'beforeswitch',
eventAfterSwitch : 'afterswitch',
//eventGroupSwitching : 'group.switching',
//eventGroupBeforeSwitch : 'group.beforeswitch',
//eventGroupAfterSwitch : 'group.afterswitch',
formNameGroup : true,
action : function(config){
$.extend(ACTIONS,config);
},
group : function(config){
$.extend(GROUP, config);
}
});
//jQuery 插件
$.fn.tinyswitch = function(){
tinySwitch(this);
return this;
};
/*
attach to jQuery object
*/
$.tinyswitch = tinySwitch;
//默认加载
$(function(){
var nameElements = $();
if(tinySwitch.formNameGroup){
nameElements = $('[name]');
$.each(GROUP, function(name){
nameElements.filter('[name="' + name + '"])').tinyswitch();
});
}
/*
收集group
*/
$('[' + tinySwitch.propRule + ']').each(function(){
var ruleStr = $(this).attr(tinySwitch.propRule);
var groupName = '';
if(groupName = ruleStr.match(/^@(\w+)/i)){
GROUP[groupName[1]] = ruleStr.split(/^@\w+\s/)[1];
$(nameElements).filter('[name="' + groupName[1] + '"]').tinyswitch();
}else{
if($(this).is('option')){
$(this).closest('select').tinyswitch();
}else{
$(this).tinyswitch();
}
}
});
});
}(jQuery)); |
/**
* Created by Kamaron on 4/22/2015.
*/
'use strict';
var index = require('../general/index');
var comp_dao = require('../../dao/competition_dao');
var RegistrationPageErrorCollection = require('../../models/RegistrationPageErrorCollection');
exports.get = function (req, res) {
var params = {
title: 'USU ACM Competition Framework',
subtitle: 'Version 0.3.1 - Zora',
redirect_url: '/register-team' + (req.query.id !== undefined ? ('?id=' + req.query.id) : ''),
comp_id: req.query.id,
page_errors: new RegistrationPageErrorCollection(),
field_values: {}
};
exports.fill_data(req, params, function (data) {
if (data.error) {
res.render('./error', data);
} else {
res.render('./general/register-team', data);
}
});
};
exports.fill_data = function (req, data, cb) {
data = data || {};
data.include_scripts = data.include_scripts || [];
data.include_scripts.push('/js/register_switch.js');
// Grab information required for registration (max team size, etc)
if (isNaN(parseInt(data.comp_id))) {
finish_this_func();
} else {
comp_dao.get_competition_data(data.comp_id, function (err, res) {
if (err) {
data.error = err;
} else {
data.comp_data = res;
}
finish_this_func();
});
}
function finish_this_func() {
index.fill_data(req, data, function (new_data) {
cb(new_data);
});
}
}; |
var selected_nodes = [];
var node_selection_frames = [];
var node_resize_frame = null;
////////////////////////////////////////////////////////////
//
// operations for selected nodes
//
function getSelectedNodes() {
return selected_nodes;
}
function setSelectedNodes(n) {
console.log("setNodeSelection()");
clearSelectedNodes();
appendSelectedNodes(n);
}
function appendSelectedNodes(n) {
if (n == null) return;
console.log("appendNodeSelection()");
clearSelectedEdge();
n.select(true);
selected_nodes.push(n);
// append node selection frame
var f = new NodeSelectionFrame(svg_selection_layer, n);
node_selection_frames.push(f);
if (node_selection_frames.length == 2) {
node_selection_frames[0].setStrokeColor("#ff0000");
node_selection_frames[1].setStrokeColor("#4400ff");
}
else {
node_selection_frames.forEach(function (n) {
n.setStrokeColor("#ff0000");
});
}
// for resize frame
if (selected_nodes.length == 1) {
createNodeResizeFrame(n, f);
}
else {
deleteNodeResizeFrame();
}
// for inspector
if (selected_nodes.length == 1) {
inspector.setObject(n);
}
else {
inspector.clearSelection();
}
}
function clearSelectedNodes() {
console.log("clearSelectedNodes()");
nodes.forEach(function(n) {
n.select(false);
});
selected_nodes = [];
node_selection_frames.forEach(function(n) {
n.dispose();
});
deleteNodeResizeFrame();
cleanupObjests();
// for inspector
inspector.clearSelection();
}
function moveSelectedNodes(dx, dy) {
setModifiedFlag();
selected_nodes.forEach(function(n) {
n.move(dx, dy);
});
node_selection_frames.forEach(function(n) {
n.move(dx, dy);
});
if (node_resize_frame != null) {
node_resize_frame.move(dx, dy);
}
// for edges
updateEdges();
}
function quantizeSelectedNodes() {
selected_nodes.forEach(function(n) {
n.quantize();
});
node_selection_frames.forEach(function(n) {
n.quantize();
});
if (node_resize_frame != null) {
node_resize_frame.quantize();
}
// for edges
updateEdges();
}
function deleteSelectedNodes() {
setModifiedFlag();
selected_nodes.forEach(function(n) {
deleteNode(n);
});
clearSelectedNodes();
// cleanup
cleanupObjests();
}
//////////////////////////////////////////////////
//
// operations for resize frame
//
function createNodeResizeFrame(node, frame) {
node_resize_frame = new NodeResizeFrame(svg_selection_layer, node, frame);
}
function deleteNodeResizeFrame() {
if (node_resize_frame != null) {
node_resize_frame.dispose();
node_resize_frame = null;
}
}
//////////////////////////////////////////////////
//
// NodeSelectionFrame class
//
function NodeSelectionFrame(svg, node) {
this.node = node;
this.w = node.w;
this.h = node.h;
SVGObject.call(this, svg, node.x, node.y);
}
NodeSelectionFrame.prototype = Object.create(SVGObject.prototype);
NodeSelectionFrame.constructor = NodeSelectionFrame;
NodeSelectionFrame.prototype.createSVGObject = function(svg) {
console.log("NodeSelectionFrame.createSVGObject()");
// create rect object
var obj = svg.append("rect")
.attr("id", this.id)
.attr("rx", 0)
.attr("ry", 0)
.style("stroke", "#ff0000")
.style("stroke-width", 3)
.style("fill", "none")
return obj;
}
NodeSelectionFrame.prototype.update = function() {
this.obj.attr("x", this.x)
.attr("y", this.y)
.attr("width", this.w)
.attr("height", this.h);
}
NodeSelectionFrame.prototype.quantize = function() {
this.x = quantize(this.x);
this.y = quantize(this.y);
this.w = quantize(this.w);
this.h = quantize(this.h);
this.update();
}
NodeSelectionFrame.prototype.setStrokeColor = function(color) {
this.obj.style("stroke", color);
}
//////////////////////////////////////////////////
//
// NodeResizeFrame class
//
function NodeResizeFrame(svg, node, node_selection) {
this.node = node;
this.node_selection = node_selection;
this.w = node.w;
this.h = node.h;
SVGObject.call(this, svg, node.x, node.y);
}
NodeResizeFrame.prototype = Object.create(SVGObject.prototype);
NodeResizeFrame.constructor = NodeResizeFrame;
NodeResizeFrame.prototype.createSVGObject = function(svg) {
console.log("NodeResizeFrame.createSVGObject()");
// create rect object
var obj = svg.append("g").attr("id", this.id);
this.c0 = obj.append("circle")
.attr("cx", this.x)
.attr("cy", this.y)
.attr("r", 10)
.style("stroke", "none")
.style("fill", "#ff00ff")
this.c1 = obj.append("circle")
.attr("cx", this.x + this.w)
.attr("cy", this.y)
.attr("r", 10)
.style("stroke", "none")
.style("fill", "#ff00ff")
this.c2 = obj.append("circle")
.attr("cx", this.x)
.attr("cy", this.y + this.h)
.attr("r", 10)
.style("stroke", "none")
.style("fill", "#ff00ff")
this.c3 = obj.append("circle")
.attr("cx", this.x + this.w)
.attr("cy", this.y + this.h)
.attr("r", 10)
.style("stroke", "none")
.style("fill", "#ff00ff")
// 下側のオブジェクトにクリックイベントを通知しないようにする
var stopPropagation = function() {
console.log("NodeResizeFrame.stopPropagation()");
d3.event.stopPropagation();
};
this.c0.on('click', stopPropagation);
this.c1.on('click', stopPropagation);
this.c2.on('click', stopPropagation);
this.c3.on('click', stopPropagation);
// drag operation
var that = this;
var drag0 = d3.behavior.drag()
.on("dragstart", function() {that.onDragStarted()})
.on("drag", function() {that.onDragged0()})
.on("dragend", function() {that.onDragEnded()});
this.c0.call(drag0);
var drag1 = d3.behavior.drag()
.on("dragstart", function() {that.onDragStarted()})
.on("drag", function() {that.onDragged1()})
.on("dragend", function() {that.onDragEnded()});
this.c1.call(drag1);
var drag2 = d3.behavior.drag()
.on("dragstart", function() {that.onDragStarted()})
.on("drag", function() {that.onDragged2()})
.on("dragend", function() {that.onDragEnded()});
this.c2.call(drag2);
var drag3 = d3.behavior.drag()
.on("dragstart", function() {that.onDragStarted()})
.on("drag", function() {that.onDragged3()})
.on("dragend", function() {that.onDragEnded()});
this.c3.call(drag3);
return obj;
}
NodeResizeFrame.prototype.dispose = function() {
this.obj.remove();
this.obj = null;
this.node = null;
this.node_selection = null;
}
NodeResizeFrame.prototype.quantize = function() {
this.x = quantize(this.x);
this.y = quantize(this.y);
this.w = quantize(this.w);
this.h = quantize(this.h);
this.update();
}
NodeResizeFrame.prototype.update = function() {
this.c0.attr("cx", this.x ).attr("cy", this.y);
this.c1.attr("cx", this.x + this.w).attr("cy", this.y);
this.c2.attr("cx", this.x ).attr("cy", this.y + this.h);
this.c3.attr("cx", this.x + this.w).attr("cy", this.y + this.h);
this.node_selection.x = this.x;
this.node_selection.y = this.y;
this.node_selection.w = this.w;
this.node_selection.h = this.h;
this.node_selection.update();
this.node.x = this.x;
this.node.y = this.y;
this.node.w = this.w;
this.node.h = this.h;
this.node.update();
}
NodeResizeFrame.prototype.onDragStarted = function() {
console.log("DraggableObject.onDragStarted:n=" + this);
d3.event.sourceEvent.stopPropagation();
}
NodeResizeFrame.prototype.onDragged0 = function() {
setModifiedFlag();
this.x += d3.event.dx;
this.y += d3.event.dy;
this.w -= d3.event.dx;
this.h -= d3.event.dy;
this.update();
}
NodeResizeFrame.prototype.onDragged1 = function() {
setModifiedFlag();
this.x += 0;
this.y += d3.event.dy;
this.w += d3.event.dx;
this.h -= d3.event.dy;
this.update();
}
NodeResizeFrame.prototype.onDragged2 = function() {
setModifiedFlag();
this.x += d3.event.dx;
this.y += 0;
this.w -= d3.event.dx;
this.h += d3.event.dy;
this.update();
}
NodeResizeFrame.prototype.onDragged3 = function() {
setModifiedFlag();
this.x += 0;
this.y += 0;
this.w += d3.event.dx;
this.h += d3.event.dy;
this.update();
}
NodeResizeFrame.prototype.onDragEnded = function() {
console.log("DraggableObject.onDragEnded:n=" + this);
setModifiedFlag();
d3.event.sourceEvent.stopPropagation();
this.quantize();
}
|
'use strict';
var conf = require('./protractor.functional.conf.js');
conf.config.onPrepare = function(){
require('jasmine-reporters');
jasmine.getEnv().addReporter(
new jasmine.JUnitXmlReporter('report/ci', true, true)
);
}
module.exports = conf;
|
var POINT_COUNT = 40;
var TRIG_XMIN = -2*Math.PI;
var TRIG_XMAX = 2*Math.PI;
var trigx = Array(POINT_COUNT);
var sin = Array(POINT_COUNT);
var cos = Array(POINT_COUNT);
var tan = Array(POINT_COUNT);
var atan = Array(POINT_COUNT);
var ints = Array(POINT_COUNT);
var squares = Array(POINT_COUNT);
for (var i=0; i<POINT_COUNT; i++) {
var x = TRIG_XMIN + (TRIG_XMAX-TRIG_XMIN)*i/(POINT_COUNT-1);
//log("in trig x=" + x);
trigx[i] = x;
sin[i] = Math.sin(x);
cos[i] = Math.cos(x);
tan[i] = Math.tan(x);
atan[i] = Math.atan(x);
ints[i] = i;
squares[i] = i*i;
}
var testFunctions = {
'category': function (p) {
p.plotLine(['A','BB','CCC','DDDD','MMMMM', 'CCC', 'A']);
p.yScale.placement = 'on'
p.render();
},
'boolean': function (p) {
p.plotLine([true, false, true, true, false, false, true]);
p.render();
},
'simpleLine' : function(p) {
p.plotLine(squares)
p.render()
},
'simpleSquares' : function(p) {
p.plotLine([0,1,2,3,4,5,6], [0,1,4,9,16,25,36]);
p.render()
},
'xyLine' : function(p) {
p.plotLine(trigx, sin)
p.render()
},
'multiPlot' : function(p) {
p.plotLine(trigx, sin)
p.plotLine(trigx, cos)
p.render()
},
'styleLine' : function(p) {
p.strokeStyle = "#00E";
p.plotLine(trigx, sin);
p.strokeStyle = "#E00";
p.plotLine(trigx, cos);
p.strokeStyle = "rgba(100, 0, 100, .5)";
p.lineWidth = '5'
p.dasharray = ".5,1,2";
p.dashoffset = 2;
p.plotLine(trigx, atan);
p.render()
},
'functionPlot' : function(p) {
p.plotFunction('Math.atan(x)', 'x', -8, 8);
p.render()
},
'trickyFunctionPlot' : function(p) {
p.plotFunction('Math.sin(1/x)', 'x', -4, 4);
p.render()
},
'decorations' : function(p) {
p.strokeStyle = 'rgba(255, 50, 50, 0.5)';
p.plotLine(trigx, sin);
p.strokeStyle = 'rgba(50, 50, 255, 0.5)';
p.plotLine(trigx, cos);
p.strokeStyle = "#888";
p.fillStyle = "#888";
p.setYScale(-1.5,1.5)
p.setXScale(-7,7)
var locations = [-2*Math.PI, -Math.PI, 0, Math.PI, 2*Math.PI]
p.setXTicks(locations)
p.setXTickLabels(locations, ['-2pi', '-pi', '0', 'pi', '2pi'])
locations = [-1, -0.5, 0, 0.5, 1]
p.setYTicks(locations)
p.setYTickLabels(locations)
p.fontSize = '10';
p.fontFamily="Verdana, Arial, Helvetica, Sans"
p.setXAxisTitle("Time (ns)");
p.setYAxisTitle("Voltage (V)");
p.render();
},
'seti': function(p) {
var voltages = [1.7, 1.5, 1.375, 1.25, 1.1, 0.95, 0.75, 0.5]
var time_ns = []
var left = []
var right = []
for (var i=0; i<100; i++) {
time_ns[i] = i/3.0
var r = Math.floor(Math.random()*voltages.length)
right[i] = voltages[r]
var l = Math.floor(Math.random()*voltages.length)
left[i] = voltages[l]
}
p.strokeStyle = "#C6C6C6";
p.fillStyle = "#C6C6C6";
p.fontSize = '7px';
//p.fontFamily = "Arial, SunSans-Regular, sans-serif"
p.addBox();
p.box.addDefaults();
p.setYScale(voltages[voltages.length-1]-0.1, voltages[0]+0.1);
p.setYTicks(voltages);
p.setYTickLabels(voltages);
p.fontSize = '10px';
p.fontFamily = "Helvetica, Geneva, Arial, SunSans-Regular, sans-serif"
p.setXAxisTitle("Time (ns)");
p.setYAxisTitle("Voltage (V)");
p.strokeStyle = 'rgba(255, 75, 75, 0.9)';
p.plotLine(time_ns, left);
p.strokeStyle = 'rgba(75, 75, 255, 0.9)';
p.plotLine(time_ns, right);
p.render();
},
'ticks' : function(p) {
p.plotLine(trigx, sin)
p.setXTicks(trigx)
p.setYTicks(sin)
p.removeXTickLabels()
p.removeYTickLabels()
p.render()
},
'axisstyles' : function(p) {
p.fillStyle = "#950";
var box = p.addBox();
box.addDefaults();
p.strokeStyle = "rgba(255,0,0,.5)";
p.plotFunction("Math.sin(x)", "x", -2 * Math.PI, 2 * Math.PI);
p.strokeStyle = "rgba(0,0,255,.5)";
p.plotFunction("Math.cos(x)", "x", -2 * Math.PI, 2 * Math.PI);
p.render();
},
'floatingaxes' : function(p) {
p.strokeStyle = "rgba(255,0,0,.5)";
p.plotFunction("Math.sin(x)", "x", -2 * Math.PI, 2 * Math.PI);
p.strokeStyle = "rgba(0,0,255,.5)";
p.plotFunction("Math.cos(x)", "x", -2 * Math.PI, 2 * Math.PI);
p.setXAxis(-.6)
p.setYAxis(-4)
p.render();
},
'dependentaxes' : function(p) {
p.addBox()
p.addView()
p.setXScale(-10, 10)
p.setYScale(-7, 7)
var colors = ['#990000', '#009900', '#000099'];
for (var i=0; i<3; i++) {
p.strokeStyle = colors[i];
p.fillStyle = colors[i];
p.addXAxis('top')
p.addXTicks('auto', 'top')
p.addXTickLabels('auto', 'auto', 'top')
p.addXTicks([-5, 0, 5], 'bottom')
p.addXTickLabels([-5, 0, 5], 'auto', 'bottom')
p.addXAxis('bottom')
p.addXTicks('auto', 'top')
p.addXTickLabels('auto', 'auto', 'top')
p.addXTicks([-5, 0, 5], 'bottom')
p.addXTickLabels([-5, 0, 5], 'auto', 'bottom')
p.addYAxis('right')
p.addYTicks('auto', 'left')
p.addYTickLabels('auto', 'auto', 'left')
p.addYTicks([-5, 0, 5], 'right')
p.addYTickLabels([-5, 0, 5], 'auto', 'right')
p.addYAxis('left')
p.addYTicks('auto', 'left')
p.addYTickLabels('auto', 'auto', 'left')
p.addYTicks([-5, 0, 5], 'right')
p.addYTickLabels([-5, 0, 5], 'auto', 'right')
}
p.strokeStyle = "rgba(255,0,0,.5)";
p.plotFunction("Math.sin(x)", "x", -2 * Math.PI, 2 * Math.PI);
p.strokeStyle = "rgba(0,0,255,.5)";
p.plotFunction("Math.cos(x)", "x", -2 * Math.PI, 2 * Math.PI);
p.render();
},
'independentaxes' : function(p) {
p.addBox()
var colors = ['#990000', '#009900', '#000099'];
for (var i=0; i<3; i++) {
p.strokeStyle = colors[i];
p.fillStyle = colors[i];
p.addView()
p.setXScale(-i*3-1, i*3+1)
p.setYScale(-i*3-1, i*3+1)
p.addXAxis('top')
p.addXTicks('auto', 'top')
p.addXTickLabels('auto', 'auto', 'top')
p.addXTicks([-5, 0, 5], 'bottom')
p.addXTickLabels([-5, 0, 5], 'auto', 'bottom')
p.addXAxis('bottom')
p.addXTicks('auto', 'top')
p.addXTickLabels('auto', 'auto', 'top')
p.addXTicks([-5, 0, 5], 'bottom')
p.addXTickLabels([-5, 0, 5], 'auto', 'bottom')
p.addYAxis('right')
p.addYTicks('auto', 'left')
p.addYTickLabels('auto', 'auto', 'left')
p.addYTicks([-5, 0, 5], 'right')
p.addYTickLabels([-5, 0, 5], 'auto', 'right')
p.addYAxis('left')
p.addYTicks('auto', 'left')
p.addYTickLabels('auto', 'auto', 'left')
p.addYTicks([-5, 0, 5], 'right')
p.addYTickLabels([-5, 0, 5], 'auto', 'right')
p.plotFunction("Math.sin(x)", "x", -2 * Math.PI, 2 * Math.PI);
}
p.render();
},
'logplot' : function(p) {
p.logplot(ints.slice(1,ints.length-1), squares.slice(1,squares.length-1))
p.render()
},
'loglogplot' : function(p) {
p.loglogplot(ints.slice(1,ints.length-1), squares.slice(1,squares.length-1))
p.render()
},
'draw_on_plot' : function(p) {
p.plotFunction("Math.sin(x)", "x", -2 * Math.PI, 2 * Math.PI);
p.render();
p.circle(Math.PI/2, Math.sin(Math.PI/2), 10);
},
/*
'label' : function(p) {
p.plotFunction("Math.sin(x)", "x", -2 * Math.PI, 2 * Math.PI);
//p.label(Math.PI/2, Math.sin(Math.PI/2), "sin(pi/2)");
//p.label(Math.PI/2, Math.sin(-Math.PI/2), "sin(-pi/2)", 'arrow');
//p.label(Math.PI/2, Math.sin(3*Math.PI/2), "sin(3pi/2)", 'dot');
//p.label(Math.PI/2, Math.sin(-3*Math.PI/2), "sin(-3pi/2)", 'line');
p.render();
},
'post_style' : function(p) {
p.plotFunction("Math.sin(x)", "x", -2 * Math.PI, 2 * Math.PI);
p.box.background = 'red'
//p.xAxis.strokeStyle = 'blue'
//p.xGrid.spacing = .3
//p.yGrid.fillStyle = "rgba(100, 0, 100, .5)";
p.render();
},
*/
'date_plot' : function(p) {
d = datetime.now()
dates = []
data = []
for (var i=0; i<20; i++) {
// Add days
date = datetime.addPeriod(d, {day: i*9})
var s = datetime.toISOTimestamp(date)
var s2 = datetime.toISOTimestamp(datetime.parse(s))
var ord = datetime.ordinalDay(date)
log(s, s2, ord)
dates.push(s)
//data.push(Math.random())
data.push(ord)
}
p.plot(dates, data)
p.render();
},
'date_simple' : function(p) {
var dates
dates = ['2007-05-01 20:20:30', '2007-05-17 13:47:19']
dates = ['2007-04-21 13:19:09', '2007-04-27 04:30:16']
var data = [-1, 1]
p.plot(dates, data);
p.render();
},
'date_plot_temp' : function(p) {
var reasonable_temp = function(row) {
return row[1] < 40
}
var tempfilt = filter(reasonable_temp, temp)
var cols = SVGPlot.prototype.transpose(tempfilt)
p.plot(cols[0], cols[1])
p.render();
},
'multi_date' : function(p) {
var points = 20
var dates_array = [[]] // Three lists of dates for x-axis
var categories = ['a','bb','ccc']
var real = [] // One list of reals
var category = [] // One list of categories
for (var i=0; i<points; i++) {
real.push(Math.random()*10)
var select = Math.floor(Math.random()*categories.length)
category.push( categories[select] )
for (var j=0; j<3; j++) {
dates_array.push([])
var date = datetime.parse('2007-05-01 20:20:30')
var period = {
day: Math.floor(Math.random()*10),
hour: Math.floor(Math.random()*24)
}
date = datetime.addPeriod(date, period)
dates_array[j].push(date)
}
}
//p.setupBox(1,3)
}
};
type = 'plot'
|
angular.module('CareyHinoki').
directive('navigateToSection', function () {
return {
link: function (scope, element, attrs) {
var element = $(element);
element.delegate('a', 'click', function (event) {
var nav_element = $(this),
nav_href = nav_element.attr('href'),
hash_index = nav_href.lastIndexOf('#');
if (hash_index == -1) {
return false;
}
var hash = nav_href.substring(hash_index, nav_href.length),
to_element = $(hash),
scroll_top = to_element.offset().top; // minus menu
$('html, body').animate({
// vcard indicates screen size max-width: 767px
scrollTop: scroll_top + ($('#vcard').is(':visible') ? 0 : -50)
}, 800);
event.preventDefault();
});
}
};
}); |
import React from 'react';
//
import * as Basic from '../../../components/basic';
import * as Advanced from '../../../components/advanced';
import { TreeNodeManager, SecurityManager } from '../../../redux';
const manager = new TreeNodeManager();
/**
* Extended tree node attributes
*
* @author Radek Tomiška
*/
export default class NodeEav extends Basic.AbstractContent {
constructor(props, context) {
super(props, context);
}
getContentKey() {
return 'content.tree.node.eav';
}
getNavigationKey() {
return 'tree-node-eav';
}
render() {
const { entityId } = this.props.match.params;
//
return (
<Advanced.EavContent
formableManager={manager}
entityId={entityId}
contentKey={this.getContentKey()}
showSaveButton={SecurityManager.hasAuthority('TREENODE_UPDATE')}/>
);
}
}
|
const startWhistle = require('./start');
const util = require('./util');
const getIntercept = require('./intercept');
const loadModule = require;
exports.getServerIp = util.getServerIp;
exports.getRandomPort = util.getPort;
exports.startWhistle = exports.startProxy = startWhistle;
exports.isRunning = util.isRunning;
exports.getProxy = util.getProxy;
exports.request = (options, cb) => util.getProxy().request(options, cb);
exports.connect = (options, cb) => util.getProxy().connect(options, cb);
exports.proxyRequest = (...args) => util.getProxy().proxyRequest.apply(null, args);
exports.createKoa2Middleware = exports.createMiddleware = (options, filter) => {
const middleware = loadModule('./createMiddleware')(options, filter, util.getProxy(options));
Object.assign(middleware, util.getProxy(options));
return middleware;
};
exports.createKoaMiddleware = (options, filter) => {
const intercept = getIntercept(options);
filter = util.getFilter(options, filter);
const middleware = function* (next) {
let res = intercept(this.req, filter);
if (res !== false) {
res = yield res;
}
if (res === false) {
return yield next;
}
this.status = res.statusCode;
this.set(res.headers);
if (res.pipe) {
this.body = res;
}
};
Object.assign(middleware, util.getProxy(options));
return middleware;
};
exports.createExpressMiddleware = (options, filter) => {
const intercept = getIntercept(options);
filter = util.getFilter(options, filter);
const middleware = (req, res, next) => {
const result = intercept(req, filter);
const errorHandler = () => res.destroy();
if (result === false) {
req.removeListener('error', errorHandler);
res.removeListener('error', errorHandler);
return next();
}
req.on('error', errorHandler);
res.on('error', errorHandler);
result.then((_res) => {
if (_res === false) {
return next();
}
res.writeHead(_res.statusCode, _res.headers);
if (_res.pipe) {
_res.pipe(res);
_res.on('error', errorHandler);
} else {
res.end();
}
}, err => res.status(500).send(err.stack));
};
Object.assign(middleware, util.getProxy(options));
return middleware;
};
|
var pkgcloud = require('pkgcloud'),
logging = require('../../../common/logging'),
config = require('../../../common/config'),
_ = require('underscore');
var log = logging.getLogger(process.env.PKGCLOUD_LOG_LEVEL || 'debug');
var client = pkgcloud.providers.rackspace.loadbalancer.createClient(config.getConfig('rackspace', 1));
client.on('log::*', logging.logFunction);
client.getLoadBalancer(process.argv[2], function (err, lb) {
if (err) {
log.error(err);
return;
}
lb.getStats(function (err, stats) {
if (err) {
log.error(err);
return;
}
log.info(stats);
});
});
|
module.exports = {
disallowBlockExpansion: true,
disallowIdLiterals: true,
disallowDuplicateAttributes: true,
disallowClassLiterals: true,
disallowLegacyMixinCall: true,
disallowMultipleLineBreaks: true,
validateTemplateString: true,
}
|
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import history from 'utils/history';
import { resetError } from 'actions';
import DevTools from 'containers/DevTools';
import configureStore from './store/configureStore';
import TournamentBrackets from 'containers/RootApp/TournamentBrackets';
const store = configureStore();
history.listen(() => {
// reset error message on route change
store.dispatch(resetError());
});
const App = () => (
<Provider store={store}>
<div>
<TournamentBrackets />
<DevTools />
</div>
</Provider>
);
render(<App />, document.getElementById('app')); |
var test = require('tape');
var path = require('path');
var level = require('level');
var mkdirp = require('mkdirp');
var through = require('through2');
var concat = require('concat-stream');
var tmpdir = path.join(
require('osenv').tmpdir(),
'forkdb-test-' + Math.random()
);
mkdirp.sync(tmpdir);
var db = level(path.join(tmpdir, 'db'));
var fdb = require('../')(db, { dir: path.join(tmpdir, 'blob') });
var hashes = [
'9c0564511643d3bc841d769e27b1f4e669a75695f2a2f6206bca967f298390a0',
'1ffcdc9a4e47ee447ec72f38744f1ddd6b200a86389895aa249c9fc49bc04289',
'b705af981e52c0fbfe9845ac1ba6d2a4f75a4677f1b6264b3b358315afe8f202',
'6d4aeea6772e7bfc715fb42d0679f3bf2ffab77afc50588fd0264694d11ebf51'
];
test('populate non-array prev', function (t) {
var docs = [
{ hash: hashes[0], body: 'beep boop\n', meta: { key: 'blorp' } },
{ hash: hashes[1], body: 'BEEP BOOP\n', meta: {
key: 'blorp',
prev: { hash: hashes[0], key: 'blorp' }
} },
{ hash: hashes[2], body: 'BeEp BoOp\n', meta: {
key: 'blorp',
prev: { hash: hashes[0], key: 'blorp' }
} },
{ hash: hashes[3], body: 'BEEPITY BOOPITY\n', meta: {
key: 'blorp',
prev: [
{ hash: hashes[1], key: 'blorp' },
{ hash: hashes[2], key: 'blorp' }
]
} }
];
t.plan(docs.length * 2);
(function next () {
if (docs.length === 0) return;
var doc = docs.shift();
var w = fdb.createWriteStream(doc.meta, function (err, hash) {
t.ifError(err);
t.equal(hash, doc.hash);
next();
});
w.end(doc.body);
})();
});
test('in order', function (t) {
t.plan(10);
var expected = {};
expected.heads = [ { hash: hashes[3] } ];
expected.tails = [ { hash: hashes[0] } ];
expected.list = [
{ hash: hashes[0], meta: { key: 'blorp' } },
{ hash: hashes[1], meta: {
key: 'blorp',
prev: { hash: hashes[0], key: 'blorp' }
} },
{ hash: hashes[2], meta: {
key: 'blorp',
prev: { hash: hashes[0], key: 'blorp' }
} },
{ hash: hashes[3], meta: {
key: 'blorp',
prev: [
{ hash: hashes[1], key: 'blorp' },
{ hash: hashes[2], key: 'blorp' }
]
} }
];
expected.links = {};
expected.links[hashes[0]] = [
{ key: 'blorp', hash: hashes[1] },
{ key: 'blorp', hash: hashes[2] }
];
expected.links[hashes[1]] = [
{ key: 'blorp', hash: hashes[3] }
];
expected.links[hashes[2]] = [
{ key: 'blorp', hash: hashes[3] }
];
check(t, fdb, expected);
fdb.createReadStream(hashes[0]).pipe(concat(function (body) {
t.equal(body.toString('utf8'), 'beep boop\n');
}));
fdb.createReadStream(hashes[1]).pipe(concat(function (body) {
t.equal(body.toString('utf8'), 'BEEP BOOP\n');
}));
fdb.createReadStream(hashes[2]).pipe(concat(function (body) {
t.equal(body.toString('utf8'), 'BeEp BoOp\n');
}));
fdb.createReadStream(hashes[3]).pipe(concat(function (body) {
t.equal(body.toString('utf8'), 'BEEPITY BOOPITY\n');
}));
});
function collect (cb) {
var rows = [];
return through.obj(write, end);
function write (row, enc, next) { rows.push(row); next() }
function end () { cb(rows) }
}
function check (t, fdb, expected) {
fdb.heads('blorp').pipe(collect(function (rows) {
t.deepEqual(rows, sort(expected.heads), 'heads');
}));
fdb.tails('blorp').pipe(collect(function (rows) {
t.deepEqual(rows, sort(expected.tails), 'tails');
}));
Object.keys(expected.links).forEach(function (hash) {
fdb.links(hash).pipe(collect(function (rows) {
t.deepEqual(rows, sort(expected.links[hash]), 'links');
}));
});
fdb.list().pipe(collect(function (rows) {
t.deepEqual(rows, sort(expected.list), 'list');
}));
}
function sort (xs) {
return xs.sort(cmp);
function cmp (a, b) {
if (a.hash !== undefined && a.hash < b.hash) return -1;
if (a.hash !== undefined && a.hash > b.hash) return 1;
}
}
|
/// <reference path="../imports.ts" />
//# sourceMappingURL=imainscope.js.map
|
import { moduleFor, test } from 'ember-qunit';
/* global expect */
moduleFor('service:dialogs', 'Unit | Service | dialogs', {
// Specify the other units that are required for this test.
// needs: ['service:foo']
});
test('alert | cordova', function(assert) {
var service = this.subject();
expect(4);
window.navigator.notification = {};
window.navigator.notification.alert = function(message, alertCallback, title, buttonName){
assert.equal(message, 'Some alert message');
assert.equal(title, 'Title');
assert.equal(buttonName, 'OK');
alertCallback();
};
service.alert({
title: 'Title',
message: 'Some alert message',
button: 'OK'
}).then(function(){
assert.ok(true);
});
});
test('alert | fallback', function(assert) {
var service = this.subject({
alertFallback: function(message, title, buttonName){
assert.equal(message, 'Some alert message');
assert.equal(title, 'Title');
assert.equal(buttonName, 'OK');
}
});
expect(4);
delete(window.navigator.notification);
service.alert({
title: 'Title',
message: 'Some alert message',
button: 'OK'
}).then(function(){
assert.ok(true);
});
});
test('confirm | cordova', function(assert) {
var service = this.subject();
expect(4);
window.navigator.notification = {};
window.navigator.notification.confirm = function(message, confirmCallback, title, buttonLabels) {
assert.equal(message, 'Something to confirm');
assert.equal(title, 'Confirm');
assert.deepEqual(buttonLabels, ['OK', 'Cancel']);
confirmCallback(1); // Pressed OK
};
service.confirm({
title: 'Confirm',
message: 'Something to confirm',
buttons: [
'OK',
'Cancel'
]
}).then(function(buttonIndex){
assert.equal(buttonIndex, 1);
});
});
test('confirm | fallback', function(assert) {
var service = this.subject({
confirmFallback: function(message, title, buttonLabels){
assert.equal(message, 'Something to confirm');
assert.equal(title, 'Confirm');
assert.deepEqual(buttonLabels, ['OK', 'Cancel']);
return 1; // Simulate pressed OK
}
});
expect(4);
delete(window.navigator.notification);
service.confirm({
title: 'Confirm',
message: 'Something to confirm',
buttons: [
'OK',
'Cancel'
]
}).then(function(buttonIndex){
assert.equal(buttonIndex, 1);
});
});
test('prompt | cordova', function(assert) {
var service = this.subject();
expect(6);
window.navigator.notification = {};
window.navigator.notification.prompt = function(message, promptCallback, title, buttonLabels, defaultText) {
assert.equal(message, 'Something to write');
assert.equal(title, 'Prompt');
assert.equal(defaultText, 'foo');
assert.deepEqual(buttonLabels, ['OK', 'Cancel']);
promptCallback({
buttonIndex: 1,
input1: 'bar'
}); // Pressed OK
};
service.prompt({
title: 'Prompt',
message: 'Something to write',
defaultText: 'foo',
buttons: [
'OK',
'Cancel'
]
}).then(function(result){
let { buttonIndex, text } = result;
assert.equal(buttonIndex, 1);
assert.equal(text, 'bar');
});
});
test('prompt | fallback', function(assert) {
var service = this.subject({
promptFallback: function(message, title, buttonLabels, defaultText){
assert.equal(message, 'Something to write');
assert.equal(title, 'Prompt');
assert.equal(defaultText, 'foo');
assert.deepEqual(buttonLabels, ['OK', 'Cancel']);
return {
text: 'bar',
buttonIndex: 1 // Simulate pressed OK
};
}
});
expect(6);
delete(window.navigator.notification);
service.prompt({
title: 'Prompt',
message: 'Something to write',
defaultText: 'foo',
buttons: [
'OK',
'Cancel'
]
}).then(function(result){
let { text, buttonIndex } = result;
assert.equal(buttonIndex, 1);
assert.equal(text, 'bar');
});
});
|
const icons = {
arrowBack: 'M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z',
menu: 'M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z',
info: 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z',
code: 'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z',
assessment: 'M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z',
business: 'M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z',
search: 'M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'
};
export default icons;
|
'use strict';
const DI = require('@scola/di');
const Connection = require('./lib/connection');
const Connector = require('./lib/connector');
const Helper = require('./lib/helper');
const Message = require('./lib/message');
const Socket = require('./lib/socket');
class Module extends DI.Module {
configure() {
this.addModule(Connection.Module);
this.addModule(Connector.Module);
this.addModule(Helper.Module);
this.addModule(Message.Module);
this.addModule(Socket.Module);
}
}
module.exports = {
Connection,
Connector,
Helper,
Message,
Module,
Socket
};
|
// spec.js
describe('Testing {Resources} CRUD Module', function() {{
var {Resource} = function() {{
{protractor_page_objects}
this.get = function() {{
browser.get('http://localhost:5000/');
}};
this.toast = function(message){{
$('.btn.btn-primary').click() // css selectors http://angular.github.io/protractor/#/api?view=build$
.then(function() {{
var EC = protractor.ExpectedConditions;
var toastMessage = $('.toast-message');
browser.wait(EC.visibilityOf(toastMessage), 6000) //wait until toast is displayed
.then(function(){{
expect(toastMessage.getText()).toBe(message);
}});
}});
}}
}};
it('Should add a new {Resource}', function() {{
var {resource} = new {Resource}();
// Get {resources} URL
{resource}.get();
// Goto the new menu
element(by.linkText('{Resources}')).click();
element(by.linkText('New')).click();
// Fill in the Fields
{protractor_add_elments}
//Expectations
{resource}.toast("{Resource} saved successfully");
}});
it('Should edit a {Resource}', function() {{
var {resource} = new {Resource}();
{resource}.get();
//Goto the edit menu
element(by.linkText('{Resources}')).click();
element(by.id('editButton')).click();
// Fill in the fields
{protractor_edit_elments}
//Expectations
{resource}.toast("Update was a success");
}});
it('Should delete a {Resource}', function() {{
browser.get('http://localhost:5000/');
element(by.linkText('{Resources}')).click();
element(by.id('deleteButton')).click()
.then(function(){{
var EC = protractor.ExpectedConditions;
var toastMessage = $('.toast-message');
browser.wait(EC.visibilityOf(toastMessage), 60) //wait until toast is displayed
.then(function(){{
expect(toastMessage.getText()).toBe("{Resource} deleted successfully")
}});
}});
}});
}});
|
/* global assert, process, setup, suite, test */
var entityFactory = require('../helpers').entityFactory;
suite('hand-controls', function () {
var component;
var el;
setup(function (done) {
el = entityFactory();
el.addEventListener('componentinitialized', function (evt) {
if (evt.detail.name !== 'hand-controls') { return; }
component = el.components['hand-controls'];
done();
});
el.setAttribute('hand-controls', '');
});
suite('determineGesture', function () {
test('makes no gesture if nothing touched or pressed', function () {
component.pressedButtons['grip'] = false;
component.pressedButtons['trigger'] = false;
component.pressedButtons['touchpad'] = false;
component.pressedButtons['thumbstick'] = false;
component.pressedButtons['menu'] = false;
component.pressedButtons['AorX'] = false;
component.pressedButtons['BorY'] = false;
component.pressedButtons['surface'] = false;
assert.notOk(component.determineGesture());
});
test('makes point gesture', function () {
var trackedControls;
el.setAttribute('tracked-controls', '');
trackedControls = el.components['tracked-controls'];
trackedControls.controller = {id: 'Foobar', connected: true};
component.pressedButtons['grip'] = true;
component.pressedButtons['trigger'] = false;
component.pressedButtons['trackpad'] = true;
component.pressedButtons['thumbstick'] = false;
component.pressedButtons['menu'] = false;
component.pressedButtons['AorX'] = false;
component.pressedButtons['BorY'] = false;
component.pressedButtons['surface'] = false;
assert.equal(component.determineGesture(), 'Point');
});
test('makes point gesture on vive', function () {
var trackedControls;
el.setAttribute('tracked-controls', '');
trackedControls = el.components['tracked-controls'];
trackedControls.controller = {id: 'OpenVR Gamepad', connected: true};
component.pressedButtons['grip'] = false;
component.pressedButtons['trigger'] = false;
component.pressedButtons['trackpad'] = true;
component.pressedButtons['thumbstick'] = false;
component.pressedButtons['menu'] = false;
component.pressedButtons['AorX'] = false;
component.pressedButtons['BorY'] = false;
component.pressedButtons['surface'] = false;
assert.equal(component.determineGesture(), 'Point');
});
test('makes fist gesture', function () {
var trackedControls;
el.setAttribute('tracked-controls', '');
trackedControls = el.components['tracked-controls'];
trackedControls.controller = {id: 'Foobar', connected: true};
component.pressedButtons['grip'] = true;
component.pressedButtons['trigger'] = true;
component.pressedButtons['trackpad'] = true;
component.pressedButtons['thumbstick'] = false;
component.pressedButtons['menu'] = false;
component.pressedButtons['AorX'] = false;
component.pressedButtons['BorY'] = false;
component.pressedButtons['surface'] = false;
assert.equal(component.determineGesture(), 'Fist');
});
test('makes fist gesture on vive', function () {
var trackedControls;
el.setAttribute('tracked-controls', '');
trackedControls = el.components['tracked-controls'];
trackedControls.controller = {id: 'OpenVR Gamepad', connected: true};
component.pressedButtons['grip'] = true;
component.pressedButtons['trigger'] = false;
component.pressedButtons['trackpad'] = false;
component.pressedButtons['thumbstick'] = false;
component.pressedButtons['menu'] = false;
component.pressedButtons['AorX'] = false;
component.pressedButtons['BorY'] = false;
component.pressedButtons['surface'] = false;
assert.equal(component.determineGesture(), 'Fist');
component.pressedButtons['grip'] = false;
component.pressedButtons['trigger'] = true;
assert.equal(component.determineGesture(), 'Fist');
component.pressedButtons['grip'] = true;
component.pressedButtons['trigger'] = true;
assert.equal(component.determineGesture(), 'Fist');
component.pressedButtons['trackpad'] = true;
assert.equal(component.determineGesture(), 'Fist');
component.pressedButtons['menu'] = true;
assert.equal(component.determineGesture(), 'Fist');
});
});
});
|
"use strict";
/*
* Copyright 2017 Palantir Technologies, Inc. All rights reserved.
*/
Object.defineProperty(exports, "__esModule", { value: true });
|
'use strict';
let path = require('path');
let port = 8000;
let srcPath = path.join(__dirname, '/../src');
let publicPath = '/assets/';
let additionalPaths = [];
let webpack = require('webpack');
module.exports = {
additionalPaths: additionalPaths,
port: port,
debug: true,
output: {
path: path.join(__dirname, '/../dist/assets'),
filename: 'app.js',
publicPath: publicPath
},
devServer: {
contentBase: './src/',
historyApiFallback: true,
hot: true,
port: port,
publicPath: publicPath,
noInfo: false
},
resolve: {
extensions: [
'',
'.js',
'.jsx'
],
alias: {
actions: srcPath + '/actions/',
components: srcPath + '/components/',
sources: srcPath + '/sources/',
stores: srcPath + '/stores/',
styles: srcPath + '/styles/',
config: srcPath + '/config/' + process.env.REACT_WEBPACK_ENV
}
},
module: {
preLoaders: [{
test: /\.(js|jsx)$/,
include: srcPath,
loader: 'eslint-loader'
}],
loaders: [
{
test: /\.css$/,
loader: 'style-loader!css-loader!postcss-loader'
},
{
test: /\.sass/,
loader: 'style-loader!css-loader!postcss-loader!sass-loader?outputStyle=expanded&indentedSyntax'
},
{
test: /\.scss/,
loader: 'style-loader!css-loader!postcss-loader!sass-loader?outputStyle=expanded'
},
{
test: /\.less/,
loader: 'style-loader!css-loader!postcss-loader!less-loader'
},
{
test: /\.styl/,
loader: 'style-loader!css-loader!postcss-loader!stylus-loader'
},
{
test: /\.(png|jpg|gif|woff|woff2|ttf|eot|svg)$/,
loader: 'url-loader?limit=8192&name=[name].[hash:6].[ext]'
}
]
},
postcss: function () {
return [];
}
}; |
define({
"viewer": {
"loading": {
"step1": "LOO LAADIMINE",
"step2": "ANDMETE LAADIMINE",
"step3": "ALUSTAN TUURI",
"loadBuilder": "LÜLITU KOOSTAMISREŽIIMILE",
"redirectSignIn": "SUUNAN ÜMBER SISSELOGIMISE LEHELE",
"redirectSignIn2": "(Teid suunatakse peale sisselogimist siia)",
"fail": "Kaardi tuuri laadimine ebaõnnestus. Vabandame.",
"failButton": "Proovi uuesti"
},
"errors": {
"boxTitle": "Esines tõrge",
"portalSelf": "Totaalne viga: Portaali seadistuse hankimine nurjus",
"invalidConfig": "Totaalne viga: vigane konfiguratsioon",
"invalidConfigOwner": "Totaalne viga: vigane konfiguratsioon (vajalik on autoriseeritud omanik)",
"invalidConfigNoWebmap": "Totaalne viga: Vigane konfiguratsioon (veebikaart või rakenduse tuvastaja ei ole index.html all määratud)",
"invalidConfigNoAppDev": "Veebikaardi rakenduse identifikaatorit ega veebikaarti pole URL-i parameetrites (?appid= or ?webmap=) määratud. Faili index.html AppID ja veebikaardi konfiguratsioon on arendusrežiimis ignoreeritud.",
"createMap": "Võimetu kaarti koostama",
"invalidApp": "Pöördumatu tõrge. Lugu ei saa laadida",
"noLayer": "Veebikaart ei sisalda kaardi tuuri jaoks sobivat kihti.",
"noLayerMobile": "Selle kuvasuuruse korral kaardituuri koosturit ei toetata. Võimaluse korral muutke koosturile juurdepääsemiseks oma brauseri suurust või looge oma lugu suurema ekraaniga seadmes.",
"noLayerMobile2": "Kaardituuri koosturi kasutamiseks pöörake oma seadet ja kasutage horisontaalpaigutust.",
"noLayerView": "Tere tulemast kaardituuri veebirakendusse.<br />Lugu pole veel konfigureeritud.",
"appSave": "Loo salvestamisel ilmnes tõrge",
"mapSave": "Viga veebikaardi salvestamisel",
"featureServiceLoad": "Viga objektiteenuse laadimisel",
"notAuthorized": "Teil puudub õigus sellele loole juurde pääseda",
"notAuthorizedBuilder": "Teil pole õigust kaardituuri koosturit kasutada.",
"oldBrowserTitle": "Brauser ei ole täielikult toetatud",
"noBuilderIE8": "Kaardi tuuri koostaja ei ole toetatud varasemaga, kui Internet Explorer 9 versiooniga.",
"ie10Win7Explain": "Kaardi tuuri interaktiivne koostaja ei ole toetatud Windows 7 operatsioonisüsteemis kasutatava Internet Explorer 10 brauseriga, kui andmeallikas on manustega objektiteenus. Manustega objektiteenuste kasutamiseks peate <a target='_blank' href='http://msdn.microsoft.com/en-us/library/ie/hh920756(v=vs.85).aspx'>käsitsi muutma dokumendi ülesehitust Internet Explorer 9 standardite alusel</a>, <a target='_blank' href='http://news.softpedia.com/news/How-to-Remove-IE10-and-Get-Back-to-IE9-on-Windows-7-308998.shtml'> Migreeri brauser Internet Explorer 9 versioonile </a> või uuenda operatsioonisüsteem Windows 8 platvormile.",
"oldBrowserExplain": "Antud brauser ei toeta automaatset pisipiltide koostamist pildiandmetest, mis on laaditud tuuri kirjeldavale kaardile. Teil on võimalik koostada kaart selles brauseris kasutamiseks, kuid peate omistama igale üles laetud pildile asjakohase pisipildi.",
"oldBrowserExplain2": "Oskuste parendamiseks, <a href='http://browsehappy.com/' target='_blank'>uuendage oma brauserit</a> või <a href='http://www.google.com/chromeframe/?redirect=true' target='_blank'>Google Chrome Frame for Internet Explorer aktiveerimiseks</a>.",
"oldBrowserExplain3": "Kaardi tuuri koostaja ei tööta Windows XP operatsioonisüsteemi Internet Explorer 10 versiooniga.",
"oldBrowserClose": "Sulge"
},
"mobileHTML": {
"showIntro": "KUVA PEALKIRI",
"hideIntro": "PEIDA PEALKIRI",
"navList": "Loend",
"navMap": "Kaart",
"navInfo": "Meedia",
"introStartBtn": "Algus"
},
"desktopHTML": {
"storymapsText": "Kaardilugu",
"builderButton": "Vaheta muutmise režiimile",
"facebookTooltip": "Jaga Facebookis",
"twitterTooltip": "Jaga Twitteris",
"bitlyTooltip": "Hangi lühike link",
"bitlyStartIndex": "Link hetke asukohale",
"tooltipAutoplayDisabled": "See pole automaatesituse režiimis saadaval",
"autoplayLabel": "Automaatesituse režiim",
"autoplayExplain1": "Automaatesituse režiimis keritakse teie lugu kindla ajavahemiku järel edasi. Seda on hea kasutada kioskite või avalike kohtade ekraanidel, kuid arvestage, et muudel juhtudel võib see raskendada teie loo lugemist. See funktsioon pole väikestel ekraanidel toetatud.",
"autoplayExplain2": "Kui see režiim on aktiveeritud, saate kasutada loo esitamise või peatamise ja liikumiskiiruse reguleerimise juhtelemente."
},
"builderHTML": {
"panelHeader": "LOO KONFIGUREERIMINE",
"buttonSave": "SALVESTA",
"buttonSettings": "Seaded",
"buttonShare": "Jaga",
"buttonView": "Vaaterežiim",
"buttonItem": "Ava veebirakenduse sisu",
"buttonHelp": "Abi",
"buttonOrganize": "Paiguta",
"buttonAdd": "Lisa",
"buttonImport": "Impordi",
"buttonImportDisabled": "Importimine ei ole kasutatav manustega objektiteenuste juures",
"dataEditionDisabled": "Selle CSV andmeallika andmete muutmine on keelatud.",
"dataSourceWarning": "Kaardituuri andmete kiht on muutunud. Kui objektide ID väärtused ei ole samaväärsed, on Teil targem järjekord lähtestada ja peita punktid <b>Paiguta</b> kaudu. Kui väljanimed on erinevad, on Teil targem väljade omadused lähtestada <b>andmete sakk Seaded</b> kaudu.",
"organizeWarning": "Üks või mitu interaktiivsest koostajast väljapoole lisatud punkti on peidetud.",
"dataPicError0a": "Kaardituur sisaldab <b>%NB%</b> mittevastavaid piltide aadresse.",
"dataPicError0b": "Kaardituuris võib sisalduda <b>%NB%</b> mittevastavaid piltide aadresse.",
"dataPicError1": "Kaardituurile on sobilikud piltide aadressid, mis lõppevad laiendustega: .jp(e)g, .png, .gif või .bmp.",
"dataPicError2": "Nõue ei mõjuta teie eksisteerivat publitseeritud kaardituuri, kuid interaktiivse looja kasutamiseks peate esmalt lahendama aadressi küsimused, tehes ühte järgnevatest tegevustest:",
"dataPicError3": "Muuda aadresse",
"dataPicError4": "See lisab <i>#isImage</i> mitte toetatud piltide aadresside lõppu. Enamik servereid toetab aadressi täiendeid. Kuid peale selle tegevuse sooritamist kontrollige punktide vahel navigeerides, et uuendatud piltide aadressid on toimivad. Kui kõik pildid laadivad end kenasti üles, siis võite kaardituuri salvestada. Kui <b>pildid ei ilmu, ärge salvestage kaardituuri</b>. Selle asemel laadige looja uuesti ning tehke teine toiming.",
"dataPicError5": "Piira tuur piltidele",
"dataPicError6": "See valik tähendab, et kõiki aadresse käsitletakse piltidena, kuid teil ei ole võimalik lisada videod interaktiivse looja kaudu. See toiming on tagasi võetav kui otsustate lisada videoid tulevikus.",
"dataPicError7": "Teie kaardituur on piiratud ainult piltidele, videoid ei saa lisada. Kui eemaldate selle piirangu, siis kontrollige, et Teie pildid ikka laevad korrektselt enne kaardituuri salvestamist. Teil on vajadusel võimalik taastada seda piirangut hiljem.",
"dataPicError8": "Eemalda piltide piirang",
"dataPicError9": "Kui need aadressid viitavad videomaterjalile, siis võite ignoreerida seda hoiatust. Kui need viitavad piltidele, siis palun teostage üht järgnevatest toimingutest:",
"modalCancel": "Tühista",
"modalApply": "Kehtesta",
"organizeHeader": "Organiseeri tuuri",
"organizeGeneralCaption": "Kasuta tuuri punktide sorteerimisel haaramise ja lohistamise meetodit",
"organizeDelete": "Kustuta",
"organizeHide": "Peida",
"organizeReset": "Lähtesta järjekord ja peida punktid",
"addMaxPointReached": "Olete jõudnud ikoonikogumi poolt lubatud maksimaalse arvu punktideni ning ei saa rohkem tuuripunkte lisada.<br /><br />Kui kustutate olemasolevad punktid, peate loo uuesti laadima.",
"addMaxPointReachedMobile": "Olete jõudnud maksimaalse arvu autoriseeritud punktideni ning ei saa seda pilti lisada. Vabandame.",
"addClose": "Sulge",
"addHeader": "Lisa uus tuuri punkt",
"addTabPicture": "Meedia",
"addTabInformation": "Info",
"addTabLocation": "Asukoht",
"addSelectCaption": "Vali või haara pilt",
"addNoteVideo": "Videomaterjali kasutamiseks tutvu tehnilise abi sisuga",
"addSelectCaptionNoFileReader": "Vali pilt",
"addChangePhoto": "Vali pilt ja pisipilt",
"addPictureResolutionIntro": "Pildi resolutsioon on nõutavast suurem:",
"addPictureResolutionOldBrowser": "Pildi resolutsioon on nõutavast suurem. Optimeeri kaardi tuuri sisu, määrates resolutsiooni madalamana kui %SOOVITUSLIK_RES%.",
"addPictureResolutionResize": "Muuda pildi resolutsioon %RESOLUTSIOON%",
"addPictureResolutionKeep": "Säilita algne resolutsioon %RESOLUTSIOON%",
"addSelectThumbnail": "Vali pisipilt",
"addNoThumbSelected": "Ühtegi pisipilti ei ole valitud",
"addThumbSelected": "Valitud",
"addCameraSettingsHeader": "KAAMERA SEADED",
"addThumbnailHeader": "PISIPILT",
"addLabelPicUrl": "Pilt",
"addLabelThumbUrl": "Pisipilt",
"addTextPlaceholderUrl": "Sisesta pildi URL",
"addTextPlaceholderUrl2": "Sisesta YouTube lehe URL",
"addTextPlaceholderUrl3": "Sisesta Vimeo lehe URL",
"addTextPlaceholderUrl4": "Sisesta videoga seotud saidi URL",
"addLabelVideo": "Video",
"addMediaVideoOther": "Muu",
"addMediaVideoHelp": "Kontrolli URL-i ja hangi vaikimisi pisipilt",
"addMediaVideoHelpTooltip1": "Kontrollimine õnnestus",
"addMediaVideoHelpTooltip2": "Kontrollimine nurjus",
"addMediaVideoHelpTooltip4": "Leia võimalus põimida video ja kopeerida video URL, mis esineb koodis",
"addLabelName": "Nimi",
"addLabelDescription": "Alapealkiri",
"addTextPlaceholder": "Kirjuta siia midagi",
"addLocatePlaceholder": "Märgi aadress või asukoht",
"addPinColor": "Värv",
"addLatitude": "Laius",
"addLongitude": "Pikkus",
"addLatitudePlaceholder": "nt 34.056",
"addLongitudePlaceholder": "nt -117.195",
"addUploading": "Laadin tuuri punkti",
"addSave": "Lisa tuuri punkt",
"addMobileUploading": "Laen pilti",
"addMobileName": "Sisesta nimi",
"addMobileNameMandatory": "Viga, palun sisesta nimi.",
"addMobileError": "Midagi läks valesti. Vabandame.",
"settingsHeader": "Loo sätted",
"settingsTabLayout": "Kujundus",
"settingsTabColor": "Värvid",
"settingsTabLogo": "Päis",
"settingsTabFields": "Andmed",
"settingsTabExtent": "Kuvaulatus",
"settingsTabZoom": "Suumimise tase",
"settingsLayoutExplain": "Valige meelepärane paigutus.",
"settingsLayoutProfessional": "Kolme paneeliga kujundus",
"settingsLayoutModern": "Integreeritud kujundus",
"settingsLayoutSelected": "Valitud kujundus",
"settingsLayoutSelect": "Vali see kujundus",
"settingsLayoutNote": "Pange tähele, et videoid kasutavad punktid paigutatakse vastava plakatina video alla ka situatsioonis, kui antud valik on välja lülitatud.",
"settingsLayoutLocBtn": "Kuva 'Määra asukoht' nupp",
"settingsLayoutLocBtnHelp": "Antud funktsionaalsus on toetatud enamikes mobiilsetes seadmetes ja veebibrauserites (Internet Explorer 9).",
"settingsColorExplain": "Muuda väljanägemist, valides selleks puhuks eelnevalt määratud teema või koostades ise uue.",
"settingsLabelColor": "Päise, sisu ja jaluse värvid",
"settingsLogoExplain": "Kohanda päise logo (maksimum on 250 x 50px).",
"settingsLogoEsri": "Esri logo",
"settingsLogoNone": "Logo puudub",
"settingsLogoCustom": "Valikuline logo",
"settingsLogoCustomPlaceholder": "Pildi URL",
"settingsLogoCustomTargetPlaceholder": "Kliki läbi lingi",
"settingsLogoSocialExplain": "Kohanda päist ülemise paremal pool asuva lingi kaudu.",
"settingsLogoSocialText": "Tekst",
"settingsLogoSocialLink": "Link",
"settingsLogoSocialDisabled": "See funktsionaalsus on administraatori poolt välja lülitatud",
"settingsDataFieldsExplain": "Vali foto nime, selgitava teksti ja värvi väljad.",
"settingsDataFieldsError": "Rakendus ei suuda määrata sobivat nime, selgitavat teksti ega värvi andmeid. Palun valige siin kasutamiseks vastavad väljad. Vastavad parameetrid on hiljem muudetavad.",
"settingsFieldsLabelName": "Nimi",
"settingsFieldsLabelDescription": "Alapealkiri",
"settingsFieldsLabelColor": "Värv",
"settingsFieldsReset": "Lähtesta väljade valik",
"settingsExtentExplain": "Määrake kaardi tuuri sisemine kuvaulatus läbi alloleva interaktiivse kaardi.",
"settingsExtentExplainBottom": "Teie määratud kuvaulatus muudab veebikaardi sisemist ulatust. Pange tähele, et seda ulatust ei kasutata, kui see ei ole esimeses tuuri punktis. Sel juhul paigutatakse tuuri avamine esimese punkti alusel.",
"settingsExtentDateLineError": "Ulatus ei saa ületada 180° pikkuskraadi",
"settingsExtentDateLineError2": "Viga ulatuse arvutamisel",
"settingsExtentDrawBtn": "Joonista uus ulatus",
"settingsExtentModifyBtn": "Muuda ulatust",
"settingsExtentApplyBtn": "Kaardituuri eelvaade",
"settingsExtentUseMainMap": "Kasuta kaardituuri kuvaulatust",
"settingsZoomExplain": "Määra looga seotud punktidele suum järgneva juhisega (valikuline).",
"settingsLabelZoom": "Mõõtkava/tase",
"settingsZoomFirstValue": "Puudub",
"settingsFieldError": "Palun vali väli igale loendile",
"dataTitle": "Looge majutatud kaardi tuurikiht",
"dataExplain": "Teie piltide ja tuuripunktide jaoks luuakse uus objektikiht. Tuurikihti ei jagata juhul, kui te ei jaga oma kaardituuri.",
"dataExplainPortal": "Selle funktsiooni jaoks on nõutav Portal for ArcGIS 10.4. Kui teil ei õnnestu luua objektikihti, siis võtke ühendust oma ArcGIS-i administraatoriga.",
"dataNameLbl": "Kihi nimi",
"dataFolderListLbl": "Kaust",
"dataFolderListFetching": "Haaran kaustu ...",
"dataRootFolder": "Juur",
"dataNameError": "Sisesta objektiteenusele nimi",
"dataFolderError": "Vali sobilik kaust",
"dataSrcContainsInvalidChar": "Objektiteenuse nimi sisaldab ühte või mitut vigast tähemärki (-, <, >, #, %, :, \", ?, &, +, / või ).",
"dataSrvAlreadyExistsError": "Sama nimega teenus on Teie organisatsioonis juba olemas. Palun valige mõni muu nimi.",
"dataBtnSave": "Looge kiht",
"dataFooterProgress": "Koostamine käib",
"dataFooterSucceed": "Koostamine on lõpetatud. Laadin",
"dataFooterError": "Koostamine ei õnnestunud. Proovi uuesti",
"tabError": "Palun kontrolli vigu kõigis osades",
"introRecordBtn": "Intro",
"introRecordActivate": "Kasuta esimest punkti tutvustusena (ei ilmu karussellis)"
},
"addPopupJS": {
"uploadingPicture": "Laen pilti",
"uploadSuccess": "Laadimine õnnestus",
"uploadError": "Viga pildi laadimisel",
"uploadError2": "Viga objekti lisamisel (vigane html tag)",
"notJpg": "Laadimiseks vali palun JPEG-formaadis pilt",
"errorNoPhoto": "Vali pilt laadimiseks",
"errorNoThumbnail": "Vali pisipilt laadimiseks",
"errorInvalidPicUrl": "Sisesta korrektne pilt (algab http(s)://, lõpeb laiendusega jpg, png, gif või bmp). Võite pildi aadressi lõppu lisada '#isImage', mis on eelneva reegli ülene.",
"errorInvalidThumbUrl": "Sisesta korrektne eelvaate pilt (algab http(s)://, lõpeb laiendusega jpg, png, gif või bmp).",
"errorInvalidVideoUrl": "Sisesta kehtiv video URL (algus stiilis http(s)://)",
"errorNoName": "Sisesta selle tuuri punktile nimetus",
"errorNoDescription": "Sisesta selle tuuri punktile selgitav tekst",
"errorNoLocation": "Määra selle tuuri punktile asukoht"
},
"builderJS": {
"noPendingChange": "Salvestamata muudatused puuduvad",
"unSavedChangeSingular": "1 mittesalvestatud muudatus",
"unSavedChangePlural": "mittesalvestatud muudatust",
"shareStatus1": "Tuur ei ole salvestatud",
"shareStatus2": "Tuur on jagatud avalikult",
"shareStatus3": "Tuur on jagatud organisatsioonis",
"shareStatus4": "Tuur ei ole jagatud",
"popoverDiscard": "Olete kindel, et soovite loobuda salvestamata muudatustest?",
"yes": "Jah",
"no": "Ei",
"popoverLoseSave": "Kui avate sirvija, siis kaotate kõik salvestamata muudatused",
"ok": "Ok",
"popoverSaveWhenDone": "Ärge unustage salvestada, kui olete lõpetanud",
"closeWithPendingChange": "Olete kindel, et soovite tegevuse kinnitada? Teie tehtud muudatused võivad kaduma minna.",
"gotIt": "Ok",
"savingApplication": "Loo salvestamine",
"saveSuccess": "Lugu on salvestatud",
"saveError": "Salvestamine ebaõnnestus, palun proovi uuesti",
"saveError2": "Salvestamine nurjus vigase html tagi tõttu nimes või kirjelduses",
"saveError3": "Pealkiri ei saa olla tühi",
"dragColorPicker": "Paigutage mind ümber<br />või muutke minu värvi",
"dataWarningExtent": "Teie andmed on väljaspool veebikaardi ulatust. Neid andmeid ei saa kasutada tuuri punktidena, mistõttu vahetage nende kasutamiseks kaardi ulatust.",
"dataWarningVisibi": "Teie kaardi tuur ei ole praeguse veebikaardi ulatuses nähtav. Veenduge, et Teie kaardi tuuri kiht on nähtav %KAARDI SUURUS% suuremal kaardil.",
"dataWarningEdit": "Muuda veebikaarti",
"dataWarningClose": "Sulge",
"signIn": "Palun logige konto kaudu sisse",
"signInTwo": "loo salvestamiseks.",
"switchBM": "Muuda aluskaarti"
},
"organizePopupJS": {
"messageStart": "Olete valinud kustutamiseks",
"messageSinglePoint": "ühe tuuri punkti",
"messageMultiPoint": "tuuri punktid",
"messagePermantRemove": "See eemaldab jäädavalt",
"messageRecord": "kirje",
"messageRecordPlural": "kirjed",
"messageConfirm": "Teie andmebaasist. Soovite jätkata?",
"labelButtonShow": "Näita",
"labelButtonHide": "Peida"
},
"picturePanelJS": {
"popoverDeleteWarningPicAndThumb": "See kustutab jäädavalt pildi ja pisipildi",
"popoverDeleteWarningThumb": "See kustutab jäädavalt pisipildi",
"popoverUploadingPhoto": "Laadin pilti ja pisipilti",
"popoverUploadingThumbnail": "Laadin pisipilti",
"popoverUploadSuccessful": "Laadimine õnnestus",
"popoverUploadError": "Laadimine ebaõnnestus, palun proovi uuesti",
"changePicAndThumb": "Vaheta pilt",
"changeThumb": "Vaheta pisipilt",
"selectPic": "Vaheta meedia",
"selectThumb": "Vaheta pisipilt",
"uploadPicAndThumb": "Kehtesta"
},
"headerJS": {
"editMe": "Muuda mind!",
"templateTitle": "Määra mallile pealkiri",
"templateSubtitle": "Määra mallile alampealkiri"
},
"crossFaderJS": {
"setPicture": "Määra pildile pealkiri",
"setCaption": "Määra pildile selgitav tekst"
},
"importPopup": {
"title": "Impordi",
"prevBtn": "Tagasi",
"nextBtn": "Järgmine"
},
"importPopupHome": {
"header": "Kus sa oma pilte hoiad?"
},
"onlinePhotoSharingCommon": {
"pictures": "pildid",
"videos": "videod",
"disabled": "See funktsioon on administraatori poolt välja lülitatud",
"disabledPortal": "Selle funktsiooni kasutamiseks on nõutav, et ArcGIS Data Store oleks konfigureeritud portaali andmebaasiks. Võtke ühendust Portal for ArcGIS-i administraatoriga.",
"header1": "Teie pildid peavad olema jagatud avalikult.",
"header2": "Importimine on limiteeritud esimeste %NB1% %MEDIA%.",
"emptyDataset": "Viga, pilte ei leitud",
"footerImport": "Impordi",
"selectAlbum": "Vali avalik album",
"selectAlbum2": "Vali album",
"pleaseChoose": "Palun vali",
"userLookup": "Otsi üles",
"userLookingup": "Otsin üles",
"csv": "CSV failis viidatud",
"advanced": "Täiendavad võimalused",
"advancedScratchLbl": "Alusta uut tuuri",
"advancedScratchTip": "Loo tühi tuur, mille saate täita viisardi abil.",
"advancedCSVLbl": "Impordi tuuri andmed CSV failist",
"advancedCSVTip": "Impordi oma tuuri sisu CSV failist.",
"advancedCommonTip": "See nõuab, et teie pildid ja videod oleks juba veebis üleval.",
"select": "Koosta valik",
"locUse": "Kasuta piltide ruumilist asukohta",
"locExplain": "Sa ei pruugi soovida kasutada piltide asukohta, sest need on pärit albumist ning tulemuseks on see, et kõigi piltide asukoht on sama.",
"locExplain2": "Sa ei pruugi soovida kasutada videote asukohta, sest need on pärit sama kasutaja seadetest ning tulemuseks on see, et kõigi videote asukoht on sama."
},
"viewFlickr": {
"title": "Flickr import",
"header": "Sisesta oma Flickri kasutajanimi ja vali fotokogum või märksõna, mida soovid importida.",
"userInputLbl": "Sisesta kasutajanimi",
"signInMsg2": "Kasutajat ei leitud",
"selectSet": "Vali fotokogum",
"selectTag": "või vali märksõna",
"footerImportTag": "Impordi valitud märksõna",
"footerImportSet": "Impordi valitud kogum"
},
"viewFacebook": {
"title": "Facebook import",
"header": "Tuvasta isik oma Facebooki kasutajanimega või kasuta avalikku lehte. Privaatseid albumeid saab kasutada avaliku kaardi tuuri tegemisel, mis ei eelda isiku tuvastamist Facebooki kasutajanimega, mis võimaldab hoida kommentaare ja meeldimisi privaatsena.",
"leftHeader": "Facebooki kasutajanimi",
"rightHeader": "Facebooki leht",
"pageExplain": "Facebooki leht on avalik kaubamärk/toode nagu <b>esrigis</b>. Saad lehe nime pärast esimest '/' lehekülje URL-il.",
"pageInputLbl": "Sisesta lehe nimi",
"lookupMsgError": "Lehte ei leitud"
},
"viewPicasa": {
"title": "Picasast importimine",
"header": "Sisestage oma e-posti aadress või Picasa ID.",
"userInputLbl": "E-post või Picasa ID",
"signInMsg2": "Kontot ei leitud",
"signInMsg3": "Avalikku albumit pole",
"howToFind": "Kuidas leida Picasa ID-d?",
"howToFind2": "Kopeerige mis tahes Picasa lehe esimese ja teise kaldkriipsu vahel asuvad numbrikohad"
},
"viewCSV": {
"title": "CSV import",
"uploadBtn": "Vali või haara CSV fail",
"resultHeaderEmpty": "CSV fail on tühi",
"resultHeaderSuccess": "Laaditud punkte: %NB_POINTS%",
"resultHasBeenLimited": "Importimine on limiteeritud esimese %VAL1% punktini %VAL2% punktist, et hoida piiri %VAL3% punkti tuuri kohta",
"browserSupport": "Teie brauserit ei toetata, CSV failide tarbeks <a href='http://browsehappy.com/' target='_blank'>uuenda brauserit</a> või kasuta ArcGIS.com veebikaardi sirvijat (vt Abi).",
"errorLatLng": "Laiuse ja pikkuse veerge ei leitud. Võimalikud laiuskraadi väärtused on: <i>%LAT%</i> ja pikkuskraadi väärtused on: <i>%LONG%</i>.",
"errorFieldsExplain": "Laadimine nurjus, kuna sobivaid veerge ei leitud",
"errorFieldsName": "<b>Nimi</b> võimalikud väärtused on: %VAL%",
"errorFieldsDesc": "<b>Kirjeldus</b> võimalikud väärtused on: %VAL%",
"errorFieldsUrl": "<b>Pildi URL</b> võimalikud väärtused on: %VAL%",
"errorFieldsThumb": "<b>Pisipildi URL</b> võimalikud väärtused on: %VAL%",
"errorFields2Explain": "Laadimine nurjus, kuna CSV fail ei kasuta samu atribuute kui kiht järgmiste atribuutide tarbeks",
"errorFields2Name": "<b>Nimi</b> kasuta %VAL1% mitte %VAL2%",
"errorFields2Desc": "<b>Kirjeldus</b> kasuta %VAL1% mitte %VAL2%",
"errorFields2Url": "<b>Pildi URL> kasuta %VAL1% mitte %VAL2%",
"errorFields2Thumb": "<b>Pisipildi URL</b> kasuta %VAL1% mitte %VAL2%",
"resultFieldsAll": "Kõik atribuudid on imporditud",
"resultFieldsNotAll": "Järgnevad atribuudid ei ole imporditud, kuna neid ei eksisteeri kaardikihis",
"resultFieldsNotAll2": "Järgnevad atribuudid on imporditud",
"footerNextBtnResult": "Impordi veebikaarti",
"footerProgress": "Toimub importimine",
"footerSucceed": "Importimine õnnestus. Laadin"
},
"viewYoutube": {
"title": "Youtube import",
"header": "Sisesta YouTube kasutajanimi, et leida avalikult jagatud videoid.",
"pageInputLbl": "Sisesta YouTube kasutajanimi",
"lookupMsgError": "Kasutajat ei leitud",
"howToFind": "Kuidas leida YouTube’i kasutajanime",
"howToFind2": "Kasutajanime kuvatakse videote all",
"found": "Leitud",
"noData": "Avalikke videoid ei leitud"
},
"viewGeoTag": {
"title": "Vali ja positsioneeri oma pildid/videod",
"header": "Klikkige või puudutage pilte, mida soovite nende paigutamiseks importida.",
"headerMore": "Miks minu pildid/videod ei ole ruumiliselt paigutatud?",
"headerExplain": "Kui piltidel on kehtiv asukoht, märgitakse need automaatselt kaardile ja teise saki all olevasse loendisse.<br /><br />Vaikimisi Picasa ega Flickr piltide EXIF metainfot ei kasutada, kontrolli Flickri/Picasa seadeid privaatsuse seadetest, et see võimaldada. Võib juhtuda, et pead kogu Flickri/Picasa impordi uuesti läbi tegema.<br /><br />Facebookis pead liikuma igale pildile, aktiveerima Muuda ning valima asukoha soovituslike valikute vahel, mis põhinevad pildiandmete EXIF sisul.",
"leftPanelTab1": "Paiguta",
"leftPanelTab2": "Paigutatud",
"clickOrTap": "Paigutamiseks klikkige kaardil või puudutage kaarti",
"clearLoc": "Tühista asukohad",
"clickDrop": "Ära impordi",
"footerImport": "Impordi",
"footerProgress": "Toimub importimine",
"footerSucceed": "Importimine õnnestus. Laadin...",
"loading": "Laen",
"error": "Piltide ruumiliste asukohtade import ebaõnnestus, asukohti ignoreeriti."
},
"initPopup": {
"title": "Tere tulemast kaardi tuuri koostajasse",
"prevBtn": "Tagasi",
"nextBtn": "Järgmine"
},
"initPopupHome": {
"header1": "Kus paiknevad Teie pildid või videod?",
"header2": "See nõustaja abistab sind kaardi tuuri loomisel, kasutades selleks kas veebis olemasolevaid pilte või importides pildid sinu ArcGIS Online for Organizations kontole.",
"title1": "Need on juba veebis üleval",
"title2": "Ma pean oma pildid üles laadima",
"hostedFSTooltip": "Laadige pildid üles ja hoidke neid kaardi tuurikihis (videot ei toeta).",
"hostedFsNA": "Peate olema publitseerija rollis või mõnes muus rollis, millel on õigused majutatud objektikihte avaldada. Võtke ühendust ArcGIS-i administraatoriga.",
"hostedFsNA2": "Saadaval ainult ArcGIS Online'i tellimusega. <a href='%LINK%'>Registreeru tasuta prooviversiooni hankimiseks</a>",
"footer1": "Kui oled valmis, ära unusta oma kaarti rakenduste lehe kaudu teistega jagada.",
"footer3": "Laadi alla CSV mall",
"footer4": "\"Salvesta nimega\" kui ei saa alla laadida",
"footer4bis": "Kasuta paremat klikki ja \"Salvesta kui\" kui allalaadimine ei käivitu",
"footer5": "Loe lähemalt",
"footerProgress": "Koostamine käib",
"footerSucceed": "Koostamine oli edukas. Laadin..."
},
"helpPopup": {
"title": "Abi",
"close": "Sulge",
"tab1": {
"title": "Tutvustus",
"div1": "Kaardi tuuri mall on loodud geograafilise teabe esitamiseks kujul, kus siduvaks elemendiks on jutustatavale loole fotod või muu meedia sisu.",
"div2": "Mall loob pilkupüüdva ja kergesti kasutatava veebirakenduse, mille abil saate väikesel hulgal paiku numbrilises järjestuses kaardil esitada ja mida kasutajad saavad sirvida. Mall on välja töötatud mistahes tüüpi veebibrauseris või seadmes (sh nutitelefonis ja tahvelarvutis) kasutamiseks. <br /><br />",
"div42": "Kui soovite vaadata näiteid teiste kasutajate loodavatest kaardituuridest, külastage <a href='http://storymaps.arcgis.com/' target='_blank'>kaardilugude veebisaidil</a> asuvat <a href='http://links.esri.com/storymaps/map_tour_gallery' target='_blank'>galeriid</a>. Samuti saate meid jälgida Twitteri kanalis <a href='https://twitter.com/EsriStoryMaps' target='_blank'>@EsriStoryMaps</a>.",
"div5": "Ootame Teie tagasisidet! Kui Teil on küsimusi, soovite küsida uusi võimalusi või arvate, et olete leidnud vea, siis palun külastage meid <a href='http://links.esri.com/storymaps/forum' target='_blank'>kaardilugude kasutajate foorumis</a>."
},
"tab2": {
"title": "Andmed",
"div1": "Kaardi tuuri loomisel tuleb eelkõige silmas pidada kohta, kuhu pildid salvestatakse. Kaardi tuuri loomisel saab kasutada pilte, mis asuvad peamistes fotopankades, mistahes veebiserveris või objektiteenuste manustena.",
"div1a": "Vaata selle vahelehe viimast sektsiooni piltide ja videote toetatud formaatide osas.",
"div2": "Interaktiivne koostaja käib tuuri piltide haldamisega seoses välja kaks valikut:",
"div3": "<ul><li>Saate kasutada <b>veebis olevaid fotosid</b> (nt fotojagamissaidil Flickr või teie enda veebilehel talletatavaid pilte). Nendele piltidele viidatakse teie kaardituuril URL-ide kaudu.</li><li>Samuti saate <b>oma arvutist pilte üles laadida</b>. Selle üleslaadimissuvandi kasutamiseks peab Teil olema ArcGIS for Organizations konto ning publitseerija või administraatori õigused, kuna Teie jaoks luuakse automaatselt majutatav objektiteenus, kus Teie fotosid talletatakse manustena.</li></ul>",
"div4": "Peamised kasutusjuhud on:",
"div4b": "<b>Teie fotosid ei majutata</b> veel ja Teil on ArcGIS for Organizations konto. Kõige mõistlikum oleks kasutada majutatavat objektiteenust. Sarnaselt avalike fotojagamise teenustega optimeeritakse ka siin pildid selliselt, et neid saab kiiresti üles laadida ja Teil on juurdepääs ArcGIS-i platvormi administraatori- ja andmehalduse funktsioonidele.",
"div5": "<b>Te ei ole organisatsiooni liige</b>: esmalt pead pildid laadima fotode jagamise keskkonda või enda veebiserverisse. Seejärel aitab Teid tuuri looja, et saaksite kasutada neid pilte, mida jätkuvalt algses asukohas hoitakse.",
"div6": "<b>Otsid olemasoleva objektiteenuse korduvkasutust,</b> mis hoiaks pilte manustena või viitaks välistele asukohtadele: vaata täpsustavat lõiku allpool.",
"div7": "<b>Oled varasema versiooni kaardi tuuri malli kasutaja</b> ja seal on juba CSV, mis viitab sinu piltidele ja pisipiltidele: sul on võimalus importida ja täiustada oma andmeid. Tuuri looja toetab vaid CSV faili, mis sisaldab pikkuse ja laiuse veergu, aadressipõhist CSV faili saab samuti kasutada sinu veebikaardi kaudu (vt lõiku allpool).",
"div8": "Impordin veebipõhisest fotode jagamise teenustest",
"div9a": "Facebooki tuge ei pakuta enam, ${learn}.",
"learn": "lisateave",
"div9": "Importimise toiming viitab juba majutatud piltidele, mis on salvestatud nende URL-ide veebikaardi objektide kollektsioonis. Pilte ei hoita ArcGIS Online all. Kui piltide lingid on vigased, ei kuvata neid ka kaardi tuuri aknas ja kuvatakse teadet \"Pilt ei ole kättesaadav\". Sõltuvalt fototeenuse pakkujast, kaardi tuur ei pruugi importida piltide nime, kirjeldust ja asukohta. Neid atribuute hoitakse veebikaardil ning tehtavad muudatused ei kajastu kaardi tuuri sisus.",
"div10": "Haldan pilte veebiserveris",
"div11": "Kui soovid pilte ise majutada, pead käsitsi looma ka pisipildid. Kui kasutad pisipiltide loomiseks piltide täisresolutsiooni, siis tulemus kõige parem ei tule. Seetõttu soovitame kasutada veebipõhiseid fotode jagamise teenuseid või objektiteenuseid.",
"div12": "Kasutan olemasolevat objektiteenust või vormifaili",
"div13": "Mistahes objektiteenuse või vormifaili punkt on kasutatav kaardi tuuri andmeallikana. Pead vaid lisama selle kihina enda veebikaardile arcgis.com kaardiakna kaudu. Juhul, kui rakendus leiab sinu kihist vajalikud atribuudid, on kõik funktsioonid ka kasutatavad.",
"div14": "Võimalikud väärtused väljade nimedeks on (tõstutundlikud):",
"div151": "Nimi",
"div152": "Kirjeldus",
"div153": "Pilt",
"div154": "Pisipilt",
"div155": "Värv ",
"div16": "Kui rakendus ei leia objektiteenusest sobivaid veerge, siis vaateaken ei toimi seni, kuni veerud tekivad. CSV- ja Shape-faili kihi lisamine veebikaardile eeldab kõiki vajalikke veerge, sest vastasel korral rakenduse koostamine ei toimi.",
"div162": "Kui kasutate manuste hoidmiseks majutusteenust, <b>siis kasutatakse ainult nähtuseid, millel on kaks manust</b>. Esimene manus defineerib peamise pildi ja teine manus pisipildi.",
"div17": "Pildi ja pisipildi veerud on esmatähtsad manusteta objektiteenuses ja valikulised (aga tungivalt soovitatavad) manustega objektiteenuste korral. Kui teenuses on manused lubatud, lubab koostaja pildid üles laadida manustena. Kui ei, saad muuta vaid pildi ja pisipildi URL-i.",
"div172": "Pildi ja eelvaate välju kasutatakse alati nende olemasolu korra ja majutusteenuse manuseid ei pärita.",
"div173": "Näidiskujul CSV- ja Shape-faili saab alla laadida",
"div18": "Koostan majutatud objektiteenuse CSV- või Shape-failist",
"div19": "Kui lood majutatud objektiteenuse CSV- või Shape failist, siis manused ei ole vaikimisi toetatud. Selleks saad avada objektiteenuse sisu lehe, klikkida väikesel noolekesel ning siis on vastav valik ka nähtav. Jätkub kaardituuri piltide ja pisipiltide kasutamine, millele oled atribuutide kaudu viidanud. Valikuliselt võib pilte laadida ka objektiteenuse manustena, seda saad teha kahe pildipaneelil asuva nupu abil (\"Muuda pilti\" ja \"Muuda pisipilti\").",
"div20": "Toetatud pildiformaadid ja videod",
"div21": "Toetatud pildiformaadid on <b>.jpg, .jpeg, .png, .gif ja .bmp</b>. Kui Teie meedia ei lõpe sellise laiendusega, siis kaardituur eeldab, et tegemist on videoga, välja arvatud siis, kui tegemist on majutusteenusega (vt allpool).",
"div22": "Kaardituuri mall ei sisalda videopleierit, seega peate kasutama välist videopleierit oma videote majutuse teenusest (leidke sealt võimalused video kaasamiseks ja kopeerige vastav aadress antud koodis). Kui soovite majutada oma videoid ise, siis võite luua HTML lehe, mis sisaldab videomängijat nagu näiteks: <a href='http://www.videojs.com/'>Video.js</a>.",
"div23": "Interaktiivne kaardituuri looja ei paku dialoogi videote lisamiseks majutusteenuse manustena, aga seda on võimalik teostada redigeerides oma andmeid väljaspool interaktiivset loojat. Arcgis.com kaardil võite muuta pildi välja ning suunata väärtused välistele videotele, lisades spetsiaalse parameetri video aadressi lõppu (#isVideo), seejärel käsitletakse seda meediat videona.",
"div24": "Pange tähele, et vajate kaht sobilikku pildimanust või Teie punkte ei kasutata. Videoklipi kasutamine majutusteenuse manustena ei ole võimalik ilma pildi- ja eelvaateväljata."
},
"tab3": {
"title": "Kohandamine",
"div1": "Koostaja võimaldab mitmeid kohandamise valikuid, mis on kättesaadavad läbi ülemises paneelis oleva SEADED nupu. Kui sa ei leia vajalikku valikut, võib kasutada ka allalaaditavat versiooni, mille saad integreerida enda veebiserverisse ning kohandada seda vastavalt oma vajadustele.",
"div2": "Soovitame kasutada majutatud versiooni, välja arvatud:",
"div3": "<li>See ei paku kasutajaliidese seadistamist nagu näiteks päise taustapildi kasutus</li><li>Kui oled arendaja ning soovid rakendust omalt poolt täiustada.</li>",
"div4": "Allalaaditav versioon on konfigureeritav läbi veebikaardi või veebikaardi rakenduse keskkonna kaudu. Peamised kasutusjuhud on järgnevad:",
"div41": "Te ehitate oma kaardituuri kasutades interaktiivset loojat majutatud keskkonnas ja konfigureerite malli kaardirakenduse identifikaatoriga. Rakendatakse sätted, mille olete defineerinud interaktiivse loojaga.",
"div42": "Te loote oma kaardituuri väljaspool interaktiivset loojat ja konfigureerite malli kaardi identifikaatoriga. Te peate lugema dokumentatsiooni, et saada infot malli konfigureerimise kohta.",
"div43": "Pane tähele et interaktiivne looja on saadaval allalaetava versioonina aga mõningaste tehniliste piirangutega veebibrauserites nagu Internet Explorer vanemad versioonid kui 10.",
"div5": "Uusima malli versiooni allalaadimiseks ja kasutamise info saamiseks külasta <a href='https://github.com/Esri/map-tour-storytelling-template-js' target='_blank'>GitHub projekti lehte</a>."
},
"tab4": {
"title": "Vihjed",
"div0": "Toetatud veebibrauserid",
"div0a": "Kaardituuri vaataja on toetatud IE8+. Interaktiivne looja on toetatud IE9+. Me testime aktiivselt kõiki enimlevinud veebibrausereid, aga kui Teil esineb tõrkeid, siis soovitame kasutada Chrome’i veebibrauserit.",
"div0b": "Kui Teil esineb tõrkeid, siis andke palun meile teada. Vahepeal proovige CSV malliga oma kaardituuri luua, kuna nii vähendate oma suhtluse interaktiivse looja keskkonnaga minimaalseks.",
"div1": "Pildid",
"div2": "Soovitame kasutada horisontaalset paigutust. Kuvasuhtega 4:3 fotod sobivad kõige paremini. Vertikaalpaigutus ei sobi väiksemate ekraanide korral nagu iPad, pilt võib selgitava teksti varju jääda, sest tekst võtab rohkem ruumi, kui see kuvatakse kitsal ja mitte laial alal. Kuigi erinevate suuruste, kujude ja paigutusega pilte võib ühe ja sama kaardi tuuri loomisel kasutada, soovitame kasutada täpselt sama suurust ja vormi kõigi piltide korral. Sellisel juhul on kasutajal infot lihtsam jälgida.",
"div2a": "Soovitame maksimaalseks pildi suuruseks 1000 pikslit laiust x 750 pikslit pikkust põhipiltidele ning 140x93 pisipiltidele.",
"div3": "Vormindan selgitava teksti HTML märgenditega",
"div4": "Päis ja pildi pealkiri võivad sisaldada HTML teeke defineerimaks kujundust ja linke. Näiteks see kood lisab kollase lingi:",
"div4a": "Kirjuta sobiv alampealkiri oma tuurile",
"div4b": "Võtke aega, et leida sobiv alapealkiri oma tuurile. Alapealkiri on hea moodus haarata inimesi oma tuuriga ning jutustada neile sisust. Samuti on see hea koht rääkimaks oma külalistele antud kaardi asukohast. Näiteks ärge eeldage, et inimesed teavad millises linnas või külas antud tuur paikneb. Teie pealkiri võib omada HTML formaati, näiteks sisaldada linke. Samas ärge muutke pealkirja liiga pikaks. Väiksemates veebibrauserite akendes või tahvlites ei pruugi see mahtuda täielikult ekraanile ja lõigatakse osaliselt. Kui te ei oska mõelda head alapealkirja, siis jätke see tühjaks.",
"div5": "Toetatud kihid",
"div6": "Saad kaardile lisada täiendavaid toetatud kihte, et pakkuda sisu kaardituurile. Need kihid võivad sisaldada muid geograafilisi nähtusi, mida soovite kuvada lisaks kaardituuri punktidele. Näiteks uurimusalad, kõndimise või sõidu teekond, mis ühendab tuuri punkte jne. Mall kuvab abistavad lisakihid veebikaardil täpsustatud kirjelduse alusel, aga hüpikaknad ei ole kättesaadavad.",
"div7": "Hoia tuuri sisu lühikese ja löövana",
"div8": "Ühes tuuris võib olla kuni 99 punkti. Enamik tuure on loomulikult lühemad. Ära oota, et külastajad on valmis läbi käima liiga arvukalt tuuripunkte. Sinu arvates võib teema olla äärmiselt huvitav, kuid ära eelda, et nemad sama arvavad!",
"div10": "Kinnitusrežiim",
"div11": "Kui te soovite lisada malli mõnele teisele veebilehele iframe abil, siis lisage valikuline parameeter \"&embed\" aadressi lõppu, et eemaldada päis. Selle võimaluse võib seadistada samuti alla laetavale versioonile läbi konfiguratsioonifaili.",
"div12": "Proovige mitte kasutada kitsaid iFrame laiusi, mis põhjustavad teie tuuri automaatselt ümberlülituma väiksemale puutetundlikule ekraanile mõeldud kujundusele. Kasutusmugavuse maksimeerimiseks. Kui olete põiminud kaardituuri oma sisu sisse, siis soovitame ikkagi lisada ka juurde lingi, et tuuri kasutajad saaksid avada tuuri täisekraanil."
},
"tab5": {
"title": "Publitseerin",
"div1": "Kui oled valmis, ära unusta tulemust jagada suurema auditooriumiga läbi JAGA nupu või ArcGIS Online konkreetse sisu lehe kaudu.",
"div2a": "Tuuri jagamine läbi vastava ehitaja",
"div2b": "JAGA nupp uuendab rakendust ja veebikaardi sisu. Kui teie andmed on salvestatud objektiteenusena, siis ka see uuendatakse. Kui olete lisanud muid kihte läbi ArcGIS.com kaardirakenduse, siis neid ei uuendata. Selle tulemusena võib kaardi jagatav tulemus näida oodatust teistsugune. Sisu millel on juba piisavalt (või rohkem) õiguseid, ei uuendata.",
"div2c": "Tuuri jagamine läbi ArcGIS Online keskkonna",
"div2d": "Kui jagate rakendust ArcGIS Online keskkonna kaudu, siis on vajalik uuendada kõiki sõltuvaid ressursse (veebikaart, objektiteenus, kujunduse kiht), mis ei ole samal viisil jagatud. Kui kaardituur on avalik ja üks teie ressurssidest ei ole kõigiga jagatud, siis suunatakse kasutajad ArcGIS Online’i sisselogimislehele.",
"div3t": "Objektiteenuse turvalisus",
"div3a": "Kui kasutate kaardi tuuri koostaja kaudu loodud majutatud objektiteenust, haldab rakendus teenuse turvalisust Teie eest ning Teie jääte ainsaks muutmisõigustega kasutajaks (ka juhul, kui teenus on avalik).",
"div3t2": "Enne oma tuuri jagamist laiema ringiga",
"div3": "Kontrollige, et tuur toimib kenasti ka siis kui te ei ole ArcGIS.com kontole sisse logitud. URL, mida kavatsete välja jagada, ei tohiks suunata sisselogimise lehele ega rakenduse loomise režiimi.",
"div4": "Kasulik on vaadata, kuidas kaardituur paistab iPad horisontaalses paigutuses, et olla kindel selle sobilikkuses sellele populaarsele seadmele. Selle kaudu saate parema ülevaate, millal pealkirjad katavad liiga suure osa piltidest. Samuti annab see infot, kas alapealkiri mahub ega ole liiga pikk, et seda lõigataks.",
"div5a": "Soovitus otsinguks",
"div5b": "Et aidata teistel kasutajatel ArcGIS Online otsingu kaudu oma kaardituuri leida, siis me soovitame, et te lisaksite ’Story map’ märksõna kaardituuri sisu lehele (mitte veebikaardi sisu lehele), koos märksõnadega nagu tuuri asukoht, linn, riik ja temaatilised märksõnad nagu 'avalik kunst', 'turisti kaart' ja 'ajaloolised kohad'. Need märksõnad aitavad ka meid, Esri inimesi, leidmaks lahedaid uusi näiteid tuuridest, mida saame promoda oma galeriides ja sotsiaalmeedias. Samuti soovitame teil laadida üles hea väljanägemisega pisipilt galeriile rakenduse sisu lehelt, nagu näiteks väike ekraanipilt tuurist või üks pilt sellest. Seda pilti kasutatakse automaatselt kui teie kaart lisatakse ArcGIS Online galeriisse."
}
},
"share": {
"firstSaveTitle": "Tuur on salvestatud",
"manageStory": "Hallake oma lugu",
"manageStoryA1": "Nõuanne. Kasutage linki %LINK1%, et kontrollida, kas teie loos esineb vigu ja muuta selle komponentide jagamist. Portaali Minu lood abil saate ka parandada oma loo ilmet, et see näeks sotsiaalvõrgustikes jagamisel hea välja. Portaali Minu lood muude kasulike funktsioonide kohta leiate lisateavet järgmiste linkide kaudu: %LINK2%.",
"manageStoryA1V1": "Minu lood",
"manageStoryA1V2": "blogipostitused",
"shareTitle": "Jaga oma tuuri",
"sharePrivateHeader": "Teie tuur ei ole jagatud, kas soovite seda jagada?",
"sharePrivateBtn1": "Jaga avalikult",
"sharePrivateBtn2": "Jaga oma organisatsiooniga",
"sharePrivateProgress": "Jagamine töös...",
"sharePrivateErr": "Jagamine ebaõnnestus, proovi uuesti või",
"sharePrivateOk": "Jagamist on värskendatud, laadimine...",
"sharePreviewAsUser": "Eelvaade",
"shareHeader1": "Teie tuur on <strong>avalikult ligipääsetav</strong>.",
"shareHeader2": "Teie tuur on saadaval teie organisatsiooni liikmetele (sisselogimine nõutud).",
"shareLinkHeader": "Jagage oma tuuri",
"shareLinkOpen": "AVA",
"shareA1": "Kasutage nuppu %SHAREIMG% <a href='%LINK1%' target='_blank'>rakenduse üksuse lehel</a>. Kui soovite tühistada ka veebikaardi jagamise, siis kasutage <a href='%LINK2%' target='_blank'>veebikaardi üksuse lehte</a>.",
"shareWarning": "%WITH% jagamine on keelatud, kuna Te ei ole <a href='%LINK%' target='_blank'>veebikaardi</a> omanik.",
"shareWarningWith1": "avalikult",
"shareWarningWith2": "avalikult ja organisatsiooniga"
},
"locator": {
"error": "Asukoht pole kättesaadav"
},
"saveErrorSocial": {
"title": "Sotsiaalmeedias jagamise värskendus",
"panel1": "Teie loo ilmet on sotsiaalmeedias täiustatud, kuid teie ArcGIS-i veebirakenduse üksuse pealkiri ei ühti teie loo pealkirjaga.",
"panel1tooltip": "Kui lisate pealkirja, kokkuvõtte ja pisipildi, näeb teie lugu välja järgmine:",
"panel2": "Millist pealkirja soovite sotsiaalmeedias kasutada:",
"panel2q1": "Loo pealkiri (soovitatav)",
"panel2q1tooltip": "Selle suvandi valimisel muudetakse teie üksuse pealkiri loo pealkirjaga samasuguseks ning sünkroonitakse täiendavad koosturis tehtud muudatused.",
"panel2q2": "Üksuse pealkiri",
"panel3": "Selleks et oma loo ilmet sotsiaalmeedias veelgi täiustada, kasutage portaali ${MYSTORIES}, et lisada kokkuvõte ja pisipilt.",
"panel4": "Ära hoiata mind enam selle loo puhul",
"mystories": "Minu lood",
"btnSave": "Salvesta"
}
}
}); |
function getScores(container){
$.getJSON("/scores", function(result){
scores = result.sort(function(left, right){
return right.scores - left.scores;
});
var limit = 10;
$.each(scores, function(index, item){
if(index > limit)
return;
var html = "<tr><td>"+item.name+"</td><td>"+item.scores+"</td></tr>";
container.append(html);
});
});
}
|
'use strict';
/**
* Module dependencies
*/
var fs = require('fs'),
util = require('util'),
avail = require('./util');
/**
* Configuration prototype
*/
var cfg = {
settings: {
geographies: [],
keywords: []
}
};
exports = module.exports = cfg;
cfg.set = function(setting, val){
if(1 === arguments.length) {
return cfg.settings[setting];
} else {
cfg.settings[setting] = val;
return cfg;
}
};
cfg.get = function(setting, val){
return cfg.set(setting);
};
cfg.authentication = function authentication(authware) {
return cfg.set('authware', authware);
}
cfg.geographies = function geographies(dir) {
var geos = [],
kws = [],
geo;
fs.readdirSync(dir).forEach(function(file) {
geo = JSON.parse(fs.readFileSync(dir+'/'+file, 'utf8'));
geos.push(geo);
kws = kws.concat((geo.properties||{}).keywords);
});
var keywords = cfg.get('keywords').concat(kws);
cfg.set('keywords', avail.unique(keywords));
return cfg.set('geographies', geos);
};
cfg.keywords = function keywords(kws) {
if(!util.isArray(kws)) {
kws = Array.prototype.slice.call(arguments);
}
return cfg.set('keywords', kws);
}
|
var Shipments = "";
$(function () {
var isInstalled = false;
var storeId = AspxCommerce.utils.GetStoreID();
var portalId = AspxCommerce.utils.GetPortalID();
var userName = AspxCommerce.utils.GetUserName();
var cultureName = AspxCommerce.utils.GetCultureName();
var customerId = AspxCommerce.utils.GetCustomerID();
var ip = AspxCommerce.utils.GetClientIP();
var countryName = AspxCommerce.utils.GetAspxClientCoutry();
var sessionCode = AspxCommerce.utils.GetSessionCode();
var userFriendlyURL = AspxCommerce.utils.IsUserFriendlyUrl();
var aspxCommonObj = {
StoreID: storeId,
PortalID: portalId,
UserName: userName,
CultureName: cultureName
};
Shipments = {
config: {
isPostBack: false,
async: false,
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{}',
dataType: "json",
baseURL: aspxservicePath + "AspxCoreHandler.ashx/",
url: "",
method: ""
},
IsModuleInstalled: function () {
var rewardPoints = 'AspxRewardPoints';
$.ajax({
type: "POST", beforeSend: function (request) {
request.setRequestHeader('ASPX-TOKEN', _aspx_token);
request.setRequestHeader("UMID", umi);
request.setRequestHeader("UName", AspxCommerce.utils.GetUserName());
request.setRequestHeader("PID", AspxCommerce.utils.GetPortalID());
request.setRequestHeader("PType", "v");
request.setRequestHeader('Escape', '0');
},
url: AspxCommerce.utils.GetAspxServicePath() + "AspxCommonHandler.ashx/" + "GetModuleInstallationInfo",
data: JSON2.stringify({ moduleFriendlyName: rewardPoints, aspxCommonObj: aspxCommonObj }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
isInstalled = response.d;
},
error: function () {
}
});
},
init: function () {
Shipments.HideDivs();
$("#divShipmentsDetails").show();
Shipments.BindShipmentsDetails(null, null, null);
Shipments.ForceNumericInput();
$("#btnShipmentBack").click(function () {
Shipments.HideDivs();
$("#divShipmentsDetails").show();
$("#divShipmentsDetailForm table >tbody").html('');
});
$("#btnShipmentsSearch").on("click", function () {
Shipments.SearchShipments();
});
$('#txtShippingMethodName,#txtOrderID,#txtSearchShipToName').keyup(function (event) {
if (event.keyCode == 13) {
$("#btnShipmentsSearch").click();
}
});
},
ajaxCall: function (config) {
$.ajax({
type: Shipments.config.type, beforeSend: function (request) {
request.setRequestHeader('ASPX-TOKEN', _aspx_token);
request.setRequestHeader("UMID", umi);
request.setRequestHeader("UName", AspxCommerce.utils.GetUserName());
request.setRequestHeader("PID", AspxCommerce.utils.GetPortalID());
request.setRequestHeader("PType", "v");
request.setRequestHeader('Escape', '0');
},
contentType: Shipments.config.contentType,
cache: Shipments.config.cache,
async: Shipments.config.async,
data: Shipments.config.data,
dataType: Shipments.config.dataType,
url: Shipments.config.url,
success: Shipments.ajaxSuccess,
error: Shipments.ajaxFailure
});
},
ForceNumericInput: function (defaultQuantityInGroup) {
$("#txtOrderID").keydown(function (e) {
if ($.inArray(e.keyCode, [8, 9, 27, 13, 110]) !== -1 ||
(e.keyCode == 65 && e.ctrlKey === true) ||
(e.keyCode >= 35 && e.keyCode <= 39)) {
return;
}
if (e.shiftKey == 190) {
e.preventDefault();
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
if (e.keyCode == 96) {
if ($(this).val() == 0) {
e.preventDefault();
}
}
if (e.keyCode == 8) {
if (($(this).val() > 0) && ($(this).val() < 9)) {
e.preventDefault();
}
}
});
},
HideDivs: function () {
$("#divShipmentsDetails").hide();
$("#divShipmentsDetailForm").hide();
},
BindShipmentsDetails: function (shippingMethodNm, orderID, shipNm) {
var shipmentObj = {
OrderID: orderID,
ShipToName: shipNm,
ShippingMethodName: shippingMethodNm
};
this.config.method = "GetShipmentsDetails";
this.config.data = { shipmentObj: shipmentObj, aspxCommonObj: aspxCommonObj };
var data = this.config.data;
var offset_ = 1;
var current_ = 1;
var perpage = ($("#gdvShipmentsDetails_pagesize").length > 0) ? $("#gdvShipmentsDetails_pagesize :selected").text() : 10;
$("#gdvShipmentsDetails").sagegrid({
url: this.config.baseURL,
functionMethod: this.config.method,
colModel: [
{ display: getLocale(AspxShipmentsManagement, 'Shipping Method ID'), name: 'shipping_methodId', cssclass: 'cssClassHide', controlclass: '', coltype: 'label', align: 'left', hide: true },
{ display: getLocale(AspxShipmentsManagement, 'Shipping Method Name'), name: 'shipping_method_name', cssclass: 'cssClassHeadNumber', controlclass: '', coltype: 'label', align: 'left' },
{ display: getLocale(AspxShipmentsManagement, 'Order ID'), name: 'order_id', cssclass: '', controlclass: '', coltype: 'label', align: 'left'},
{ display: getLocale(AspxShipmentsManagement, 'Ship to Name'), name: 'ship_to_name', cssclass: '', controlclass: '', coltype: 'label', align: 'left' },
{ display: getLocale(AspxShipmentsManagement, 'Shipping Cost'), name: 'shipping_rate', cssclass: '', controlclass: 'cssClassFormatCurrency', coltype: 'currency', align: 'right' },
{ display: getLocale(AspxShipmentsManagement, 'Actions'), name: 'action', cssclass: 'cssClassAction', coltype: 'label', align: 'center' }
],
buttons: [
{ display: getLocale(AspxShipmentsManagement, 'View'), name: 'view', enable: true, _event: 'click', trigger: '3', callMethod: 'Shipments.ViewShipments', arguments: '1,2,3,4,5,6' }
],
rp: perpage,
nomsg: getLocale(AspxShipmentsManagement, "No Records Found!"),
param: data,
current: current_,
pnew: offset_,
sortcol: { o: { sorter: true }, 5: { sorter: false} }
});
$('.cssClassFormatCurrency').formatCurrency({ colorize: true, region: '' + region + '' });
},
ViewShipments: function (tblID, argus) {
switch (tblID) {
case "gdvShipmentsDetails":
Shipments.HideDivs();
$("#divShipmentsDetailForm").show();
Shipments.BindShippindMethodDetails(argus[4]);
break;
}
},
BindShippindMethodDetails: function (orderId) {
this.config.url = this.config.baseURL + "BindAllShipmentsDetails";
this.config.data = JSON2.stringify({ orderID: orderId, aspxCommonObj: aspxCommonObj });
this.config.ajaxCallMode = 1;
this.ajaxCall(this.config);
},
SearchShipments: function (data) {
var shippingMethodNm = $.trim($("#txtShippingMethodName").val());
var orderID = $.trim($("#txtOrderID").val());
var shipNm = $.trim($("#txtSearchShipToName").val());
if (shippingMethodNm.length < 1) {
shippingMethodNm = null;
}
if (orderID.length < 1) {
orderID = null;
}
if (shipNm.length < 1) {
shipNm = null;
}
Shipments.BindShipmentsDetails(shippingMethodNm, orderID, shipNm);
},
ajaxSuccess: function (data) {
switch (Shipments.config.ajaxCallMode) {
case 0:
break;
case 1:
Shipments.IsModuleInstalled();
var tableElements = '';
var grandTotal = '';
var dicountAmount = '';
var couponAmount = '';
var rewardAmount = '';
var taxTotal = '';
var subTotal = '';
var shippingCost = '';
var additionalNote = "";
var giftCard = "";
$.each(data.d, function (index, value) {
var cv = "";
if (value.CostVariants != "") {
cv = "(" + value.CostVariants + ")";
}
tableElements += '<tr>';
tableElements += '<td>' + value.ItemName + cv + '</td>';
$("#shipmentDate").html(value.ShipmentDate);
tableElements += '<td>' + value.SKU + '</td>';
tableElements += '<td>' + value.ShippingAddress + '</td>';
tableElements += '<td>' + value.ShippingMethod + '</td>';
tableElements += '<td class="cssClassAlignRight"><span class="cssClassFormatCurrency" >' + value.ShippingRate + '</span></td>';
tableElements += '<td class="cssClassAlignRight"><span class="cssClassFormatCurrency" >' + value.Price.toFixed(2) + '</span></td>';
tableElements += '<td>' + value.Quantity + '</td>';
tableElements += '<td class="cssClassAlignRight"><span class="cssClassFormatCurrency" >' + (value.Price * value.Quantity).toFixed(2) + '</span></td>';
tableElements += '</tr>';
if (index == 0) {
subTotal = '<tr>';
subTotal += '<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td class="cssClassLabel cssClassOrderPrice"><b>'+getLocale(AspxShipmentsManagement,"Sub Total:")+'</b></td>';
subTotal += '<td><span class="cssClassFormatCurrency" >' + (value.GrandSubTotal).toFixed(2) + '</span></td>';
subTotal += '</tr>';
var orderID = value.OrderID;
$.ajax({
type: "POST",
url: Shipments.config.baseURL + "GetTaxDetailsByOrderID",
data: JSON2.stringify({ orderId: orderID, aspxCommonObj: aspxCommonObj }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
$.each(msg.d, function (index, val) {
if (val.TaxSubTotal != 0) {
taxTotal += '<tr>';
taxTotal += '<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td class="cssClassLabel"><b>' + val.TaxManageRuleName + ':' + '</b></td>';
taxTotal += '<td><span class="cssClassFormatCurrency" >' + (val.TaxSubTotal).toFixed(2) + '</span></td>';
taxTotal += '</tr>';
}
});
}
});
shippingCost = '<tr>';
shippingCost += '<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td class="cssClassLabel cssClassOrderPrice"><b>'+getLocale(AspxShipmentsManagement,"Shipping Cost:")+'</b></td>';
shippingCost += '<td class="cssClassAlignRight"><span class="cssClassFormatCurrency" >' + value.TotalShippingCost.toFixed(2) + '</span></td>';
shippingCost += '</tr>';
dicountAmount = '<tr>';
dicountAmount += '<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td class="cssClassLabel cssClassOrderPrice"><b>'+getLocale(AspxShipmentsManagement,"Discount Amount:")+'</b></td>';
dicountAmount += '<td class="cssClassAlignRight"><span class="cssClassFormatCurrency" > - ' + value.DiscountAmount.toFixed(2) + '</span></td>';
dicountAmount += '</tr>';
couponAmount = '<tr>';
couponAmount += '<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td class="cssClassLabel cssClassOrderPrice"><b>'+getLocale(AspxShipmentsManagement,"Coupon Amount:")+'</b></td>';
couponAmount += '<td class="cssClassAlignRight"><span class="cssClassFormatCurrency" > - ' + value.CouponAmount.toFixed(2) + '</span></td>';
couponAmount += '</tr>';
rewardAmount = '<tr>';
rewardAmount += '<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td class="cssClassLabel cssClassOrderPrice"><b>'+getLocale(AspxShipmentsManagement,"Discount(RewardPoints):")+'</b></td>';
rewardAmount += '<td class="cssClassAlignRight"><span class="cssClassFormatCurrency" > - ' + value.RewardDiscountAmount.toFixed(2) + '</span></td>';
rewardAmount += '</tr>';
if (value.GiftCard != "" && value.GiftCard != null) {
var giftCardUsed = value.GiftCard.split('#');
for (var g = 0; g < giftCardUsed.length; g++) {
var keyVal = giftCardUsed[g].split("=");
giftCard += '<tr><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td class="cssClassLabel cssClassOrderPrice"><b>'+getLocale(AspxShipmentsManagement,"GiftCard")+'(' + keyVal[0] + '):</b></td>';
giftCard += '<td class="cssClassAlignRight"><span class="cssClassFormatCurrency" >' + keyVal[1] + '</span></td>';
giftCard += '</tr>';
}
}
grandTotal = '<tr>';
grandTotal += '<td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td class="cssClassLabel cssClassOrderPrice"><b>'+getLocale(AspxShipmentsManagement,"Grand Total:")+'</b></td>';
grandTotal += '<td class="cssClassAlignRight"><span class="cssClassFormatCurrency" >' + value.GrandTotal.toFixed(2) + '</span></td>';
grandTotal += '</tr>';
additionalNote = value.Remarks;
}
});
$("#divShipmentsDetailForm").find('table>tbody').html(tableElements);
$("#divShipmentsDetailForm").find('table>tbody').append(subTotal);
$("#divShipmentsDetailForm").find('table>tbody').append(taxTotal);
$("#divShipmentsDetailForm").find('table>tbody').append(shippingCost);
$("#divShipmentsDetailForm").find('table>tbody').append(dicountAmount);
$("#divShipmentsDetailForm").find('table>tbody').append(couponAmount);
if (isInstalled == true) {
$("#divShipmentsDetailForm").find('table>tbody').append(rewardAmount);
}
$("#divShipmentsDetailForm").find('table>tbody').append(giftCard);
$("#divShipmentsDetailForm").find('table>tbody').append(grandTotal);
$("#divShipmentsDetailForm").find("table>tbody tr:even").addClass("sfEven");
$("#divShipmentsDetailForm").find("table>tbody tr:odd").addClass("sfOdd");
if (additionalNote != '' && additionalNote != undefined) {
$(".remarks").html("").html("*Additional Note :- '" + additionalNote + "'");
} else {
$(".remarks").html("");
}
Shipments.HideDivs();
$("#divShipmentsDetailForm").show();
$('.cssClassFormatCurrency').formatCurrency({ colorize: true, region: '' + region + '' });
break;
}
}
};
Shipments.init();
}); |
const app = getApp();
const util = require('../../utils/util.js');
Page({
data: {
id: "#24",
text: "",
fileName: "",
item: null
},
onLoad: function (options) {
let id = options.id;
this.setData({
id: id
});
// if (!id) {
// id = (new Date()).getTime();
// }
let item = app.globalData.list.find(d => d.id === id);
if (item) {
this.setData({
fileName: id,
item: item
});
let FileSystemManager = wx.getFileSystemManager();
FileSystemManager.readFile({
filePath: `${wx.env.USER_DATA_PATH}/${item.fileName}`,
encoding: "utf8",
success: (res) => {
let data = res.data;
if (data) {
this.setData({
text: data
});
}
},
fail: () => {
this.setData({
text: ""
});
}
});
} else {
let new_item = {
id: id,
fileName: id,
des: "",
time: util.formatTime(new Date())
};
this.setData({
fileName: id
});
app.globalData.list.push(new_item);
this.setData({
item: new_item
});
}
},
input: util.debounce(function (e) {
let val = e.detail.value;
this.data.item.des = val.substr(0, 50);
const fs = wx.getFileSystemManager();
fs.writeFileSync(`${wx.env.USER_DATA_PATH}/${this.data.fileName}`, val, 'utf8');
}, 3000)
}); |
const webpack = require('webpack');
const path = require('path');
const buildPath = path.resolve(__dirname, 'build');
const nodeModulesPath = path.resolve(__dirname, 'node_modules');
const TransferWebpackPlugin = require('transfer-webpack-plugin');
const config = {
// Entry points to the project
entry: [
'webpack/hot/dev-server',
'webpack/hot/only-dev-server',
path.join(__dirname, '/src/app/app.js'),
],
// Server Configuration options
devServer: {
contentBase: 'src/www', // Relative directory for base of server
devtool: 'eval',
hot: true, // Live-reload
inline: true,
port: 3000, // Port Number
host: 'localhost', // Change to '0.0.0.0' for external facing server
},
devtool: 'eval',
output: {
path: buildPath, // Path of output file
filename: 'app.js',
chunkFilename: '/[name].js'
},
plugins: [
// Enables Hot Modules Replacement
new webpack.HotModuleReplacementPlugin(),
// Allows error warnings but does not stop compiling.
new webpack.NoErrorsPlugin(),
// Moves files
new TransferWebpackPlugin([
{from: 'www'},
], path.resolve(__dirname, 'src')),
],
module: {
loaders: [
{
// React-hot loader and
test: /\.js$/, // All .js files
loaders: ['react-hot', 'babel-loader'], // react-hot is like browser sync and babel loads jsx and es6-7
exclude: [nodeModulesPath],
},
],
},
};
module.exports = config;
|
/**
* A wrapper-promise which rejects when discarded
*/
let DiscardablePromise = /** @class */ (() => {
class DiscardablePromise {
constructor(promise) {
this.promise = promise;
}
then(onfulfilled, onrejected) {
return this.promise.then(x => {
if (this.isDiscarded) {
return Promise.reject(DiscardablePromise.discarded);
}
else {
return Promise.resolve(x);
}
}).then(onfulfilled, onrejected);
}
discard() {
this.isDiscarded = true;
}
}
DiscardablePromise.discarded = Symbol("discarded");
return DiscardablePromise;
})();
export { DiscardablePromise };
//# sourceMappingURL=discardable-promise.js.map |
'use strict';
const Message = function () {
//constructor
}
Message.prototype.userId = function (userId) {
this.userId = userId;
}
Message.prototype.text = function (text) {
this.text = text;
}
module.exports = Message; |
import { config } from 'rebass'
const caps = {
textTransform: 'uppercase',
letterSpacing: '.2em'
}
const dark = {
name: 'Dark',
fontFamily: '"Avenir Next", Helvetica, sans-serif',
color: '#eee',
backgroundColor: '#111',
borderRadius: 5,
borderColor: `rgba(255, 255, 255, ${1/16})`,
colors: {
...config.colors,
blue: '#00d9f7',
info: '#00d9f7',
green: '#0f8',
success: '#0f8',
orange: '#fb3',
warning: '#fb3',
primary: '#778',
midgray: '#778',
gray: '#333339',
secondary: '#333339',
red: '#f04',
error: '#f04'
},
inverted: '#222',
scale: [
0, 10, 20, 40, 80
],
Card: {
backgroundColor: '#222',
border: 0,
},
Panel: {
borderWidth: 2,
backgroundColor: '#000'
},
NavItem: {
fontSize: 12,
...caps
},
Heading: {
...caps
},
Button: {
...caps,
fontSize: 12,
color: '#00d9f7',
opacity: 7/8
},
ButtonOutline: {
...caps,
fontSize: 12,
color: '#00d9f7',
opacity: 7/8
},
Toolbar: {
minHeight: 64,
color: '#00d9f7',
backgroundColor: `rgba(0, 0, 0, ${7/8})`
},
Label: { opacity: 5/8 },
Menu: {
color: '#00d9f7',
backgroundColor: '#000'
},
Message: {
color: '#111',
opacity: 15/16
},
Text: {
opacity: 7/8
},
Footer: {
opacity: 1/2
}
}
export default dark |
var gulp = require("gulp");
var ts = require("gulp-typescript");
var uglify_js = require("gulp-uglify");
var sourcemaps = require("gulp-sourcemaps");
var rename = require("gulp-rename");
var header = require("gulp-header");
var replace = require("gulp-replace");
var merge = require("merge2");
var config = require("./config.json");
var pkg = require("../package.json");
gulp.task("js", ["js:header"]);
gulp.task("js:build", function() {
var ts_result = gulp.src("js/main.ts")
.pipe(sourcemaps.init())
.pipe(ts({
removeComments: true,
declarationFiles: true,
target: "ES5",
out: "timeline.js"
}));
return merge([
ts_result.dts.pipe(gulp.dest("dist")),
ts_result.js
.pipe(sourcemaps.write(".", {
includeContent: true
}))
.pipe(gulp.dest("dist"))
]);
});
gulp.task("js:compress", ["js:build"], function() {
return gulp.src("dist/timeline.js")
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(uglify_js({
mangle: true
}))
.pipe(rename({
extname: ".min.js"
}))
.pipe(sourcemaps.write(".", {
includeContent: true,
sourceRoot: "."
}))
.pipe(gulp.dest("dist"));
});
gulp.task("js:clean", ["js:compress"], function() {
return gulp.src(["dist/**/*.d.ts"])
.pipe(replace(/^[/]{2,}\s?<reference.*/g, ""))
.pipe(gulp.dest("dist"));
});
gulp.task("js:header", ["js:clean"], function() {
return gulp.src("dist/*.js")
.pipe(header(config.banner, {
pkg: pkg,
year: (new Date()).getFullYear()
}))
.pipe(gulp.dest("dist"));
});
|
/**
* Creatine is a power-up to the CreateJS libraries, providing data structures
* and algorithms for game development. You see here:
*
* - **Scene management** - *with scene stacks based on Cocos2D Director*
* - **Scene transitions** - *you can also create new transitions*
* - **Input handling** - *keyboard, mouse, touch and gamepads*
* - **Resources and Factories** - *facilitates the access to PreloadJS*
* - **Sound handling** - *facilitates the access to SoundJS*
* - **Storage helper** - *easy use of localStorage*
* - **Plugins** - *create and install plugins that work together with the
* engine*
* - **Particles** - *a fast particle system for canvas*
* - **Tile Maps** - *total integration with Tiled, supporting all map
* projections*
*
* Feel free to use, modify, improve, make additions and suggestions.
*
* ## Usage
*
* You can access creatine function by the namespace `creatine` or its shortcut
* `tine`:
*
* console.log(creatine.VERSION);
*
* // is the same as
* console.log(tine.VERSION);
*
* To start your development with creatine, you need to create a Game object,
* which will create a canvas object inside the page. The basic signature for
* the game object:
*
* var game = new tine.Game(config, state);
*
* where `config` is a configuration object or an url for a JSON, and `state`
* is a collection of functions that will be called by the game in certain
* moments.
*
* You can use 5 functions inside the state: `boot`, `preload`, `create`,
* `update`, or `draw`. The `boot` function is called right after the game
* create the canvas and initialize the managers and right before the
* preloading; you can initialize 3th party libraries here. The `preload`
* function is called after booting and before the preloading itself; you can
* add items to be loaded here. When preloading is finished, the game call the
* `create` function, where you can create the objects of you game or
* initialize the base scenes. The functions `update` and `draw` are called
* periodically in that order. The recommended way to pass these function is
* like this:
*
* var game = new tine.Game(null, {
* boot : function() { ... },
* preload : function() { ... },
* create : function() { ... },
* update : function() { ... },
* draw : function() { ... }
* })
*
* The configuration object must be an object or an url for a JSON in the
* following format:
*
* var config = {
* project : 'creatine_game',
* width : 800,
* height : 600,
* container : null,
* framerate : 60,
* showfps : false,
* background_color : '#000',
* resources : {
* base_path : './',
* manifest : []
* }
* }
*
* This configuration is also the default options of the engine. You can
* provide only a part of these variables because game will use the default
* configuration for missing values.
*
* ## Links
*
* - **Site**: http://creatine.guineashots.com
* - **Repository**: http://github.com/renatopp/creatine
* - **API**: http://docs.guineashots.com/creatine
* - **User Guide**: http://docs.guineashots.com/creatine/guide
* - **Examples**: http://creatine.guineashots.com/examples
*
*
* @module creatine
* @main creatine
*/ |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require ace/ace
//= require_tree .
//= require ace/ace
//= require ace/theme-github
//= require jquery-ace.min
//= require_self
$(function() {
$('.code-area').ace({ theme: 'github' });
$('.code-area').data('ace').editor.session().setTabSize(2);
}); |
/**
* Panelify - smooth, vertical sliding panels using Waypoints.
*
* @param {string} {default: 'bottom-in-view'} offset - where the panel sliding triggers.
* @param {number} {default: 1068 } minScreenWidth - minimum screen with (in pixels) where panelify should be applied.
*
*/
var panelify = new Panelify(); // default, desktop (1068px min width)
// var panelify = new Panelify('bottom-in-view'); // default, desktop (1068px min width)
// var panelify = new Panelify('0%'); // triggers at the top of each panel, desktop (1068px min width)
// NOTE: Tablet and Mobile support is buggy (to varying degrees) and therefore the constructors below work
// and will work fine for small desktop browser windows but are not fully supported/mobile friendly
// var panelify = new Panelify('0%', 350); // triggers at the top of each panel, mobile and greater (350px min width).
// var panelify = new Panelify('bottom-in-view', 768); // triggers at the bottom of each panel, tablets and greater (768px min width).
|
// Package metadata for Meteor.js web platform (https://www.meteor.com/)
// This file is defined within the Meteor documentation at
//
// http://docs.meteor.com/#/full/packagejs
//
// and it is needed to define a Meteor package
'use strict';
var Both = ['client', 'server'];
var Client = 'client';
Package.describe({
name: 'useraccounts:oauth',
summary: 'UserAccounts oauth package.',
version: '2.0.0',
git: 'https://github.com/meteor-useraccounts/oauth.git',
});
Package.onUse(function pkgOnUse(api) {
api.versionsFrom('1.0');
// Logger
api.use([
'service-configuration',
'jag:pince@0.0.9',
'underscore',
'useraccounts:core@2.0.0',
], Both);
api.imply([
'service-configuration',
'useraccounts:core',
], Both);
api.use([
'templating',
], Client);
api.addFiles([
'src/texts.js',
'src/templates/ua_oauth.html',
'src/templates/ua_oauth_btn.html',
'src/templates/ua_oauth_btn.css',
], Client);
api.addFiles([
'src/_globals.js',
'src/logger.js',
'src/modules/oauth_module.js',
'src/main.js',
], Both);
});
|
//AppliedRules.defineSetByTag
module.exports = (function( tagId ){
if( this.rules ){
this.ruleIds = Object.keys( this.rules ).filter( ruleId => (
this.rules[ruleId].tags && this.rules[ruleId].tags.includes( tagId )
))
} else this.ruleIds = [];
return this.ruleIds;
}); |
/* eslint-env jasmine */
'use strict'
require('../../jsdom.setup.js')
var React = require('react')
var expect = require('chai').expect
var enzyme = require('enzyme')
var render = enzyme.render
var mount = enzyme.mount
var PlotlyComponent = require('../../../../js/components/assessment/plotlyComponent')
const mockedData = [
{
x: ['one', 'two', 'three'],
y: [1, 2, 3],
name: 'Current',
type: 'bar',
marker: {
color: '#337ab7'
}
},
{
x: ['one', 'two', 'three'],
y: [2, 4, 6],
name: 'Target',
type: 'bar',
marker: {
color: '#b7b7b7',
line: {
color: '#b7b7b7',
width: 5
}
}
}
]
const mockedLayout = {}
const mockedConfig = {}
describe('Plotly component', function () {
it('plotly render', function () {
const wrapper = render(<PlotlyComponent data={mockedData} layout={mockedLayout} config={mockedConfig} />)
expect(wrapper.find('div'))
.to
.have
.length(1)
})
it.skip('plotly mount', function () {
// TODO: shim enough of D3 to get this to run
// See also: https://gist.github.com/etpinard/bee7d62b43b6bb286950
const wrapper = mount(<PlotlyComponent data={mockedData} layout={mockedLayout} config={mockedConfig} />)
expect(wrapper.find('.plotly'))
.to
.have
.length(1)
})
})
|
$(document).ready(function() {
$('.image-link').magnificPopup({type:'image'});
});
$('.images-container').magnificPopup({
delegate: 'a',
type: 'image'
});
$('.budynek-link').magnificPopup({
type: 'image'
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.