code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
(function(){
'use strict';
var should = require('chai').should();
var nakedGunQuotes = require('../src/lib/index.js');
describe('Naked Gun Quotes', function(){
it('should contains at least 10 items', function(){
var enoughQuotes = Object.keys(nakedGunQuotes.all).length > 9;
enoughQuotes.should.equal(true);
});
it('should return a quote', function(){
var quote = nakedGunQuotes.random();
var enoughLength = quote.length > 2;
quote.should.be.a('string');
enoughLength.should.equal(true);
});
it('should match Cuban', function(){
var allQuotes = nakedGunQuotes.all;
allQuotes[0].should.match(/Cuban/);
});
it('should return undefined', function(){
var allQuotes = nakedGunQuotes.all;
should.equal(allQuotes[10000], undefined);
});
});
var rewire = require("rewire");
var nGQRewire = rewire('../src/lib/index.js');
describe('Naked Gun Quotes Rewire', function(){
it('should throw an exception', function(){
(function() {
nGQRewire.__set__('nakedGunQuotes', {});
nGQRewire.random();
}).should.throw('Expected an array');
});
});
})();
| earl-hacker/naked-gun-quotes | test/test.js | JavaScript | mit | 1,195 |
module.exports = {
'onProgress callbacks should be called on each notify' : function(test) {
var promise = Vow.promise(),
calledArgs1 = [],
calledArgs2 = [];
promise.progress(function(val) {
calledArgs1.push(val);
});
promise.then(null, null, function(val) {
calledArgs2.push(val);
});
promise.notify(1);
promise.notify(2);
promise.then(function() {
test.deepEqual(calledArgs1, [1, 2]);
test.deepEqual(calledArgs2, [1, 2]);
test.done();
});
promise.fulfill();
},
'onProgress callbacks shouldn\'t be called after promise has been fulfilled' : function(test) {
var promise = Vow.promise(),
called = false;
promise.progress(function() {
called = true;
});
promise.fulfill();
promise.notify();
promise.notify();
promise.then(function() {
test.ok(!called);
test.done();
});
},
'onProgress callbacks shouldn\'t be called after promise has been rejected' : function(test) {
var promise = Vow.promise(),
called = false;
promise.progress(function() {
called = true;
});
promise.reject();
promise.notify();
promise.notify();
promise.fail(function() {
test.ok(!called);
test.done();
});
}
}; | vladrudych/realvnz | node_modules/bem-node/node_modules/vow/test/promise.notify.js | JavaScript | mit | 1,502 |
var module = angular.module('restangular', ['ngResource']);
module.provider('Restangular', function() {
// Configuration
/**
* Those are HTTP safe methods for which there is no need to pass any data with the request.
*/
var safeMethods= ["get", "head", "options", "trace"];
function isSafe(operation) {
return _.contains(safeMethods, operation);
}
/**
* This is the BaseURL to be used with Restangular
*/
var baseUrl = "";
this.setBaseUrl = function(newBaseUrl) {
baseUrl = newBaseUrl;
}
/**
* Sets the extra fields to keep from the parents
*/
var extraFields = [];
this.setExtraFields = function(newExtraFields) {
extraFields = newExtraFields;
}
/**
* Some default $http parameter to be used in EVERY call
**/
var defaultHttpFields = {};
this.setDefaultHttpFields = function(values) {
defaultHttpFields = values;
}
function withHttpDefaults(obj) {
return _.defaults(obj, defaultHttpFields);
}
/**
* Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override
**/
var methodOverriders = [];
this.setMethodOverriders = function(values) {
var overriders = _.extend([], values);
if (isOverridenMethod('delete', overriders)) {
overriders.push("remove");
}
methodOverriders = overriders;
}
var isOverridenMethod = function(method, values) {
var search = values || methodOverriders;
return !_.isUndefined(_.find(search, function(one) {
return one.toLowerCase() === method.toLowerCase();
}));
}
/**
* Sets the URL creator type. For now, only Path is created. In the future we'll have queryParams
**/
var urlCreator = "path";
this.setUrlCreator = function(name) {
if (!_.has(urlCreatorFactory, name)) {
throw new Error("URL Path selected isn't valid");
}
urlCreator = name;
}
/**
* You can set the restangular fields here. The 3 required fields for Restangular are:
*
* id: Id of the element
* route: name of the route of this element
* parentResource: the reference to the parent resource
*
* All of this fields except for id, are handled (and created) by Restangular. By default,
* the field values will be id, route and parentResource respectively
*/
var restangularFields = {
id: "id",
route: "route",
parentResource: "parentResource",
restangularCollection: "restangularCollection",
what: "restangularWhat"
}
this.setRestangularFields = function(resFields) {
restangularFields = _.extend(restangularFields, resFields);
}
/**
* Sets the Response parser. This is used in case your response isn't directly the data.
* For example if you have a response like {meta: {'meta'}, data: {name: 'Gonto'}}
* you can extract this data which is the one that needs wrapping
*
* The ResponseExtractor is a function that receives the response and the method executed.
*/
var responseExtractor = function(response) {
return response;
}
this.setResponseExtractor = function(extractor) {
responseExtractor = extractor;
}
this.setResponseInterceptor = this.setResponseExtractor;
/**
* Request interceptor is called before sending an object to the server.
*/
var requestInterceptor = function(element) {
return element;
}
this.setRequestInterceptor = function(interceptor) {
requestInterceptor = interceptor;
}
/**
* This method is called after an element has been "Restangularized".
*
* It receives the element, a boolean indicating if it's an element or a collection
* and the name of the model
*
*/
var onElemRestangularized = function(elem) {
return elem;
}
this.setOnElemRestangularized = function(post) {
onElemRestangularized = post;
}
/**
* Sets the getList type. The getList returns an Array most of the time as it's a collection of values.
* However, sometimes you have metadata and in that cases, the getList ISN'T an array.
* By default, it's going to be set as array
*/
var listTypeIsArray = true;
this.setListTypeIsArray = function(val) {
listTypeIsArray = val;
};
/**
* This lets you set a suffix to every request.
*
* For example, if your api requires that for JSon requests you do /users/123.json, you can set that
* in here.
*
*
* By default, the suffix is null
*/
var suffix = null;
this.setRequestSuffix = function(newSuffix) {
suffix = newSuffix;
}
var resourceMethods = ['$delete','$get','$getList','$head','$options','$patch',
'$post','$put','$query','$remove','$save', '$trace'];
//Internal values and functions
var urlCreatorFactory = {};
/**
* Base URL Creator. Base prototype for everything related to it
**/
var BaseCreator = function() {
};
BaseCreator.prototype.parentsArray = function(current) {
var parents = [];
while(!_.isUndefined(current)) {
parents.push(current);
current = current[restangularFields.parentResource];
}
return parents.reverse();
}
BaseCreator.prototype.resource = function(current, $resource, headers) {
var reqParams = {};
return $resource(this.base(current) + "/:" + restangularFields.what + (suffix || '') , {}, {
getList: withHttpDefaults({method: 'GET', params: reqParams, isArray: listTypeIsArray, headers: headers || {}}),
get: withHttpDefaults({method: 'GET', params: reqParams, isArray: false, headers: headers || {}}),
put: withHttpDefaults({method: 'PUT', params: reqParams, isArray: false, headers: headers || {}}),
post: withHttpDefaults({method: 'POST', params: reqParams, isArray: false, headers: headers || {}}),
remove: withHttpDefaults({method: 'DELETE', params: reqParams, isArray: false, headers: headers || {}}),
head: withHttpDefaults({method: 'HEAD', params: reqParams, isArray: false, headers: headers || {}}),
trace: withHttpDefaults({method: 'TRACE', params: reqParams, isArray: false, headers: headers || {}}),
options: withHttpDefaults({method: 'OPTIONS', params: reqParams, isArray: false, headers: headers || {}}),
patch: withHttpDefaults({method: 'PATCH', params: reqParams, isArray: false, headers: headers || {}})
});
}
/**
* This is the Path URL creator. It uses Path to show Hierarchy in the Rest API.
* This means that if you have an Account that then has a set of Buildings, a URL to a building
* would be /accounts/123/buildings/456
**/
var Path = function() {
};
Path.prototype = new BaseCreator();
Path.prototype.base = function(current) {
return baseUrl + _.reduce(this.parentsArray(current), function(acum, elem) {
var currUrl = acum + "/" + elem[restangularFields.route];
if (!elem[restangularFields.restangularCollection]) {
currUrl += "/" + elem[restangularFields.id];
}
return currUrl;
}, '');
}
Path.prototype.fetchUrl = function(current, params) {
var baseUrl = this.base(current);
if (params[restangularFields.what]) {
baseUrl += "/" + params[restangularFields.what];
}
return baseUrl;
}
urlCreatorFactory.path = Path;
this.$get = ['$resource', '$q', function($resource, $q) {
var urlHandler = new urlCreatorFactory[urlCreator]();
function restangularizeBase(parent, elem, route) {
elem[restangularFields.route] = route;
elem.addRestangularMethod = _.bind(addRestangularMethodFunction, elem);
if (parent) {
var restangularFieldsForParent = _.union(
_.values( _.pick(restangularFields, ['id', 'route', 'parentResource']) ),
extraFields
);
elem[restangularFields.parentResource]= _.pick(parent, restangularFieldsForParent);
}
return elem;
}
function one(parent, route, id) {
var elem = {};
elem[restangularFields.id] = id;
return restangularizeElem(parent, elem , route);
}
function all(parent, route) {
return restangularizeCollection(parent, {} , route, true);
}
// Promises
function restangularizePromise(promise, isCollection) {
promise.call = _.bind(promiseCall, promise);
promise.get = _.bind(promiseGet, promise);
promise[restangularFields.restangularCollection] = isCollection;
if (isCollection) {
promise.push = _.bind(promiseCall, promise, "push");
}
return promise;
}
function promiseCall(method) {
var deferred = $q.defer();
var callArgs = arguments;
this.then(function(val) {
var params = Array.prototype.slice.call(callArgs, 1);
var func = val[method];
func.apply(val, params);
deferred.resolve(val);
});
return restangularizePromise(deferred.promise, this[restangularFields.restangularCollection]);
}
function promiseGet(what) {
var deferred = $q.defer();
this.then(function(val) {
deferred.resolve(val[what]);
});
return restangularizePromise(deferred.promise, this[restangularFields.restangularCollection]);
}
// Elements
function stripRestangular(elem) {
return _.omit(elem, _.values(_.omit(restangularFields, 'id')));
}
function addCustomOperation(elem) {
elem.customOperation = _.bind(customFunction, elem);
_.each(["put", "post", "get", "delete"], function(oper) {
_.each(["do", "custom"], function(alias) {
var name = alias + oper.toUpperCase();
elem[name] = _.bind(customFunction, elem, oper);
});
});
elem.customGETLIST = _.bind(fetchFunction, elem);
elem.doGETLIST = elem.customGETLIST;
}
function copyRestangularizedElement(fromElement) {
var copiedElement = angular.copy(fromElement);
return restangularizeElem(copiedElement[restangularFields.parentResource],
copiedElement, copiedElement[restangularFields.route]);
}
function restangularizeElem(parent, elem, route) {
var localElem = restangularizeBase(parent, elem, route);
localElem = _.omit(localElem, resourceMethods);
localElem[restangularFields.restangularCollection] = false;
localElem.get = _.bind(getFunction, localElem);
localElem.getList = _.bind(fetchFunction, localElem);
localElem.put = _.bind(putFunction, localElem);
localElem.post = _.bind(postFunction, localElem);
localElem.remove = _.bind(deleteFunction, localElem);
localElem.head = _.bind(headFunction, localElem);
localElem.trace = _.bind(traceFunction, localElem);
localElem.options = _.bind(optionsFunction, localElem);
localElem.patch = _.bind(patchFunction, localElem);
//RequestLess connection
localElem.one = _.bind(one, localElem, localElem);
localElem.all = _.bind(all, localElem, localElem);
addCustomOperation(localElem);
return onElemRestangularized(localElem, false, route);
}
function restangularizeCollection(parent, elem, route) {
var localElem = restangularizeBase(parent, elem, route);
localElem[restangularFields.restangularCollection] = true;
localElem.post = _.bind(postFunction, localElem, null);
localElem.head = _.bind(headFunction, localElem);
localElem.trace = _.bind(traceFunction, localElem);
localElem.options = _.bind(optionsFunction, localElem);
localElem.patch = _.bind(patchFunction, localElem);
localElem.getList = _.bind(fetchFunction, localElem, null);
addCustomOperation(localElem);
return onElemRestangularized(localElem, true, route);
}
function whatObject(what) {
var search = {};
if (what) {
search[restangularFields.what] = what;
}
return search;
}
function fetchFunction(what, params, headers) {
var search = whatObject(what);
var __this = this;
var deferred = $q.defer();
urlHandler.resource(this, $resource, headers).getList(_.extend(search, params), function(resData) {
var data = responseExtractor(resData, 'getList', what, urlHandler.fetchUrl(__this, search));
var processedData = _.map(data, function(elem) {
if (!__this[restangularFields.restangularCollection]) {
return restangularizeElem(__this, elem, what);
} else {
return restangularizeElem(null, elem, __this[restangularFields.route]);
}
});
processedData = _.extend(data, processedData);
if (!__this[restangularFields.restangularCollection]) {
deferred.resolve(restangularizeCollection(__this, processedData, what));
} else {
deferred.resolve(restangularizeCollection(null, processedData, __this[restangularFields.route]));
}
}, function error(response) {
deferred.reject(response);
});
return restangularizePromise(deferred.promise, true);
}
function elemFunction(operation, params, obj, headers) {
var __this = this;
var deferred = $q.defer();
var resParams = params || {};
var resObj = obj || this;
var route = resParams[restangularFields.what] || this[restangularFields.route];
var fetchUrl = urlHandler.fetchUrl(this, resParams);
var callObj = obj || stripRestangular(this);
callObj = requestInterceptor(callObj, operation, route, fetchUrl)
var okCallback = function(resData) {
var elem = responseExtractor(resData, operation, route, fetchUrl) || resObj;
if (operation === "post" && !__this[restangularFields.restangularCollection]) {
deferred.resolve(restangularizeElem(__this, elem, resParams[restangularFields.what]));
} else {
deferred.resolve(restangularizeElem(__this[restangularFields.parentResource], elem, __this[restangularFields.route]));
}
};
var errorCallback = function(response) {
deferred.reject(response);
};
// Overring HTTP Method
var callOperation = operation;
var callHeaders = _.extend({}, headers);
var isOverrideOperation = isOverridenMethod(operation);
if (isOverrideOperation) {
callOperation = 'post';
callHeaders = _.extend(callHeaders, {'X-HTTP-Method-Override': operation});
}
if (isSafe(operation)) {
if (isOverrideOperation) {
urlHandler.resource(this, $resource, callHeaders)[callOperation](resParams, {}, okCallback, errorCallback);
} else {
urlHandler.resource(this, $resource, callHeaders)[callOperation](resParams, okCallback, errorCallback);
}
} else {
urlHandler.resource(this, $resource, callHeaders)[callOperation](resParams, callObj, okCallback, errorCallback);
}
return restangularizePromise(deferred.promise);
}
function getFunction(params, headers) {
return _.bind(elemFunction, this)("get", params, undefined, headers);
}
function deleteFunction(params, headers) {
return _.bind(elemFunction, this)("remove", params, {}, headers);
}
function putFunction(params, headers) {
return _.bind(elemFunction, this)("put", params, undefined, headers);
}
function postFunction(what, elem, params, headers) {
return _.bind(elemFunction, this)("post", _.extend(whatObject(what), params), elem, headers);
}
function headFunction(params, headers) {
return _.bind(elemFunction, this)("head", params, undefined, headers);
}
function traceFunction(params, headers) {
return _.bind(elemFunction, this)("trace", params, undefined, headers);
}
function optionsFunction(params, headers) {
return _.bind(elemFunction, this)("options", params, undefined, headers);
}
function patchFunction(params, headers) {
return _.bind(elemFunction, this)("patch", params, undefined, headers);
}
function customFunction(operation, path, params, headers, elem) {
return _.bind(elemFunction, this)(operation, _.extend(whatObject(path), params), elem, headers);
}
function addRestangularMethodFunction(name, operation, path, defaultParams, defaultHeaders, defaultElem) {
var bindedFunction;
if (operation === 'getList') {
bindedFunction = _.bind(fetchFunction, this, path);
} else {
bindedFunction = _.bind(customFunction, this, operation, path);
}
this[name] = function(params, headers, elem) {
var callParams = _.defaults({
params: params,
headers: headers,
elem: elem
}, {
params: defaultParams,
headers: defaultHeaders,
elem: defaultElem
});
return bindedFunction(callParams.params, callParams.headers, callParams.elem);
}
}
var service = {};
service.copy = _.bind(copyRestangularizedElement, service);
service.one = _.bind(one, service, null);
service.all = _.bind(all, service, null);
return service;
}];
}
); | maratgaip/notakg | app/components/restangular/src/restangular.js | JavaScript | mit | 20,727 |
require('normalize.css/normalize.css');
require('styles/App.scss');
import React from 'react';
import ReactDOM from 'react-dom';
//获取图片相关的数据
let imageDatas = require('../../data/imageData.json');
//获取区间内的一个随机值
function getRangeRandom(left, right){
return Math.ceil(Math.random()*(right-left)+left);
}
function get30DegRandom(){
return (Math.random()>0.5?"":"-") +Math.ceil(Math.random()*30)
}
//将图片名信息转换成图片的URL信息
imageDatas = (function genImageURL(imageDataArr){
for(let i=0,j=imageDataArr.length;i<j;i++){
let singleImageData = imageDataArr[i];
singleImageData.imageURL = require('../images/' + singleImageData.fileName);
imageDataArr[i] = singleImageData;
}
return imageDataArr;
})(imageDatas);
//imageDatas = genImageURL(imageDatas);
class ImgFigure extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
/*
*
*/
handleClick(e){
if(this.props.arrange.isCenter){
this.props.inverse();
}else{
this.props.center();
}
e.stopPropagation();
e.preventDefault();
}
render(){
let styleObj = {};
if(this.props.arrange.pos){
styleObj = this.props.arrange.pos;
}
if(this.props.arrange.isCenter){
styleObj['zIndex'] = 11;
}
//如果图片的旋转角度有值,添加旋转css
if(this.props.arrange.rotate){
(['MozTransform','msTransform','WebkitTransform','transform']).forEach(function(value){
styleObj[value]='rotate('+this.props.arrange.rotate+'deg)';
}.bind(this));
}
let imgFigureClassName = "img-figure";
imgFigureClassName += this.props.arrange.isInverse?' is-inverse ':'';
return(
<figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}>
<img src = {this.props.data.imageURL}
alt = {this.props.data.title}
/>
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
<div className="img-back" onClick={this.handleClick}>
<p>
{this.props.data.desc}
</p>
</div>
</figcaption>
</figure>
)
}
}
//控制组件
class ControllerUnit extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
// 如果点击的是当前正在选中态的按钮,则翻转图片,否则将对应的图片居中
if (this.props.arrange.isCenter) {
this.props.inverse();
} else {
this.props.center();
}
e.stopPropagation();
e.preventDefault();
}
render(){
let controlelrUnitClassName = "controller-unit";
// 如果对应的是居中的图片,显示控制按钮的居中态
if (this.props.arrange.isCenter) {
controlelrUnitClassName += " is-Center";
// 如果同时对应的是翻转图片, 显示控制按钮的翻转态
if (this.props.arrange.isInverse) {
controlelrUnitClassName += " is-inverse";
}
}
return(
<span className={controlelrUnitClassName} onClick={this.handleClick}></span>
);
}
}
class AppComponent extends React.Component {
constructor(props) {
super(props);
this.state = {imgArrangeArr: [
/*{ pos: {
left: '0',
top: '0'
},
rotate: 0, //旋转角度
isInverse: false, //图片正反面
isCenter: false
}*/
]};
this.constant = {
centerPos:{
left: 0,
top:0
},
hPosRange: {
leftSecX: [0, 0],
rightSecX: [0, 0],
y: [0, 0]
},
vPosRange: {
x: [0, 0],
topY: [0, 0]
}};
}
/*
* 翻转图片
*/
inverse(index){
return function(){
let imgArrangeArr = this.state.imgArrangeArr;
imgArrangeArr[index].isInverse = !imgArrangeArr[index].isInverse;
this.setState({
imgArrangeArr:imgArrangeArr
});
}.bind(this);
}
/*
* 重新布局所有图片
*/
rearrange(centerIndex){
let imgArrangeArr = this.state.imgArrangeArr,
constant = this.constant,
centerPos = constant.centerPos,
hPosRange = constant.hPosRange,
vPosRange = constant.vPosRange,
hPosRangeLeftSecX = constant.hPosRange.leftSecX,
hPosRangeRightSecX = hPosRange.rightSecX,
hPosRangeY = hPosRange.y,
vPosRangeTopY = vPosRange.topY,
vPosRangeX = vPosRange.x,
imgArrangeTopArr = [],
topImgNum = Math.floor(Math.random() * 2),
topImgSpliceIndex = 0,
imgArrangeCenterArr = imgArrangeArr.splice(centerIndex,1);
imgArrangeCenterArr[0] = {
pos : centerPos,
rotate : 0,
isCenter: true
}
//中间的 图片不需要旋转
topImgSpliceIndex = Math.ceil(Math.random()*(imgArrangeArr.length - topImgNum))
imgArrangeTopArr = imgArrangeArr.splice(topImgSpliceIndex, topImgNum);
//布局上侧图片
imgArrangeTopArr.forEach(function(value,index){
imgArrangeTopArr[index] = {
pos: {
left: getRangeRandom(vPosRangeX[0], vPosRangeX[1]),
top: getRangeRandom(vPosRangeTopY[0],vPosRangeTopY[1])
},
rotate:get30DegRandom(),
isCenter: false
}
});
//布局左右两侧的图片
for(let i=0, j=imgArrangeArr.length, k=j/2; i<j; i++){
let hPosRangeLORX = null;
//
if(i < k){
hPosRangeLORX = hPosRangeLeftSecX;
}else{
hPosRangeLORX = hPosRangeRightSecX;
}
imgArrangeArr[i] = {
pos: {
left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]),
top: getRangeRandom(hPosRangeY[0], hPosRangeY[1])
},
rotate:get30DegRandom(),
isCenter: false
}
}
if(imgArrangeTopArr && imgArrangeTopArr[0]){
imgArrangeArr.splice(topImgSpliceIndex, 0, imgArrangeTopArr[0]);
}
imgArrangeArr.splice(centerIndex, 0, imgArrangeCenterArr[0]);
//更新状态
this.setState({
imgArrangeArr:imgArrangeArr
});
}
/*
*
*/
center(index){
return function(){
this.rearrange(index);
}.bind(this);
}
componentDidMount() {
console.log('componentDidMount ' + this.refs.stage);
//拿到舞台的大小
let stageDOM = ReactDOM.findDOMNode(this.refs.stage),
stageW = stageDOM.scrollWidth,
stageH = stageDOM.scrollHeight,
halfStageW = Math.ceil(stageW / 2),
halfStageH = Math.ceil(stageH / 2);
//拿到一个imgfigure的大小
let imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0),
imgW = imgFigureDOM.scrollWidth,
imgH = imgFigureDOM.scrollHeight,
halfImgW = Math.ceil(imgW / 2),
halfImgH = Math.ceil(imgH / 2);
//计算中心图片的位置点
console.log(this.constant);
this.constant.centerPos = {
left: halfStageW - halfImgW,
top: halfStageH - halfImgH
}
//计算左侧位置图片
this.constant.hPosRange = {
leftSecX:[-halfImgW, halfStageW - halfImgW*3],
rightSecX:[halfStageW + halfImgW, stageW - halfImgW],
y:[-halfImgH, stageH - halfImgH]
}
this.constant.vPosRange = {
topY:[-halfImgH, halfStageH - halfImgH * 3],
x:[halfStageW - imgW, halfStageW]
}
this.rearrange(0);
}
render() {
let controllerUnits = [],
imgFigures = [];
// console.log(this.state);
imageDatas.forEach(function(value,index){
if (!this.state.imgArrangeArr[index]) {
this.state.imgArrangeArr[index] = {
pos: {
left:0,
top:0
},
rotate: 0,
isInverse: false
}
}
imgFigures.push(<ImgFigure key={index} data={value} ref={"imgFigure" + index} arrange={this.state.imgArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
controllerUnits.push(<ControllerUnit key={index} arrange={this.state.imgArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
}.bind(this));
return (
<section className="stage" ref="stage">
<section className="img-sec">
{imgFigures}
</section>
<nav className="controller-nav">
{controllerUnits}
</nav>
</section>
);
}
}
AppComponent.defaultProps = {
};
export default AppComponent;
| geniusq1981/gallery-by-react | src/components/Main.js | JavaScript | mit | 8,539 |
// flow-typed signature: 765715ff54fe6fa81326e12a000dd3bf
// flow-typed version: <<STUB>>/rc-tabs_v^9.1.4/flow_v0.53.1
/**
* This is an autogenerated libdef stub for:
*
* 'rc-tabs'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'rc-tabs' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'rc-tabs/dist/rc-tabs' {
declare module.exports: any;
}
declare module 'rc-tabs/dist/rc-tabs.min' {
declare module.exports: any;
}
declare module 'rc-tabs/es/index' {
declare module.exports: any;
}
declare module 'rc-tabs/es/InkTabBar' {
declare module.exports: any;
}
declare module 'rc-tabs/es/InkTabBarMixin' {
declare module.exports: any;
}
declare module 'rc-tabs/es/KeyCode' {
declare module.exports: any;
}
declare module 'rc-tabs/es/ScrollableInkTabBar' {
declare module.exports: any;
}
declare module 'rc-tabs/es/ScrollableTabBar' {
declare module.exports: any;
}
declare module 'rc-tabs/es/ScrollableTabBarMixin' {
declare module.exports: any;
}
declare module 'rc-tabs/es/SwipeableInkTabBar' {
declare module.exports: any;
}
declare module 'rc-tabs/es/SwipeableTabBarMixin' {
declare module.exports: any;
}
declare module 'rc-tabs/es/SwipeableTabContent' {
declare module.exports: any;
}
declare module 'rc-tabs/es/TabBar' {
declare module.exports: any;
}
declare module 'rc-tabs/es/TabBarMixin' {
declare module.exports: any;
}
declare module 'rc-tabs/es/TabContent' {
declare module.exports: any;
}
declare module 'rc-tabs/es/TabPane' {
declare module.exports: any;
}
declare module 'rc-tabs/es/Tabs' {
declare module.exports: any;
}
declare module 'rc-tabs/es/utils' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/index' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/InkTabBar' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/InkTabBarMixin' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/KeyCode' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/ScrollableInkTabBar' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/ScrollableTabBar' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/ScrollableTabBarMixin' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/SwipeableInkTabBar' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/SwipeableTabBarMixin' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/SwipeableTabContent' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/TabBar' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/TabBarMixin' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/TabContent' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/TabPane' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/Tabs' {
declare module.exports: any;
}
declare module 'rc-tabs/lib/utils' {
declare module.exports: any;
}
// Filename aliases
declare module 'rc-tabs/dist/rc-tabs.js' {
declare module.exports: $Exports<'rc-tabs/dist/rc-tabs'>;
}
declare module 'rc-tabs/dist/rc-tabs.min.js' {
declare module.exports: $Exports<'rc-tabs/dist/rc-tabs.min'>;
}
declare module 'rc-tabs/es/index.js' {
declare module.exports: $Exports<'rc-tabs/es/index'>;
}
declare module 'rc-tabs/es/InkTabBar.js' {
declare module.exports: $Exports<'rc-tabs/es/InkTabBar'>;
}
declare module 'rc-tabs/es/InkTabBarMixin.js' {
declare module.exports: $Exports<'rc-tabs/es/InkTabBarMixin'>;
}
declare module 'rc-tabs/es/KeyCode.js' {
declare module.exports: $Exports<'rc-tabs/es/KeyCode'>;
}
declare module 'rc-tabs/es/ScrollableInkTabBar.js' {
declare module.exports: $Exports<'rc-tabs/es/ScrollableInkTabBar'>;
}
declare module 'rc-tabs/es/ScrollableTabBar.js' {
declare module.exports: $Exports<'rc-tabs/es/ScrollableTabBar'>;
}
declare module 'rc-tabs/es/ScrollableTabBarMixin.js' {
declare module.exports: $Exports<'rc-tabs/es/ScrollableTabBarMixin'>;
}
declare module 'rc-tabs/es/SwipeableInkTabBar.js' {
declare module.exports: $Exports<'rc-tabs/es/SwipeableInkTabBar'>;
}
declare module 'rc-tabs/es/SwipeableTabBarMixin.js' {
declare module.exports: $Exports<'rc-tabs/es/SwipeableTabBarMixin'>;
}
declare module 'rc-tabs/es/SwipeableTabContent.js' {
declare module.exports: $Exports<'rc-tabs/es/SwipeableTabContent'>;
}
declare module 'rc-tabs/es/TabBar.js' {
declare module.exports: $Exports<'rc-tabs/es/TabBar'>;
}
declare module 'rc-tabs/es/TabBarMixin.js' {
declare module.exports: $Exports<'rc-tabs/es/TabBarMixin'>;
}
declare module 'rc-tabs/es/TabContent.js' {
declare module.exports: $Exports<'rc-tabs/es/TabContent'>;
}
declare module 'rc-tabs/es/TabPane.js' {
declare module.exports: $Exports<'rc-tabs/es/TabPane'>;
}
declare module 'rc-tabs/es/Tabs.js' {
declare module.exports: $Exports<'rc-tabs/es/Tabs'>;
}
declare module 'rc-tabs/es/utils.js' {
declare module.exports: $Exports<'rc-tabs/es/utils'>;
}
declare module 'rc-tabs/lib/index.js' {
declare module.exports: $Exports<'rc-tabs/lib/index'>;
}
declare module 'rc-tabs/lib/InkTabBar.js' {
declare module.exports: $Exports<'rc-tabs/lib/InkTabBar'>;
}
declare module 'rc-tabs/lib/InkTabBarMixin.js' {
declare module.exports: $Exports<'rc-tabs/lib/InkTabBarMixin'>;
}
declare module 'rc-tabs/lib/KeyCode.js' {
declare module.exports: $Exports<'rc-tabs/lib/KeyCode'>;
}
declare module 'rc-tabs/lib/ScrollableInkTabBar.js' {
declare module.exports: $Exports<'rc-tabs/lib/ScrollableInkTabBar'>;
}
declare module 'rc-tabs/lib/ScrollableTabBar.js' {
declare module.exports: $Exports<'rc-tabs/lib/ScrollableTabBar'>;
}
declare module 'rc-tabs/lib/ScrollableTabBarMixin.js' {
declare module.exports: $Exports<'rc-tabs/lib/ScrollableTabBarMixin'>;
}
declare module 'rc-tabs/lib/SwipeableInkTabBar.js' {
declare module.exports: $Exports<'rc-tabs/lib/SwipeableInkTabBar'>;
}
declare module 'rc-tabs/lib/SwipeableTabBarMixin.js' {
declare module.exports: $Exports<'rc-tabs/lib/SwipeableTabBarMixin'>;
}
declare module 'rc-tabs/lib/SwipeableTabContent.js' {
declare module.exports: $Exports<'rc-tabs/lib/SwipeableTabContent'>;
}
declare module 'rc-tabs/lib/TabBar.js' {
declare module.exports: $Exports<'rc-tabs/lib/TabBar'>;
}
declare module 'rc-tabs/lib/TabBarMixin.js' {
declare module.exports: $Exports<'rc-tabs/lib/TabBarMixin'>;
}
declare module 'rc-tabs/lib/TabContent.js' {
declare module.exports: $Exports<'rc-tabs/lib/TabContent'>;
}
declare module 'rc-tabs/lib/TabPane.js' {
declare module.exports: $Exports<'rc-tabs/lib/TabPane'>;
}
declare module 'rc-tabs/lib/Tabs.js' {
declare module.exports: $Exports<'rc-tabs/lib/Tabs'>;
}
declare module 'rc-tabs/lib/utils.js' {
declare module.exports: $Exports<'rc-tabs/lib/utils'>;
}
| boldr/boldr-ui | flow-typed/npm/rc-tabs_vx.x.x.js | JavaScript | mit | 7,085 |
'use strict';
angular.module('guestyCities.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'guestyCtrl'
});
}])
.controller('guestyCtrl', function($scope, loadDataFromAirbnb, $timeout, $http, $location) {
$scope.vouchersData = [];
$scope.cities = [{
city: 'London',
London: 'London'
}, {
city: 'Tel-Aviv',
TelAviv: 'Tel-Aviv'
}, {
city: 'New York',
NewYork: 'New York'
}, {
city: 'Paris',
Paris: 'Paris'
}];
$scope.city = $scope.cities[2].city;
$scope.openDetailsView = function(id, name, address, city) {
$location.url('/view2/' + id + '/' + name + '/' + address + '/' + city);
}
loadDataFromAirbnb.getData($scope.cities[2]).then(function(response) {
$scope.vouchersData = response.data.search_results;
});
}); | didiyakovleva/guesty-airbnb | app/view1/view1.js | JavaScript | mit | 1,002 |
class Rectangle extends Shape {
// 1
} | dogescript/dogescript | test/language-spec/grows/declaration/simple/expect.js | JavaScript | mit | 42 |
import { ValidationError } from 'api/errors';
import validations from 'lib/validations';
function assert(v) {
if (!v.test) {
throw new ValidationError(v.message);
}
}
const validate = {};
for (const name of Object.keys(validations)) {
validate[name] = (x) => assert(validations[name](x));
}
export default validate;
| juanmadurand/flatboard | app/src/api/validate.js | JavaScript | mit | 330 |
'use strict';
var readline = require('readline');
var semver = require('semver');
var utils = require('./utils');
var Autoversion = function() {
this.events = {
// format:
// `eventName: [callback, ...]`
};
};
Autoversion.prototype.utils = utils;
Autoversion.prototype.read = function() { return this; };
Autoversion.prototype.write = function(currentVersion, nextVersion) { return this; };
Autoversion.prototype.on = function(eventName, callback) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
};
Autoversion.prototype.off = function(eventName, callback) {
if (!callback) {
delete this.events[eventName];
} else {
this.events[eventName].forEach(function(event) {
if(event == callback) {
delete this.events[eventName][event];
}
});
}
};
Autoversion.prototype.trigger = function(eventName, args) {
if (this.events[eventName]) {
this.events[eventName].forEach(function(event) {
event(args);
});
}
};
var autoversion = new Autoversion();
process.nextTick(function() {
var argv = require('minimist')(process.argv.slice(2));
var commands = argv._;
var tasks = ['patch', 'minor', 'major'];
var allTasks = tasks.slice();
allTasks.unshift('version');
if (commands.length > 1 || allTasks.indexOf(commands[0]) < 0) {
console.log('Usage: autoversion ' + allTasks.join('|') + ' [-y, --yes]');
return;
}
if (tasks.indexOf(commands[0]) < 0) {
console.log( autoversion.read() );
} else {
var version = autoversion.read();
var newVersion = semver.inc(version, commands[0]);
var setVersion = function() {
autoversion.write(version, newVersion);
autoversion.trigger(commands[0], newVersion);
autoversion.trigger('any', newVersion);
};
if (argv.y || argv.yes) {
setVersion();
} else {
var rl = readline.createInterface(process.stdin, process.stdout);
console.log('New version will be ' + newVersion);
rl.question('Do you want to continue? [y/n] ', function(answer) {
rl.close();
if (['y', 'yes'].indexOf(answer.toLowerCase()) < 0) {
console.log('Aborting!');
process.exit(1);
}
setVersion();
});
}
}
});
module.exports = autoversion
| philipvonbargen/autoversion | lib/autoversion.js | JavaScript | mit | 2,319 |
const JarvisModule = require('jarvis-module')
describe('JarvisModule test suite', () => {
describe('constructor tests', () => {
it('should instantiate virtual module without errors', () => {
expect(() => {
const mod = new JarvisModule()
expect(mod).toBeTruthy()
}).not.toThrow();
});
});
describe('init tests', () => {
it('should init fine', () => {
const mod = new JarvisModule()
expect(() => {
mod.init()
}).not.toThrow()
});
});
});
| gehsekky/jarvis | lib/__tests__/jarvis-module.test.js | JavaScript | mit | 516 |
export default class DataTable
{
constructor( dataTable )
{
this.dataTable = dataTable;
this.rows = this.dataTable.getElementsByTagName( 'tr' );
this.headers = this.dataTable.getElementsByTagName( 'th' );
this.setRole();
this.renderHtml();
}
setRole()
{
this.dataTable.setAttribute( 'role', 'table' );
for( let row of this.rows )
{
row.setAttribute( 'role', 'row' );
}
for( let header of this.headers )
{
header.setAttribute( 'role', 'columnheader' );
}
}
renderHtml()
{
let container = document.createElement( 'div' );
this.dataTable.parentNode.insertBefore( container, this.dataTable );
container.classList.add( 'data-table--responsive' );
container.appendChild( this.dataTable );
}
} | SuperDJ/smaterial | src/js/classes/DataTable.js | JavaScript | mit | 738 |
var expect = chai.expect;
describe("/notes", function() {
describe("GET /notes", function() {
// it('Should Only be able to access when Authed', function(done){
// superagent
// .get('/notes')
// .set('PHP_AUTH_USER', 'test')
// .set('PHP_AUTH_PW', 'test')
// .end(function(err, res) {
// res.should.have.status(401);
// done();
// });
// });
});
}); | oo7ph/US-Backend-Candidate-Lab | public/scripts/api_tests.js | JavaScript | mit | 432 |
(function () {
'use strict';
angular
.module('dopplerRelay')
.service('reports', reports);
reports.$inject = [
'$http',
'$window',
'$q',
'auth',
'RELAY_CONFIG',
'linkUtilities',
'$log'
];
function reports($http, $window, $q, auth, RELAY_CONFIG, linkUtilities, $log) {
var reportsService = {
getRecords: getRecords,
getMoreRecordsFromUrl: getMoreRecordsFromUrl,
selectedRecord: selectedRecord,
getReportRequests: getReportRequests,
createReportRequest: createReportRequest,
getDeliveriesAggregations: getDeliveriesAggregations,
getEventsAggregations: getEventsAggregations
};
return reportsService;
function getDeliveriesAggregations(from, to, aggregationsInterval) {
var url = RELAY_CONFIG.baseUrl
+ '/accounts/' + auth.getAccountName()
+ '/statistics/deliveries/' + aggregationsInterval
+ '?per_page=200';
if (from) {
url = url + '&from=' + from.toISOString();
}
if (to) {
url = url + '&to=' + to.toISOString();
}
return $http({
actionDescription: 'Gathering deliveries aggregations',
method: 'GET',
avoidStandarErrorHandling: true,
url: url
})
.then(function (response) {
return response;
})
.catch(function (reason) {
$log.error(reason);
return $q.reject(reason);
});
}
function getEventsAggregations(from, to, aggregationsInterval) {
var url = RELAY_CONFIG.baseUrl
+ '/accounts/' + auth.getAccountName()
+ '/statistics/events/' + aggregationsInterval
+ '?per_page=200';
if (from) {
url = url + '&from=' + from.toISOString();
}
if (to) {
url = url + '&to=' + to.toISOString();
}
return $http({
actionDescription: 'Gathering events aggregations',
method: 'GET',
avoidStandarErrorHandling: true,
url: url
})
.then(function (response) {
return response;
})
.catch(function (reason) {
$log.error(reason);
return $q.reject(reason);
});
}
function selectedRecord(item) {
var results = [];
if (item) {
for (var i = 0; i < 5; i++) {
if (item == jsonReports[i].email) {
results.push(jsonReports[i]);
}
}
return results;
} else {
return false;
}
}
function getFormatedNumber(num) {
var suffix;
var separator = ',';
var shortNumber = num.toString().substring(0, 3);
if (num.toString().length <= 9 && num.toString().length > 8) {
suffix = 'm';
return shortNumber = shortNumber + suffix;
}
if (num.toString().length <= 8 && num.toString().length > 7) {
suffix = 'm';
return shortNumber = shortNumber.substring(0, 2) + separator + shortNumber.substring(2) + suffix;
}
if (num.toString().length <= 7 && num.toString().length > 6) {
suffix = 'm';
return shortNumber = shortNumber.substring(0, 1) + separator + shortNumber.substring(1) + suffix;
}
if (num.toString().length <= 6 && num.toString().length > 5) {
suffix = 'k';
return shortNumber = shortNumber + suffix;
}
if (num.toString().length <= 5 && num.toString().length > 4) {
suffix = 'k';
return shortNumber = shortNumber.substring(0, 2) + separator + shortNumber.substring(2) + suffix;
}
return num;
}
function getRecords(from, to, filter, perPage) {
var accountName = auth.getAccountName();
var url = '/accounts/' + accountName + '/deliveries';
// TODO: UrlEncode parameters
var params = [];
if (filter) {
params.push('filter=' + filter);
}
if (from) {
params.push('from=' + from.toISOString());
}
if (to) {
params.push('to=' + to.toISOString());
}
if (perPage) {
params.push('per_page=' + perPage);
}
if (params.length)
{
url += '?' + params.join('&');
}
return getMoreRecordsFromUrl(url);
}
function getMoreRecordsFromUrl(url) {
return $http({
actionDescription: 'Gathering records',
method: 'GET',
url: RELAY_CONFIG.baseUrl + url
})
.then(function (response) {
var nextLink = linkUtilities.findNextLink(response.data._links);
return ({ records: response.data.items, nextLink: nextLink && nextLink.href, deliveriesCount: response.data.itemsCount });
})
.catch(function (reason) {
$log.error(reason);
return $q.reject(reason);
});
}
function getReportRequests() {
return $http({
actionDescription: 'Gathering report requests',
method: 'GET',
url: RELAY_CONFIG.baseUrl + '/reports/reportrequests'
}).then(function (response) {
return (response.data.items);
});
}
function createReportRequest(reportRequest) {
var data = {
start_date: reportRequest.startDate.toISOString(),
end_date: reportRequest.endDate.toISOString()
};
return $http({
actionDescription: 'Creating report request',
method: 'POST',
url: RELAY_CONFIG.baseUrl + '/reports/reportrequest',
data: data
});
}
}
})();
| DopplerRelay/relay-webapp | src/wwwroot/services/reports.js | JavaScript | mit | 5,473 |
/**
* @ngdoc function
* @name AQ.controller:LocationsController
* @requires factories/AQ.factory:data
* @requires factories/AQ.factory:state
* @requires factories/AQ.factory:api
*
* @description
* Controller for the Locations state.
*/
AQ.controller('LocationsController', function (data, state, api) {
'use strict';
state.setTitle('Locations');
if (_.isEmpty(data.locations)) {
api.getLocations();
}
});
| ExCiteS/airquality | app/scripts/controllers/LocationsController.js | JavaScript | mit | 428 |
'use strict';
import { TaskDoneList } from './TaskList';
import ProjectList from '../project/ProjectList';
import Collapse from '../generic/rcc-collapse';
export default class TaskBoard extends React.Component {
render() {
let { unDoneTasks, doneTasks, ...other } = this.props;
return (
<section className="main">
<Collapse className='undone' title="UnDone Tasks" element='article' collapsed={false}>
<ProjectList className='undone' orderBy='priority' ascending={false} tasks={unDoneTasks} {...other} />
</Collapse>
<hr/>
<Collapse className='done' title="Done Tasks" element='article' collapsed={true}>
<TaskDoneList className="done" orderBy='updatedAt' ascending={false} tasks={doneTasks} />
</Collapse>
</section>
)
}
}
| Juan1ll0/TwoDu | frontend/components/task/TaskBoard.js | JavaScript | mit | 901 |
const nodeExternals = require('webpack-node-externals');
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const webpackOpts = {
mode: 'development',
entry: './src/index.ts',
target: 'node',
output: {
path: path.join(__dirname, 'lib'),
filename: 'index.js',
libraryTarget: 'commonjs2',
},
resolve: {
extensions: ['.ts', '.js'],
},
plugins: [
new webpack.LoaderOptionsPlugin({
options: {
test: /\.ts$/,
ts: {
compiler: 'typescript',
configFile: 'tsconfig.json',
},
tslint: {
emitErrors: true,
failOnHint: true,
},
},
}),
],
devtool: 'source-map',
module: {
rules: [
{
test: /\.ts$/,
loaders: 'ts-loader',
},
],
},
externals: [
nodeExternals({ modulesDir: '../../node_modules' }),
nodeExternals(),
],
};
module.exports = webpackOpts;
| cdmbase/fullstack-pro | packages/sample-core/webpack.config.js | JavaScript | mit | 1,152 |
'use strict';
angular.module('main').controller('MainController', ['$scope','$rootScope', '$state', '$location',
function ($scope,$rootScope, $state,$location) {
// $scope.gotoRetro = function (){
// $location.path('/retro');
// };
}
]); | TCSAgile/AgileToolKit | public/modules/main/controllers/main.client.controller.js | JavaScript | mit | 266 |
"use strict";
angular.module('calibrus')
.controller('DataEntrySummaryAndSignatureCtrl', function ($scope, $ionicModal, $ionicPopup, enrollmentService) {
var vm = this;
vm.enableSignature = true;
vm.refreshEnrollment = function () {
vm.order = enrollmentService.getEnrollment();
vm.hasSigned = !!vm.order.signature;
};
vm.signaturePad = {};
vm.signature = null;
$ionicModal.fromTemplateUrl('templates/modals/signature.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function (modal) {
vm.modal = modal;
});
vm.toggleAgreeAndSign = function () {
if (!vm.order.signature) return vm.showSignatureModal();
$ionicPopup.confirm({
title: 'Confirm',
template: 'Are you sure you want to remove your signature?'
}).then(function (res) {
if (res) {
enrollmentService.setSignature(null);
}
vm.refreshEnrollment();
});
};
vm.toggleContactPreference = function (contactPreference) {
enrollmentService.setContactPreference(contactPreference);
vm.refreshEnrollment();
};
vm.showSignatureModal = function () {
vm.modal.show();
};
vm.sign = function (signature) {
enrollmentService.setSignature(signature);
vm.modal.hide();
};
$scope.$on('modal.hidden', function() {
vm.refreshEnrollment();
});
$scope.$on('$destory', function () {
vm.modal && vm.modal.remove && vm.modal.remove();
});
vm.refreshEnrollment();
});
| tazmanrising/IntiotgAngular | Companies/Calibrus/Mobileapp/www/js/controllers/data-entry-summary-and-signature.js | JavaScript | mit | 1,556 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
/**
* Link to the project's GitHub page:
* https://github.com/pickhardt/coffeescript-codemirror-mode
*/
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../src/lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("coffeescript", function(conf) {
var ERRORCLASS = "error";
function wordRegexp(words) {
return new RegExp("^((" + words.join(")|(") + "))\\b");
}
var operators = /^(?:->|=>|\+[+=]?|-[\-=]?|\*[\*=]?|\/[\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\|=?|\^=?|\~|!|\?)/;
var delimiters = /^(?:[()\[\]{},:`=;]|\.\.?\.?)/;
var identifiers = /^[_A-Za-z$][_A-Za-z$0-9]*/;
var properties = /^(@|this\.)[_A-Za-z$][_A-Za-z$0-9]*/;
var wordOperators = wordRegexp(["and", "or", "not",
"is", "isnt", "in",
"instanceof", "typeof"]);
var indentKeywords = ["for", "while", "loop", "if", "unless", "else",
"switch", "try", "catch", "finally", "class"];
var commonKeywords = ["break", "by", "continue", "debugger", "delete",
"do", "in", "of", "new", "return", "then",
"this", "throw", "when", "until"];
var keywords = wordRegexp(indentKeywords.concat(commonKeywords));
indentKeywords = wordRegexp(indentKeywords);
var stringPrefixes = /^('{3}|\"{3}|['\"])/;
var regexPrefixes = /^(\/{3}|\/)/;
var commonConstants = ["Infinity", "NaN", "undefined", "null", "true", "false", "on", "off", "yes", "no"];
var constants = wordRegexp(commonConstants);
// Tokenizers
function tokenBase(stream, state) {
// Handle scope changes
if (stream.sol()) {
if (state.scope.align === null) state.scope.align = false;
var scopeOffset = state.scope.offset;
if (stream.eatSpace()) {
var lineOffset = stream.indentation();
if (lineOffset > scopeOffset && state.scope.type == "coffee") {
return "indent";
} else if (lineOffset < scopeOffset) {
return "dedent";
}
return null;
} else {
if (scopeOffset > 0) {
dedent(stream, state);
}
}
}
if (stream.eatSpace()) {
return null;
}
var ch = stream.peek();
// Handle docco title comment (single line)
if (stream.match("####")) {
stream.skipToEnd();
return "comment";
}
// Handle multi line comments
if (stream.match("###")) {
state.tokenize = longComment;
return state.tokenize(stream, state);
}
// Single line comment
if (ch === "#") {
stream.skipToEnd();
return "comment";
}
// Handle number literals
if (stream.match(/^-?[0-9\.]/, false)) {
var floatLiteral = false;
// Floats
if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) {
floatLiteral = true;
}
if (stream.match(/^-?\d+\.\d*/)) {
floatLiteral = true;
}
if (stream.match(/^-?\.\d+/)) {
floatLiteral = true;
}
if (floatLiteral) {
// prevent from getting extra . on 1..
if (stream.peek() == "."){
stream.backUp(1);
}
return "number";
}
// Integers
var intLiteral = false;
// Hex
if (stream.match(/^-?0x[0-9a-f]+/i)) {
intLiteral = true;
}
// Decimal
if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) {
intLiteral = true;
}
// Zero by itself with no other piece of number.
if (stream.match(/^-?0(?![\dx])/i)) {
intLiteral = true;
}
if (intLiteral) {
return "number";
}
}
// Handle strings
if (stream.match(stringPrefixes)) {
state.tokenize = tokenFactory(stream.current(), false, "string");
return state.tokenize(stream, state);
}
// Handle regex literals
if (stream.match(regexPrefixes)) {
if (stream.current() != "/" || stream.match(/^.*\//, false)) { // prevent highlight of division
state.tokenize = tokenFactory(stream.current(), true, "string-2");
return state.tokenize(stream, state);
} else {
stream.backUp(1);
}
}
// Handle operators and delimiters
if (stream.match(operators) || stream.match(wordOperators)) {
return "operator";
}
if (stream.match(delimiters)) {
return "punctuation";
}
if (stream.match(constants)) {
return "atom";
}
if (stream.match(keywords)) {
return "keyword";
}
if (stream.match(identifiers)) {
return "variable";
}
if (stream.match(properties)) {
return "property";
}
// Handle non-detected items
stream.next();
return ERRORCLASS;
}
function tokenFactory(delimiter, singleline, outclass) {
return function(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\/\\]/);
if (stream.eat("\\")) {
stream.next();
if (singleline && stream.eol()) {
return outclass;
}
} else if (stream.match(delimiter)) {
state.tokenize = tokenBase;
return outclass;
} else {
stream.eat(/['"\/]/);
}
}
if (singleline) {
if (conf.mode.singleLineStringErrors) {
outclass = ERRORCLASS;
} else {
state.tokenize = tokenBase;
}
}
return outclass;
};
}
function longComment(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^#]/);
if (stream.match("###")) {
state.tokenize = tokenBase;
break;
}
stream.eatWhile("#");
}
return "comment";
}
function indent(stream, state, type) {
type = type || "coffee";
var offset = 0, align = false, alignOffset = null;
for (var scope = state.scope; scope; scope = scope.prev) {
if (scope.type === "coffee") {
offset = scope.offset + conf.indentUnit;
break;
}
}
if (type !== "coffee") {
align = null;
alignOffset = stream.column() + stream.current().length;
} else if (state.scope.align) {
state.scope.align = false;
}
state.scope = {
offset: offset,
type: type,
prev: state.scope,
align: align,
alignOffset: alignOffset
};
}
function dedent(stream, state) {
if (!state.scope.prev) return;
if (state.scope.type === "coffee") {
var _indent = stream.indentation();
var matched = false;
for (var scope = state.scope; scope; scope = scope.prev) {
if (_indent === scope.offset) {
matched = true;
break;
}
}
if (!matched) {
return true;
}
while (state.scope.prev && state.scope.offset !== _indent) {
state.scope = state.scope.prev;
}
return false;
} else {
state.scope = state.scope.prev;
return false;
}
}
function tokenLexer(stream, state) {
var style = state.tokenize(stream, state);
var current = stream.current();
// Handle "." connected identifiers
if (current === ".") {
style = state.tokenize(stream, state);
current = stream.current();
if (/^\.[\w$]+$/.test(current)) {
return "variable";
} else {
return ERRORCLASS;
}
}
// Handle scope changes.
if (current === "return") {
state.dedent += 1;
}
if (((current === "->" || current === "=>") &&
!state.lambda &&
!stream.peek())
|| style === "indent") {
indent(stream, state);
}
var delimiter_index = "[({".indexOf(current);
if (delimiter_index !== -1) {
indent(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
}
if (indentKeywords.exec(current)){
indent(stream, state);
}
if (current == "then"){
dedent(stream, state);
}
if (style === "dedent") {
if (dedent(stream, state)) {
return ERRORCLASS;
}
}
delimiter_index = "])}".indexOf(current);
if (delimiter_index !== -1) {
while (state.scope.type == "coffee" && state.scope.prev)
state.scope = state.scope.prev;
if (state.scope.type == current)
state.scope = state.scope.prev;
}
if (state.dedent > 0 && stream.eol() && state.scope.type == "coffee") {
if (state.scope.prev) state.scope = state.scope.prev;
state.dedent -= 1;
}
return style;
}
var external = {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
scope: {offset:basecolumn || 0, type:"coffee", prev: null, align: false},
lastToken: null,
lambda: false,
dedent: 0
};
},
token: function(stream, state) {
var fillAlign = state.scope.align === null && state.scope;
if (fillAlign && stream.sol()) fillAlign.align = false;
var style = tokenLexer(stream, state);
if (fillAlign && style && style != "comment") fillAlign.align = true;
state.lastToken = {style:style, content: stream.current()};
if (stream.eol() && stream.lambda) {
state.lambda = false;
}
return style;
},
indent: function(state, text) {
if (state.tokenize != tokenBase) return 0;
var scope = state.scope;
var closer = text && "])}".indexOf(text.charAt(0)) > -1;
if (closer) while (scope.type == "coffee" && scope.prev) scope = scope.prev;
var closes = closer && scope.type === text.charAt(0);
if (scope.align)
return scope.alignOffset - (closes ? 1 : 0);
else
return (closes ? scope.prev : scope).offset;
},
lineComment: "#",
fold: "indent"
};
return external;
});
CodeMirror.defineMIME("text/x-coffeescript", "coffeescript");
});
| kdzwinel/betwixt | src/dt/cm_modes/coffeescript.js | JavaScript | mit | 10,112 |
'use strict';
const bcrypt = require('bcryptjs');
module.exports = options => {
const opts = options || {};
const genSalt = () => new Promise((resolve, reject) =>
bcrypt.genSalt(opts.rounds|| 10, (err, salt) => {
return (err) ? reject(err): resolve(salt);
}));
const hashWithSalt = (password, salt) => new Promise((resolve, reject) =>
bcrypt.hash(password, salt, (err, hash) => {
return (err) ? reject(err) : resolve(hash);
}));
const hash = password => genSalt().then(salt => hashWithSalt(password, salt));
return {
hash,
compare: bcrypt.compare,
};
};
| dennoa/stateless-auth | lib/password-support.js | JavaScript | mit | 615 |
import axios from 'axios';
import { API_BASE } from 'src/config/constants';
// Resources for /posts endpoint on API
// @see https://github.com/mzabriskie/axios#creating-an-instance
export const postsResource = axios.create({
baseURL: `${API_BASE}/posts/`
});
export const emailResource = axios.create({
baseURL: `${API_BASE}/email/`
});
export const usersResource = axios.create({
baseURL: `${API_BASE}/users`,
timeout: 8000,
//headers: {'X-Custom-Header': 'foobar'}
});
export const eventsResource = axios.create({
baseURL: `${API_BASE}/events`,
timeout: 15000,
//headers: {'X-Custom-Header': 'foobar'}
});
| hacksu/2017-kenthackenough-ui-main | src/util/resources.js | JavaScript | mit | 629 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*---------------------------------------------------------------------------------------------
* Copyright (c) Red Hat. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const testHelper_1 = require("./utils/testHelper");
const verifyError_1 = require("./utils/verifyError");
const serviceSetup_1 = require("./utils/serviceSetup");
const errorMessages_1 = require("./utils/errorMessages");
const assert = require("assert");
const uri = 'http://json.schemastore.org/bowerrc';
const fileMatch = ['*.yml', '*.yaml'];
const languageSettingsSetup = new serviceSetup_1.ServiceSetup()
.withValidate()
.withCustomTags(['!Test', '!Ref sequence'])
.withSchemaFileMatch({ uri, fileMatch: fileMatch });
const languageService = testHelper_1.configureLanguageService(languageSettingsSetup.languageSettings);
// Defines a Mocha test suite to group tests of similar kind together
suite('Validation Tests', () => {
// Tests for validator
describe('Validation', function () {
function parseSetup(content) {
const testTextDocument = testHelper_1.setupTextDocument(content);
return languageService.doValidation(testTextDocument, false);
}
//Validating basic nodes
describe('Test that validation does not throw errors', function () {
it('Basic test', done => {
const content = 'analytics: true';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Test that boolean value without quotations is valid', done => {
const content = 'analytics: no';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Test that boolean is valid when inside strings', done => {
const content = 'cwd: "no"';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Basic test', done => {
const content = 'analytics: true';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Basic test on nodes with children', done => {
const content = 'scripts:\n preinstall: test1\n postinstall: test2';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Advanced test on nodes with children', done => {
const content = 'analytics: true\ncwd: this\nscripts:\n preinstall: test1\n postinstall: test2';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Type string validates under children', done => {
const content = 'registry:\n register: file://test_url';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Include with value should not error', done => {
const content = 'customize: !include customize.yaml';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Null scalar value should be treated as string', done => {
const content = 'cwd: Null';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Anchor should not not error', done => {
const content = 'default: &DEFAULT\n name: Anchor\nanchor_test:\n <<: *DEFAULT';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Anchor with multiple references should not not error', done => {
const content = 'default: &DEFAULT\n name: Anchor\nanchor_test:\n <<: *DEFAULT\nanchor_test2:\n <<: *DEFAULT';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Multiple Anchor in array of references should not not error', done => {
const content = 'default: &DEFAULT\n name: Anchor\ncustomname: &CUSTOMNAME\n custom_name: Anchor\nanchor_test:\n <<: [*DEFAULT, *CUSTOMNAME]';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Multiple Anchors being referenced in same level at same time', done => {
const content = 'default: &DEFAULT\n name: Anchor\ncustomname: &CUSTOMNAME\n custom_name: Anchor\nanchor_test:\n <<: *DEFAULT\n <<: *CUSTOMNAME\n';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Custom Tags without type', done => {
const content = 'analytics: !Test false';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Custom Tags with type', done => {
const content = 'resolvers: !Ref\n - test';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
describe('Type tests', function () {
it('Type String does not error on valid node', done => {
const content = 'cwd: this';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Type Boolean does not error on valid node', done => {
const content = 'analytics: true';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Type Number does not error on valid node', done => {
const content = 'timeout: 60000';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Type Object does not error on valid node', done => {
const content = 'registry:\n search: file://test_url';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Type Array does not error on valid node', done => {
const content = 'resolvers:\n - test\n - test\n - test';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
it('Do not error when there are multiple types in schema and theyre valid', done => {
const content = 'license: MIT';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
});
});
describe('Test that validation DOES throw errors', function () {
it('Error when theres a finished untyped item', done => {
const content = 'cwd: hello\nan';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 2);
assert.deepEqual(result[0], verifyError_1.createExpectedError(errorMessages_1.BlockMappingEntryError, 1, 13, 1, 13));
assert.deepEqual(result[1], verifyError_1.createExpectedError(errorMessages_1.ColonMissingError, 1, 13, 1, 13));
}).then(done, done);
});
it('Error when theres no value for a node', done => {
const content = 'cwd:';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 1);
assert.deepEqual(result[0], verifyError_1.createExpectedError(errorMessages_1.StringTypeError, 0, 4, 0, 4));
}).then(done, done);
});
it('Error on incorrect value type (number)', done => {
const content = 'cwd: 100000';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 1);
assert.deepEqual(result[0], verifyError_1.createExpectedError(errorMessages_1.StringTypeError, 0, 5, 0, 11));
}).then(done, done);
});
it('Error on incorrect value type (boolean)', done => {
const content = 'cwd: False';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 1);
assert.deepEqual(result[0], verifyError_1.createExpectedError(errorMessages_1.StringTypeError, 0, 5, 0, 10));
}).then(done, done);
});
it('Error on incorrect value type (string)', done => {
const content = 'analytics: hello';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 1);
assert.deepEqual(result[0], verifyError_1.createExpectedError(errorMessages_1.BooleanTypeError, 0, 11, 0, 16));
}).then(done, done);
});
it('Error on incorrect value type (object)', done => {
const content = 'scripts: test';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 1);
assert.deepEqual(result[0], verifyError_1.createExpectedError(errorMessages_1.ObjectTypeError, 0, 9, 0, 13));
}).then(done, done);
});
it('Error on incorrect value type (array)', done => {
const content = 'resolvers: test';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 1);
assert.deepEqual(result[0], verifyError_1.createExpectedError(errorMessages_1.ArrayTypeError, 0, 11, 0, 15));
}).then(done, done);
});
it('Include without value should error', done => {
const content = 'customize: !include';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 1);
assert.deepEqual(result[0], verifyError_1.createExpectedError(errorMessages_1.IncludeWithoutValueError, 0, 19, 0, 19));
}).then(done, done);
});
it('Test that boolean value in quotations is not interpreted as boolean i.e. it errors', done => {
const content = 'analytics: "no"';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 1);
assert.deepEqual(result[0], verifyError_1.createExpectedError(errorMessages_1.BooleanTypeError, 0, 11, 0, 15));
}).then(done, done);
});
it('Test that boolean is invalid when no strings present and schema wants string', done => {
const content = 'cwd: no';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 1);
assert.deepEqual(result[0], verifyError_1.createExpectedError(errorMessages_1.StringTypeError, 0, 5, 0, 7));
}).then(done, done);
});
});
describe('Test with no schemas', () => {
function parseSetup(content) {
const testTextDocument = testHelper_1.setupTextDocument(content);
return languageService.doValidation(testTextDocument, true);
}
it('Duplicate properties are reported', done => {
languageService.configure({
validate: true,
isKubernetes: true
});
const content = 'kind: a\ncwd: b\nkind: c';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 2);
assert.equal(result[1].message, 'duplicate key');
}).then(done, done);
});
});
describe('Test anchors specifically against gitlab schema', function () {
it('Test that anchors do not report Property << is not allowed', done => {
languageService.configure({
schemas: [{
uri: 'http://json.schemastore.org/gitlab-ci',
fileMatch: ['*.yaml', '*.yml']
}],
validate: true
});
const content = '.test-cache: &test-cache\n cache: {}\nnodejs-tests:\n <<: *test-cache\n script: test';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 0);
}).then(done, done);
});
});
describe('Test with custom schemas', function () {
function parseSetup(content) {
const testTextDocument = testHelper_1.setupTextDocument(content);
return languageService.doValidation(testTextDocument, true);
}
it('Test that properties that match multiple enums get validated properly', done => {
const schema = {
'definitions': {
'ImageStreamImport': {
'type': 'object',
'properties': {
'kind': {
'type': 'string',
'enum': [
'ImageStreamImport'
]
}
}
},
'ImageStreamLayers': {
'type': 'object',
'properties': {
'kind': {
'type': 'string',
'enum': [
'ImageStreamLayers'
]
}
}
}
},
'oneOf': [
{
'$ref': '#/definitions/ImageStreamImport'
},
{
'$ref': '#/definitions/ImageStreamLayers'
}
]
};
languageService.configure({
schemas: [{
uri: 'file://test.yaml',
fileMatch: ['*.yaml', '*.yml'],
schema
}],
validate: true,
isKubernetes: true
});
const content = 'kind: ';
const validator = parseSetup(content);
validator.then(function (result) {
assert.equal(result.length, 2);
// tslint:disable-next-line:quotemark
assert.equal(result[1].message, `Value is not accepted. Valid values: "ImageStreamImport", "ImageStreamLayers".`);
}).then(done, done);
});
});
});
});
//# sourceMappingURL=schemaValidation.test.js.map | karan/dotfiles | .vscode/extensions/redhat.vscode-yaml-0.7.2/node_modules/yaml-language-server/out/server/test/schemaValidation.test.js | JavaScript | mit | 18,332 |
import React from 'react';
/* component styles */
import { styles } from './styles.scss';
export const Footer = () =>
<footer className={`${styles}`}>
<div className="container">
<div className="row">
<div className="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<p>© Unmesh Shukla 2016</p>
</div>
</div>
</div>
</footer>;
| unmeshpro/easyPost | static/src/components/Footer/index.js | JavaScript | mit | 422 |
(function(window, factory) {
if (typeof define === 'function' && define.amd) {
define([], function() {
return factory();
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
(window.LocaleData || (window.LocaleData = {}))['es_SV'] = factory();
}
}(typeof window !== "undefined" ? window : this, function() {
return {
"LC_ADDRESS": {
"postal_fmt": "%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N",
"country_name": "El Salvador",
"country_post": null,
"country_ab2": "SV",
"country_ab3": "SLV",
"country_num": 222,
"country_car": "ES",
"country_isbn": null,
"lang_name": "espa\u00f1ol",
"lang_ab": "es",
"lang_term": "spa",
"lang_lib": "spa"
},
"LC_MEASUREMENT": {
"measurement": 1
},
"LC_MESSAGES": {
"yesexpr": "^[+1sSyY]",
"noexpr": "^[-0nN]",
"yesstr": "s\u00ed",
"nostr": "no"
},
"LC_MONETARY": {
"currency_symbol": "$",
"mon_decimal_point": ".",
"mon_thousands_sep": ",",
"mon_grouping": [
3,
3
],
"positive_sign": "",
"negative_sign": "-",
"frac_digits": 2,
"p_cs_precedes": 1,
"p_sep_by_space": 1,
"n_cs_precedes": 1,
"n_sep_by_space": 1,
"p_sign_posn": 1,
"n_sign_posn": 1,
"int_curr_symbol": "USD ",
"int_frac_digits": 2,
"int_p_cs_precedes": null,
"int_p_sep_by_space": null,
"int_n_cs_precedes": null,
"int_n_sep_by_space": null,
"int_p_sign_posn": null,
"int_n_sign_posn": null
},
"LC_NAME": {
"name_fmt": "%d%t%g%t%m%t%f",
"name_gen": null,
"name_mr": null,
"name_mrs": null,
"name_miss": null,
"name_ms": null
},
"LC_NUMERIC": {
"decimal_point": ".",
"thousands_sep": ",",
"grouping": [
3,
3
]
},
"LC_PAPER": {
"height": 279,
"width": 216
},
"LC_TELEPHONE": {
"tel_int_fmt": "+%c %a %l",
"tel_dom_fmt": null,
"int_select": "00",
"int_prefix": "503"
},
"LC_TIME": {
"date_fmt": "%a %b %e %H:%M:%S %Z %Y",
"abday": [
"dom",
"lun",
"mar",
"mi\u00e9",
"jue",
"vie",
"s\u00e1b"
],
"day": [
"domingo",
"lunes",
"martes",
"mi\u00e9rcoles",
"jueves",
"viernes",
"s\u00e1bado"
],
"week": [
7,
19971130,
1
],
"abmon": [
"ene",
"feb",
"mar",
"abr",
"may",
"jun",
"jul",
"ago",
"sep",
"oct",
"nov",
"dic"
],
"mon": [
"enero",
"febrero",
"marzo",
"abril",
"mayo",
"junio",
"julio",
"agosto",
"septiembre",
"octubre",
"noviembre",
"diciembre"
],
"d_t_fmt": "%a %d %b %Y %T %Z",
"d_fmt": "%d\/\/%m\/\/%y",
"t_fmt": "%T",
"am_pm": [
"",
""
],
"t_fmt_ampm": "",
"era": null,
"era_year": null,
"era_d_t_fmt": null,
"era_d_fmt": null,
"era_t_fmt": null,
"alt_digits": null,
"first_weekday": null,
"first_workday": null,
"cal_direction": null,
"timezone": null
}
};
}));
| jsor/locale-data | data/es_SV.js | JavaScript | mit | 4,473 |
angular
.module('tas')
.config(tasConfig);
function tasConfig($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'js/tas/table.html',
controller: 'TasController',
controllerAs: 'tas',
private: true
})
.when('/new', {
templateUrl: 'js/tas/form.html',
controller: 'TasController',
controllerAs: 'tas',
private: true
})
.when('/show/:uuid', {
templateUrl: 'js/tas/show.html',
controller: 'ShowController',
controllerAs: 'show',
private: true
})
.when('/show/:uuid/edit', {
templateUrl: 'js/tas/form.html',
controller: 'EditController',
controllerAs: 'tas',
private: true
})
.otherwise({
redirectTo: '/'
})
}
| Bespinoza10/AngularappB | js/main.config.js | JavaScript | mit | 828 |
const eth = require('../server/eth');
const SpiceMembers = eth.contracts.SpiceMembers;
eth.prepare().then(() => {
console.log('Adding members');
}).then(() => {
const members = SpiceMembers.deployed();
return members.addMember('0x6799a1d5f574ef1c376f5515ee7e2b8b06b30754', { gas: 1000000 });
}).then(() => {
const members = SpiceMembers.deployed();
return members.setMemberLevel('0x6799a1d5f574ef1c376f5515ee7e2b8b06b30754', 3, { gas: 1000000 });
}).then(() => {
const members = SpiceMembers.deployed();
return members.addMember('0x6b8ba21c8875342f49a9d7b5eb31a0b1df099cd3', { gas: 1000000 });
}).then(() => {
const members = SpiceMembers.deployed();
return members.setMemberLevel('0x6b8ba21c8875342f49a9d7b5eb31a0b1df099cd3', 2);
}).then(() => {
const members = SpiceMembers.deployed();
return members.addMember('0xf086f7d8e8adD5CD3D8788f85f5724655d52923b', { gas: 1000000 });
}).then(() => {
const members = SpiceMembers.deployed();
return members.setMemberLevel('0xf086f7d8e8adD5CD3D8788f85f5724655d52923b', 3, { gas: 1000000 });
}).then(() => {
console.log('Added members successfully');
}).catch(err => console.log(err));
| jvah/spicehours | scripts/addMembers.js | JavaScript | mit | 1,157 |
$.fn.jselect = function( action, opt) {
$.select = this;
//create input select
$.create_options = function(opt){
var field_html = '';
for( var option_index = 0; option_index < opt.data.length; option_index++ ){
var selected = '';
/*
if(data[opt.field_value] == opt.value ){
selected = 'selected';
}
*/
field_html += '<option value='+opt.field_value+' '+selected+'>'+ opt.data[option_index][opt.field_text]+'</option>';
}
$.select .html(field_html);
}
if( action == 'create' ){
$.create_options(opt);
}
};
| drecon/jscomponents | dist/jselect.js | JavaScript | mit | 572 |
function GetHausNummer(street)
{
var i = 0;
var nr = "";
if (0 != street.length)
{
for (i=street.length-1;i>-1;i--)
{
if (" " == (street.substring(i,i+1)) )
{
nr = (street.substring(i,(street.length)));
break;
}
}
}
return nr;
}
function GetStrasse(street)
{
var i = 0;
var strStrasse = street;
if (0 != street.length)
{
for (i=street.length-1;i>-1;i--)
{
if (" " == (street.substring(i,i+1)))
{
strStrasse = (street.substring(0,i));
break;
}
}
}
return strStrasse;
}
function TestDatum(Tag, Monat, Jahr)
{
var jetzt = new Date();
var nMonat = Monat - 1;
jetzt.setYear(jetzt.getYear() - 18);
var burstday = new Date(Jahr,nMonat,Tag);
// alert(burstday+" "+jetzt+" "+burstday.getTime()+" "+jetzt.getTime());
return ( burstday.getTime()>jetzt.getTime());
}
function TestAdrDaten(reg)
{
var ErrorText = new Array(30);
var nErrorCnt = 0;
var ErrMsg = "";
var nIdx = 0;
var day = 0;
var month = 0;
var year = 0;
var msg = "";
var msg1 = "";
var msg2 = "";
var em = "";
showLayer('ShowError','hide');
document.getElementById("Anrede").className = "";
document.getElementById("Vorname").className = "Text";
document.getElementById("Nachname").className = "Text";
document.getElementById("strassez").className = "Text";
document.getElementById("strassez").value = Trim(document.getElementById("strassez").value);
document.getElementById("hausnr").className = "Text";
document.getElementById("hausnr").value = Trim(document.getElementById("hausnr").value);
document.getElementById("PLZ").className = "Text";
document.getElementById("Ort").className = "Text";
// Lieferadresse ?
if (true == document.getElementById("abweichend").checked)
{
document.getElementById("lanrede").className = "";
document.getElementById("lvorname").className = "Text";
document.getElementById("lnachname").className = "Text";
document.getElementById("lstrassex").className = "Text";
document.getElementById("lstrassex").value = Trim(document.getElementById("lstrassex").value);
document.getElementById("lhausnr").className = "Text";
document.getElementById("lhausnr").value = Trim(document.getElementById("lhausnr").value);
document.getElementById("lplz").className = "Text";
document.getElementById("lort").className = "Text";
}
// Angaben
document.getElementById("TT").className = "Text";
document.getElementById("MM").className = "Text";
document.getElementById("YYYY").className = "Text";
document.getElementById("Telefon").className = "Text";
document.forms["adrdata"].elements["EMail"].className = "Text";
document.getElementById("email2").className = "Text";
// Rechnungsadresse
if (document.getElementById("Anrede").value == "")
{
ErrorText[nErrorCnt] = "You have not selected a salutaion of address.";
document.getElementById("Anrede").className = "ErrorMessage";
nErrorCnt++;
}
if (document.getElementById("Vorname").value == "")
{
ErrorText[nErrorCnt] = "You have not specified your first name.";
document.getElementById("Vorname").className = "ErrorMessage";
nErrorCnt++;
}
if (document.getElementById("Nachname").value == "")
{
ErrorText[nErrorCnt] = "You have not specified your last name.";
document.getElementById("Nachname").className = "ErrorMessage";
nErrorCnt++;
}
if (document.getElementById("strassez").value == "")
{
ErrorText[nErrorCnt] = "You have not entered the street.";
document.getElementById("strassez").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.getElementById("hausnr").value == "")
{
ErrorText[nErrorCnt] = "They have indicated to the street with no house number.";
document.getElementById("hausnr").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.getElementById("PLZ").value == "")
{
ErrorText[nErrorCnt] = "You have not entered your postal code.";
document.getElementById("PLZ").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.getElementById("Ort").value == "")
{
ErrorText[nErrorCnt] = "You have not specified your place of residence.";
document.getElementById("Ort").className = "ErrorMessage";
nErrorCnt ++;
}
msg = "You have entered an invalid birth date ";
msg1 = "(testing day)";
msg2 = ", we need the date to check the age of majority.";
if (document.getElementById("TT").value == "")
{
ErrorText[nErrorCnt] = msg + msg1 + msg2;
document.getElementById("TT").className = "ErrorMessage";
document.getElementById("MM").className = "ErrorMessage";
document.getElementById("YYYY").className = "ErrorMessage";
nErrorCnt ++;
}
else
{
if (false == IsNumeric(document.getElementById("TT").value))
{
ErrorText[nErrorCnt] = msg + msg1 + msg2;
document.getElementById("TT").className = "ErrorMessage";
document.getElementById("MM").className = "ErrorMessage";
document.getElementById("YYYY").className = "ErrorMessage";
nErrorCnt ++;
}
else
{
day = parseInt(document.getElementById("TT").value,10);
if ((day < 1) || (day > 31))
{
ErrorText[nErrorCnt] = msg + msg1 + msg2;
document.getElementById("TT").className = "ErrorMessage";
document.getElementById("MM").className = "ErrorMessage";
document.getElementById("YYYY").className = "ErrorMessage";
nErrorCnt ++;
}
}
}
msg1 = "(testing month)";
var monatcheck = true;
if (document.getElementById("MM").value == "")
{
monatcheck = false;
}
else
{
if (false == IsNumeric(document.getElementById("MM").value))
{
monatcheck = false;
}
else
{
month = parseInt(document.getElementById("MM").value,10);
if ((month < 1) || (month > 12))
{
monatcheck = false;
}
}
}
if (!monatcheck)
{
ErrorText[nErrorCnt] = msg + msg1 + msg2;
document.getElementById("TT").className = "ErrorMessage";
document.getElementById("MM").className = "ErrorMessage";
document.getElementById("YYYY").className = "ErrorMessage";
nErrorCnt ++;
}
msg1 = "(testing year)";
var jahrcheck = true;
if (document.getElementById("YYYY").value == "")
{
jahrcheck = false;
}
else
{
if (false == IsNumeric(document.getElementById("YYYY").value))
{
jahrcheck = false;
}
else
{
year = parseInt(document.getElementById("YYYY").value,10);
if ((year < 1901) || (year > 2010))
{
jahrcheck = false;
}
}
}
if (!jahrcheck)
{
ErrorText[nErrorCnt] = msg + msg1 + msg2;
document.getElementById("TT").className = "ErrorMessage";
document.getElementById("MM").className = "ErrorMessage";
document.getElementById("YYYY").className = "ErrorMessage";
nErrorCnt ++;
}
msg1 = "(testing day)";
if (month==4 || month==6 || month==9 || month==11)
{
if (day > 30)
{
ErrorText[nErrorCnt] = msg + msg1 + msg2;
document.getElementById("TT").className = "ErrorMessage";
document.getElementById("MM").className = "ErrorMessage";
nErrorCnt ++;
}
}
if (month==2)
{
if (day > 29)
{
ErrorText[nErrorCnt] = msg + msg1 + msg2;
document.getElementById("TT").className = "ErrorMessage";
document.getElementById("MM").className = "ErrorMessage";
nErrorCnt ++;
}
else
{
if (year%4!=0 || (year%100==0 && year%400!=0))
{
if (day > 28)
{
ErrorText[nErrorCnt] = msg + msg1 + msg2;
document.getElementById("TT").className = "ErrorMessage";
document.getElementById("MM").className = "ErrorMessage";
nErrorCnt ++;
}
}
}
}
msg1 = "(You are not 18 years old)";
if (TestDatum(document.getElementById("TT").value, document.getElementById("MM").value, document.getElementById("YYYY").value))
{
ErrorText[nErrorCnt] = msg + msg1 + msg2;
document.getElementById("TT").className = "ErrorMessage";
document.getElementById("MM").className = "ErrorMessage";
document.getElementById("YYYY").className = "ErrorMessage";
nErrorCnt ++;
}
// Lieferadresse ?
if (true == document.getElementById("abweichend").checked)
{
if (document.getElementById("lanrede").value == "")
{
ErrorText[nErrorCnt] = "You have no delivery addresses salutaion selected.";
document.getElementById("lanrede").className = "ErrorMessage";
nErrorCnt++;
}
if (document.getElementById("lvorname").value == "")
{
ErrorText[nErrorCnt] = "You have not specified the delivery address given names.";
document.getElementById("lvorname").className = "ErrorMessage";
nErrorCnt++;
}
if (document.getElementById("lnachname").value == "")
{
ErrorText[nErrorCnt] = "You have not specified the delivery address last name.";
document.getElementById("lnachname").className = "ErrorMessage";
nErrorCnt++;
}
if (document.getElementById("lstrassex").value == "")
{
ErrorText[nErrorCnt] = "You have not specified the delivery addresses Street.";
document.getElementById("lstrassex").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.getElementById("lhausnr").value == "")
{
ErrorText[nErrorCnt] = "You specified for delivery addresses street with no house number.";
document.getElementById("lhausnr").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.getElementById("lplz").value == "")
{
ErrorText[nErrorCnt] = "You have not specified the delivery address zip code.";
document.getElementById("lplz").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.getElementById("lort").value == "")
{
ErrorText[nErrorCnt] = "You have not specified the delivery address of residence.";
document.getElementById("lort").className = "ErrorMessage";
nErrorCnt ++;
}
}
if (document.getElementById("Telefon").value == "")
{
ErrorText[nErrorCnt] = "They have not specified a telephone number where we can reach you if questions should arise in the execution of your orders.";
document.getElementById("Telefon").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.forms["adrdata"].elements["EMail"].value == "")
{
ErrorText[nErrorCnt] = "You have to enter any e-mail address. This is needed to access your account.";
document.forms["adrdata"].elements["EMail"].className = "ErrorMessage";
nErrorCnt ++;
}
else
{
em = document.forms["adrdata"].elements["EMail"].value;
if ((em.indexOf ("@") == -1) || (em.indexOf (".") == -1) || (em.indexOf(" ")!=-1) || (em.length < 6))
{
ErrorText[nErrorCnt] = "You have entered your e-mail address in the wrong format. Format Example: user@host.com or benutzer@domain.de ...";
document.forms["adrdata"].elements["EMail"].className = "ErrorMessage";
nErrorCnt ++;
}
}
if (document.getElementById("email2").value == "")
{
ErrorText[nErrorCnt] = "Please enter your email address a second time in the field provided.";
document.getElementById("email2").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.getElementById("email2").value != document.forms["adrdata"].elements["EMail"].value)
{
ErrorText[nErrorCnt] = "Your first e-mail address is not identical to your second e-mail address, please correct the entry.";
document.forms["adrdata"].elements["EMail"].className = "ErrorMessage";
document.getElementById("email2").className = "ErrorMessage";
nErrorCnt ++;
}
if ('1' == reg)
{
document.getElementById("CustPasswort").className = "Text";
document.getElementById("Password2").className = "Text";
if (document.getElementById("CustPasswort").value == "")
{
ErrorText[nErrorCnt] = "You have not specified a password. This is needed to get access to your account at Verdener Turniergesellschaft mbH.";
document.getElementById("CustPasswort").className = "ErrorMessage";
nErrorCnt ++;
}
else
{
em = document.getElementById("CustPasswort").value;
if (em.length < 6)
{
ErrorText[nErrorCnt] = "You have a password with less than 6 characters specified.";
document.getElementById("CustPasswort").className = "ErrorMessage";
nErrorCnt ++;
}
else
{
var em1 = "";
var ic = 0;
for (ic = 0; ic < em.length; ic++)
{
em1 = em1 + em.substr(0,1);
}
if ( (0 == em.localeCompare("123456") ) || (em == em1) )
{
ErrorText[nErrorCnt] = "You did an insecure password. Format Example: '123456' or 'xxxxxx'";
document.getElementById("CustPasswort").className = "ErrorMessage";
nErrorCnt ++;
}
}
}
if (document.getElementById("Password2").value == "")
{
ErrorText[nErrorCnt] = "Please enter your password a second time in the field provided.";
document.getElementById("Password2").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.getElementById("Password2").value != document.getElementById("CustPasswort").value)
{
ErrorText[nErrorCnt] = "Your first password is not identical to your second password please correct the entry.";
document.getElementById("CustPasswort").className = "ErrorMessage";
document.getElementById("Password2").className = "ErrorMessage";
nErrorCnt ++;
}
}
if (0 != nErrorCnt)
{
for (nIdx=0; nIdx < nErrorCnt; nIdx++)
{
ErrMsg = ErrMsg + ErrorText[nIdx] + "<br />";
}
document.getElementById("ErrorLines").innerHTML = ErrMsg;
showLayer('ShowError','show');
}
else
{
// Alles gut...
showLayer('ShowError','hide');
return(true);
}
return(false);
}
function CheckPassword(strOldPassword)
{
var ErrorText = new Array(30);
var nErrorCnt = 0;
var ErrMsg = "";
var nIdx = 0;
var em = "";
var em1 = "";
var ic = 0;
showLayer('ShowError','hide');
document.getElementById("Password").className = "Text";
document.getElementById("NewPassword").className = "Text";
document.getElementById("NewPassword2").className = "Text";
if (document.getElementById("Password").value != strOldPassword)
{
ErrorText[nErrorCnt] = "You have entered a wrong password.";
document.getElementById("Password").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.getElementById("NewPassword").value == strOldPassword)
{
ErrorText[nErrorCnt] = "Your old password is identical with the new password.";
document.getElementById("NewPassword").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.getElementById("NewPassword").value == "")
{
ErrorText[nErrorCnt] = "You have not specified a password. This is required to obtain access to your account";
document.getElementById("NewPassword").className = "ErrorMessage";
nErrorCnt ++;
}
else
{
em = document.getElementById("NewPassword").value;
if (em.length < 6)
{
ErrorText[nErrorCnt] = "They were using a password with fewer than six characters.";
document.getElementById("NewPassword").className = "ErrorMessage";
nErrorCnt ++;
}
else
{
em1 = "";
for (ic = 0; ic < em.length; ic++)
{
em1 = em1 + em.substr(0,1);
}
if ( (0 == em.localeCompare("123456") ) || (em == em1) )
{
ErrorText[nErrorCnt] = "You have specified an insecure password. Format Example: '123456' or 'xxxxxx'";
document.getElementById("NewPassword").className = "ErrorMessage";
nErrorCnt ++;
}
}
}
if (document.getElementById("NewPassword2").value == "")
{
ErrorText[nErrorCnt] = "Please enter your password a second time in the field provided.";
document.getElementById("NewPassword2").className = "ErrorMessage";
nErrorCnt ++;
}
if (document.getElementById("NewPassword2").value != document.getElementById("NewPassword").value)
{
ErrorText[nErrorCnt] = "Your first password is not identical to the second of your password please correct the entry.";
document.getElementById("NewPassword").className = "ErrorMessage";
document.getElementById("NewPassword2").className = "ErrorMessage";
nErrorCnt ++;
}
if (0 != nErrorCnt)
{
for (nIdx=0; nIdx < nErrorCnt; nIdx++)
{
ErrMsg = ErrMsg + ErrorText[nIdx] + "<br />";
}
document.getElementById("ErrorLines").innerHTML = ErrMsg;
showLayer('ShowError','show');
}
else
{
// Alles gut...
showLayer('ShowError','hide');
return(true);
}
return(false);
}
| yanhongwang/TicketBookingSystem | web/jsp/scripts/elektratesadr_en.js | JavaScript | mit | 17,914 |
import * as remoteCall from 'actions/remoteCall_actions';
describe( 'remote call actions', () =>
{
const payload = { id: 1, data: [] };
it( 'should have types', () =>
{
expect( remoteCall.TYPES ).toBeDefined();
} );
it( 'should add a remote call', () =>
{
const expectedAction = {
type : remoteCall.TYPES.ADD_REMOTE_CALL,
payload
};
expect( remoteCall.addRemoteCall( payload ) ).toEqual( expectedAction );
} );
it( 'should remove a remote call', () =>
{
const expectedAction = {
type : remoteCall.TYPES.REMOVE_REMOTE_CALL,
payload
};
expect( remoteCall.removeRemoteCall( payload ) ).toEqual( expectedAction );
} );
it( 'should update a remote call', () =>
{
const expectedAction = {
type : remoteCall.TYPES.UPDATE_REMOTE_CALL,
payload
};
expect( remoteCall.updateRemoteCall( payload ) ).toEqual( expectedAction );
} );
} );
| joshuef/peruse | __tests__/actions/remoteCall.spec.js | JavaScript | mit | 1,033 |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Revrec = mongoose.model('Revrec'),
_ = require('lodash');
/**
* Create a revrec
*/
exports.create = function(req, res) {
var revrec = new Revrec(req.body);
revrec.user = req.user;
revrec.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(revrec);
}
});
};
/**
* Show the current revrec
*/
exports.read = function(req, res) {
res.json(req.revrec);
};
/**
* Update a revrec
*/
exports.update = function(req, res) {
var revrec = req.revrec;
revrec = _.extend(revrec, req.body);
revrec.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(revrec);
}
});
};
/**
* Delete an revrec
*/
exports.delete = function(req, res) {
var revrec = req.revrec;
revrec.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(revrec);
}
});
};
/**
* List of Revrecs
*/
exports.list = function(req, res) {
Revrec.find().sort('-created').populate('user', 'displayName').exec(function(err, revrecs) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(revrecs);
}
});
};
/**
* Revrec middleware
*/
exports.revrecByID = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Revrec is invalid'
});
}
Revrec.findById(id).populate('user', 'displayName').exec(function(err, revrec) {
if (err) return next(err);
if (!revrec) {
return res.status(404).send({
message: 'Revrec not found'
});
}
req.revrec = revrec;
next();
});
};
/**
* Revrec authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.revrec.user.id !== req.user.id) {
return res.status(403).send({
message: 'User is not authorized'
});
}
next();
};
| flysnob/gaaplogic-dev | app/controllers/revrecs.server.controller.js | JavaScript | mit | 2,152 |
'use strict';
var chalk = require('chalk');
module.exports = {
addAsPrivateProps: function(target, source) {
Object.keys(source).forEach(function(key) {
target['_' + key] = source[key];
});
},
promptAndSaveResponse: function(generator, prompts, cb) {
if (generator.options['skip-prompts']) {
prompts.forEach(function(prompt) {
generator['_' + prompt.name] = (typeof prompt.default === 'function') ? prompt.default() : prompt.default;
});
cb();
} else {
generator.prompt(prompts, function(answers) {
Object.keys(answers).forEach(function(key) {
generator['_' + key] = answers[key];
});
cb();
});
}
},
makeSDKContext: function(self) {
return {
appKey: self['_' + self.developerInfoKeys.AppKey],
sharedSecret: self['_' + self.developerInfoKeys.SharedSecret],
baseUrl: process.env.MOZU_HOMEPOD || self._homePod,
developerAccountId: self._developerAccountId,
developerAccount: {
emailAddress: self['_' + self.developerInfoKeys.AccountLogin]
},
workingApplicationKey: self._applicationKey
};
},
trimString: function(str) {
return str.trim();
},
trimAll: function(obj) {
return Object.keys(obj).reduce(function(result, k) {
result[k] = (typeof obj[k] === 'string') ? obj[k].trim() : obj[k];
return result;
}, {});
},
merge: function() {
return Object.assign.apply(Object, arguments);
},
remark: function(ctx, str) {
ctx.log(chalk.green('>> ') + str + '\n');
},
lament: function(ctx, str, e) {
ctx.log(chalk.bold.red(str + '\n'));
if (process.env.NODE_DEBUG && process.env.NODE_DEBUG.indexOf('mozu-app') !== -1) {
ctx.log(e && chalk.bold.red('Details: \n' + require('util').inspect(e, { depth: 4 })));
}
}
};
| Mozu/generator-mozu-app | utils/helpers.js | JavaScript | mit | 1,840 |
var React = require('react');
function supportMdlShadow(spec) {
var shadowPrefix = 'mdl-shadow';
return React.createClass({
displayName: spec.displayName,
propTypes: {
className: React.PropTypes.string,
shadow: React.PropTypes.string
},
getDefaultProps: function() {
return {
className: '',
shadow: null
};
},
getShadowClassName: function() {
var shadow = this.props.shadow;
if (shadow >= 1 && shadow <= 6) {
var depth = 2;
switch (shadow) {
case '1': depth = 2; break;
case '2': depth = 3; break;
case '3': depth = 4; break;
case '4': depth = 6; break;
case '5': depth = 8; break;
case '6': depth = 16; break;
}
return shadowPrefix + '--' + depth + 'dp';
} else if (shadow && shadow.replace('dp', '') > 0){
return shadowPrefix + '--' + shadow;
} else {
return '';
}
},
render: function() {
var element = React.createElement(spec, this.props),
classList = this.props.className.split(' '),
shadowClass = this.getShadowClassName();
return React.cloneElement(element, {
className: [shadowClass].concat(classList).join(' ')
});
}
});
}
module.exports = supportMdlShadow;
| EdStudio/react-mdlite | src/utils/mdlShadow.js | JavaScript | mit | 1,347 |
Maildog.Models.EmailThread = Backbone.Model.extend({
urlRoot: "api/email_threads",
toJSON: function(){
var json = { email_thread: _.clone(this.attributes) };
return json;
},
parse: function(payload) {
if (payload.tail) {
this.tail().set(this.tail().parse(payload.tail));
delete payload.tail;
}
if (payload.emails) {
this.emails().reset(payload.emails, { parse: true });
delete payload.emails;
}
if (payload.labels) {
this.labels().reset(payload.labels, { parse: true });
delete payload.labels;
}
if (payload.trashCount) {
this.trashCount = payload.trashCount;
delete payload.trashCount;
}
if (payload.nonTrashCount) {
this.nonTrashCount = payload.nonTrashCount;
delete payload.nonTrashCount;
}
return payload
},
labels: function() {
this._labels = (this._labels || new Maildog.Collections.Labels([], {
url: function() {
return "api/email_threads/" + this.id + "/labels"
}.bind(this)
}));
return this._labels;
},
displayCount: function(folder) {
var count;
if (folder === "trash") {
count = this.trashCount;
}
else {
count = this.nonTrashCount;
}
if (count > 1) { return "(" + count + ")" }
},
tail: function() {
this._tail = (this._tail || new Maildog.Models.Email());
return this._tail;
},
emails: function() {
this._emails = (this._emails || new Maildog.Collections.Emails());
return this._emails;
},
replyTo: function() {
for (var i = this.emails().length - 1; i >= 0; i--) {
var sender = this.emails().at(i).sender();
if (sender.get('email') != Maildog.currentUser.get('email')) {
return sender
}
}
return this.emails().last().sender();
}
});
| petrgazarov/Maildog | app/assets/javascripts/models/emailThread.js | JavaScript | mit | 1,833 |
//@flow
export default {
header: {
title: 'Образовательные программы ',
description: {
description: 'Курсы лекций про саунд, продюссирование и запись музыки content',
},
},
description: {
title: 'Описание ',
description: {
description: 'Какое-то описание',
},
},
descriptionMedia: {
file: {
url:
'//images.contentful.com/vx768p4z763o/attachment_post_2388/0a993490d760786e33dd51c6b09f759e/attachment_post_2388',
},
},
}
| Galernaya20/galernaya20.com | src/components/pages/OneBlockPage/fixture.js | JavaScript | mit | 584 |
/*
* esrislurp
* https://github.com/steveoh/esrislurp
*
* Copyright (c) 2014 steveoh
* Licensed under the MIT license.
*/
'use strict';
var fs = require('fs'),
path = require('path'),
async = require('async'),
beautify_js = require('js-beautify').js_beautify,
beautify_css = require('js-beautify').css,
mkdirp = require('mkdirp'),
os = require('os'),
request = require('request'),
S = require('string'),
unwind = require('./unwinder');
function noop(){}
module.exports = function(basePath, version, beautify, onSuccess, onError, onProgress) {
onSuccess = onSuccess || noop;
onError = onError || noop;
onProgress = onProgress || noop;
var packageLocation = S(basePath).ensureRight(path.sep).s;
mkdirp.sync(packageLocation);
var esriModules = require('./modules/esriModules-' + version);
var esriVersionBaseUrl = 'http://js.arcgis.com/' + version;
if(+version > 3.10){
esriVersionBaseUrl += 'amd/esri/';
}
else{
esriVersionBaseUrl += 'amd/js/esri/';
}
var total = esriModules.length,
count = 0;
function signalProgessUpdate() {
onProgress({count: count, total: total});
}
async.eachLimit(esriModules, 20, function(file, callback) {
var subPath = S(path.dirname(file)).ensureRight('/').s,
fileFolder = path.join(packageLocation, subPath),
fileName = path.basename(file),
httpUrl = esriVersionBaseUrl + subPath + fileName;
if (!fs.existsSync(fileFolder)) {
mkdirp.sync(fileFolder);
}
request({
uri: httpUrl,
encoding: 'binary'
},
function(error, response, body) {
count += 1;
if (body.length < 1) {
signalProgessUpdate();
callback(error, body);
return;
}
var newFile = path.join(packageLocation, file);
var extension = path.extname(file);
if (extension === '.js' || extension === '.css') {
body = unwind(body);
if (beautify) {
try {
if (extension === '.js') {
body = beautify_js(body);
} else if (extension = '.css') {
body = beautify_css(body);
}
} catch (e) {
console.log(os.EOL + 'error beautifying: ' + file + ' ' + e);
// swallow it's not the end of the world if it's not beautiful
}
}
}
fs.writeFile(newFile, body, 'binary');
signalProgessUpdate();
callback(error, body);
});
}, function(err) {
if (err) {
onError(err);
} else {
onSuccess();
}
});
};
| phillipgreenii/esrislurp | esri_slurp.js | JavaScript | mit | 2,742 |
var fs = require('fs');
var browserify = require('browserify');
// Browserify client side app
var b = browserify('./lib/client.js');
//NOTE, ignore any javascript that should not be sent to the client
b.ignore('express');
b.bundle().pipe(
fs.createWriteStream('app.js', { flags : 'w' })
);
// Start Server
require('./lib/server');
| nheyn/react-router-server | examples/basic/index.js | JavaScript | mit | 336 |
var RssCleaner = RssCleaner || {};
RssCleaner.getBasePath = function () {
if (window.location.pathname.indexOf('app_dev.php') >= 0) {
return '/cc/app_dev.php';
} else {
return '/cc';
}
};
RssCleaner.search = {
isRunning: false,
init: function () {
$('#rss_cleaner_bundle_expression_type_expression').on('keyup', function() {
RssCleaner.search.getSearchText();
});
},
getSearchText: function () {
var text = $('#rss_cleaner_bundle_expression_type_expression').val();
if (text.length >= 3 && this.isRunning !== true) {
RssCleaner.search.isRunning = true;
RssCleaner.rest.apiGet(text, RssCleaner.search.showResult);
}
},
showResult: function (ajaxObject) {
$('#searchResult').html(ajaxObject.data);
RssCleaner.search.isRunning = false;
}
};
RssCleaner.rest = {
apiGet: function(data, callback) {
var url = RssCleaner.getBasePath() + '/rsscleaner/entries/search/';
jQuery.ajax({
type: "GET",
url: url + encodeURIComponent(data),
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data, status, jqXHR) {
var obj = RssCleaner.ajaxObject;
obj.data = data;
obj.status = status;
callback(obj);
},
error: function (jqXHR, status) {
var obj = RssCleaner.ajaxObject;
obj.data = 'Error';
obj.status = status;
callback(obj);
}
});
}
};
RssCleaner.ajaxObject = {
status: 0,
data: ''
}; | dknx01/comcenter | src/RssCleanerBundle/Resources/public/js/rsscleaner.js | JavaScript | mit | 1,720 |
import baseModel from './baseModel';
import playModel from './play';
import util from '../../util';
export default (() => {
const { deepFreeze } = util;
const schema = deepFreeze({
name: 'match',
canDelete: true,
columns: {
id: {
type: 'number',
required: false,
canCreate: false,
canUpdate: false
},
away_team_id: {
type: 'number',
required: true,
canCreate: true,
canUpdate: false
},
home_team_id: {
type: 'number',
required: true,
canCreate: true,
canUpdate: false
},
match_site_id: {
type: 'number',
required: false,
canCreate: true,
canUpdate: true
},
season_id: {
type: 'number',
required: false,
canCreate: true,
canUpdate: true
},
rulset_id: {
type: 'number',
required: true,
canCreate: true,
canUpdate: false
}
}
});
const base = baseModel(schema);
const getPlays = (id) => {
return playModel.getPlaysByMatchId(id);
};
return Object.freeze({
getSchema: base.getSchema,
getTableName: base.getTableName,
create: base.create,
get: base.get,
getById: base.getById,
getPlays,
update: base.update,
updateById: base.updateById,
deleteById: base.deleteById
});
})();
| HolyMeekrob/scorage-postgres | src/db/models/match.js | JavaScript | mit | 1,241 |
import React, { PropTypes } from 'react';
import classNames from 'classnames';
const TH = (props) => {
const { className, ascending, descending, nonNumeric, children,
...otherProps } = props;
const classes = classNames({
'mdl-data-table__header--sorted-ascending': ascending,
'mdl-data-table__header--sorted-descending': descending,
'mdl-data-table__cell--non-numeric': nonNumeric
}, className);
return (
<th className={classes} {...otherProps}>
{children}
</th>
)
}
TH.propTypes = {
className: PropTypes.string,
ascending: PropTypes.bool,
descending: PropTypes.bool,
nonNumeric: PropTypes.bool
}
TH.defaultProps = {
ascending: false,
descending: false,
nonNumeric: false
}
export { TH }
| iporaitech/react-to-mdl | src/dataTable/TH.js | JavaScript | mit | 749 |
'use strict';
var csp = require('../../dist/index');
csp.top(csp.go(function*() {
var ticker = csp.ticker(500);
for (var i = 0; i < 10; ++i) {
yield csp.pull(ticker);
console.log(i);
}
ticker.close();
}));
| AppliedMathematicsANU/plexus-csp | examples/channels/ticker.js | JavaScript | mit | 226 |
export const ic_grading_twotone = {"viewBox":"0 0 24 24","children":[{"name":"g","attribs":{},"children":[{"name":"rect","attribs":{"fill":"none","height":"24","width":"24"},"children":[{"name":"rect","attribs":{"fill":"none","height":"24","width":"24"},"children":[]}]}]},{"name":"g","attribs":{},"children":[{"name":"path","attribs":{"d":"M4,7h16v2H4V7z M4,13h16v-2H4V13z M4,17h7v-2H4V17z M4,21h7v-2H4V21z M15.41,18.17L14,16.75l-1.41,1.41L15.41,21L20,16.42 L18.58,15L15.41,18.17z M4,3v2h16V3H4z"},"children":[{"name":"path","attribs":{"d":"M4,7h16v2H4V7z M4,13h16v-2H4V13z M4,17h7v-2H4V17z M4,21h7v-2H4V21z M15.41,18.17L14,16.75l-1.41,1.41L15.41,21L20,16.42 L18.58,15L15.41,18.17z M4,3v2h16V3H4z"},"children":[]}]}]}]}; | wmira/react-icons-kit | src/md/ic_grading_twotone.js | JavaScript | mit | 721 |
module.exports = function(app, passport) {
var express = require('express');
var router = express.Router();
passport.checkAuth = require('../middlewares/auth');
router.use('/scans', require('./scans')(app, passport));
router.use('/users', require('./users')(app, passport));
router.use('/kegs', require('./kegs')(app, passport));
router.use('/purchases', require('./purchases')(app, passport));
router.use('/payments', require('./payments')(app, passport));
router.use('/charge', require('./charge')(app, passport));
return router;
}; | chuckdrew/theofficekeg | controllers/index.js | JavaScript | mit | 576 |
var api = require('zenircbot-api');
var bot_config = api.load_config('../bot.json');
var zen = new api.ZenIRCBot(bot_config.redis.host,
bot_config.redis.port,
bot_config.redis.db);
var sub = zen.get_redis_client();
var ticket = /(?:\s|^)([a-zA-Z][a-zA-Z]-\d+)/g;
var config = api.load_config('./jira.json');
zen.register_commands('jira_ticket.js', []);
sub.subscribe('in');
sub.on('message', function(channel, message){
var msg = JSON.parse(message);
if (msg.version == 1 && msg.type == 'privmsg') {
if (config.channels.indexOf(msg.data.channel) != -1) {
var result = ticket.exec(msg.data.message);
while (result) {
console.log(result[1]);
zen.send_privmsg(config.channels,
config.jira_url + 'browse/' + result[1]);
lastIndex = ticket.lastIndex;
result = ticket.exec(msg.data.message);
}
}
}
});
| zenirc/zenircbot | services/jira_ticket.js | JavaScript | mit | 1,016 |
$(() => {
const host='https://judgetests.firebaseio.com/schedule/';
let id='depot';
const spanInfo=$('.info');
let departBtn=$('#depart');
let arriveBtn=$('#arrive');
departBtn.click(depart);
arriveBtn.click(arrive);
function depart() {
let address=host+id+'.json';
console.log(address);
$.ajax({
url: address,
success: departSuccess,
error:errorFunction
});
function departSuccess(data) {
let name=data.name;
console.log(name);
spanInfo.text(`Next stop ${name}`);
departBtn.prop('disabled',true);
arriveBtn.prop('disabled',false);
}
}
function arrive() {
let address=host+id+'.json';
$.ajax({
url: address,
success: arriveSuccess,
error:errorFunction
});
function arriveSuccess(data) {
let name=data.name;
let next=data.next;
spanInfo.text(`Arriving at ${name}`);
departBtn.prop('disabled',false);
arriveBtn.prop('disabled',true);
id=next;
}
}
function errorFunction() {
spanInfo.text(`Error`);
}
}); | mitaka00/SoftUni | Front-End Development/JS FOR FRONT-END/AJAX/Bus Schedule/busSchedule.js | JavaScript | mit | 1,286 |
'use strict';
module.exports = {
httpPort: 3381,
mongodb: (
'mongodb://' +
(process.env.MONGO_PORT_27017_TCP_ADDR || '127.0.0.1') +
':' +
(process.env.MONGO_PORT_27017_TCP_PORT || 27017) +
'/' +
(process.env.MONGO_DBNAME || 'tntu-schedcap-test')
),
};
| tarquas/tntu-schedcap | app/config/testing.js | JavaScript | mit | 284 |
import {ST_SET} from '../service/storage'
export const localStoragePlugin = store => {
// 当 store 初始化后调用
store.subscribe((mutation, state) => {
// 每次 mutation 之后调用
// mutation 的格式为 { type, payload }
ST_SET('TODOLIST', JSON.stringify(state.TodoList))
ST_SET('DONELIST', JSON.stringify(state.DoneList))
})
}
| moyunchen/vue-todo | src/plugin/localStoragePlugin.js | JavaScript | mit | 363 |
version https://git-lfs.github.com/spec/v1
oid sha256:9193b24ed1102e4e76244447e3377f8bc3dc0f131fea3d7ffafd85a31e8941a2
size 14291
| yogeshsaroya/new-cdnjs | ajax/libs/machina.js/0.3.5/machina.js | JavaScript | mit | 130 |
version https://git-lfs.github.com/spec/v1
oid sha256:5d54f60298f898f42de202b1fb988125c04b705f46c5b06641117dce8d6475ad
size 64626
| yogeshsaroya/new-cdnjs | ajax/libs/html-inspector/0.8.1/html-inspector.js | JavaScript | mit | 130 |
/**************************
* This is an attempt to visualize the "students" object and the objects it
* contains based on what we talked about on Sunday. Please feel free to
* make adjustments or correct mistakes.
*
* Everything is assumed to work within the constraints set by csv-standards.
**************************/
Section: { // filled in by getRequest
students: { // object container of students indexed by repo id see below for student definition
//TODO Discuss Gradebook-like object per erics suggestion
student: {
letterGrade:"A", // typeof char (string w/ length 1)
note:"lovely test", // typeof string
totalGrade:"90.5", // typeof number (%)
section:"cs1", // typeof string
repo:"2k4", // typeof string
scores: {
// quiz: typeof object: { [name: typeof number]* }
"quiz": { "q1": 9,"q2": 6,"q3": 5,"q4":"","q5": 7 },
// midterm: typeof object: { [name: typeof number]* }
"midterm": { "m1": 7,"m2": 8,"m3": 6,"m4": 5 },
// I believe "final" is a reserved JS word, so this one gets to be verbose:
// finalExam: typeof object: { [name: typeof number] }
"finalExam": { "finalExam": 32 },
// hw: typeof object: { [name: typeof number]* }
"hw": {
"hw1": 7,
"hw2": 6,
"hw3": 8,
"hw4": 9,
"hw5": 5,
"hw6": 7,
"hw7": 7
}
}
};
};
classStats: { // Filled by Eric (gradeStats.js)
averageGrade = typeof number; // percentage
medianGrade = typeof number; // percentage
gradeRange = typeof number; // percentage
};
assignmentInfo: { // Contains prorates and any other assignment specific data.
quiz: {
q1: { weight: 00, max: 00, prorate: ??? }
}
midterm: {
m1: { weight: 00, max: 00, prorate: ??? }
}
hw: {
hw1: { weight: 00, max: 00, prorate: ??? }
}
finalExam: {
finalExam: { weight: 00, max: 00, prorate: ??? }
}
};
cutoffs: {
"A": 90,
"B": 80,
"C": 70,
"D": 60 // etc.
};
/* Items below are under discussion and not currently used...
gradeBook = {
categories = { // Filled by Josh (jRequest.js)
catName = { // hw, project, quiz, exam, total...
itemName = { // hw#, project#, quiz#, exam#, total...
weight = typeof number; // percentage?
pointsPossible = typeof number;
classAverage = typeof number; // Calculated by gradeStats.js
classMedian = typeof number; // Calculated by gradeStats.js
date = typeof Date; // assigned/due?
// Maybe letter grade (cutoff), etc, can be calculated on the fly.
}
}
}
}
students = {
repo = { // Repeat for each enrolled student. Filled by Josh (jRequest.js)
catName = { // Repeat for each category in students.categories.
itemName = { // Repeat for each itemName in students.categories.catName.
section = typeof string; // letter/number?
pointsEarned = typeof number;
feedback = typeof string;
// Maybe letter grade (cutoff), etc, can be calculated on the fly.
}
}
}
}
*/
}
| schredder/FD2l | docs/student-object.js | JavaScript | mit | 3,444 |
import {createStore, combineReducers, applyMiddleware} from "redux";
import logger from "redux-logger";
import userReducer from "../reducers/userReducer";
const userStore = createStore(
combineReducers({user: userReducer}),
{},
applyMiddleware(logger())
);
export default userStore;
| pedroaugustofr/TeamProjectBoard | src/code/store/store.js | JavaScript | mit | 291 |
require('babel-register')();
import { expect } from 'chai';
import sinon from 'sinon';
import { jsdom } from 'jsdom';
import MockLocalStorage from 'mock-localstorage';
// Export expect and sinon so we don't have to keep requiring them
// Place any additional boilerplate here, and expose it on `global`
global.expect = expect;
global.sinon = sinon;
const mockStorage = new MockLocalStorage();
const exposedProperties = ['window', 'navigator', 'document'];
global.localStorage = mockStorage;
global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property);
global[property] = document.defaultView[property];
}
});
global.navigator = {
userAgent: 'node.js'
};
| neilff/smoker-js | testing/testConfig.js | JavaScript | mit | 819 |
'use strict';
exports = module.exports = function(app, passport) {
var BasicStrategy = require('passport-http').BasicStrategy,
LocalStrategy = require('passport-local').Strategy,
BearerStrategy = require('passport-http-bearer').Strategy,
TwitterStrategy = require('passport-twitter').Strategy,
GitHubStrategy = require('passport-github').Strategy,
FacebookStrategy = require('passport-facebook').Strategy,
GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
function findUsers(username, password, done) {
var conditions = { isActive: 'yes' };
if (username.indexOf('@') === -1) {
conditions.username = username;
}
else {
conditions.email = usernames;
}
app.db.models.User.findOne(conditions, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'Unknown user' });
}
app.db.models.User.validatePassword(password, user.password, function(err, isValid) {
if (err) {
return done(err);
}
if (!isValid) {
return done(null, false, { message: 'Invalid password' });
}
return done(null, user);
});
});
}
passport.use(new LocalStrategy(findUsers));
passport.use(new BasicStrategy(findUsers));
passport.use(new BearerStrategy(
//function(username, password, done) {
function (token, done) {
var conditions = { token: token };
app.db.models.User.findOne(conditions, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'Unknown user' });
}
return done(null, user);
});
}
));
if (app.get('twitter-oauth-key')) {
passport.use(new TwitterStrategy({
consumerKey: app.get('twitter-oauth-key'),
consumerSecret: app.get('twitter-oauth-secret')
},
function(token, tokenSecret, profile, done) {
done(null, false, {
token: token,
tokenSecret: tokenSecret,
profile: profile
});
}
));
}
if (app.get('github-oauth-key')) {
passport.use(new GitHubStrategy({
clientID: app.get('github-oauth-key'),
clientSecret: app.get('github-oauth-secret'),
customHeaders: { "User-Agent": app.get('project-name') }
},
function(accessToken, refreshToken, profile, done) {
done(null, false, {
accessToken: accessToken,
refreshToken: refreshToken,
profile: profile
});
}
));
}
if (app.get('facebook-oauth-key')) {
passport.use(new FacebookStrategy({
clientID: app.get('facebook-oauth-key'),
clientSecret: app.get('facebook-oauth-secret')
},
function(accessToken, refreshToken, profile, done) {
done(null, false, {
accessToken: accessToken,
refreshToken: refreshToken,
profile: profile
});
}
));
}
if (app.get('google-oauth-key')) {
passport.use(new GoogleStrategy({
clientID: app.get('google-oauth-key'),
clientSecret: app.get('google-oauth-secret')
},
function(accessToken, refreshToken, profile, done) {
done(null, false, {
accessToken: accessToken,
refreshToken: refreshToken,
profile: profile
});
}
));
}
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
app.db.models.User.findOne({ _id: id }).populate('roles.admin').populate('roles.account').exec(function(err, user) {
if (user.roles && user.roles.admin) {
user.roles.admin.populate("groups", function(err, admin) {
done(err, user);
});
}
else {
done(err, user);
}
});
});
};
| Alexandrescu/drywall | passport.js | JavaScript | mit | 4,130 |
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
// some constants to help with marching squares algorithm
// where does the path start for each index?
BOTTOMSTART: [1, 9, 13, 104, 713],
TOPSTART: [4, 6, 7, 104, 713],
LEFTSTART: [8, 12, 14, 208, 1114],
RIGHTSTART: [2, 3, 11, 208, 1114],
// which way [dx,dy] do we leave a given index?
// saddles are already disambiguated
NEWDELTA: [
null, [-1, 0], [0, -1], [-1, 0],
[1, 0], null, [0, -1], [-1, 0],
[0, 1], [0, 1], null, [0, 1],
[1, 0], [1, 0], [0, -1]
],
// for each saddle, the first index here is used
// for dx||dy<0, the second for dx||dy>0
CHOOSESADDLE: {
104: [4, 1],
208: [2, 8],
713: [7, 13],
1114: [11, 14]
},
// after one index has been used for a saddle, which do we
// substitute to be used up later?
SADDLEREMAINDER: {1: 4, 2: 8, 4: 1, 7: 13, 8: 2, 11: 14, 13: 7, 14: 11},
// length of a contour, as a multiple of the plot area diagonal, per label
LABELDISTANCE: 2,
// number of contour levels after which we start increasing the number of
// labels we draw. Many contours means they will generally be close
// together, so it will be harder to follow a long way to find a label
LABELINCREASE: 10,
// minimum length of a contour line, as a multiple of the label length,
// at which we draw *any* labels
LABELMIN: 3,
// max number of labels to draw on a single contour path, no matter how long
LABELMAX: 10,
// constants for the label position cost function
LABELOPTIMIZER: {
// weight given to edge proximity
EDGECOST: 1,
// weight given to the angle off horizontal
ANGLECOST: 1,
// weight given to distance from already-placed labels
NEIGHBORCOST: 5,
// cost multiplier for labels on the same level
SAMELEVELFACTOR: 10,
// minimum distance (as a multiple of the label length)
// for labels on the same level
SAMELEVELDISTANCE: 5,
// maximum cost before we won't even place the label
MAXCOST: 100,
// number of evenly spaced points to look at in the first
// iteration of the search
INITIALSEARCHPOINTS: 10,
// number of binary search iterations after the initial wide search
ITERATIONS: 5
}
};
| iongroup/plotly.js | src/traces/contour/constants.js | JavaScript | mit | 2,577 |
import { combineReducers } from 'redux';
import drawer from './drawer';
import route from './route';
import user from './user';
import list from './list';
import escolaSabatina from './escolaSabatina';
export default combineReducers({
drawer,
route,
user,
list,
escolaSabatina,
});
| lemol/diario-escola-sabatina | react-native/nativebase/js/reducers/index.js | JavaScript | mit | 297 |
(function () {
function createJsConsole(selector) {
var self = this;
var consoleElement = document.querySelector(selector);
if (consoleElement.className) {
consoleElement.className = consoleElement.className + " js-console";
}
else {
consoleElement.className = "js-console";
}
var textArea = document.createElement("p");
consoleElement.appendChild(textArea);
self.write = function jsConsoleWrite(text) {
var textLine = document.createElement("span");
textLine.innerHTML = text;
textArea.appendChild(textLine);
consoleElement.scrollTop = consoleElement.scrollHeight;
};
self.writeLine = function jsConsoleWriteLine(text) {
self.write(text);
textArea.appendChild(document.createElement("br"));
};
self.read = function readText(inputSelector) {
var element = document.querySelector(inputSelector);
if (element.innerHTML) {
return element.innerHTML;
}
else {
return element.value;
}
};
self.readInteger = function readInteger(inputSelector) {
var text = self.read(inputSelector);
return parseInt(text);
};
self.readFloat = function readFloat(inputSelector) {
var text = self.read(inputSelector);
return parseFloat(text);
};
return self;
}
jsConsole = new createJsConsole("#console");
}).call(this); | Steffkn/TelerikAcademy | HTML and CSS/JS/Exam/JS DOM IZPIT/izpit proverki/domashni/7.2 -gotino/js/js-console.js | JavaScript | mit | 1,305 |
define(['directives/directives'], function (directives) {
'use strict';
directives.directive('enzoInputPhone', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attr, ctrl) {
var opts = angular.extend({flag: true}, scope.$eval(attr.enzoInputPhone));
if (opts.flag) {
element.wrap('<div class="left-inner-addon"></div>');
element.before('<i></i>');
element.css('width', '100%');
} else if (!attr['class']) {
element.addClass('input-medium');
}
ctrl.$formatters.push(function (value) {
if (!value) {
element.removeAttr('data-enzo-validate-phone');
ctrl.$setValidity('phone', true);
if (opts.flag) {
element.parent().find('i').removeAttr('class').attr('class', '');
}
return value;
}
var region = PhoneNumber.Parse(value, 'BR');
if (region) {
element.removeAttr('data-enzo-validate-phone');
ctrl.$setValidity('phone', true);
if (opts.flag) {
element.parent().find('i').removeAttr('class').attr('class', '').addClass('flag flag-' + region.region.toLowerCase());
}
return region.internationalFormat;
} else {
element.attr('data-enzo-validate-phone', scope.$eval(attr.enzoInputPhoneMessage) || I18n.t('enzo.validation.type.phone'));
ctrl.$setValidity('phone', false);
if (opts.flag) {
element.parent().find('i').removeAttr('class').attr('class', '');
}
return value;
}
});
ctrl.$parsers.push(function (value) {
if (!value) {
element.removeAttr('data-enzo-validate-phone');
ctrl.$setValidity('phone', true);
if (opts.flag) {
element.parent().find('i').removeAttr('class').attr('class', '');
}
return value;
}
var region = PhoneNumber.Parse(value, 'BR');
if (region && region.internationalFormat) {
element.removeAttr('data-enzo-validate-phone');
ctrl.$setValidity('phone', true);
if (opts.flag) {
element.parent().find('i').removeAttr('class').attr('class', '').addClass('flag flag-' + region.region.toLowerCase());
}
return PhoneNumber.Normalize(value);
} else {
element.attr('data-enzo-validate-phone', scope.$eval(attr.enzoInputPhoneMessage) || I18n.t('enzo.validation.type.phone'));
ctrl.$setValidity('phone', false);
if (opts.flag) {
element.parent().find('i').removeAttr('class').attr('class', '');
}
return undefined;
}
});
element.change(function () {
var region = PhoneNumber.Parse($(this).val(), 'BR');
if (region && region.internationalFormat) {
$(this).val(region.internationalFormat);
}
});
}
};
});
});
| leonardosalles/enzo | static/js/directives/inputPhone.js | JavaScript | mit | 2,754 |
const EventEmitter = require('events');
//
// Robot
//
class Robot extends EventEmitter {
/**
* Creates an Robot instance.
*/
constructor(options) {
super();
this._init(options);
}
/**
* Initializes robot instance.
* @param {object} options - robot options.
*/
_init(options) {
this._options = options;
}
/**
* Executes a command of this robot with play options.
* @param {string} command - command name.
* @param {object} playOptions - play options.
*/
do(command, playOptions) {
const sequence = options.commands[command];
sequence.play(Object.assign({}, options.playOptions, playOptions));
}
};
module.exports = Robot;
| Gary-Ascuy/ssc | lib/robot.js | JavaScript | mit | 687 |
import { reduceInto } from "reiter";
import * as matchers from "./matchers.js";
expect.extend(matchers);
describe("reduceInto(reducer, accumulator, iterable)", () => {
test("reduces into an accumulator", () => {
const multiply = jest.fn((a, b) => a * b);
expect(reduceInto(multiply, 1, [2, 3, 2])).toBe(12);
expect(multiply.mock.calls).toEqual([[1, 2], [2, 3], [6, 2]]);
});
test("empty iterable returns the accumulator and does not call the reducer", () => {
const notCalled = jest.fn();
expect(reduceInto(notCalled, 42, [])).toBe(42);
expect(notCalled.mock.calls).toHaveLength(0);
});
});
| sulcata/reiter | test/reduceInto.test.js | JavaScript | mit | 626 |
import { createElement as ce } from 'react';
import t from 'es2015-i18n-tag';
const WalkRoute = ({ markers }) => (
ce('section', { className: 'walkRoute' },
ce('a', { name: 'Walk Route' }),
ce('h2', {}, t`Walk Route`),
ce('ol', {}, markers.map(({ properties: { title, description } }, i) => (
ce('li', { key: `routeentry${i}` },
ce('h2', {}, title),
ce('p', {}, description),
)
))),
)
);
export default WalkRoute;
| jkoudys/janeswalk-web | themes/janeswalk/js/components/pages/Walk/Route.js | JavaScript | mit | 464 |
module.exports = {
description: "",
ns: "react-material-ui",
type: "ReactNode",
dependencies: {
npm: {
"material-ui/svg-icons/maps/local-bar": require('material-ui/svg-icons/maps/local-bar')
}
},
name: "MapsLocalBar",
ports: {
input: {},
output: {
component: {
title: "MapsLocalBar",
type: "Component"
}
}
}
} | nodule/react-material-ui | MapsLocalBar.js | JavaScript | mit | 379 |
/*!
* htamale: lib/utils/router.js
*/
'use strict';
const datetime = require('./_datetime'),
interval = require('./_interval'),
html = require('./_html');
/**
* Avoids circular dependencies while still allowing
* recursive parsing
*
* @param {String} type
* @param {Object} obj
* @param {Object} opts
* @returns {String}
* @api private
*/
function handler(obj, opts = {}) {
const dest = {
html: {
fun: html,
prop: ['html']
},
datetime: {
fun: datetime,
prop: []
},
interval: {
fun: interval,
prop: ['start', 'delim', 'end']
}
};
dest[obj.type].prop.forEach(function (prop) {
if (obj.hasOwnProperty(prop) && 'string' !== typeof obj[prop] ) {
obj[prop] = route(obj[prop]);
}
if (opts.hasOwnProperty(prop) && 'string' !== typeof opts[prop] ) {
opts[prop] = route(opts[prop]);
}
});
return dest[obj.type].fun(obj, opts);
}
/**
* Route object to correct parser
*
* @param {*} obj
* @param {Object} opts
* @returns {String|null}
* @throws {Error}
*/
function route(obj, opts) {
if (!obj) {
return;
}
if (typeof obj === 'function') {
throw new Error('Cannot parse functions.');
}
if ( typeof obj !== 'object' ) {
return String(obj);
} else if ( obj.constructor === Array ) {
return obj.map(function(item) {
return route(item, opts);
}).join('\n');
} else if (obj.hasOwnProperty('_value')) {
return route(obj._value, opts);
} else if ( !obj.hasOwnProperty('type') ) {
return null;
}
return handler(obj, opts);
}
module.exports = route; | imatlopez/htamale | lib/utils/router.js | JavaScript | mit | 1,625 |
{
"name": "svg.tooltip.js",
"url": "https://github.com/weconquered/svg.tooltip.js.git"
}
| bower/components | packages/svg.tooltip.js | JavaScript | mit | 93 |
import React, { Component, PropTypes } from 'react';
import { reduxForm } from 'redux-form';
import validations from './blitzFormValidation';
import { blitzCreateLead as create } from 'redux/modules/blitzCreateLead';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
// import { Row, Col } from 'react-bootstrap';
@connect(
() => ({}),
( dispatch ) => bindActionCreators( { blitzCreateLead: create }, dispatch)
)
@reduxForm({
form: 'blitzLeadForm',
fields: [
'name',
'phone'
],
validate: validations
})
export default class BlitzLeadForm extends Component {
static propTypes = {
fields: PropTypes.object.isRequired,
values: PropTypes.object,
valid: PropTypes.bool,
title: PropTypes.string,
buttonText: PropTypes.string,
touchAll: PropTypes.func.isRequired,
blitzCreateLead: PropTypes.func,
captureLeadInfo: PropTypes.func
}
constructor(props) {
super(props);
}
submitHander(event) {
event.preventDefault();
const { touchAll, valid, values } = this.props;
// const that = this;
touchAll();
const formData = {};
for (const prop in values) {
if ( values.hasOwnProperty(prop)) {
formData[prop] = values[prop];
}
}
if (valid) {
this.props.blitzCreateLead(formData).then(() => {
this.props.captureLeadInfo(formData);
});
}
}
render() {
const styles = require('./BlitzLeadForm.scss');
const {
fields: { name, phone },
buttonText, title
} = this.props;
return (
<div className={styles.leadformwrapper}>
<form onSubmit={this.submitHander.bind(this)} className = {styles.form }>
<div className="form-group">
<div className={styles.formtitle}>{ title }</div>
<input type="text" className={styles.remove + ' form-control'} placeholder="Full Name" {...name}/>
{name.touched && name.error && <div className={styles.errorMessage}>{name.error}</div>}
</div>
<div className="form-group">
<div className="input-group">
<span className={styles.removeback + ' input-group-addon'}>+91</span>
<input type="text" className={styles.remove + ' form-control'} maxLength={10} placeholder="Enter your 10 digit phone number" {...phone}/>
</div>
{phone.touched && phone.error && <div className={styles.errorMessage}>{phone.error}</div>}
</div>
<div className = {styles.btnWrapper + ' form-group'}>
<button type="submit" onClick={this.submitHander.bind(this)} className={styles.butn + ' btn'}>{ buttonText }</button>
</div>
</form>
</div>
);
}
}
| Anshul-HL/blitz-row | src/components/Blitz/BlitzLeadForm.js | JavaScript | mit | 2,759 |
import RawDecoder from './raw';
import LZWDecoder from './lzw';
import JpegDecoder from './jpeg';
import DeflateDecoder from './deflate';
import PackbitsDecoder from './packbits';
import LercDecoder from './lerc';
export function getDecoder(fileDirectory) {
switch (fileDirectory.Compression) {
case undefined:
case 1: // no compression
return new RawDecoder();
case 5: // LZW
return new LZWDecoder();
case 6: // JPEG
throw new Error('old style JPEG compression is not supported.');
case 7: // JPEG
return new JpegDecoder(fileDirectory);
case 8: // Deflate as recognized by Adobe
case 32946: // Deflate GDAL default
return new DeflateDecoder();
case 32773: // packbits
return new PackbitsDecoder();
case 34887: // LERC
return new LercDecoder(fileDirectory);
default:
throw new Error(`Unknown compression method identifier: ${fileDirectory.Compression}`);
}
}
| constantinius/geotiff.js | src/compression/index.js | JavaScript | mit | 952 |
var keylime = require('./');
var _ = require('lodash');
var KeylimePost = keylime('KeylimePost')
.attr('draft', true)
.attr('title', '')
.attr('tags', [])
.attr('date', function createDate() {
return Date.now();
});
var HybridPost = keylime(function HybridPost(title, options) {
this.keylime.init(this, options);
this.title = title;
})
.attr('title', '')
.attr('draft', true)
.attr('tags', [])
.attr('date', function() {
return Date.now();
});
var plainAttrs = {
title: '',
tags: [],
draft: true,
date: function createDate() {
return Date.now();
}
};
function BarePost(params) {
this.title = params.title || '';
this.tags = params.tags || [];
this.draft = params.draft || true;
this.date = params.date || Date.now();
}
function PlainPost(params) {
var value;
for (var attrName in plainAttrs) {
if (plainAttrs.hasOwnProperty(attrName)) {
if (params && params[attrName] !== undefined) {
value = params[attrName];
} else {
value = plainAttrs[attrName];
}
if (typeof value === 'function') {
this[attrName] = value();
} else {
this[attrName] = value;
}
}
}
}
suite('creating instances with \'new\'', function() {
bench('bare post', function() {
new BarePost({title: 'New Post'});
});
bench('plain constructor', function() {
new PlainPost({title: 'New Post'});
});
bench('keylime', function() {
new KeylimePost({title: 'New Post'});
});
bench('hybrid', function() {
new HybridPost('New Post');
});
});
suite('init handlers', function() {
var Post1 = keylime('Post').attr('attr1', 'value1').on('init', function() {});
var Post3 = keylime('Post').attr('attr1', 'value1').on('init', function() {}).on('init', function() {}).on('init', function() {});
var Post5 = keylime('Post').attr('attr1', 'value1').on('init', function() {}).on('init', function() {}).on('init', function() {}).on('init', function() {}).on('init', function() {});
bench('1 handlers', function() {
new Post1();
});
bench('3 handlers', function() {
new Post3();
});
bench('5 handlers', function() {
new Post5();
});
});
suite('attribute handlers', function() {
var Post1 = keylime('Post').attr('attr1', 'value1', {handlers: function() { return 1;} });
var Post3 = keylime('Post').attr('attr1', 'value1', {handlers: [function() { return 1;}, function(value) { return ++value; }, function(value) { return ++value; }]});
var Post5 = keylime('Post').attr('attr1', 'value1', {handlers: [function() { return 1;}, function(value) { return ++value; }, function(value) { return ++value; }, function(value) { return ++value; }, function(value) { return ++value; }]});
bench('1 handlers', function() {
new Post1();
});
bench('3 handlers', function() {
new Post3();
});
bench('5 handlers', function() {
new Post5();
});
});
suite('using \'new\' vs .create()', function() {
var Post = keylime('Post').attr('title').attr('date', Date.now).attr('comments', []);
bench('new', function() {
new Post({title: 'hello world'});
});
bench('.create()', function() {
Post.create({title: 'hello world'});
});
});
suite('attribute counts', function() {
var Jedi0 = keylime('Jedi');
var Jedi3 = keylime('Jedi').attr('one', 1).attr('two', 2).attr('three', 3);
var Jedi5 = keylime('Jedi').attr('one', 1).attr('two', 2).attr('three', 3).attr('four', 4).attr('five', 5);
bench('0 attributes', function() {
new Jedi0();
});
bench('3 attributes', function() {
new Jedi3();
});
bench('5 attributes', function() {
new Jedi5();
});
});
| stevenschobert/keylime | benchmarks.js | JavaScript | mit | 3,697 |
var Application = Application || {};
Application.Controllers
.controller("SignInCtrl",
function ($scope) {
"use strict";
$scope.pageTitle = "Sign-in to Project Seed Project";
});
| ernestlombardi/venti | components/sign-in/sign-in-controller.js | JavaScript | mit | 208 |
/*!
* ExpressionEngine - by EllisLab
*
* @package ExpressionEngine
* @author EllisLab Dev Team
* @copyright Copyright (c) 2003 - 2012, EllisLab, Inc.
* @license http://ellislab.com/expressionengine/user-guide/license.html
* @link http://ellislab.com
* @since Version 2.0
* @filesource
*/
$(document).ready(function(){$.ee_watermark()});$.ee_watermark=function(){"text"==$('input[name="wm_type"]:checked').val()?$(".image_type").hide():$(".text_type").hide();$.ee_watermark.type_toggle()};$.ee_watermark.type_toggle=function(){$("input[name=wm_type]").change(function(){$(".text_type").toggle();$(".image_type").toggle()})};
$.ee_watermark.watermark_test=function(){var a=document.forms[0],b="",d=a.gallery_wm_use_font[0].checked?"y":"n",e=a.gallery_wm_use_drop_shadow[0].checked?"y":"n",f=a.gallery_wm_font_color.value,g=a.gallery_wm_shadow_color.value;a.gallery_wm_type[1].checked?b="t":a.gallery_wm_type[2].checked&&(b="g");var c=a.gallery_wm_text.value,c=c.replace("/;/g","").replace("?",""),a="<?php echo $basepath; ?>&P=wm_tester&gallery_wm_type="+b+"&gallery_wm_text="+c+"&gallery_wm_image_path="+a.gallery_wm_image_path.value+
"&gallery_wm_use_font="+d+"&gallery_wm_font="+a.gallery_wm_font.value+"&gallery_wm_font_size="+a.gallery_wm_font_size.value+"&gallery_wm_vrt_alignment="+a.gallery_wm_vrt_alignment.value+"&gallery_wm_hor_alignment="+a.gallery_wm_hor_alignment.value+"&gallery_wm_padding="+a.gallery_wm_padding.value+"&gallery_wm_hor_offset="+a.gallery_wm_hor_offset.value+"&gallery_wm_vrt_offset="+a.gallery_wm_vrt_offset.value+"&gallery_wm_x_transp="+a.gallery_wm_x_transp.value+"&gallery_wm_y_transp="+a.gallery_wm_y_transp.value+
"&gallery_wm_font_color="+f.substring(1)+"&gallery_wm_use_drop_shadow="+e+"&gallery_wm_shadow_color="+g.substring(1)+"&gallery_wm_shadow_distance="+a.gallery_wm_shadow_distance.value+"&gallery_wm_opacity="+a.gallery_wm_opacity.value+"&gallery_wm_test_image_path="+a.gallery_wm_test_image_path.value;window.open(a,"wm_tester","width=<?php echo $testwidth; ?>,height=<?php echo $testheight; ?>,screenX=0,screenY=0,top=0,left=0,toolbar=0,status=0,scrollbars=0,location=0,menubar=1,resizable=1");return!1};
| ProJobless/nyus | themes/javascript/compressed/cp/files/watermark_settings.js | JavaScript | mit | 2,184 |
'use strict';
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
var init = require("Espresso/oop").init;
var trim = require("Espresso/trim").trim;
var isA = require("Espresso/oop").isA;
var oop = require("Espresso/oop").oop;
function PostStartEvent( component ){
if(!isA(component,"Espresso/Component/ComponentInterface"))
throw new TypeException('component has to be of type "Espresso/Component/ComponentInterface"');
oop(this,"Espresso/Component/Event/PostStartEvent");
this.__.component = component;
}
function getComponent(){
return this.__.component;
}
PostStartEvent.prototype.getComponent = getComponent;
module.exports = PostStartEvent; | quimsy/espresso | Component/Event/PostStartEvent.js | JavaScript | mit | 686 |
import React, { Component, PropTypes } from 'react'
import cx from 'classnames'
import { Input } from '../input'
import { FieldLabel } from '../field-label'
import './field-text.view.styl'
export class FieldText extends Component {
static propTypes = {
className: PropTypes.string,
label: PropTypes.string,
name: PropTypes.string,
defaultValue: PropTypes.string,
placeholder: PropTypes.string,
autosize: PropTypes.object,
autoFocus: PropTypes.bool,
prefix: PropTypes.element,
type: PropTypes.string,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
onChange: PropTypes.func,
// Redux from
input: PropTypes.object,
meta: PropTypes.object
}
getRootClassNames () {
const {
className,
meta
} = this.props
return cx(
'fieldText',
meta.touched && meta.error ? 'isError' : null,
className
)
}
saveInputRef = (ref) => {
this.inputRef = ref
}
focus () {
window.setTimeout(() =>
this.inputRef.focus()
, 10)
}
renderLabel () {
const {
label,
name
} = this.props
if (!label) {
return null
}
return (
<FieldLabel
htmlFor={name}
text={label}
/>
)
}
handleFocus = (e) => {
if (this.props.onFocus) {
this.props.onFocus(e)
}
this.props.input.onFocus(e)
}
handleBlur = (e) => {
if (this.props.onBlur) {
this.props.onBlur(e)
}
this.props.input.onBlur(e)
}
handleChange = (e) => {
if (this.props.onChange) {
this.props.onChange(e)
}
this.props.input.onChange(e)
}
renderInput () {
const {
input,
name,
placeholder,
defaultValue,
autosize,
autoFocus,
prefix,
type
} = this.props
if (!input.value) {
input.value = defaultValue
}
const specialOptions = {}
if (prefix) {
specialOptions.prefix = prefix
}
return (
<div className='inputWrap'>
<Input
ref={this.saveInputRef}
defaultValue={input.value}
name={name}
placeholder={placeholder}
autosize={autosize}
autoFocus={autoFocus}
type={type}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onChange={this.handleChange}
{...specialOptions}
/>
</div>
)
}
render () {
return (
<div className={this.getRootClassNames()}>
{this.renderLabel()}
{this.renderInput()}
</div>
)
}
}
| seccom/kpass | web/src/uis/data-entries/field-text/field-text.view.js | JavaScript | mit | 2,580 |
const canvas = document.getElementById('playground')
const context = canvas.getContext('2d')
class Ball {
constructor(radius, color) {
this.x = 0
this.y = 0
this.vx = 0
this.vy = 0
this.radius = radius || 40
this.rotation = 0
this.scaleX = 1
this.scaleY = 1
this.color = color || '#FF0000'
this.lineWidth = 1
}
draw(context) {
context.save()
context.translate(this.x, this.y)
context.rotate(this.rotation)
context.scale(this.scaleX, this.scaleY)
context.lineWidth = this.lineWidth
context.fillStyle = this.color
context.beginPath()
// 画圆弧
context.arc(0, 0, this.radius, 0, (Math.PI * 2), true)
context.closePath()
context.fill()
if (this.lineWidth > 0) {
context.stroke()
}
context.restore()
}
}
const captureMouse = function(canvas) {
let x = 0, y = 0
const handler = e => {
x = e.offsetX
y = e.offsetY
}
const obj = {
dispose() {
canvas.removeEventListener('mousemove', handler)
},
get x() { return x },
get y() { return y }
}
canvas.addEventListener('mousemove', handler)
return obj
}
const ball = new Ball()
const ball1 = new Ball()
const ball2 = new Ball()
const spring = 0.1
const targetX = canvas.width / 2
const targetY = canvas.height / 2
let vx = 0, vy = 0
const friction = 0.95
const gravity = 2
const mouse = captureMouse(canvas)
function move(ball, targetX, targetY) {
ball.vx += (targetX - ball.x) * spring
ball.vy += (targetY - ball.y) * spring
ball.vy += gravity
ball.vx *= friction
ball.vy *= friction
ball.x += ball.vx
ball.y += ball.vy
}
;(function drawFrame() {
requestAnimationFrame(drawFrame, canvas)
context.clearRect(0, 0, canvas.width, canvas.height)
move(ball, mouse.x, mouse.y)
move(ball1, ball.x, ball.y)
move(ball2, ball1.x, ball1.y)
context.beginPath()
context.moveTo(ball.x, ball.y)
context.lineTo(mouse.x, mouse.y)
context.stroke()
ball.draw(context)
ball1.draw(context)
ball2.draw(context)
})()
| leozdgao/animation-basic-learning | public/spring.js | JavaScript | mit | 2,048 |
/**
* Tests Two.js WebGl Rendering Functionality:
*/
(function() {
QUnit.module('WebGLRenderer');
var getRatio = function(v) { return Math.round(window.devicePixelRatio); };
var deviceRatio = getRatio(document.createElement('canvas').getContext('2d'));
var suffix = '@' + deviceRatio + 'x.png';
QUnit.test('Two.makeLine', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
}).appendTo(document.body);
two.makeLine(0, 0, two.width, two.height);
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/line' + suffix, two.renderer, 'Two.makeLine renders properly.');
});
QUnit.test('Two.makeRectangle', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
two.makeRectangle(two.width / 2, two.height / 2, 100, 100);
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/rectangle' + suffix, two.renderer, 'Two.makeRectangle renders properly.');
});
QUnit.test('Two.makeEllipse', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
two.makeEllipse(two.width / 2, two.height / 2, 100, 100);
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/ellipse' + suffix, two.renderer, 'Two.makeEllipse renders properly.');
});
QUnit.test('Two.makeCircle', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
two.makeCircle(two.width / 2, two.height / 2, 50);
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/circle' + suffix, two.renderer, 'Two.makeCircle renders properly.');
});
QUnit.test('Two.makePoints', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: 1
});
var points = two.makePoints(200, 200, 220, 200, 180, 200);
points.size = 10;
points.noStroke();
points.fill = '#00AEFF';
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/points' + suffix, two.renderer, 'Two.makePoints renders properly.');
});
QUnit.test('Two.makePath', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
var amount = 20;
var points = [];
for (var i = 0; i < amount; i++) {
var pct = i / amount;
var x = pct * 300 + 50;
var y = i % 2 ? 25 : 75;
points.push(new Two.Anchor(x, y));
}
two.makePath(points, true);
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/polygon' + suffix, two.renderer, 'Two.makePath renders properly.');
});
QUnit.test('Two.makeCurve', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
var amount = 20;
var points = [];
for (var i = 0; i < amount; i++) {
var pct = i / amount;
var x = pct * 300 + 50;
var y = i % 2 ? 25 : 75;
points.push(new Two.Anchor(x, y));
}
two.makeCurve(points, true);
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/curve' + suffix, two.renderer, 'Two.makeCurve renders properly.');
});
QUnit.test('Two.makeLinearGradient', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
var gradient = two.makeLinearGradient(0, - two.height / 2, 0, two.height / 2,
new Two.Gradient.Stop(0, 'rgb(255, 100, 100)'), new Two.Gradient.Stop(1, 'rgb(100, 100, 255)'));
var rect = two.makeRectangle(two.width / 2, two.height / 2, two.width / 4, two.height / 4);
rect.fill = gradient;
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/linear-gradient' + suffix, two.renderer, 'Two.makeLinearGradient renders properly.');
});
QUnit.test('Two.makeRadialGradient', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
var gradient = two.makeRadialGradient(0, 0, 4,
new Two.Gradient.Stop(0, 'rgb(255, 100, 100)'), new Two.Gradient.Stop(1, 'rgb(100, 100, 255)'));
var rect = two.makeRectangle(two.width / 2, two.height / 2, two.width / 4, two.height / 4);
rect.fill = gradient;
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/radial-gradient' + suffix, two.renderer, 'Two.makeLinearGradient renders properly.');
});
QUnit.test('two.makeSprite (Simple)', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
var path = '/tests/images/sequence/00000.png';
var sprite = two.makeSprite(path, two.width / 2, two.height / 2);
var texture = sprite.texture;
var loaded = function() {
texture.unbind(Two.Events.Types.load, loaded);
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/sprite-simple' + suffix, two.renderer, 'Two.makeSprite renders properly.');
};
texture.bind(Two.Events.Types.load, loaded);
texture._update();
});
QUnit.test('two.makeImageSequence', function(assert) {
assert.expect(2);
assert.done = assert.async(2);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
var paths = [];
for (var i = 0; i < 30; i++) {
paths.push('/tests/images/sequence/' + QUnit.Utils.digits(i, 5) + '.png');
}
var sequence = two.makeImageSequence(paths, two.width / 2, two.height / 2, 2);
sequence.index = 3;
var texture = sequence.textures[sequence.index];
var loaded = function() {
texture.unbind(Two.Events.Types.load, loaded);
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/image-sequence-1' + suffix, two.renderer, 'Two.ImageSequence applied the correct texture properly.', function() {
sequence.index = 7;
texture = sequence.textures[sequence.index];
texture._flagImage = true;
texture.bind(Two.Events.Types.load, function() {
texture.unbind(Two.Events.Types.load);
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/image-sequence-2' + suffix, two.renderer, 'Two.ImageSequence can change index properly.');
});
texture._update();
});
};
texture.bind(Two.Events.Types.load, loaded);
texture._update();
two.renderer.domElement.style.cursor = 'pointer';
two.renderer.domElement.addEventListener('click', function() {
if (two.playing) {
two.pause();
} else {
sequence.loop = true;
sequence.play();
two.play();
}
}, false);
});
QUnit.test('two.makeSprite', function(assert) {
assert.expect(2);
assert.done = assert.async(2);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
var path = '/tests/images/spritesheet.jpg';
var sprite = two.makeSprite(path, two.width / 2, two.height / 2, 4, 4, 2, false);
var texture = sprite.texture;
sprite.index = 3;
var loaded = function() {
texture.unbind(Two.Events.Types.load, loaded);
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/image-sequence-1' + suffix, two.renderer, 'Two.makeSprite renders properly.', function() {
sprite.index = 7;
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/image-sequence-2' + suffix, two.renderer, 'Two.Sprite changed index properly.');
});
};
texture.bind(Two.Events.Types.load, loaded);
texture._update();
two.renderer.domElement.style.cursor = 'pointer';
two.renderer.domElement.addEventListener('click', function() {
if (two.playing) {
two.pause();
} else {
sprite.loop = true;
sprite.play();
two.play();
}
}, false);
});
QUnit.test('Two.makeText', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
var text = two.makeText('Hello World', two.width / 2, two.height / 2);
text.fill = '#00aeff';
text.noStroke();
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/text' + suffix, two.renderer, 'Two.makeText renders properly.');
});
QUnit.test('Styles', function(assert) {
assert.expect(1);
assert.done = assert.async(1);
var two = new Two({
type: Two.Types.webgl,
width: 400,
height: 400,
ratio: deviceRatio
});
var shape = two.makeRectangle(two.width / 2, two.height / 2, 50, 50);
shape.rotation = Math.PI / 2;
shape.scale = 0.5;
shape.fill = 'lightcoral';
shape.stroke = '#333';
shape.linewidth = 10;
shape.opacity = 0.5;
shape.join = 'miter';
shape.cap = 'butt';
shape.miter = 10;
shape.closed = false;
shape.curved = true;
shape.visible = false;
shape.visible = true;
two.update();
QUnit.Utils.compare.call(assert, './images/canvas/styles' + suffix, two.renderer, 'Styles render properly.');
});
})();
| jonobr1/two.js | tests/suite/webgl.js | JavaScript | mit | 10,182 |
angular.module('pret.services', [])
/**
* A simple example service that returns some data.
*/
.factory('Footprints', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var footprints = [
{ id: 0, name: 'Puffy' },
{ id: 1, name: 'Dogo' },
{ id: 2, name: 'Miss Frizzle' },
{ id: 3, name: 'Ashy' }
];
return {
all: function() {
return footprints;
},
get: function(footprintId) {
// Simple index lookup
return footprints[footprintId];
}
}
});
| hrsalazar/pret | www/js/services.js | JavaScript | mit | 549 |
/* global AutoForm:true */
/* global formPreserve */
/* global Utility */
/* global Hooks */
/* global templatesById */
/* global deps */
/* global globalDefaultTemplate:true */
/* global defaultTypeTemplates:true */
/* global SimpleSchema */
/* global getFormValues */
/* global formValues */
/* global formData */
/* global inputTypeDefinitions */
/* global _validateField */
/* global _validateForm */
/* global arrayTracker */
/* global getInputType */
/* global formDeps */
// This file defines the public, exported API
AutoForm = AutoForm || {}; //exported
AutoForm.formPreserve = formPreserve;
AutoForm.Utility = Utility;
/**
* @method AutoForm.addHooks
* @public
* @param {String[]|String|null} formIds Form `id` or array of form IDs to which these hooks apply. Specify `null` to add hooks that will run for every form.
* @param {Object} hooks Hooks to add, where supported names are "before", "after", "formToDoc", "docToForm", "onSubmit", "onSuccess", and "onError".
* @returns {undefined}
*
* Defines hooks to be used by one or more forms. Extends hooks lists if called multiple times for the same
* form.
*/
AutoForm.addHooks = function autoFormAddHooks(formIds, hooks, replace) {
if (typeof formIds === "string") {
formIds = [formIds];
}
// If formIds is null, add global hooks
if (!formIds) {
Hooks.addHooksToList(Hooks.global, hooks, replace);
} else {
_.each(formIds, function (formId) {
// Init the hooks object if not done yet
Hooks.form[formId] = Hooks.form[formId] || {
before: {},
after: {},
formToDoc: [],
docToForm: [],
onSubmit: [],
onSuccess: [],
onError: [],
beginSubmit: [],
endSubmit: []
};
Hooks.addHooksToList(Hooks.form[formId], hooks, replace);
});
}
};
/**
* @method AutoForm.hooks
* @public
* @param {Object} hooks
* @returns {undefined}
*
* Defines hooks by form id. Extends hooks lists if called multiple times for the same
* form.
*/
AutoForm.hooks = function autoFormHooks(hooks, replace) {
_.each(hooks, function(hooksObj, formId) {
AutoForm.addHooks(formId, hooksObj, replace);
});
};
/**
* @method AutoForm.resetForm
* @public
* @param {String} formId
* @param {TemplateInstance} [template] Looked up if not provided. Pass in for efficiency.
* @returns {undefined}
*
* Resets an autoform, including resetting validation errors. The same as clicking the reset button for an autoform.
*/
AutoForm.resetForm = function autoFormResetForm(formId, template) {
template = template || templatesById[formId];
if (template && template.view._domrange) {
template.$("form")[0].reset();
}
};
/**
* @method AutoForm.setDefaultTemplate
* @public
* @param {String} template
*/
AutoForm.setDefaultTemplate = function autoFormSetDefaultTemplate(template) {
globalDefaultTemplate = template;
deps.defaultTemplate.changed();
};
/**
* @method AutoForm.getDefaultTemplate
* @public
*
* Reactive.
*/
AutoForm.getDefaultTemplate = function autoFormGetDefaultTemplate() {
deps.defaultTemplate.depend();
return globalDefaultTemplate;
};
/**
* @method AutoForm.setDefaultTemplateForType
* @public
* @param {String} type
* @param {String} template
*/
AutoForm.setDefaultTemplateForType = function autoFormSetDefaultTemplateForType(type, template) {
if (!deps.defaultTypeTemplates[type]) {
deps.defaultTypeTemplates[type] = new Tracker.Dependency();
}
if (template !== null && !Template[type + "_" + template]) {
throw new Error("setDefaultTemplateForType can't set default template to \"" + template + "\" for type \"" + type + "\" because there is no defined template with the name \"" + type + "_" + template + "\"");
}
defaultTypeTemplates[type] = template;
deps.defaultTypeTemplates[type].changed();
};
/**
* @method AutoForm.getDefaultTemplateForType
* @public
* @param {String} type
* @return {String} Template name
*
* Reactive.
*/
AutoForm.getDefaultTemplateForType = function autoFormGetDefaultTemplateForType(type) {
if (!deps.defaultTypeTemplates[type]) {
deps.defaultTypeTemplates[type] = new Tracker.Dependency();
}
deps.defaultTypeTemplates[type].depend();
return defaultTypeTemplates[type];
};
/**
* @method AutoForm.getFormValues
* @public
* @param {String} formId The `id` attribute of the `autoForm` you want current values for.
* @return {Object}
*
* Returns an object representing the current values of all schema-based fields in the form.
* The returned object contains two properties, "insertDoc" and "updateDoc", which represent
* the field values as a normal object and as a MongoDB modifier, respectively.
*/
AutoForm.getFormValues = function autoFormGetFormValues(formId) {
var template = templatesById[formId];
if (!template || !template.view._domrange) {
throw new Error("getFormValues: There is currently no autoForm template rendered for the form with id " + formId);
}
// Get a reference to the SimpleSchema instance that should be used for
// determining what types we want back for each field.
var context = template.data;
var ss = AutoForm.Utility.getSimpleSchemaFromContext(context, formId);
return getFormValues(template, formId, ss);
};
/**
* @method AutoForm.getFieldValue
* @public
* @param {String} formId The `id` attribute of the `autoForm` you want current values for.
* @param {String} fieldName The name of the field for which you want the current value.
* @return {Any}
*
* Returns the value of the field (the value that would be used if the form were submitted right now).
* This is a reactive method that will rerun whenever the current value of the requested field changes.
*/
AutoForm.getFieldValue = function autoFormGetFieldValue(formId, fieldName) {
// reactive dependency
formValues[formId] = formValues[formId] || {};
formValues[formId][fieldName] = formValues[formId][fieldName] || new Tracker.Dependency();
formValues[formId][fieldName].depend();
// find AutoForm template
var template = templatesById[formId];
if (!template || !template.view._domrange) {
return;
}
// find AutoForm schema
var data = formData[formId];
// ss will be the schema for the `schema` attribute if present,
// else the schema for the collection
var ss = data.ss;
// get element reference
var element = template.$('[data-schema-key="' + fieldName + '"]')[0];
return AutoForm.getInputValue(element, ss);
};
/**
* @method AutoForm.getInputTypeTemplateNameForElement
* @public
* @param {DOMElement} element The input DOM element, generated by an autoform input control
* @return {String}
*
* Returns the name of the template used to render the element.
*/
AutoForm.getInputTypeTemplateNameForElement = function autoFormGetInputTypeTemplateNameForElement(element) {
// get the enclosing view
var view = Blaze.getView(element);
// if the enclosing view is not a template, perhaps because
// the template contains a block helper like if, with, each,
// then look up the view chain until we arrive at a template
while (view && view.name.slice(0, 9) !== "Template.") {
view = view.parentView;
}
if (!view) {
throw new Error("The element does not appear to be in a template view");
}
// View names have "Template." at the beginning so we slice that off.
return view.name.slice(9);
};
/**
* @method AutoForm.getInputValue
* @public
* @param {DOMElement} element The input DOM element, generated by an autoform input control, which must have a `data-schema-key` attribute set to the correct schema key name.
* @param {SimpleSchema} [ss] Provide the SimpleSchema instance if you already have it.
* @return {Any}
*
* Returns the value of the field (the value that would be used if the form were submitted right now).
* Unlike `AutoForm.getFieldValue`, this function is not reactive.
*/
AutoForm.getInputValue = function autoFormGetInputValue(element, ss) {
var field, fieldName, fieldType, arrayItemFieldType, val, typeDef, inputTypeTemplate, dataContext, autoConvert;
dataContext = Blaze.getData(element);
if (dataContext && dataContext.atts) {
autoConvert = dataContext.atts.autoConvert;
}
// Get jQuery field reference
field = $(element);
// Get the field/schema key name
fieldName = field.attr("data-schema-key");
// If we have a schema, we can autoconvert to the correct data type
if (ss) {
fieldType = ss.schema(fieldName).type;
}
// Get the name of the input type template used to render the input element
inputTypeTemplate = AutoForm.getInputTypeTemplateNameForElement(element);
// Slice off the potential theme template, after the underscore.
inputTypeTemplate = inputTypeTemplate.split("_")[0];
// Figure out what registered input type was used to render this element
typeDef = _.where(inputTypeDefinitions, {template: inputTypeTemplate})[0];
// If field has a "data-null-value" attribute, value should always be null
if (field.attr("data-null-value") !== void 0) {
val = null;
}
// Otherwise get the field's value using the input type's `valueOut` function if provided
else if (typeDef && typeDef.valueOut) {
val = typeDef.valueOut.call(field);
}
// Otherwise get the field's value in a default way
else {
val = field.val();
}
// run through input's type converter if provided
if (val !== void 0 && autoConvert !== false && typeDef && typeDef.valueConverters && fieldType) {
var converterFunc;
if (fieldType === String) {
converterFunc = typeDef.valueConverters.string;
} else if (fieldType === Number) {
converterFunc = typeDef.valueConverters.number;
} else if (fieldType === Boolean) {
converterFunc = typeDef.valueConverters.boolean;
} else if (fieldType === Date) {
converterFunc = typeDef.valueConverters.date;
} else if (fieldType === Array) {
arrayItemFieldType = ss.schema(fieldName + ".$").type;
if (arrayItemFieldType === String) {
converterFunc = typeDef.valueConverters.stringArray;
} else if (arrayItemFieldType === Number) {
converterFunc = typeDef.valueConverters.numberArray;
} else if (arrayItemFieldType === Boolean) {
converterFunc = typeDef.valueConverters.booleanArray;
} else if (arrayItemFieldType === Date) {
converterFunc = typeDef.valueConverters.dateArray;
}
}
if (typeof converterFunc === "function") {
val = converterFunc.call(field, val);
}
}
return val;
};
/**
* @method AutoForm.addInputType
* @public
* @param {String} name The type string that this definition is for.
* @param {Object} definition Defines how the input type should be rendered.
* @param {String} definition.componentName The component name. A template with the name <componentName>_bootstrap3, and potentially others, must be defined.
* @return {undefined}
*
* Use this method to add custom input components.
*/
AutoForm.addInputType = function afAddInputType(name, definition) {
var obj = {};
obj[name] = definition;
_.extend(inputTypeDefinitions, obj);
};
/**
* @method AutoForm.validateField
* @public
* @param {String} formId The `id` attribute of the `autoForm` you want to validate.
* @param {String} fieldName The name of the field within the `autoForm` you want to validate.
* @param {Boolean} [skipEmpty=false] Set to `true` to skip validation if the field has no value. Useful for preventing `required` errors in form fields that the user has not yet filled out.
* @return {Boolean} Is it valid?
*
* In addition to returning a boolean that indicates whether the field is currently valid,
* this method causes the reactive validation messages to appear.
*/
AutoForm.validateField = function autoFormValidateField(formId, fieldName, skipEmpty) {
var template = templatesById[formId];
if (!template || !template.view._domrange) {
throw new Error("validateField: There is currently no autoForm template rendered for the form with id " + formId);
}
return _validateField(fieldName, template, skipEmpty, false);
};
/**
* @method AutoForm.validateForm
* @public
* @param {String} formId The `id` attribute of the `autoForm` you want to validate.
* @return {Boolean} Is it valid?
*
* In addition to returning a boolean that indicates whether the form is currently valid,
* this method causes the reactive validation messages to appear.
*/
AutoForm.validateForm = function autoFormValidateForm(formId) {
// Gather all form values
var formDocs = AutoForm.getFormValues(formId);
return _validateForm(formId, formData[formId], formDocs);
};
/**
* @method AutoForm.getValidationContext
* @public
* @param {String} formId The `id` attribute of the `autoForm` for which you want the validation context
* @return {SimpleSchemaValidationContext} The SimpleSchema validation context object.
*
* Use this method to get the validation context, which can be used to check
* the current invalid fields, manually invalidate fields, etc.
*/
AutoForm.getValidationContext = function autoFormGetValidationContext(formId) {
var data = formData[formId];
// ss will be the schema for the `schema` attribute if present,
// else the schema for the collection
var ss = data.ss;
return ss.namedContext(formId);
};
/**
* @method AutoForm.find
* @public
* @return {Object} The data context for the closest autoform.
*
* Call this method from a UI helper to get the data context for the closest autoform. Always returns the context or throws an error.
*/
AutoForm.find = function autoFormFind(type) {
var n = 0, af;
do {
af = Template.parentData(n++);
} while (af && !af._af);
if (!af || !af._af) {
throw new Error((type || "AutoForm.find") + " must be used within an autoForm block");
}
return af._af;
};
/**
* @method AutoForm.findAttribute
* @param {String} attrName Attribute name
* @public
* @return {Any|undefined} Searches for the given attribute, looking up the parent context tree until the closest autoform is reached.
*
* Call this method from a UI helper. Might return undefined.
*/
AutoForm.findAttribute = function autoFormFindAttribute(attrName) {
var n = 0, af, val, stopAt = -1;
// we go one level past _af so that we get the original autoForm or quickForm attributes, too
do {
af = Template.parentData(n++);
if (af && af.atts && af.atts[attrName] !== void 0) {
val = af.atts[attrName];
} else if (af && af[attrName] !== void 0) {
val = af[attrName];
}
if (af && af._af) {
stopAt = n + 1;
}
} while (af && stopAt < n && val === void 0);
return val;
};
/**
* @method AutoForm.findAttributesWithPrefix
* @param {String} prefix Attribute prefix
* @public
* @return {Object} An object containing all of the found attributes and their values, with the prefix removed from the keys.
*
* Call this method from a UI helper. Searches for attributes that start with the given prefix, looking up the parent context tree until the closest autoform is reached.
*/
AutoForm.findAttributesWithPrefix = function autoFormFindAttributesWithPrefix(prefix) {
var n = 0, af, searchObj, stopAt = -1, obj = {};
// we go one level past _af so that we get the original autoForm or quickForm attributes, too
do {
af = Template.parentData(n++);
if (af) {
if (af.atts) {
searchObj = af.atts;
} else {
searchObj = af;
}
if (_.isObject(searchObj)) {
_.each(searchObj, function (v, k) {
if (k.indexOf(prefix) === 0) {
obj[k.slice(prefix.length)] = v;
}
});
}
if (af._af) {
stopAt = n + 1;
}
}
} while (af && stopAt < n);
return obj;
};
/**
* @method AutoForm.debug
* @public
*
* Call this method in client code while developing to turn on extra logging.
*/
AutoForm.debug = function autoFormDebug() {
SimpleSchema.debug = true;
AutoForm._debug = true;
AutoForm.addHooks(null, {
onError: function (operation, error) {
console.log("Error in " + this.formId, operation, error);
}
});
};
/**
* @property AutoForm.arrayTracker
* @public
*/
AutoForm.arrayTracker = arrayTracker;
/**
* @method AutoForm.getInputType
* @param {Object} atts The attributes provided to afFieldInput.
* @public
* @return {String} The input type. Most are the same as the `type` attributes for HTML input elements, but some are special strings that autoform interprets.
*
* Call this method from a UI helper to get the type string for the input control.
*/
AutoForm.getInputType = getInputType;
/**
* @method AutoForm.getSchemaForField
* @public
* @param {String} name The field name attribute / schema key.
* @param {Object} [autoform] The autoform context. Optionally pass this if you've already retrieved it using AutoForm.find as a performance enhancement.
* @return {Object}
*
* Call this method from a UI helper to get the field definitions based on the schema used by the closest containing autoForm.
* Always throws an error or returns the schema object.
*/
AutoForm.getSchemaForField = function autoFormGetSchemaForField(name, autoform) {
var ss;
if (autoform) {
ss = autoform.ss;
}
if (!ss) {
ss = AutoForm.find().ss;
}
return AutoForm.Utility.getDefs(ss, name);
};
/**
* @method AutoForm.invalidateFormContext
* @public
* @param {String} formId The form ID.
* @return {undefined}
*
* Call this to force invalidate the form context, such as when you're changing the `doc`
* and it does not react by itself.
*/
AutoForm.invalidateFormContext = function autoFormInvalidateFormContext(formId) {
formDeps[formId] = formDeps[formId] || new Tracker.Dependency();
formDeps[formId].changed();
};
| mxab/meteor-autoform | autoform-api.js | JavaScript | mit | 17,760 |
module.exports = function(config) {
config.set({
autoWatch: false,
basePath: '..',
frameworks: ['mocha', 'chai', 'sinon'],
browsers: ['PhantomJS'],
singleRun: true,
files: [
'components/lodash/dist/lodash.js',
'components/angular/angular.js',
'components/angular-mocks/angular-mocks.js',
'tests/libraries/mocker.js',
'module.js',
'beat-factory.js',
'tests/*.js'
]
});
};
| nucleus-angular/beat | karma/unit-tests.phantom.js | JavaScript | mit | 445 |
export const userType = {
NEW_INSTANCE: Symbol("user/newInstance")
};
| oneut/async-react-router | examples/flux-utils/src/actionTypes/UserType.js | JavaScript | mit | 72 |
import React from 'react'
import { compose } from 'redux'
import { connect } from 'react-redux'
import reduxForm from 'redux-form/es/reduxForm'
import { bindRoutineCreators } from 'actions'
import { updateProfile } from 'security/actions'
import { DangerAlert } from 'components/Alert'
import { EmailField, TextField } from 'components/Form'
import { injectSagas } from 'utils/async'
const FORM_NAME = 'updateProfile'
const UpdateProfile = (props) => {
const { error, handleSubmit, pristine, submitting } = props
return (
<div>
<h2>Update Profile!</h2>
{error && <DangerAlert>{error}</DangerAlert>}
<form onSubmit={handleSubmit(updateProfile)}>
<TextField name="firstName"
autoFocus
/>
<TextField name="lastName" />
<TextField name="username" />
<EmailField name="email" />
<div className="row">
<button type="submit"
className="btn btn-primary"
disabled={pristine || submitting}
>
{submitting ? 'Saving...' : 'Save'}
</button>
</div>
</form>
</div>
)
}
const withForm = reduxForm({ form: FORM_NAME })
const withConnect = connect(
(state) => ({ initialValues: state.security.user }),
)
const withSagas = injectSagas(require('security/sagas/updateProfile'))
export default compose(
withConnect,
withForm,
withSagas,
)(UpdateProfile)
| briancappello/flask-react-spa | frontend/app/security/pages/Profile/UpdateProfile.js | JavaScript | mit | 1,439 |
define([
'esri/units',
'esri/geometry/Extent',
'esri/config',
'esri/tasks/GeometryService',
'esri/layers/ImageParameters'
], function (units, Extent, esriConfig, GeometryService, ImageParameters) {
// url to your proxy page, must be on same machine hosting you app. See proxy folder for readme.
esriConfig.defaults.io.proxyUrl = 'proxy/proxy.ashx';
esriConfig.defaults.io.alwaysUseProxy = false;
// url to your geometry server.
esriConfig.defaults.geometryService = new GeometryService('http://geodata.npolar.no/arcgis/rest/services/Utilities/Geometry/GeometryServer');
//image parameters for dynamic services, set to png32 for higher quality exports.
var imageParameters = new ImageParameters();
imageParameters.format = 'png32';
return {
// used for debugging your app
isDebug: false,
//default mapClick mode, mapClickMode lets widgets know what mode the map is in to avoid multipult map click actions from taking place (ie identify while drawing).
defaultMapClickMode: 'identify',
// map options, passed to map constructor. see: https://developers.arcgis.com/javascript/jsapi/map-amd.html#map1
/*mapOptions: {
basemap: 'streets',
center: [15.59179687497497, 78.09596293629694],
zoom: 5,
sliderStyle: 'small'
},*/
mapOptions: {
//basemap: 'topography',
logo: false,
extent: new Extent({
xmin:-173159.3372224797,
ymin:7864422.526051709,
xmax:1434826.4745111547,
ymax:8896196.684665617,
spatialReference:{wkid:32637}})
},
initialExtent: {
xmin:-173159.3372224797,
ymin:7864422.526051709,
xmax:1434826.4745111547,
ymax:8896196.684665617,
spatialReference:{wkid:32637}
},
// url to your geometry server.
geometryService: {
url: 'http://geodata.npolar.no/arcgis/rest/services/Utilities/Geometry/GeometryServer'
},
// panes: {
// left: {
// splitter: true
// },
// right: {
// id: 'sidebarRight',
// placeAt: 'outer',
// region: 'right',
// splitter: true,
// collapsible: true
// },
// bottom: {
// id: 'sidebarBottom',
// placeAt: 'outer',
// splitter: true,
// collapsible: true,
// region: 'bottom'
// },
// top: {
// id: 'sidebarTop',
// placeAt: 'outer',
// collapsible: true,
// splitter: true,
// region: 'top'
// }
// },
// collapseButtonsPane: 'center', //center or outer
// operationalLayers: Array of Layers to load on top of the basemap: valid 'type' options: 'dynamic', 'tiled', 'feature'.
// The 'options' object is passed as the layers options for constructor. Title will be used in the legend only. id's must be unique and have no spaces.
// 3 'mode' options: MODE_SNAPSHOT = 0, MODE_ONDEMAND = 1, MODE_SELECTION = 2
operationalLayers: [
/*{
type: 'feature',
url: 'http://geodata.npolar.no/arcgis/rest/services/Barentsportal/EnvironmentalManagement/0',
title: 'Editable',
options: {
id: 'features',
opacity: 1.0,
visible: true,
outFields: ['*'],
mode: 0
},
editorLayerInfos: {
disableGeometryUpdate: false
}
},*/{
type: 'dynamic',
url: 'http://geodata.npolar.no/arcgis/rest/services/Barentsportal/Biodiversity/MapServer',
title: 'Biodiversity',
options: {
id: 'biodiversity',
opacity: 1.0,
visible: true,
imageParameters: imageParameters
},
layerControlLayerInfos: {
swipe: true,
metadataUrl: true
}
},{
type: 'dynamic',
url: 'http://geodata.npolar.no/arcgis/rest/services/Barentsportal/Pollution/MapServer',
title: 'Pollution',
options: {
id: 'pollution',
opacity: 1.0,
visible: true,
imageParameters: imageParameters
},
layerControlLayerInfos: {
swipe: true,
metadataUrl: true
}
}, {
type: 'dynamic',
url: 'http://geodata.npolar.no/arcgis/rest/services/Barentsportal/HumanActivities/MapServer',
title: 'Human Activities',
options: {
id: 'humanactivities',
opacity: 1.0,
visible: true,
imageParameters: imageParameters
},
layerControlLayerInfos: {
swipe: true,
metadataUrl: true
}
}, {
type: 'dynamic',
url: 'http://willem.npolar.no/arcgis/rest/services/Barentsportal/Oceanography/MapServer',
title: 'Oceanography',
options: {
id: 'oceanography',
opacity: 1.0,
visible: true,
imageParameters: imageParameters
},
layerControlLayerInfos: {
swipe: true,
metadataUrl: true
}
}, {
type: 'dynamic',
url: 'http://geodata.npolar.no/arcgis/rest/services/Barentsportal/Glaciers/MapServer',
title: 'Glaciers',
options: {
id: 'glaciers',
opacity: 1.0,
visible: true,
imageParameters: imageParameters
},
layerControlLayerInfos: {
swipe: true,
metadataUrl: true
}
}, {
type: 'dynamic',
url: 'http://geodata.npolar.no/arcgis/rest/services/Barentsportal/EnvironmentalManagement/MapServer',
title: 'Environmental Management',
options: {
id: 'environmentalManagement',
opacity: 1.0,
visible: true,
imageParameters: imageParameters
},
layerControlLayerInfos: {
swipe: true,
metadataUrl: true
}//,
//identifyLayerInfos: {
// layerIds: [2, 4, 5, 8, 12, 21]
//}
}],
// set include:true to load. For titlePane type set position the the desired order in the sidebar
widgets: {
growler: {
include: true,
id: 'growler',
type: 'domNode',
path: 'gis/dijit/Growler',
srcNodeRef: 'growlerDijit',
options: {}
},
geocoder: {
include: true,
id: 'geocoder',
type: 'domNode',
path: 'gis/dijit/Geocoder',
srcNodeRef: 'geocodeDijit',
options: {
map: true,
mapRightClickMenu: true,
geocoderOptions: {
autoComplete: true,
arcgisGeocoder: {
placeholder: 'Enter an address or place'
}
}
}
},
identify: {
include: true,
id: 'identify',
type: 'titlePane',
path: 'gis/dijit/Identify',
title: 'Identify',
open: false,
position: 3,
options: 'config/identify'
},
basemaps: {
include: true,
id: 'basemaps',
type: 'domNode',
path: 'gis/dijit/Basemaps',
srcNodeRef: 'basemapsDijit',
options: 'config/basemaps'
},
mapInfo: {
include: false,
id: 'mapInfo',
type: 'domNode',
path: 'gis/dijit/MapInfo',
srcNodeRef: 'mapInfoDijit',
options: {
map: true,
mode: 'dms',
firstCoord: 'y',
unitScale: 3,
showScale: true,
xLabel: '',
yLabel: '',
minWidth: 286
}
},
scalebar: {
include: true,
id: 'scalebar',
type: 'map',
path: 'esri/dijit/Scalebar',
options: {
map: true,
attachTo: 'bottom-left',
scalebarStyle: 'line',
scalebarUnit: 'dual'
}
},
locateButton: {
include: true,
id: 'locateButton',
type: 'domNode',
path: 'gis/dijit/LocateButton',
srcNodeRef: 'locateButton',
options: {
map: true,
publishGPSPosition: true,
highlightLocation: true,
useTracking: true,
geolocationOptions: {
maximumAge: 0,
timeout: 15000,
enableHighAccuracy: true
}
}
},
overviewMap: {
include: true,
id: 'overviewMap',
type: 'map',
path: 'esri/dijit/OverviewMap',
options: {
map: true,
attachTo: 'bottom-right',
color: '#0000CC',
height: 100,
width: 125,
opacity: 0.30,
visible: false
}
},
homeButton: {
include: true,
id: 'homeButton',
type: 'domNode',
path: 'esri/dijit/HomeButton',
srcNodeRef: 'homeButton',
options: {
map: true,
extent: new Extent({
xmin:-173159.3372224797,
ymin:7864422.526051709,
xmax:1434826.4745111547,
ymax:8896196.684665617,
spatialReference:{wkid:32637}
})
}
},
legend: {
include: true,
id: 'legend',
type: 'titlePane',
path: 'esri/dijit/Legend',
title: 'Legend',
open: false,
position: 0,
options: {
map: true,
legendLayerInfos: true
}
},
layerControl: {
include: true,
id: 'layerControl',
type: 'titlePane',
path: 'gis/dijit/LayerControl',
title: 'Layers',
open: false,
position: 0,
options: {
map: true,
layerControlLayerInfos: true,
separated: true,
vectorReorder: true,
overlayReorder: true
}
},
bookmarks: {
include: true,
id: 'bookmarks',
type: 'titlePane',
path: 'gis/dijit/Bookmarks',
title: 'Bookmarks',
open: false,
position: 2,
options: 'config/bookmarks'
},
find: {
include: false,
id: 'find',
type: 'titlePane',
canFloat: true,
path: 'gis/dijit/Find',
title: 'Find',
open: false,
position: 3,
options: 'config/find'
},
draw: {
include: true,
id: 'draw',
type: 'titlePane',
canFloat: true,
path: 'gis/dijit/Draw',
title: 'Draw',
open: false,
position: 4,
options: {
map: true,
mapClickMode: true
}
},
measure: {
include: true,
id: 'measurement',
type: 'titlePane',
canFloat: true,
path: 'gis/dijit/Measurement',
title: 'Measurement',
open: false,
position: 5,
options: {
map: true,
mapClickMode: true,
defaultAreaUnit: units.SQUARE_MILES,
defaultLengthUnit: units.MILES
}
},
print: {
include: true,
id: 'print',
type: 'titlePane',
canFloat: true,
path: 'gis/dijit/Print',
title: 'Print',
open: false,
position: 6,
options: {
map: true,
printTaskURL: 'https://utility.arcgisonline.com/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task',
copyrightText: 'Copyright 2014',
authorText: 'Me',
defaultTitle: 'Viewer Map',
defaultFormat: 'PDF',
defaultLayout: 'Letter ANSI A Landscape'
}
},
directions: {
include: false,
id: 'directions',
type: 'titlePane',
path: 'gis/dijit/Directions',
title: 'Directions',
open: false,
position: 7,
options: {
map: true,
mapRightClickMenu: true,
options: {
routeTaskUrl: 'http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Route',
routeParams: {
directionsLanguage: 'en-US',
directionsLengthUnits: units.MILES
}
}
}
},
editor: {
include: true,
id: 'editor',
type: 'titlePane',
path: 'gis/dijit/Editor',
title: 'Editor',
open: false,
position: 8,
options: {
map: true,
mapClickMode: true,
editorLayerInfos: true,
settings: {
toolbarVisible: true,
showAttributesOnClick: true,
enableUndoRedo: true,
createOptions: {
polygonDrawTools: ['freehandpolygon', 'autocomplete']
},
toolbarOptions: {
reshapeVisible: true,
cutVisible: true,
mergeVisible: true
}
}
}
},
streetview: {
include: false,
id: 'streetview',
type: 'titlePane',
canFloat: true,
position: 9,
path: 'gis/dijit/StreetView',
title: 'Google Street View',
options: {
map: true,
mapClickMode: true,
mapRightClickMenu: true
}
},
help: {
include: true,
id: 'help',
type: 'floating',
path: 'gis/dijit/Help',
title: 'Help',
options: {}
}
}
};
});
| etes/ConfigurableViewerJSAPI | viewer/js/config/viewer.js | JavaScript | mit | 11,413 |
'use strict';
describeComponent('component/onTrigger', function () {
// Initialize the component and attach it to the DOM
beforeEach(function () {
setupComponent();
});
it('should be defined', function () {
expect(this.component).toBeDefined();
});
it('should do something', function () {
expect(true).toBe(false);
});
});
| omkawak/bambi | test/spec/component/onTrigger.spec.js | JavaScript | mit | 354 |
var http = require('http');
var fusionHost = "localhost";
var fusionPort = 8764;
var username = "admin";
var password = "password123";
var server = http.createServer(onRequest).listen(9292);
function onRequest(client_req, client_res) {
client_res.setHeader('Access-Control-Allow-Origin', '*');
client_res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
client_res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
console.log('serve: ' + client_req.url);
var auth = 'Basic ' + new Buffer(username+":"+password).toString('base64');
var header = {
'Authorization': auth
};
var options = {
hostname: fusionHost,
port: fusionPort,
path: client_req.url,
method: client_req.method,
headers: header
};
var proxy = http.request(options, function (res) {
res.pipe(client_res, {
end: true
});
});
client_req.pipe(proxy, {
end: true
});
}
| LucidWorks/fusion-seed-app | proxy-server/fusion-proxy.js | JavaScript | mit | 1,060 |
/*
* Copyright (C) 2017 Alasdair Mercer
*
* 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.
*/
'use strict';
const HttpService = require('../HttpService');
/**
* An implementation of {@link HttpService} that checks whether the name is available on
* <a href="https://ello.co">Ello</a>.
*/
class ElloService extends HttpService {
/**
* Creates an instance of {@link ElloService} under the specified <code>category</code>.
*
* @param {string} category - the category to be used
* @public
*/
constructor(category) {
super(category, 'Ello');
}
/**
* @override
* @inheritDoc
*/
getRequestOptions(name) {
return {
method: 'GET',
uri: `https://ello.co/${encodeURIComponent(name)}`
};
}
}
module.exports = ElloService;
| neocotic/throne | src/service/social/ElloService.js | JavaScript | mit | 1,806 |
/**
* Search Tool
*
* @class search-vm
*/
(function() {
"use strict";
define([
"dojo/dom-construct",
"dojo/_base/array",
"dojo/_base/lang",
"dojo/on",
"dojo/dom-style",
"esri/dijit/Search",
"esri/layers/FeatureLayer",
"esri/tasks/locator",
"esri/geometry/Extent",
"esri/graphic",
"esri/symbols/PictureMarkerSymbol",
"esri/symbols/SimpleFillSymbol",
"dojo/text!app/views/search-view.html",
"app/models/map-model",
"app/config/searchConfig",
"app/vm/demographic-vm",
"dojo/domReady!"
],
function(dc, da, lang, on, ds, Search, FeatureLayer, Locator, Extent, Graphic, PictureMarkerSymbol, SimpleFillSymbol, view, mapModel, searchConfig, demographicVM) {
var SearchVM = new function() {
/**
* Store reference to module this object.
*
* @property self
* @type {*}
*/
var self = this;
/**
* Initialize the class.
*
* @method init
*/
self.init = function() {
dc.place(view, "titlebar", "after");
var s = new Search({
enableLabel: false,
autoNavigate: false,
maxSuggestions: 4,
enableInfoWindow: true,
showInfoWindowOnSelect: false,
sources: [],
map: mapModel.getMap()
}, "search");
s.set("sources", searchConfig.Sources);
s.startup();
on(s, "select-result", function(e) {
mapModel.clearGraphics();
self.UpdateMap(e);
});
on(s, "clear-search", function(e) {
mapModel.clearGraphics();
//self.UpdateMap(e);
});
}; //end init
self.UpdateMap = function(e) {
// console.log(e);
if (e.result.name) {
var communityName = e.result.name;
}
var searchType = "";
switch (e.sourceIndex) {
case 1:
searchType = "county";
break;
case 2:
searchType = "supervisor";
break;
case 3:
searchType = "place";
break;
case 4:
searchType = "council";
break;
case 5:
searchType = "zip";
break;
}
if (e.sourceIndex === 6) {
$("#summaryLink").show();
var symbol = mapModel.getSymbol(e.result.feature.geometry, "cyan");
var graphic = new Graphic(e.result.feature.geometry, symbol);
mapModel.addGraphic(graphic, undefined, true, true);
} else if (e.sourceIndex === 0) {
$("#summaryLink").hide();
var symbol = new PictureMarkerSymbol("app/resources/img/Point.png", 36, 36).setOffset(9, 18);
var graphic = new Graphic(e.result.feature.geometry, symbol);
mapModel.addGraphic(graphic, undefined, true, true);
} else {
$("#summaryLink").show();
demographicVM.openWindow(communityName, searchType);
}
};
}; //end
return SearchVM;
}
);
}()); | AZMAG/map-DemographicRegional | src/app/vm/search-vm.js | JavaScript | mit | 4,165 |
(function () {
angular.module('nopsSelect',[
'offClick'
])
.directive('nopsSelect', function () {
return {
restrict: 'E',
templateUrl: 'nopsSelect.html',
require: 'ngModel',
link: function (scope, elem, attrs,ngModelCtrl) {
if(!ngModelCtrl) return;
if(scope.required) {
ngModelCtrl.$setValidity('required',false);
var modelVal = function () {
return ngModelCtrl.$viewValue;
};
scope.$watch(modelVal, function (newValue, oldValue) {
if(newValue === oldValue) return;
ngModelCtrl.$setValidity('required','' != newValue);
});
}
scope.isHidden = true;
scope.selectedName = '';
scope.selectDt = function (dt) {
scope.selectedName = dt.name;
ngModelCtrl.$setViewValue(dt.id);
scope.isHidden = true;
};
scope.checkKeyPress = function ($event) {
var keyCode = $event.which || $event.keyCode;
if(keyCode == 32)
scope.isHidden = false;
};
scope.selectMore = function () {
scope.executeMore();
scope.isHidden = true;
};
},
scope: {
data: '=dtList',
executeMore: '&more',
required: '=isRequired'
}
};
});
})(); | s-o-r-o-u-s-h/nopsSelect | nopsSelect.js | JavaScript | mit | 1,856 |
var TimeAgo;
dependenciesLoader(["React"], function(){
TimeAgo = React.createClass({
displayName: 'Time-Ago',
timeoutId: 0,
getDefaultProps: function(){
return {
live: true,
component: 'span',
minPeriod: 0,
maxPeriod: Infinity,
formatter: function (value, unit, suffix) {
if(value !== 1){
unit += 's'
}
return value + ' ' + unit + ' ' + suffix
}
}
},
propTypes:{
live: React.PropTypes.bool.isRequired,
minPeriod: React.PropTypes.number.isRequired,
maxPeriod: React.PropTypes.number.isRequired,
component: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.func]).isRequired,
formatter: React.PropTypes.func.isRequired,
date: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, React.PropTypes.instanceOf(Date)]).isRequired
},
componentDidMount: function(){
if(this.props.live) {
this.tick(true)
}
},
componentDidUpdate: function(lastProps){
if(this.props.live !== lastProps.live || this.props.date !== lastProps.date){
if(!this.props.live && this.timeoutId){
clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
this.tick()
}
},
componentWillUnmount: function(){
if(this.timeoutId) {
clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
},
tick: function(refresh){
if(!this.isMounted() || !this.props.live){
return
}
var period = 1000
var then = (new Date(this.props.date)).valueOf();
var now = Date.now();
var seconds = Math.round(Math.abs(now-then)/1000);
if(seconds < 60){
period = 1000
}else if(seconds < 60*60){
period = 1000 * 60
}else if(seconds < 60*60*24){
period = 1000 * 60 * 60
}else{
period = 0
}
period = Math.min(Math.max(period, this.props.minPeriod), this.props.maxPeriod)
if(!!period){
this.timeoutId = setTimeout(this.tick, period)
}
if(!refresh){
this.forceUpdate()
}
},
render: function(){
var then = (new Date(this.props.date)).valueOf();
var now = Date.now();
var seconds = Math.round(Math.abs(now-then)/1000);
var suffix = then < now ? 'ago' : 'from now';
var value, unit;
if(seconds < 60){
value = Math.round(seconds)
unit = 'second'
}else if(seconds < 60*60){
value = Math.round(seconds/60)
unit = 'minute'
}else if(seconds < 60*60*24){
value = Math.round(seconds/(60*60))
unit = 'hour'
}else if(seconds < 60*60*24*7){
value = Math.round(seconds/(60*60*24))
unit = 'day'
}else if(seconds < 60*60*24*30){
value = Math.round(seconds/(60*60*24*7))
unit = 'week'
}else if(seconds < 60*60*24*365){
value = Math.round(seconds/(60*60*24*30))
unit = 'month'
}else{
value = Math.round(seconds/(60*60*24*365))
unit = 'year'
}
var props = Object.assign({}, this.props);
delete props.date
delete props.formatter
delete props.component
return React.createElement( this.props.component, props, this.props.formatter(value, unit, suffix, then));
}
}
);
});
| synchroniseiorepo/server | public/js-react/libraries/timeAgo.js | JavaScript | mit | 4,104 |
var searchData=
[
['o',['O',['../namespace_lumengine.html#a72e1aee4161e394b4686c476f44b2722af186217753c37b9b9f958d906208506e',1,'Lumengine']]]
];
| Kw1kk/Lumengine | Lumengine/Documentation/html/search/enumvalues_e.js | JavaScript | mit | 148 |
import React, { Component } from 'react';
import { Treemap } from 'react-vis';
import Button from '../button';
const MODE = [
'circlePack',
'partition',
'partition-pivot',
'squarify',
'resquarify',
'slice',
'dice',
'slicedice',
'binary'
];
export default class simpleTreeMap extends Component {
state = {
modeIndex: 0
}
updateModeIndex = increment => () => {
const newIndex = this.state.modeIndex + (increment ? 1 : -1);
const modeIndex = newIndex < 0 ? MODE.length - 1 : newIndex >= MODE.length ? 0 : newIndex;
this.setState({modeIndex});
}
render() {
const {modeIndex} = this.state;
const { datas, width, height } = this.props;
return (
<div className="isoChartWrapper">
<div className="isoChartControl">
<span> {MODE[modeIndex]} </span>
<Button onClick={this.updateModeIndex(false)} buttonContent={'PREV'} />
<Button onClick={this.updateModeIndex(true)} buttonContent={'NEXT'} />
</div>
<Treemap
animation
className="nested-tree-example"
colorType="literal"
data={datas}
mode={MODE[modeIndex]}
height={width}
width={height}/>
</div>
);
}
}
| EncontrAR/backoffice | src/containers/Charts/reactVis/charts/simpleTreeMap.js | JavaScript | mit | 1,247 |
isString(anything);
| AmpersandJS/amp | modules/is-string/sig.js | JavaScript | mit | 20 |
module.exports = function()
{
var job,
init = function(_job)
{
job = _job;
return this;
},
execute = function(_data, _callback)
{
var cDb = require("../../modules/queryDB.js");
db = new cDb();
var sql = "select * from client_account where account = '"+_data.username+"'";
db.queryDB(sql,_data._config,function(err,result)
{
if(!err)
{
_data.userRepeat = (result.rowCount > 0)? true : false;
//insert client_info & client_account
if(_data.userRepeat == false)
{
var sql = "insert into client_info(machine_number,machine_ip,machine_name,contact,status)"+
" values('"+_data.machineNumber+"','"+_data.machineIp+"','"+_data.machineName+"','"+JSON.stringify(_data.contact)+"',"+_data.status+") returning client_id;";
db.queryDB(sql,_data._config,function(err,result)
{
if(!err)
{
var insertedClientId = result.rows[0].client_id;
var sql = "insert into client_account(client_id,account,password) values("+insertedClientId+",'"+_data.username+"','"+_data.password+"')";
db.queryDB(sql,_data._config,function(err,result)
{
if(!err)
{
_data._result.message ="register success";
_data._result.result = 1;
_data._result.data = {"clientId": insertedClientId};
}
else
{
_data._result.message ="register error(3)";
_data._result.result = 0;
}
_callback(false, job);
});
}
else
{
_data._result.message ="register error(2)";
_data._result.result = 0;
_callback(false, job);
}
});
}
else
{
_data._result.message = "client repeat";
_data._result.result = 1;
_callback(false, job);
}
}
else
{
_data._result.message ="register error(1)";
_data._result.result = 0;
_callback(false, job);
}
});
},
that =
{
init: init,
execute: execute
};
return that;
} | Luphia/Elucia-storage-center | commands/iServStorage/registerClient.js | JavaScript | mit | 2,032 |
var SurfaceCtrls = {};
SurfaceCtrls.MainCtrl = function($scope, $state, $http, navigator, appState) {
$scope.init = function() {
$scope.params = {
url: appState.url || '',
headers: []
};
};
$scope.fetchUrl = function(params) {
var url = params.url,
headers = params.headers;
appState.url = url;
headers.forEach(function (header) {
if (
header.key
&& header.value
&& header.key.length > 0
&& header.value.length > 0
) {
$http.defaults.headers.common[header.key] = header.value;
}
});
navigator.transitionTo(url, { url: url });
};
$scope.addHeader = function () {
$scope.params.headers.push({
key: '',
value: ''
});
}
$scope.removeHeader = function (index) {
$scope.params.headers.splice(index, 1);
}
};
SurfaceCtrls.HomeCtrl = function($scope, $state, navigator, appState) {
$scope.init = function() {
$scope.model = { collection: null, query: null };
$scope.fields = {};
$scope.model.url = appState.url = $state.params.url;
$scope.model.url = appState.url;
$scope.model.collection = appState.collection;
$scope.model.query = appState.query;
navigator.fetch($state.params.url, $state.params).then(function(data) {
angular.forEach(data.actions, function(action) {
if (action.name === 'search') {
angular.forEach(action.fields, function(field) {
$scope.fields[field.name] = field;
});
}
});
if (!$scope.model.collection || $scope.model.collection === '') {
$scope.model.collection = $scope.fields.collection.value[0];
}
if (!$scope.model.query || $scope.model.query === '') {
$scope.model.query = $scope.fields.query.value;
}
});
};
$scope.search = function(fields) {
var rootUrl = appState.url = fields.url;
var collection = appState.collection = fields.collection;
var query = appState.query = fields.query;
var url = SurfaceCtrls.Common.buildUrl(rootUrl, collection, query);
var params = fields;
navigator.execute('search', fields, params);
};
};
SurfaceCtrls.EntityCtrl = function($scope, $state, $http, $location, navigator) {
$scope.init = function() {
var params = $state.params;
var rootUrl = params.url;
var collection = params.collection;
var query = params.query;
follow(rootUrl, collection, query);
};
$scope.go = function(url) {
$state.transitionTo('entity', { url: url });
};
$scope.execute = function(action) {
navigator.execute(action).then(function(result) {
if (result.noop) {
return;
}
var data = result.data;
var config = result.config;
$scope.main.properties = null;
$scope.main.class = null;
$scope.main.actions = [];
$scope.main.entities = [];
$scope.main.links = [];
$scope.url = config.url;
$state.params.url = config.url;
showData(data);
});
};
var showData = function(data) {
if (typeof data === 'string') data = JSON.parse(data);
$scope.main.properties = JSON.stringify(data.properties, null, 2);
$scope.main.class = JSON.stringify(data.class);
$scope.main.actions = data.actions;
if (data.entities) {
angular.forEach(data.entities, function(entity) {
entity.properties = JSON.stringify(entity.properties, null, 2);
var heading = [];
if (entity.class) {
heading.push('class: ' + JSON.stringify(entity.class));
}
if (entity.rel) {
heading.push('rel: ' + JSON.stringify(entity.rel));
}
entity.heading = heading.join(', ') || '[unknown class]';
if (entity.links) {
var links = [];
angular.forEach(entity.links, function(link) {
angular.forEach(link.rel, function(rel) {
links.push({ rel: rel, href: link.href });
});
});
entity.links = links;
}
$scope.main.entities.push(entity);
});
};
if (data.links) {
angular.forEach(data.links, function(link) {
angular.forEach(link.rel, function(rel) {
$scope.main.links.push({ rel: rel, href: link.href });
});
});
}
};
var follow = function(rootUrl, collection, query) {
var url = SurfaceCtrls.Common.buildUrl(rootUrl, collection, query);
$scope.main = {
properties: [],
entities: [],
links: []
};
$scope.isOneAtATime = true;
$scope.url = url;
$state.params.url = url;
$state.params.collection = collection;
$state.params.query = query;
navigator.redirectOrFetch(url, $state.params).then(function(data) {
showData(data);
});
};
};
SurfaceCtrls.Common = {
buildUrl: function(rootUrl, collection, query) {
var url = '';
if (rootUrl) {
url += rootUrl;
}
if (collection) {
if (url.slice(-1) === '/') {
url = url.slice(0, -1);
}
url += '/' + encodeURIComponent(collection);
}
if (query) {
url += '?query=' + encodeURIComponent(query);
}
return url;
}
};
| kevinswiber/siren-api-browser | scripts/controllers.js | JavaScript | mit | 5,205 |
module.exports.main = function () {
var data = {
'nodes':[
{'id':'1','name':'first','size':'8','color':'red'},
{'id':'2','name':'second','size':'6','color':'blue'},
{'id':'3','name':'third','size':'6','color':'blue'},
{'id':'4','name':'fouth','size':'3','color':'green'},
{'id':'5','name':'fifth','size':'3','color':'green'},
{'id':'6','name':'sixth','size':'3','color':'green'},
{'id':'7','name':'seventh','size':'3','color':'green'},
{'id':'8','name':'eight','size':'3','color':'green'}
],
'edges': [
{'id':'1','fromId':'1','toId':'2','color':'yellow','linewidth':'60'},
{'id':'2','fromId':'1','toId':'4','color':'yellow','linewidth':'60'},
{'id':'3','fromId':'1','toId':'5','color':'yellow','linewidth':'60'},
{'id':'4','fromId':'1','toId':'6','color':'yellow','linewidth':'60'},
{'id':'5','fromId':'2','toId':'3','color':'pink','linewidth':'1'},
{'id':'6','fromId':'2','toId':'7','color':'pink','linewidth':'1'},
{'id':'7','fromId':'3','toId':'8','color':'purple','linewidth':'1'}
]
};
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "js/threex.domevents.js");
document.getElementsByTagName("head")[0].appendChild(fileref);
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "js/three.js");
document.getElementsByTagName("head")[0].appendChild(fileref);
setTimeout(function(){
var graph = require('ngraph.graph')();
var threeGraphics = require('ngraph.three')(graph,{ interactive: true, container: document.getElementById('container') });
var THREE = threeGraphics.THREE;
var camera = threeGraphics.camera;
var domEvents = new THREEx.DomEvents(camera, threeGraphics.renderer.domElement, THREE);
// tell graphics we want custom UI
threeGraphics.createNodeUI(function (node) {
var nodeGeometry = new THREE.SphereGeometry(node.data.size);
var nodeMaterial = new THREE.MeshBasicMaterial({ color: node.data.color });
var result = new THREE.Mesh(nodeGeometry, nodeMaterial);
result['nodeId'] = node.id;
domEvents.addEventListener(result, 'mouseover',onMouseOver);
domEvents.addEventListener(result, 'mouseout',onMouseOut);
domEvents.addEventListener(result, 'click',onMouseClick);
return result;
}).createLinkUI(function(link) {
var linkGeometry = new THREE.Geometry();
// we don't care about position here. linkRenderer will update it
linkGeometry.vertices.push(new THREE.Vector3(0, 0, 0));
linkGeometry.vertices.push(new THREE.Vector3(0, 0, 0));
var linkMaterial = new THREE.LineBasicMaterial({ color: link.data.color });
return new THREE.Line(linkGeometry, linkMaterial);
});
createGraph(graph,data);
addEventListeners(graph);
threeGraphics.run();
function onMouseOver(e) {
var nodeId = e.target.nodeId;
/*console.info('nodeId - ' + nodeId + ' nodeIdUI - ' + e.target.id);*/
var node = graph.getNode(nodeId);
/*console.info('node name ' + node.data.name);*/
var links = node.links;
for (var i=0; i < links.length; i++) {
var link = threeGraphics.getLinkUI(links[i].id);
if (link) link.material.color.setHex(0xff0000);
}
}
function onMouseClick(e) {
var nodeId = e.target.nodeId;
var node = graph.getNode(nodeId);
graph.forEachNode(function(nodes){
nodes.data['selected'] = false;
});
node.data['selected'] = true;
console.info('nodeId selected ' + node.id);
}
function onMouseOut(e) {
var nodeId = e.target.nodeId;
var node = graph.getNode(nodeId);
var links = node.links;
for (var i=0; i < links.length; i++) {
var link = threeGraphics.getLinkUI(links[i].id);
if (link) link.material.color.setStyle(links[i].data.color);
}
}
function addEventListeners(graph) {
var el = document.getElementById('butt');
el.addEventListener("click",function(e) {
graph.beginUpdate();
var node = graph.addNode(9,{'id':'1','name':'first','size':'8','color':'white'});
if(graph.getNode(3) && graph.getNode(9))
{
graph.addLink(3,9,{'id':'8','fromId':'3','toId':'9','color':'purple','linewidth':'1'});
}
graph.endUpdate();
});
var rel = document.getElementById('removeButton');
rel.addEventListener("click",function(e) {
graph.beginUpdate();
console.info('to remove');
graph.forEachNode(function(node){
if(node.data.selected == true)
{
console.info('nodeId removed ' + node.id);
var toDel = threeGraphics.getNodeUI(node.id);
domEvents.removeEventListener(toDel, 'mouseover',onMouseOver);
domEvents.removeEventListener(toDel, 'click',onMouseClick);
domEvents.removeEventListener(toDel, 'mouseout',onMouseOut);
graph.removeNode(node.id);
}
});
graph.endUpdate();
});
}
}, 500);
};
function createGraph(graph, data) {
graph.beginUpdate();
for (var i = 0; i < data.nodes.length; i++) {
graph.addNode(data.nodes[i].id, data.nodes[i]);
}
for (var i = 0; i < data.edges.length; i++) {
graph.addLink(data.edges[i].fromId, data.edges[i].toId, data.edges[i]);
}
graph.endUpdate();
}
| kalpas-team/hackaton | src/main/webapp/js/index.js | JavaScript | mit | 5,469 |
'use strict';
/**
* Module dependencies.
*/
var users = require('../../app/controllers/users.server.controller'),
articles = require('../../app/controllers/articles.server.controller'),
push = require('../../app/notifications/notifications');
module.exports = function(app) {
// Article Routes
app.route('/articles')
.get(users.requiresLogin,articles.list)
.post(users.requiresLogin, articles.create);
app.route('/push')
.get(push.pushNotification)
app.route('/articles/:articleId')
.get(articles.read)
.put(users.requiresLogin, articles.hasAuthorization, articles.update)
.delete(users.requiresLogin, articles.hasAuthorization, articles.delete);
// Finish by binding the article middleware
app.param('articleId', articles.articleByID);
}; | Miyada2000/miybnd | app/routes/articles.server.routes.js | JavaScript | mit | 768 |
const questionnaires = [
{
id: 'fr.insee-POPO-QPO-DOC',
name: 'DOC',
label: ['Je suis le titre du questionnaire'],
declarations: [],
redirections: [],
controls: [],
genericName: 'QUESTIONNAIRE',
children: [
{
id: 'ir6cju1z',
name: 'SIMPLE',
label: ['Module des questions ouvertes : je suis le libellé du module'],
declarations: [
{
declarationType: 'INSTRUCTION',
text: 'Ceci est une déclaration de type consigne.\n'
}
],
redirections: [],
controls: [],
genericName: 'MODULE',
children: [
{
id: 'iwm8qg8x',
name: 'INTRODUCTI',
label: ['Introduction : je suis le libellé du paragraphe'],
declarations: [
{
declarationType: 'INSTRUCTION',
text:
"Ce questionnaire est un exemple de ce qu'il est possible de faire en utilisant les outils Eno et Pogues. Il se découpe en plusieurs modules (un module par page), regroupant les différents types de questions. Dans chaque module, vous trouverez la description des questions de chaque type, ainsi que des exemples tirés de questionnaires Insee.\n\n\n"
}
],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'iwm8r0ba',
name: 'COCHEZ',
label: [
'##{"label":"Cochez la case pour afficher la suite du questionnaire\\n","conditions":[]}\nCochez la case pour afficher la suite du questionnaire\n'
],
declarations: [],
redirections: [
{
id: 'iwnegyn6',
description:
'Si vous avez coché la case, poursuivez le questionnaire.',
expression: "${S1-S1-Q1-R1}='' or ${S1-S1-Q1-R1}='0' ", // eslint-disable-line no-template-curly-in-string
ifTrue: 'isg13cuk'
}
],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
}
],
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
},
{
id: 'ir6co0qf',
name: 'MODULE_TEXTE',
label: ['Sous-module : questions de type texte'],
declarations: [],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'ir6cqzev',
name: 'TEXTE_LONG',
label: [
'##{"label":"Je suis le libellé de la question de type texte de longueur supérieure à 250 caractères\\n","conditions":[]}\nJe suis le libellé de la question de type texte de longueur supérieure à 250 caractères\n'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text: 'Je suis le texte de la consigne\n',
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'TEXT',
maxLength: 250,
pattern: '',
type: 'TextDatatypeType'
}
}
],
type: 'QuestionType'
},
{
id: 'ir6cm77g',
name: 'TEXTE_COURT',
label: [
'##{"label":"Je suis le libellé de la question de type texte de longueur inférieure à 200 caractères","conditions":[]}\nJe suis le libellé de la question de type texte de longueur inférieure à 200 caractères'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'TEXT',
maxLength: 150,
pattern: '',
type: 'TextDatatypeType'
}
}
],
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
},
{
id: 'ir6cruy6',
name: 'MODULE_NUM',
label: ['Sous-module : questions de type numérique'],
declarations: [],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'ir6cifax',
name: 'NUM_ENTIER',
label: [
'##{"label":"Je suis le libellé de la question de type numérique entier","conditions":[]}\nJe suis le libellé de la question de type numérique entier'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: 120,
decimals: null,
type: 'NumericDatatypeType'
}
}
],
type: 'QuestionType'
},
{
id: 'ir6cmuqa',
name: 'NUM_DECIMAL',
label: [
'##{"label":"Je suis le libellé de la question de type numérique décimal","conditions":[]}\nJe suis le libellé de la question de type numérique décimal'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text: 'Je suis le texte de la consigne\n',
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: 1,
type: 'NumericDatatypeType'
}
}
],
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
},
{
id: 'ir6ctbkt',
name: 'SOUSMODULE',
label: ['Sous-module : questions de type date et durée'],
declarations: [],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'ir6ct69u',
name: 'SIMPLE_DATE',
label: [
'##{"label":"Je suis le libellé de la question de type date au format JJ/MM/AAAA","conditions":[]}\nJe suis le libellé de la question de type date au format JJ/MM/AAAA'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'DATE',
minimum: '',
maximum: '',
format: '',
type: 'DateDatatypeType'
}
}
],
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
},
{
id: 'isg1kh8l',
name: 'SOUSMODULE',
label: ['Sous modules : question booléen'],
declarations: [],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'isg1hh9m',
name: 'BOOL',
label: [
'##{"label":"Je suis le libellé de la question simple de type booléen","conditions":[]}\nJe suis le libellé de la question simple de type booléen'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
}
],
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
},
{
id: 'iwnfdy97',
name: 'EXEMPLES',
label: ['Exemples'],
declarations: [],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'iwm6shxx',
name: 'ACT_PRIN',
label: [
'##{"label":"Veuillez indiquer l\'activité principale de l\'entreprise sous son appellation usuelle","conditions":[]}\nVeuillez indiquer l\'activité principale de l\'entreprise sous son appellation usuelle'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text:
'(par exemple : commerce de fruits et légumes, boulangerie, charcuterie artisanale ou industrielle, commerce de détail de meubles...)\n',
position: 'AFTER_QUESTION_TEXT'
},
{
declarationType: 'INSTRUCTION',
text: "Exemple tiré de l'enquête sectorielle annuelle\n",
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'TEXT',
maxLength: 200,
pattern: '',
type: 'TextDatatypeType'
}
}
],
type: 'QuestionType'
},
{
id: 'iwm8woim',
name: 'PROFESSION',
label: [
'##{"label":"Indiquez le plus précisément possible la profession exercée dans votre emploi actuel","conditions":[]}\nIndiquez le plus précisément possible la profession exercée dans votre emploi actuel'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text:
'Soyez très précis sur votre métier : « Caissière » (et non « employée »), « Fleuriste » (et non « Commerçant »), « Professeur des écoles»\n',
position: 'AFTER_QUESTION_TEXT'
},
{
declarationType: 'INSTRUCTION',
text: "Question issue de l'enquête EVA 2016\n",
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'TEXT',
maxLength: 200,
pattern: '',
type: 'TextDatatypeType'
}
}
],
type: 'QuestionType'
},
{
id: 'iw7ux0w8',
name: 'QUELESTLEM',
label: [
'##{"label":"Quel est le montant total des investissements réalisés dans votre entreprise ?","conditions":[]}\nQuel est le montant total des investissements réalisés dans votre entreprise ?'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: 999999999,
decimals: null,
type: 'NumericDatatypeType'
}
}
],
type: 'QuestionType'
},
{
id: 'iwm8v2g4',
name: 'SALAIRE',
label: [
'##{"label":"Quel était le montant net de votre salaire mensuel correspondant à cet emploi en mars 2016 ?","conditions":[]}\nQuel était le montant net de votre salaire mensuel correspondant à cet emploi en mars 2016 ?'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text: "Question issue de l'enquête EVA 2016\n",
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'NUMERIC',
minimum: null,
maximum: 99999,
decimals: null,
type: 'NumericDatatypeType'
}
}
],
type: 'QuestionType'
},
{
id: 'iwm8t2p5',
name: 'CLOT',
label: [
'##{"label":"Quelle est la date de clôture du dernier exercice comptable clos ?","conditions":[]}\nQuelle est la date de clôture du dernier exercice comptable clos ?'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text:
"Définition de l'exercice comptable sur lequel porte ce questionnaire :\n\nLes informations à fournir se rapportent à votre exercice comptable 2015.\n\n\n\nVotre exercice comptable 2015 doit être clôturé entre le 1er juin 2015 et le 31 mai 2016.\n\n\n\nSi vous avez clotûré deux exercices sur cette période, prendre celui qui a leplus de mois en 2015.\n\n\n\nVous devez également répondre à l'énquête si votre entreprise a cessé son activité :\n\nen 2015 et a plus de 6 mois d'activité ;\n\nen 2016.\n",
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType'
}
}
],
type: 'QuestionType'
},
{
id: 'iwm99upn',
name: 'DEPUISQUEL',
label: [
'##{"label":"Depuis quelle date travailliez-vous dans cette entreprise / dans la fonction publique ?","conditions":[]}\nDepuis quelle date travailliez-vous dans cette entreprise / dans la fonction publique ?'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text: "Question issue de l'enquête EVA 2016\n",
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'DATE',
minimum: '',
maximum: '',
format: '',
type: 'DateDatatypeType'
}
}
],
type: 'QuestionType'
},
{
id: 'iwnevs21',
name: 'ACT_PROD',
label: [
'##{"label":"Si votre établissement n’a pas d’activité industrielle de production ou de transformation, cochez la case ci-contre :","conditions":[]}\nSi votre établissement n’a pas d’activité industrielle de production ou de transformation, cochez la case ci-contre :'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text:
"Question issue de l'enquête annuelle sur les consommations d'énergie dans l'industrie (EACEI)\n",
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'SIMPLE',
responses: [
{
mandatory: false,
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
}
],
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
}
],
depth: 1,
type: 'SequenceType'
},
{
id: 'isg1ikbn',
name: 'SINGLE',
label: ['Module des questions à choix unique'],
declarations: [],
redirections: [],
controls: [],
genericName: 'MODULE',
children: [
{
id: 'isg13cuk',
name: 'SINGLE_RADIO',
label: [
'##{"label":"Je suis le libellé de la question à choix unique sous forme de bouton radio","conditions":[]}\nJe suis le libellé de la question à choix unique sous forme de bouton radio'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text: 'La consigne est après la question\n',
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'SINGLE_CHOICE',
responses: [
{
codeListReference: 'isg1g6zo',
mandatory: false,
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
}
],
type: 'QuestionType'
},
{
id: 'isg1hq0f',
name: 'SINGLE_DROPDOWN',
label: [
'##{"label":"Je suis le libellé de la question à choix unique sous forme de liste déroulante","conditions":[]}\nJe suis le libellé de la question à choix unique sous forme de liste déroulante'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'SINGLE_CHOICE',
responses: [
{
codeListReference: 'isg1g6zo',
mandatory: false,
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'DROPDOWN'
}
}
],
type: 'QuestionType'
},
{
id: 'isg1bz8h',
name: 'SINGLE_CHECKBOX',
label: [
'##{"label":"Je suis le libellé de la question à choix unique sous forme de cases à cocher","conditions":[]}\nJe suis le libellé de la question à choix unique sous forme de cases à cocher'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'SINGLE_CHOICE',
responses: [
{
codeListReference: 'isg1g6zo',
mandatory: false,
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
}
}
],
type: 'QuestionType'
},
{
id: 'iwnesc00',
name: 'EXEMPLES',
label: ['Exemples'],
declarations: [],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'iw22nmhl',
name: 'FILTRE_INV',
label: [
'##{"label":"Avez-vous, au cours du dernier exercice comptable, investi dans des équipements spécifiquement dédiés à l’environnement : bennes, filtres, bacs de rétention, instruments de mesure de la pollution","conditions":[]}\nAvez-vous, au cours du dernier exercice comptable, investi dans des équipements spécifiquement dédiés à l’environnement : bennes, filtres, bacs de rétention, instruments de mesure de la pollution'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text: "Cette question est extraite de l'enquête Antipol\n",
position: 'AFTER_RESPONSE'
}
],
redirections: [],
controls: [],
questionType: 'SINGLE_CHOICE',
responses: [
{
codeListReference: 'isg1uorv',
mandatory: false,
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
}
}
],
type: 'QuestionType'
},
{
id: 'iwm6zyaq',
name: 'VENTES_MARCH',
label: [
'##{"label":"Vendez vous vos marchandises majoritairement\\n","conditions":[]}\nVendez vous vos marchandises majoritairement\n'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text:
"Question issue de l'enquête sectorielle annuelle (commerce)\n",
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'SINGLE_CHOICE',
responses: [
{
codeListReference: 'iwm8rneb',
mandatory: false,
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
}
}
],
type: 'QuestionType'
},
{
id: 'iwm9e4pi',
name: 'TEMPSPLEIN',
label: [
'##{"label":"Toujours au 1er mars 2016, vous travailliez","conditions":[]}\nToujours au 1er mars 2016, vous travailliez'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text: "Question issue de l'enquête EVA 2016\n",
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'SINGLE_CHOICE',
responses: [
{
codeListReference: 'iwm8zloc',
mandatory: false,
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
}
}
],
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
}
],
depth: 1,
type: 'SequenceType'
},
{
id: 'isg1gytw',
name: 'MULTIPLE',
label: ['Module des questions à choix multiple'],
declarations: [],
redirections: [],
controls: [],
genericName: 'MODULE',
children: [
{
id: 'isg1j5rw',
name: 'MULTIPLE_BOOL',
label: [
'##{"label":"Je suis le libellé de la question à choix multiple sous forme de booléen","conditions":[]}\nJe suis le libellé de la question à choix multiple sous forme de booléen'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'MULTIPLE_CHOICE',
responses: [
{
datatype: { typeName: 'BOOLEAN', type: 'BooleanDatatypeType' }
},
{
datatype: { typeName: 'BOOLEAN', type: 'BooleanDatatypeType' }
},
{
datatype: { typeName: 'BOOLEAN', type: 'BooleanDatatypeType' }
},
{
datatype: { typeName: 'BOOLEAN', type: 'BooleanDatatypeType' }
},
{ datatype: { typeName: 'BOOLEAN', type: 'BooleanDatatypeType' } }
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'isg1g6zo'
},
{ dimensionType: 'MEASURE', dynamic: 0 }
]
},
type: 'QuestionType'
},
{
id: 'isg1gjjt',
name: 'MULTIPLE_RADIO',
label: [
'##{"label":"Je suis le libellé de la question à choix multiple sous forme de bouton radio","conditions":[]}\nJe suis le libellé de la question à choix multiple sous forme de bouton radio'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'MULTIPLE_CHOICE',
responses: [
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
},
codeListReference: 'isg1uorv'
}
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'isg1g6zo'
},
{ dimensionType: 'MEASURE', dynamic: 0 }
]
},
type: 'QuestionType'
},
{
id: 'isg20r8n',
name: 'MULTIPLE_DROPDOWN',
label: [
'##{"label":"Je suis le libellé de la question à choix multiple sous forme de liste déroulante","conditions":[]}\nJe suis le libellé de la question à choix multiple sous forme de liste déroulante'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text: 'La consigne est avant la question\n',
position: 'BEFORE_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'MULTIPLE_CHOICE',
responses: [
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'DROPDOWN'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'DROPDOWN'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'DROPDOWN'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'DROPDOWN'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'DROPDOWN'
},
codeListReference: 'isg1uorv'
}
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'isg1g6zo'
},
{ dimensionType: 'MEASURE', dynamic: 0 }
]
},
type: 'QuestionType'
},
{
id: 'isg1uc3w',
name: 'MULTIPLE_CHECKBOX',
label: [
'##{"label":"Je suis le libellé de la question à choix multiple sous forme de cases à cocher","conditions":[]}\nJe suis le libellé de la question à choix multiple sous forme de cases à cocher'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'MULTIPLE_CHOICE',
responses: [
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
},
codeListReference: 'isg1uorv'
}
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'isg1g6zo'
},
{ dimensionType: 'MEASURE', dynamic: 0 }
]
},
type: 'QuestionType'
},
{
id: 'iwnevbej',
name: 'EXEMPLES',
label: ['Exemples'],
declarations: [],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'iwm8wtis',
name: 'SITE_ENTREPRISE',
label: [
'##{"label":"Le site ou la page d’accueil de votre entreprise propose-t-il actuellement les services suivants :type de contrat suivant :\\n","conditions":[]}\nLe site ou la page d’accueil de votre entreprise propose-t-il actuellement les services suivants :type de contrat suivant :\n'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text: "Question issue de l'enquête Tic-TPE 2016\n",
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'MULTIPLE_CHOICE',
responses: [
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
},
codeListReference: 'isg1uorv'
},
{
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
},
codeListReference: 'isg1uorv'
}
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'iwm8rfv5'
},
{ dimensionType: 'MEASURE', dynamic: 0 }
]
},
type: 'QuestionType'
},
{
id: 'iwm8xktl',
name: 'FORMATION',
label: [
'##{"label":"Depuis la fin de ces études, avez-vous suivi une ou plusieurs des formations suivantes ?","conditions":[]}\nDepuis la fin de ces études, avez-vous suivi une ou plusieurs des formations suivantes ?'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'MULTIPLE_CHOICE',
responses: [
{
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
},
{
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
},
{
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
},
{
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
},
{
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
}
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'iwm9fhue'
},
{ dimensionType: 'MEASURE', dynamic: 0 }
]
},
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
}
],
depth: 1,
type: 'SequenceType'
},
{
id: 'isg1qnrf',
name: 'TABLE',
label: ['Module des questions sous forme de tableau'],
declarations: [],
redirections: [],
controls: [],
genericName: 'MODULE',
children: [
{
id: 'isg24et5',
name: 'TABLE_1A',
label: ["Sous module des tableaux à un seul axe d'information"],
declarations: [],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'isg1s9ho',
name: 'TABLE_1A_1M',
label: [
'##{"label":"Je suis le libellé de la question tableau un axe - une mesure","conditions":[]}\nJe suis le libellé de la question tableau un axe - une mesure'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'TABLE',
responses: [
{
datatype: {
typeName: 'TEXT',
maxLength: 20,
pattern: '',
type: 'TextDatatypeType'
}
},
{
datatype: {
typeName: 'TEXT',
maxLength: 20,
pattern: '',
type: 'TextDatatypeType'
}
},
{
datatype: {
typeName: 'TEXT',
maxLength: 20,
pattern: '',
type: 'TextDatatypeType'
}
},
{
datatype: {
typeName: 'TEXT',
maxLength: 20,
pattern: '',
type: 'TextDatatypeType'
}
},
{
datatype: {
typeName: 'TEXT',
maxLength: 20,
pattern: '',
type: 'TextDatatypeType'
}
}
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'isg1g6zo'
},
{
dimensionType: 'MEASURE',
dynamic: 0,
label: 'Mesure 1 texte'
}
]
},
type: 'QuestionType'
},
{
id: 'isg28ywr',
name: 'TABLE_1A_nM',
label: [
'##{"label":"Je suis le libellé de la question tableau un axe - plusieurs mesures","conditions":[]}\nJe suis le libellé de la question tableau un axe - plusieurs mesures'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'TABLE',
responses: [
{
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
},
{
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
},
{
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
},
{
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
},
{
datatype: {
typeName: 'BOOLEAN',
type: 'BooleanDatatypeType'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: 1,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: 1,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: 1,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: 1,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: 1,
type: 'NumericDatatypeType'
}
}
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'isg1g6zo'
},
{
dimensionType: 'MEASURE',
dynamic: 0,
label: 'Mesure simple booléen'
},
{
dimensionType: 'MEASURE',
dynamic: 0,
label: 'Mesure unique radio'
},
{
dimensionType: 'MEASURE',
dynamic: 0,
label: 'Mesure simple entier'
}
]
},
type: 'QuestionType'
},
{
id: 'isg1rx4a',
name: 'TABLE_LIST',
label: [
'##{"label":"Je suis le libellé de la question liste","conditions":[]}\nJe suis le libellé de la question liste'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'TABLE',
responses: [
{
datatype: {
typeName: 'TEXT',
maxLength: 50,
pattern: '',
type: 'TextDatatypeType'
}
},
{
datatype: {
typeName: 'DATE',
minimum: '',
maximum: '',
format: '',
type: 'DateDatatypeType'
}
}
],
responseStructure: {
dimensions: [
{ dimensionType: 'PRIMARY', dynamic: '-' },
{
dimensionType: 'MEASURE',
dynamic: 0,
label: 'Mesure texte'
},
{
dimensionType: 'MEASURE',
dynamic: 0,
label: 'Mesure date'
}
]
},
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
},
{
id: 'iwnexpuc',
name: 'EXEMPLES',
label: ['Exemples'],
declarations: [],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'iw22jcng',
name: 'EFFECTIFSS',
label: [
'##{"label":"Effectifs salariés au 31/12/2015","conditions":[]}\nEffectifs salariés au 31/12/2015'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text:
'Comptez la totalité des salariés rémunérés directement par l’entreprise et inscrits à la date du 31/12/2015, y compris les dirigeants de sociétés et gérants salariés, le personnel saisonnier ou occasionnel.\n\n\n',
position: 'AFTER_QUESTION_TEXT'
},
{
declarationType: 'INSTRUCTION',
text:
'Ne comptez pas le personnel rémunéré par d’autres entreprises (travail temporaire, personnel prêté par d’autres entreprises) ni les stagiaires non rémunérés.\n',
position: 'AFTER_QUESTION_TEXT'
},
{
declarationType: 'INSTRUCTION',
text:
"Cette question est extraite de l'enquête structurelle auprès des entreprises mahoraises\n",
position: 'AFTER_RESPONSE'
}
],
redirections: [],
controls: [],
questionType: 'TABLE',
responses: [
{
datatype: {
typeName: 'NUMERIC',
minimum: null,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: null,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: null,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: null,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: null,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
}
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'iw22xe2u'
},
{
dimensionType: 'MEASURE',
dynamic: 0,
label: 'Effectifs salariés'
}
]
},
type: 'QuestionType'
},
{
id: 'iwncfpwn',
name: 'LISTE_PERS',
label: [
'##{"label":"Liste des personnes qui habitent ce logement\\n","conditions":[]}\nListe des personnes qui habitent ce logement\n'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text:
"Veuillez inscrire un par un les prénoms des personnes qui habitent ce logement, même une partie de la semaine y compris celles qui sont temporairement absentes au moment de l’enquête (vacances, voyage d'affaires, hospitalisation, élèves ou étudiants vivant ailleurs pour leurs études mais encore rattachés au logement, conjoints éloignés pour raisons professionnelles, enfants en garde alternée, personnes âgées en institution …)\n",
position: 'AFTER_QUESTION_TEXT'
}
],
redirections: [],
controls: [],
questionType: 'TABLE',
responses: [
{
datatype: {
typeName: 'TEXT',
maxLength: 50,
pattern: '',
type: 'TextDatatypeType'
}
},
{
codeListReference: 'iw22fswu',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'CHECKBOX'
}
},
{
datatype: {
typeName: 'DATE',
minimum: '',
maximum: '',
format: '',
type: 'DateDatatypeType'
}
}
],
responseStructure: {
dimensions: [
{ dimensionType: 'PRIMARY', dynamic: '-' },
{ dimensionType: 'MEASURE', dynamic: 0, label: 'Prénom' },
{ dimensionType: 'MEASURE', dynamic: 0, label: 'Sexe' },
{
dimensionType: 'MEASURE',
dynamic: 0,
label: 'Date de naissance'
}
]
},
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
},
{
id: 'isg1x9p9',
name: 'TABLE_2A',
label: ["Sous module des tableaux à deux axes d'information"],
declarations: [],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'isg1v5d2',
name: 'TABLE_2A_1SIMPLE',
label: [
'##{"label":"Je suis le libellé d\'un tableau à deux axes 1 mesure simple","conditions":[]}\nJe suis le libellé d\'un tableau à deux axes 1 mesure simple'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'TABLE',
responses: [
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 1,
maximum: 10,
decimals: null,
type: 'NumericDatatypeType'
}
}
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'isg1g6zo'
},
{
dimensionType: 'SECONDARY',
dynamic: 0,
codeListReference: 'isg27fpv'
},
{
dimensionType: 'MEASURE',
dynamic: 0,
label: 'Mesure nombre'
}
]
},
type: 'QuestionType'
},
{
id: 'isg3ixbk',
name: 'JESUISLELI',
label: [
'##{"label":"Je suis le libellé d\'un tableau à deux axes 1 mesure unique","conditions":[]}\nJe suis le libellé d\'un tableau à deux axes 1 mesure unique'
],
declarations: [],
redirections: [],
controls: [],
questionType: 'TABLE',
responses: [
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
},
{
codeListReference: 'isg1uorv',
datatype: {
typeName: 'TEXT',
maxLength: 1,
pattern: '',
type: 'TextDatatypeType',
visHint: 'RADIO'
}
}
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'isg1g6zo'
},
{
dimensionType: 'SECONDARY',
dynamic: 0,
codeListReference: 'isg27fpv'
},
{
dimensionType: 'MEASURE',
dynamic: 0,
label: 'Mesure unique'
}
]
},
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
},
{
id: 'iwnet09y',
name: 'EXEMPLES',
label: ['Exemples'],
declarations: [],
redirections: [],
controls: [],
genericName: 'SUBMODULE',
children: [
{
id: 'iw22jwft',
name: 'RENSEIGNEZ',
label: [
'##{"label":"Renseignez dans le tableau ci-dessous le montant des investissements spécifiquement dédiés à l\'environnement, selon leur nature et le domaine","conditions":[]}\nRenseignez dans le tableau ci-dessous le montant des investissements spécifiquement dédiés à l\'environnement, selon leur nature et le domaine'
],
declarations: [
{
declarationType: 'INSTRUCTION',
text: "Cette question est extraite de l'enquête Antipol\n",
position: 'AFTER_RESPONSE'
}
],
redirections: [],
controls: [
{
id: 'iw7ukiat',
description: '',
expression:
"(NUM(${S1-S1-Q1-R1})-(NUM(${S1-S1-Q3-R1})+NUM(${S1-S1-Q3-R2})+NUM(${S1-S1-Q3-R3})+NUM(${S1-S1-Q3-R4})+NUM(${S1-S1-Q3-R5})+NUM(${S1-S1-Q3-R6})+NUM(${S1-S1-Q3-R7})+NUM(${S1-S1-Q3-R8})+NUM(${S1-S1-Q3-R9})+NUM(${S1-S1-Q3-R10})+NUM(${S1-S1-Q3-R11})+NUM(${S1-S1-Q3-R12})+NUM(${S1-S1-Q3-R13})+NUM(${S1-S1-Q3-R14})+NUM(${S1-S1-Q3-R15})+NUM(${S1-S1-Q3-R16})+NUM(${S1-S1-Q3-R17})+NUM(${S1-S1-Q3-R18})+NUM(${S1-S1-Q3-R19})+NUM(${S1-S1-Q3-R20})+NUM(${S1-S1-Q3-R21})+NUM(${S1-S1-Q3-R22})+NUM(${S1-S1-Q3-R23})+NUM(${S1-S1-Q3-R24}))<0 ) and ${S1-S1-Q1-R1}!=''", // eslint-disable-line no-template-curly-in-string
failMessage:
"Le montant des investissements spécifiquement dédiés à l'environnement est supérieur au montant total des investissements."
}
],
questionType: 'TABLE',
responses: [
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
},
{
datatype: {
typeName: 'NUMERIC',
minimum: 0,
maximum: null,
decimals: null,
type: 'NumericDatatypeType'
}
}
],
responseStructure: {
dimensions: [
{
dimensionType: 'PRIMARY',
dynamic: 0,
codeListReference: 'iw22r14q'
},
{
dimensionType: 'SECONDARY',
dynamic: 0,
codeListReference: 'iw22dla9'
},
{
dimensionType: 'MEASURE',
dynamic: 0,
label: 'Montant des investissements en Keuros'
}
]
},
type: 'QuestionType'
}
],
depth: 2,
type: 'SequenceType'
}
],
depth: 1,
type: 'SequenceType'
}
],
depth: 0,
type: 'SequenceType',
agency: 'fr.insee',
survey: { agency: 'fr.insee', name: 'POPO' },
componentGroups: [
{
name: 'PAGE_1',
label: 'Components for page 1',
Member: [
'ir6cju1z',
'iwm8qg8x',
'iwm8r0ba',
'ir6co0qf',
'ir6cqzev',
'ir6cm77g',
'ir6cruy6',
'ir6cifax',
'ir6cmuqa',
'ir6ctbkt',
'ir6ct69u',
'isg1kh8l',
'isg1hh9m',
'iwnfdy97',
'iwm6shxx',
'iwm8woim',
'iw7ux0w8',
'iwm8v2g4',
'iwm8t2p5',
'iwm99upn',
'iwnevs21',
'isg1ikbn',
'isg13cuk',
'isg1hq0f',
'isg1bz8h',
'iwnesc00',
'iw22nmhl',
'iwm6zyaq',
'iwm9e4pi',
'isg1gytw',
'isg1j5rw',
'isg1gjjt',
'isg20r8n',
'isg1uc3w',
'iwnevbej',
'iwm8wtis',
'iwm8xktl',
'isg1qnrf',
'isg24et5',
'isg1s9ho',
'isg28ywr',
'isg1rx4a',
'iwnexpuc',
'iw22jcng',
'iwncfpwn',
'isg1x9p9',
'isg1v5d2',
'isg3ixbk',
'iwnet09y',
'iw22jwft'
],
id: 'j3ft4xup'
}
],
codeLists: {
codeList: [
{
id: 'isg1g6zo',
name: '',
label: 'LISTE_TEST',
codes: [
{ label: 'choix 1', value: '' },
{ label: 'choix 2', value: '' },
{ label: 'choix 3', value: '' },
{ label: 'choix 4', value: '' },
{ label: 'choix 5', value: '' }
]
},
{
id: 'isg1uorv',
name: '',
label: 'Oui_Non',
codes: [{ label: 'Oui', value: '' }, { label: 'Non', value: '' }]
},
{
id: 'isg27fpv',
name: '',
label: 'LISTE_TEST_2',
codes: [
{ label: 'choix 6', value: '' },
{ label: 'choix 7', value: '' },
{ label: 'choix 8', value: '' },
{ label: 'choix 9', value: '' }
]
},
{
id: 'iw22dla9',
name: '',
label: 'DOMAINE',
codes: [
{ label: 'Eaux usées', value: '' },
{ label: 'Déchets hors radioactifs', value: '' },
{ label: 'Protection de l’air', value: '' },
{
label: 'Limitation des émissions de gaz à effet de serre',
value: ''
},
{ label: 'Bruits et vibrations', value: '' },
{ label: 'Sols, eaux souterraines et de surface', value: '' },
{ label: 'Sites, paysages et biodiversité', value: '' },
{
label: 'Autres (rayonnement, R&D sur l’environnement…)',
value: ''
}
]
},
{
id: 'iw22fswu',
name: '',
label: 'L_SEXE',
codes: [
{ label: 'Masculin', value: '' },
{ label: 'Féminin', value: '' }
]
},
{
id: 'iw22r14q',
name: '',
label: 'NATURE',
codes: [
{ label: 'Pré-traitement, traitement et élimination', value: '' },
{ label: 'Mesure et contrôle', value: '' },
{ label: 'Recyclage, tri et valorisation', value: '' },
{ label: 'Prévention des pollutions', value: '' }
]
},
{
id: 'iw22xe2u',
name: '',
label: 'L_effectifs',
codes: [
{ label: 'Effectifs salariés à temps plein', value: '' },
{
label: 'Effectifs salariés à temps partiel moins de 6 mois',
value: ''
},
{
label: 'Effectifs salariés à temps partiel 6 mois et plus',
value: ''
},
{ label: 'Apprentis, stagiaires rémunérés', value: '' },
{ label: 'Total', value: '' }
]
},
{
id: 'iw25euzq',
name: '',
label: 'L_GLACE',
codes: [
{ label: 'vanille', value: '' },
{ label: 'chocolat', value: '' },
{ label: 'fraise', value: '' },
{ label: 'abricot', value: '' },
{ label: 'citron', value: '' },
{ label: 'rhum raisins', value: '' }
]
},
{
id: 'iw25voxc',
name: '',
label: 'L_fréquence',
codes: [
{ label: 'Toujours', value: '' },
{ label: 'Souvent', value: '' },
{ label: 'Parfois', value: '' },
{ label: 'Jamais', value: '' }
]
},
{
id: 'iwg8titv',
name: '',
label: 'LIST_ONE',
codes: [
{ label: 'Item 1', value: '' },
{ label: 'Item 2', value: '' },
{ label: 'Item 3', value: '' },
{ label: 'Item 4', value: '' },
{ label: 'Item 5', value: '' }
]
},
{ id: 'iwgdyhwp', name: '', label: '', codes: [] },
{
id: 'iwgdzvye',
name: '',
label: 'weather_list',
codes: [
{ label: 'sunny', value: '' },
{ label: 'cloudy', value: '' },
{ label: 'rainy', value: '' },
{ label: "a mix of all, I'm in Brittany", value: '' }
]
},
{
id: 'iwge4s84',
name: '',
label: 'LIST_TWO',
codes: [
{ label: 'item 6', value: '' },
{ label: 'item 7', value: '' },
{ label: 'item 8', value: '' },
{ label: 'item 9', value: '' },
{ label: 'item 10', value: '' }
]
},
{
id: 'iwgebn3a',
name: '',
label: 'EVENING',
codes: [
{ label: 'Drink some beers', value: '' },
{ label: 'Go to cinema', value: '' },
{ label: 'Watch a movie at home', value: '' },
{ label: 'Cook good meals for my friends', value: '' },
{ label: 'Read a novel', value: '' }
]
},
{
id: 'iwgeg7ek',
name: '',
label: 'LIST_SEX_EN',
codes: [{ label: 'Man', value: '' }, { label: 'Woman', value: '' }]
},
{
id: 'iwgehiif',
name: '',
label: 'Yes_No_EN',
codes: [{ label: 'Yes', value: '' }, { label: 'No', value: '' }]
},
{
id: 'iwm8rfv5',
name: '',
label: 'L_TIC_TPE',
codes: [
{
label:
'La commande ou la réservation en ligne (panier virtuel) ?',
value: ''
},
{
label:
'La description de biens ou services, ou des listes de prix ?',
value: ''
},
{
label:
'Des liens permettant d’accéder aux pages de l’entreprise dans les médias sociaux (Facebook, Twitter, Google+, LinkedIn, Viadeo, etc.) ?',
value: ''
}
]
},
{
id: 'iwm8rneb',
name: '',
label: 'L_ventes',
codes: [
{ label: 'A des particuliers', value: '' },
{ label: 'A des professionnels ou revendeurs', value: '' }
]
},
{
id: 'iwm8zloc',
name: '',
label: 'L_activite',
codes: [
{ label: 'à temps complet', value: '' },
{ label: 'à temps partiel 80 % ou plus', value: '' },
{ label: 'de mi-temps à moins de 80 %', value: '' },
{ label: 'moins d’un mi-temps', value: '' }
]
},
{
id: 'iwm9fhue',
name: '',
label: 'L_formation',
codes: [
{
label:
'Formation financée ou organisée par l’employeur ou une agence d’intérim (hors apprentissage et contrats de professionnalisation)',
value: ''
},
{
label:
'Formation donnée par une école de la 2e chance, par l’EPIDE',
value: ''
},
{
label:
'Formation conseillée ou organisée par Pôle emploi, par une mission locale, une chambre des métiers, une agence de placement (APEC, INGEUS, …), (y compris ateliers de techniques de recherche d’emploi, ateliers CV)',
value: ''
},
{
label:
'Une formation professionnalisante ou à but professionnel (pour trouver un emploi, améliorer votre situation, …)',
value: ''
},
{
label:
'Aucune de ces formations depuis la fin des études, même pour quelques jours',
value: ''
}
]
}
],
codeListSpecification: []
}
}
];
export default questionnaires;
| Zenika/Pogues | src/utils/model/__mocks__/questionnaires.js | JavaScript | mit | 93,585 |
/* eslint import/prefer-default-export: 0 */
export { default as Brush } from './Brush';
| williaster/data-ui | packages/xy-chart/src/utils/brush/index.js | JavaScript | mit | 89 |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["FormidableReactComponentBoilerplate"] = factory(require("react"));
else
root["FormidableReactComponentBoilerplate"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
module.exports = {
FormidableReactComponentBoilerplate: __webpack_require__(1)
};
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var FormidableReactComponentBoilerplate = (function (_React$Component) {
_inherits(FormidableReactComponentBoilerplate, _React$Component);
function FormidableReactComponentBoilerplate() {
_classCallCheck(this, FormidableReactComponentBoilerplate);
_get(Object.getPrototypeOf(FormidableReactComponentBoilerplate.prototype), "constructor", this).apply(this, arguments);
}
_createClass(FormidableReactComponentBoilerplate, [{
key: "render",
value: function render() {
return _react2["default"].createElement(
"div",
null,
"Edit me!"
);
}
}]);
return FormidableReactComponentBoilerplate;
})(_react2["default"].Component);
exports["default"] = FormidableReactComponentBoilerplate;
module.exports = exports["default"];
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ }
/******/ ])
});
;
//# sourceMappingURL=formidable-react-component-boilerplate.js.map | FormidableLabs/formidable-react-component-boilerplate | dist/formidable-react-component-boilerplate.js | JavaScript | mit | 5,326 |
/**
* Created by Ivanna on 13.05.2015.
*/
$(function(){
$('.owl-item').height(document.body.clientWidth/3);
$(window).resize(function(){
$('.owl-item').height(document.body.clientWidth/3);
});
});
function textSliderCentr(count) { /* Центрування тексту картинки слайдеру*/
for(var i=1;i<=count;i++){
var elHalfWidth=$('.about'+i).css('width').slice(0, -2)/2;
$('.about'+i).css('margin-left', (document.body.clientWidth*$('.about'+i).attr('left')/100-elHalfWidth)+'px');
}
}
function sliderBoxCentr() { /* Центрування центрального боксу слайдера*/
$('#sliderCenterBox').css('margin-top', document.body.clientWidth/3/2+'px');
}
$(function() { sliderBoxCentr(); });
$(window).resize(function() { sliderBoxCentr(); });
function centrSliderButtons() { /* центрування кнопок прокрутки слайдеру*/
$('.owl-controls').css('margin-left', '0');
$('.owl-controls').css('left', '8%');
$('.owl-controls').css('width', 'auto');
}
$(function() { centrSliderButtons(); });
$(window).resize(function() { centrSliderButtons(); });
| ITAAcademy/KievStatic | js/sliderAboutUs.js | JavaScript | mit | 1,180 |
module.exports = function sample(){
return this.type
}
| stylish/stylish | packages/skypager-project/test/fixture/exporters/sample.js | JavaScript | mit | 57 |
/*
WebsocketRails JavaScript Client
Setting up the dispatcher:
var dispatcher = new WebSocketRails('localhost:3000/websocket');
dispatcher.on_open = function() {
// trigger a server event immediately after opening connection
dispatcher.trigger('new_user',{user_name: 'guest'});
})
Triggering a new event on the server
dispatcherer.trigger('event_name',object_to_be_serialized_to_json);
Listening for new events from the server
dispatcher.bind('event_name', function(data) {
console.log(data.user_name);
});
Stop listening for new events from the server
dispatcher.unbind('event')
*/
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
this.WebSocketRails = (function() {
function WebSocketRails(url, use_websockets) {
this.url = url;
this.use_websockets = use_websockets != null ? use_websockets : true;
this.connection_stale = __bind(this.connection_stale, this);
this.supports_websockets = __bind(this.supports_websockets, this);
this.dispatch_channel = __bind(this.dispatch_channel, this);
this.unsubscribe = __bind(this.unsubscribe, this);
this.subscribe_private = __bind(this.subscribe_private, this);
this.subscribe = __bind(this.subscribe, this);
this.dispatch = __bind(this.dispatch, this);
this.trigger_event = __bind(this.trigger_event, this);
this.trigger = __bind(this.trigger, this);
this.bind = __bind(this.bind, this);
this.connection_established = __bind(this.connection_established, this);
this.new_message = __bind(this.new_message, this);
this.reconnect = __bind(this.reconnect, this);
this.callbacks = {};
this.channels = {};
this.queue = {};
this.connect();
}
WebSocketRails.prototype.connect = function() {
this.state = 'connecting';
if (!(this.supports_websockets() && this.use_websockets)) {
this._conn = new WebSocketRails.HttpConnection(this.url, this);
} else {
this._conn = new WebSocketRails.WebSocketConnection(this.url, this);
}
return this._conn.new_message = this.new_message;
};
WebSocketRails.prototype.disconnect = function() {
if (this._conn) {
this._conn.close();
delete this._conn._conn;
delete this._conn;
}
return this.state = 'disconnected';
};
WebSocketRails.prototype.reconnect = function() {
var event, id, old_connection_id, _ref, _ref1;
old_connection_id = (_ref = this._conn) != null ? _ref.connection_id : void 0;
this.disconnect();
this.connect();
_ref1 = this.queue;
for (id in _ref1) {
event = _ref1[id];
if (event.connection_id === old_connection_id && !event.is_result()) {
this.trigger_event(event);
}
}
return this.reconnect_channels();
};
WebSocketRails.prototype.new_message = function(data) {
var event, _ref;
event = new WebSocketRails.Event(data);
if (event.is_result()) {
if ((_ref = this.queue[event.id]) != null) {
_ref.run_callbacks(event.success, event.data);
}
this.queue[event.id] = null;
} else if (event.is_channel()) {
this.dispatch_channel(event);
} else {
this.dispatch(event);
}
if (this.state === 'connecting' && event.name === 'client_connected') {
return this.connection_established(event);
}
};
WebSocketRails.prototype.connection_established = function(event) {
this.state = 'connected';
this._conn.setConnectionId(event.connection_id);
this._conn.flush_queue();
if (this.on_open != null) {
return this.on_open(event.data);
}
};
WebSocketRails.prototype.bind = function(event_name, callback) {
var _base;
if ((_base = this.callbacks)[event_name] == null) {
_base[event_name] = [];
}
return this.callbacks[event_name].push(callback);
};
WebSocketRails.prototype.trigger = function(event_name, data, success_callback, failure_callback) {
var event;
event = new WebSocketRails.Event([
event_name, data, {
connection_id: this.connection_id
}
], success_callback, failure_callback);
this.queue[event.id] = event;
return this._conn.trigger(event);
};
WebSocketRails.prototype.trigger_event = function(event) {
var _base, _name;
if ((_base = this.queue)[_name = event.id] == null) {
_base[_name] = event;
}
this._conn.trigger(event);
return event;
};
WebSocketRails.prototype.dispatch = function(event) {
var callback, _i, _len, _ref, _results;
if (this.callbacks[event.name] == null) {
return;
}
_ref = this.callbacks[event.name];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
callback = _ref[_i];
_results.push(callback(event.data));
}
return _results;
};
WebSocketRails.prototype.subscribe = function(channel_name, success_callback, failure_callback) {
var channel;
if (this.channels[channel_name] == null) {
channel = new WebSocketRails.Channel(channel_name, this, false, success_callback, failure_callback);
this.channels[channel_name] = channel;
return channel;
} else {
return this.channels[channel_name];
}
};
WebSocketRails.prototype.subscribe_private = function(channel_name, success_callback, failure_callback) {
var channel;
if (this.channels[channel_name] == null) {
channel = new WebSocketRails.Channel(channel_name, this, true, success_callback, failure_callback);
this.channels[channel_name] = channel;
return channel;
} else {
return this.channels[channel_name];
}
};
WebSocketRails.prototype.unsubscribe = function(channel_name) {
if (this.channels[channel_name] == null) {
return;
}
this.channels[channel_name].destroy();
return delete this.channels[channel_name];
};
WebSocketRails.prototype.dispatch_channel = function(event) {
if (this.channels[event.channel] == null) {
return;
}
return this.channels[event.channel].dispatch(event.name, event.data);
};
WebSocketRails.prototype.supports_websockets = function() {
return typeof WebSocket === "function" || typeof WebSocket === "object";
};
WebSocketRails.prototype.connection_stale = function() {
return this.state !== 'connected';
};
WebSocketRails.prototype.reconnect_channels = function() {
var callbacks, channel, name, _ref, _results;
_ref = this.channels;
_results = [];
for (name in _ref) {
channel = _ref[name];
callbacks = channel._callbacks;
channel.destroy();
delete this.channels[name];
channel = channel.is_private ? this.subscribe_private(name) : this.subscribe(name);
channel._callbacks = callbacks;
_results.push(channel);
}
return _results;
};
return WebSocketRails;
})();
}).call(this);
| websocket-rails/websocket-rails-js | src/websocket_rails/websocket_rails.js | JavaScript | mit | 7,219 |
$(function() {
$("#btnOpenAddNew").click(function(){
$("#frmSalePromotion")[0].reset();
});
$("#frmSalePromotion")
.submit(
function(event) {
event.preventDefault();
modal = UIkit.modal.blockUI("<div class='uk-text-center'>Processing...<br/><img class='uk-margin-top' src='"+SITE_URL+"public/assets/img/spinners/spinner.gif' alt=''");
$.ajax({
type : "POST",
url : SITE_URL + "salepromotion/addsalepromotion",
dataType : 'json',
data : {
code : $.trim($("#code").val()),
name : $.trim($("#name").val()),
description : $.trim($("#description").val()),
//type : $.trim($("#type").val()),
/*start_date : $.trim($("#start_date").val()),
end_date : $.trim($("#end_date").val())*/
},success: function(data){
console.log(data);
if(data["ERROR"]==true){
console.log(data["MSG"]);
modal.hide();
if(data["FIELD"] == "CODE"){
$("#msg").text("Code has already existed.");
$("#code").css('border-color','red').focus();
}else if(data["FIELD"] == "NAME"){
$("#msg").text("Name has already existed.");
$("#name").css('border-color','red').focus();
}else{
$("#msg").text("Name and code have already existed.");
$("#name").css('border-color','red').focus();
$("#code").css('border-color','red').focus();
}
$("#msgError").fadeIn(2500);
}else{
UIkit.modal.alert(data["MSG"]);
console.log(data["MSG"]);
setTimeout(function(){
location.href= SITE_URL + "salepromotion";
}, 1000);
}
},
error: function(data){
modal.hide();
console.log("ERROR" + data );
}
});
});
$(document).on('click','#btnUpdate', function(){
var id = $(this).attr("data");
modal = UIkit.modal.blockUI("<div class='uk-text-center'>Processing...<br/><img class='uk-margin-top' src='"+SITE_URL+"public/assets/img/spinners/spinner.gif' alt=''");
$.ajax({
url: SITE_URL+'salepromotion/update/'+id,
type: "GET",
dataType: "JSON",
success: function(data){
console.log("Success " +data.code);
/*var $selectType = $("#type").selectize();
var selectType = $selectType[0].selectize;*/
$("#code").val(data.code);
$("#oldcode").val(data.code);
$("#name").val(data.name);
$("#oldname").val(data.name);
//selectType.setValue(data.type);
/*$("#start_date").val(data.start_date);
$("#end_date").val(data.end_date);*/
$("#description").val(data.description);
modal.hide();
$("#btnSave").hide();
$("#btnUpdateSave").attr('data',data.id);
$("#btnUpdateSave").show();
var modalPopup = UIkit.modal("#modalSalePromotion");
if ( modalPopup.isActive() ) {
modalPopup.hide();
} else {
modalPopup.show();
}
$('.md-input-wrapper').addClass('md-input-filled');
},
error: function(data){
console.log("Error" + data);
modal.hide();
UIkit.modal.alert(data.message);
}
});
});
$("#btnUpdateSave").click(function(){
modal = UIkit.modal.blockUI("<div class='uk-text-center'>Processing...<br/><img class='uk-margin-top' src='"+SITE_URL+"public/assets/img/spinners/spinner.gif' alt=''");
var id = $(this).attr('data');
$.ajax({
url: SITE_URL+'salepromotion/updatesalepromotion/'+id,
type: "POST",
dataType: "JSON",
data : {
code : $.trim($("#code").val()),
name : $.trim($("#name").val()),
oldname : $.trim($("#oldname").val()),
oldcode : $.trim($("#oldcode").val()),
description : $.trim($("#description").val())
//type : $.trim($("#type").val()),
/*start_date : $.trim($("#start_date").val()),
end_date : $.trim($("#end_date").val())*/
},
success: function(data){
console.log(data);
if(data["ERROR"]==true){
console.log(data["MSG"]);
modal.hide();
if(data["FIELD"] == "CODE"){
$("#msg").text("Code has already existed.");
$("#code").css('border-color','red').focus();
}else if(data["FIELD"] == "NAME"){
$("#msg").text("Name has already existed.");
$("#name").css('border-color','red').focus();
}else{
$("#msg").text("Name and code have already existed.");
$("#name").css('border-color','red').focus();
$("#code").css('border-color','red').focus();
}
$("#msgError").fadeIn(2500);
}else{
UIkit.modal.alert(data["MSG"]);
console.log(data);
setTimeout(function(){
location.href= SITE_URL + "salepromotion";
}, 1000);
}
},
error: function(data){
modal.hide();
console.log("ERROR" + data );
}
});
});
}); | phengtola/UnileverPro | public/scripts/salepromotion.js | JavaScript | mit | 4,886 |
/**
* Created by wizard on 28/09/15.
*/
module.exports = (function(){
var $nextButton = $('#next'),
$references = $('#references'),
$referenceTmpl = $('#references-tmpl'),
page = 1,
$spinner = $('#spinner'),
getNextReferences = function () {
return $.ajax({
url: '/wp/wp-admin/admin-ajax.php',
type: 'get',
dataType: 'json',
data: {
action: 'get_references',
post_id: $references.data('postId'),
page: page
},
beforeSend: function () {
showSpinner();
},
success: function (response) {
showNextReferences(response.data);
if (page >= $references.data('pageCount')) { hideNextButton(); }
},
error: function (jqXHR, status, err) {
console.log(status);
console.log(err);
$spinner.addClass('hide');
}
});
},
hideSpinner = function () {
$spinner.addClass('hide');
},
showSpinner = function () {
$spinner.removeClass('hide');
},
hideNextButton = function () {
$nextButton.addClass('hide');
},
newReferences = function () {
return $references.find('.new-references').last();
},
showNextReferences = function (references) {
console.log(references);
Mustache.parse($referenceTmpl.html());
$references.append(Mustache.render($referenceTmpl.html(), { references: references } ));
hideSpinner();
setTimeout(function () {
newReferences().addClass('new-references-show');
},100);
},
loadNextReferences = function(){
$nextButton.click(function (event) {
page++;
event.preventDefault();
getNextReferences();
});
};
return {
init: function() {
loadNextReferences();
}
};
})(); | wizard2nd/rizikove_kaceni_teplice | web/app/themes/rizikove_kaceni_sage_based/assets/scripts/pages/references.js | JavaScript | mit | 2,289 |
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var RotateMatrix = require('./RotateMatrix');
/**
* Rotates the array matrix 180 degrees.
*
* @function Phaser.Utils.Array.Matrix.Rotate180
* @since 3.0.0
*
* @param {array} matrix - The array to rotate.
*
* @return {array} The rotated matrix array. The source matrix should be discard for the returned matrix.
*/
var Rotate180 = function (matrix)
{
return RotateMatrix(matrix, 180);
};
module.exports = Rotate180;
| englercj/phaser | src/utils/array/matrix/Rotate180.js | JavaScript | mit | 632 |
/**
* Created by baidu on 15/4/9.
*/
define(function (require) {
//以require作为参数
console.log(require('app/b'));
return 'module a';
}); | xzzw9987/Memos | project/LearnRequire/scripts/lib/a.js | JavaScript | mit | 164 |