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(win) {
'use strict';
/*global console, alert, window, document */
/*global */
win.APP.BB.Unit.SkeletonModel = win.APP.BB.Unit.BaseUnitModel.extend({
defaults: win.APP.unitMaster.list.skeleton
});
})(window);
| webbestmaster/ae3 | _res/ae2-res/www/js/app/model/unit/unit-skeleton.js | JavaScript | mit | 247 |
import {Modal} from './utilities'
import {Text} from './speech'
var text = new Text(),
detailActivityActive = null
var activities = Array.from(document.querySelectorAll('.activity')),
confirmActivityWindow = new Modal('confirmActivityWindow','.contentWidth')
function RangeTolerance (options){
var developed = options.developed | false
var currentTime = new Date(),
date = options.date
date.setDate(currentTime.getDate())
date.setFullYear(currentTime.getFullYear())
date.setMonth(currentTime.getMonth())
var lowerLimit = new Date(currentTime.setMinutes(currentTime.getMinutes() - options.tolerance)),
upperLimit = new Date(currentTime.setMinutes(currentTime.getMinutes() + options.tolerance*2))
if (!developed){
if(date < lowerLimit) return options.onBefore()
else if(date > upperLimit) return options.onAfter()
else if (date >= lowerLimit && date <= upperLimit) return options.onDuring()
}else{
return options.onDuring()
}
}
activities.forEach((activity) => {
var date = new Date(activity.dataset.date),
dataDate = date.getHours() > 6 && date.getHours() < 18 ? {classcss:'morning'} : {classcss:'nigth'}
activity.querySelector('[rol=time]').innerHTML = date.toHour12()
activity.querySelector('.date').classList.add(dataDate.classcss)
activity.addEventListener('click', confirmActivity)
})
function confirmActivity () {
var reminder = this.querySelector('[data-statereminder]')
if (reminder.dataset.statereminder != 'inprocess') return text.toVoice('Ya has completado esta actiidad.')
RangeTolerance({
developed: false,
date: new Date(this.dataset.date),
tolerance: parseInt(this.dataset.tolerance),
onBefore : () => {
// text.toVoice('Vas un poco tarde, Intenta Mañana.')
text.toVoice('Vas un poco tarde.')
registerActivity.bind(this)()
},
onDuring : registerActivity.bind(this),
onAfter : () => text.toVoice('Aun no es hora de realizar esta actividad.')
})
}
function registerActivity (){
detailActivityActive = this.dataset
text.toVoice(this.dataset.speech)
var template = document.querySelector('#templateConfirmActivityWindow'),
clone = document.importNode(template.content,true)
confirmActivityWindow
.setTitle(this.dataset.text)
.addContent(clone)
.show()
}
| carlosturnerbenites/rememberHelp | src/js/activities.js | JavaScript | mit | 2,246 |
import { TextFieldComponent } from '../textfield/TextField';
import { BaseComponent } from '../base/Base';
import _defaultsDeep from 'lodash/defaultsDeep';
import _delay from 'lodash/delay';
import _get from 'lodash/get';
export class AddressComponent extends TextFieldComponent {
constructor(component, options, data) {
super(component, options, data);
let src = 'https://maps.googleapis.com/maps/api/js?v=3&libraries=places&callback=googleMapsCallback';
if (component.map && component.map.key) {
src += '&key=' + component.map.key;
}
if (component.map && component.map.region) {
src += '®ion=' + component.map.region;
}
BaseComponent.requireLibrary('googleMaps', 'google.maps.places', src);
// Keep track of the full addresses.
this.addresses = [];
}
setValueAt(index, value) {
if (value === null || value === undefined) {
value = this.defaultValue;
}
this.addresses[index] = value;
if (value && value.formatted_address) {
this.inputs[index].value = value.formatted_address;
}
}
getValueAt(index) {
return this.addresses[index];
}
/**
* Start the autocomplete and the input listeners
*
* @param input
* The input field
* @param autoCompleteOptions
* The default option for the autocompletion
*/
autoCompleteInit(input, autoCompleteOptions) {
// Set attribute autoComplete to off
input.setAttribute("autocomplete", "off");
// Init suggestions list
this.autoCompleteSuggestions = []
// Start Google AutocompleteService
const autoComplete = new google.maps.places.AutocompleteService();
// Create suggestions container
const suggestionContainer = document.createElement('div');
suggestionContainer.classList.add('pac-container', 'pac-logo');
input.parentNode.appendChild(suggestionContainer);
// Add listener on input field for input event
this.addEventListener(input, 'input', (event) => {
if (input.value) {
let options = {
input: input.value
}
autoComplete.getPlacePredictions(_defaultsDeep(options, autoCompleteOptions),
(suggestions, status) => {
this.autoCompleteDisplaySuggestions(suggestions, status, suggestionContainer, input);
});
} else {
this.autoCompleteCleanSuggestions(suggestionContainer);
suggestionContainer.style.display = 'none';
}
});
// Add listener on input field for blur event
this.addEventListener(input, 'blur', (event) => {
// Delay to allow click on suggestion list
_delay(function() {
suggestionContainer.style.display = 'none';
}, 100);
});
// Add listener on input field for focus event
this.addEventListener(input, 'focus', (event) => {
if (suggestionContainer.childElementCount) {
suggestionContainer.style.display = 'block';
}
});
// Add listener on input field for focus event
this.addEventListener(window, 'resize', (event) => {
// Set the same width as input field
suggestionContainer.style.width = input.offsetWidth + 'px';
});
// Add listiner on input field for key event
this.autoCompleteKeyboardListener(suggestionContainer, input);
}
/**
* Add listiner on input field for key event
*
* @param suggestionContainer
* Suggestions container
* @param input
* Input field to listen
*/
autoCompleteKeyboardListener(suggestionContainer, input) {
this.autoCompleteKeyCodeListener = (event) => {
if (input.value) {
switch (event.keyCode) {
case 38:
// UP
this.autoCompleteKeyUpInteraction(suggestionContainer, input);
break;
case 40:
// DOWN
this.autoCompleteKeyDownInteraction(suggestionContainer, input);
break;
case 9:
// TAB
this.autoCompleteKeyValidationInteraction(suggestionContainer, input);
break;
case 13:
// ENTER
this.autoCompleteKeyValidationInteraction(suggestionContainer, input);
break;
}
}
};
this.addEventListener(input, 'keydown', this.autoCompleteKeyCodeListener)
}
/**
* Action when key up is trigger
*
* @param suggestionContainer
* Suggestions container
* @param input
* Input field to listen
*/
autoCompleteKeyUpInteraction(suggestionContainer, input) {
let elementSelected = document.querySelector('.pac-item-selected');
if (!elementSelected) {
// Returns the bottom of the list.
return this.autoCompleteListDecorator(suggestionContainer.lastChild, input);
} else {
// Transverse the list in reverse order.
const previousSibling = elementSelected.previousSibling;
if (previousSibling) {
this.autoCompleteListDecorator(previousSibling, input);
} else {
// Return to input value
elementSelected.classList.remove('pac-item-selected');
input.value = this.autoCompleteInputValue;
}
}
}
/**
* Action when key down is trigger
*
* @param suggestionContainer
* Suggestions container
* @param input
* Input field to listen
*/
autoCompleteKeyDownInteraction(suggestionContainer, input) {
let elementSelected = document.querySelector('.pac-item-selected');
if (!elementSelected) {
// Start at the top of the list.
if (suggestionContainer.firstChild) {
return this.autoCompleteListDecorator(suggestionContainer.firstChild, input);
}
} else {
// Transverse the list from top down.
const nextSibling = elementSelected.nextSibling;
if (nextSibling) {
this.autoCompleteListDecorator(nextSibling, input);
} else {
// Return to input value
elementSelected.classList.remove('pac-item-selected');
input.value = this.autoCompleteInputValue;
}
}
}
/**
* Action when validation is trigger
*
* @param suggestionContainer
* Suggestions container
* @param input
* Input field to listen
*/
autoCompleteKeyValidationInteraction(suggestionContainer, input) {
let elementSelected = document.querySelector('.pac-item-selected');
if (elementSelected) {
for (const suggestion of this.autoCompleteSuggestions) {
let content = elementSelected.textContent || elementSelected.innerText;
if (content === suggestion.description) {
this.autoCompleteServiceListener(suggestion, suggestionContainer, input);
}
}
elementSelected.classList.remove('pac-item-selected');
}
}
/**
* Highlight suggestion selected
*
* @param item
* Item selected in suggestions container
* @param input
* Input field to listen
*/
autoCompleteListDecorator(item, input) {
let elementSelected = document.querySelector('.pac-item-selected');
if (elementSelected) {
elementSelected.classList.remove('pac-item-selected');
}
input.value = item.textContent || suggestionContainer.innerText;
item.classList.add('pac-item-selected');
}
/**
* Filter method to return if the suggestion should be displayed
*
* @param data
* Data to check
* @returns {Boolean}
*/
autoCompleteFilterSuggestion(data) {
try {
let script = '(function() { var show = true;';
script += this.component.map.autoCompleteFilter.toString();
script += '; return show; })()';
let result = eval(script);
return result.toString() === 'true';
}
catch (e) {
console.warn('An error occurred in a custom autoComplete filter statement for component ' + this.component.key, e);
return true;
}
}
/**
* Clean suggestions list
*
* @param suggestionContainer
* Container tag
*/
autoCompleteCleanSuggestions(suggestionContainer) {
// Clean click listener
for (const suggestion of this.autoCompleteSuggestions) {
suggestion.item.removeEventListener('click', suggestion.clickListener);
}
this.autoCompleteSuggestions = [];
// Delete current suggestion list
while (suggestionContainer.firstChild) {
suggestionContainer.removeChild(suggestionContainer.firstChild);
}
}
/**
* Display suggestions when API returns value
*
* @param suggestions
* Suggestions returned
* @param status
* State returned
* @param suggestionContainer
* Suggestions container
* @param input
* Input field to listen
*/
autoCompleteDisplaySuggestions(suggestions, status, suggestionContainer, input) {
// Set the same width as input field
suggestionContainer.style.width = input.offsetWidth + 'px';
// Set the default input value
this.autoCompleteInputValue = input.value;
this.autoCompleteCleanSuggestions(suggestionContainer);
if (status != google.maps.places.PlacesServiceStatus.OK) {
suggestionContainer.style.display = 'none';
return;
}
for (const suggestion of suggestions) {
if (this.autoCompleteFilterSuggestion(suggestion)) {
this.autoCompleteSuggestions.push(suggestion);
this.autoCompleteSuggestionBuilder(suggestion, suggestionContainer, input);
}
}
if (!suggestionContainer.childElementCount) {
this.autoCompleteCleanSuggestions(suggestionContainer);
suggestionContainer.style.display = 'none';
}
else {
suggestionContainer.style.display = 'block';
}
}
/**
* Draw a suggestion in the list
*
* @param suggestion
* Suggestion to draw
* @param suggestionContainer
* Suggestions container
* @param input
* Input field to listen
*/
autoCompleteSuggestionBuilder(suggestion, suggestionContainer, input) {
const item = document.createElement('div');
item.classList.add('pac-item');
const itemLogo = document.createElement('span');
itemLogo.classList.add('pac-icon', 'pac-icon-marker');
item.appendChild(itemLogo);
// Draw Main part
const itemMain = document.createElement('span');
itemMain.classList.add('pac-item-query');
if (suggestion.structured_formatting.main_text_matched_substrings) {
let matches = suggestion.structured_formatting.main_text_matched_substrings;
for(let k in matches) {
let part = matches[k];
if (k == 0 && part.offset > 0) {
itemMain.appendChild(document.createTextNode(suggestion.structured_formatting.main_text.substring(0, part.offset)));
}
const itemBold = document.createElement('span');
itemBold.classList.add('pac-matched');
itemBold.appendChild(document.createTextNode(suggestion.structured_formatting.main_text.substring(part.offset, (part.offset + part.length))));
itemMain.appendChild(itemBold);
if (k == (matches.length - 1)) {
let content = suggestion.structured_formatting.main_text.substring((part.offset + part.length));
if (content.length > 0) {
itemMain.appendChild(document.createTextNode(content));
}
}
}
}
else {
itemMain.appendChild(document.createTextNode(suggestion.structured_formatting.main_text));
}
item.appendChild(itemMain);
// Draw secondary part
if (suggestion.structured_formatting.secondary_text) {
const itemSecondary = document.createElement('span')
if (suggestion.structured_formatting.secondary_text_matched_substrings) {
let matches = suggestion.structured_formatting.secondary_text_matched_substrings;
for(let k in matches) {
let part = matches[k];
if (k == 0 && part.offset > 0) {
itemSecondary.appendChild(document.createTextNode(suggestion.structured_formatting.secondary_text.substring(0, part.offset)));
}
const itemBold = document.createElement('span');
itemBold.classList.add('pac-matched');
itemBold.appendChild(document.createTextNode(suggestion.structured_formatting.secondary_text.substring(part.offset, (part.offset + part.length))));
itemSecondary.appendChild(itemBold);
if (k == (matches.length - 1)) {
let content = suggestion.structured_formatting.secondary_text.substring((part.offset + part.length));
if (content.length > 0) {
itemSecondary.appendChild(document.createTextNode(content));
}
}
}
}
else {
itemSecondary.appendChild(document.createTextNode(suggestion.structured_formatting.secondary_text));
}
item.appendChild(itemSecondary);
}
suggestionContainer.appendChild(item);
let clickListener = (event) => {
input.value = suggestion.description;
this.autoCompleteInputValue = suggestion.description;
this.autoCompleteServiceListener(suggestion, suggestionContainer, input);
};
suggestion.clickListener = clickListener;
suggestion.item = item;
if ('addEventListener' in item){
item.addEventListener('click', clickListener, false);
} else if ('attachEvent' in item) {
item.attachEvent('onclick', clickListener);
}
}
/**
* Get detailed information and set it as value
*
* @param suggestion
* Suggestion to draw
* @param suggestionContainer
* Suggestions container
* @param input
* Input field to listen
*/
autoCompleteServiceListener(suggestion, suggestionContainer, input) {
const service = new google.maps.places.PlacesService(input);
service.getDetails({
placeId: suggestion.place_id,
}, (place, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
this.setValue(place);
}
});
}
addInput(input, container) {
super.addInput(input, container);
BaseComponent.libraryReady('googleMaps').then(() => {
let autoCompleteOptions = {};
if (this.component.map) {
autoCompleteOptions = this.component.map.autoCompleteOptions || {};
if (autoCompleteOptions.location) {
autoCompleteOptions.location = new google.maps.LatLng(autoCompleteOptions.location.lat, autoCompleteOptions.location.lng);
}
}
if (this.component.map && this.component.map.autoCompleteFilter) {
// Call custom autoComplete to filter suggestions
this.autoCompleteInit(input, autoCompleteOptions);
}
else {
let autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener("place_changed", () => this.setValue(autocomplete.getPlace()));
}
});
}
elementInfo() {
let info = super.elementInfo();
info.attr.class += ' address-search';
return info;
}
get view() {
const value = this.getValue();
return _get(value, 'formatted_address', '');
}
}
| GuillaumeSmaha/formio.js | src/components/address/Address.js | JavaScript | mit | 14,889 |
/* globals Stats, dat*/
'use strict';
var VJS = VJS || {};
VJS.loaders = VJS.loaders || {};
VJS.loaders.dicom = require('../../src/loaders/loaders.dicom');
VJS.controls = VJS.controls || {};
VJS.controls.orbitControls2D = require('../../src/controls/OrbitControls2D');
VJS.shaders = VJS.shaders || {};
VJS.shaders.data = require('../../src/shaders/shaders.data');
var glslify = require('glslify');
var VJS = VJS || {};
// standard global variables
var controls, renderer, stats, scene, camera, bbox, bboxMin, bboxMax, spheres, directions, steps, testSpheres;
// FUNCTIONS
function init() {
testSpheres = {
'nbSpheres': 20
};
// this function is executed on each animation frame
function animate() {
// update spheres positions
if (spheres && spheres.length === testSpheres.nbSpheres) {
for (var i = 0; i < testSpheres.nbSpheres; i++) {
if (spheres[i].position.x >= bbox[1].x) {
directions[i].x = -1;
} else if (spheres[i].position.x <= bbox[0].x) {
directions[i].x = 1;
}
if (spheres[i].position.y >= bbox[1].y) {
directions[i].y = -1;
} else if (spheres[i].position.y <= bbox[0].y) {
directions[i].y = 1;
}
if (spheres[i].position.z >= bbox[1].z) {
directions[i].z = -1;
} else if (spheres[i].position.z <= bbox[0].z) {
directions[i].z = 1;
}
spheres[i].position.x += directions[i].x * steps[i].x;
spheres[i].position.y += directions[i].y * steps[i].y;
spheres[i].position.z += directions[i].z * steps[i].z;
}
}
// render
controls.update();
renderer.render(scene, camera);
stats.update();
// request new frame
requestAnimationFrame(function() {
animate();
});
}
// renderer
var threeD = document.getElementById('r3d');
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(threeD.offsetWidth, threeD.offsetHeight);
renderer.setClearColor(0xFFFFFF, 1);
var maxTextureSize = renderer.context.getParameter(renderer.context.MAX_TEXTURE_SIZE);
window.console.log(maxTextureSize);
threeD.appendChild(renderer.domElement);
// stats
stats = new Stats();
threeD.appendChild(stats.domElement);
// scene
scene = new THREE.Scene();
// camera
camera = new THREE.PerspectiveCamera(45, threeD.offsetWidth / threeD.offsetHeight, 1, 10000000);
camera.position.x = 150;
camera.position.y = 150;
camera.position.z = 100;
camera.lookAt(scene.position);
// controls
controls = new VJS.controls.orbitControls2D(camera, renderer.domElement);
animate();
}
function createSphere(position, material) {
var direction = new THREE.Vector3(Math.random() < 0.5 ? -1 : 1, Math.random() < 0.5 ? -1 : 1, Math.random() < 0.5 ? -1 : 1);
var step = new THREE.Vector3(Math.random(), Math.random(), Math.random());
var radius = Math.floor((Math.random() * 30) + 1);
var sphereGeometry = new THREE.SphereGeometry(radius, 32, 32);
var sphere = new THREE.Mesh(sphereGeometry, material);
sphere.position.x = bbox[0].x + (bbox[1].x - bbox[0].x) / 2;
sphere.position.y = bbox[0].y + (bbox[1].y - bbox[0].y) / 2;
sphere.position.z = bbox[0].z + (bbox[1].z - bbox[0].z) / 2;
spheres.push(sphere);
directions.push(direction);
steps.push(step);
scene.add(sphere);
}
window.onload = function() {
// init threeJS...
init();
var file = '../../data/dcm/fruit.dcm.tar';
// instantiate the loader
var loader = new VJS.loaders.dicom();
loader.load(
file,
// on load
function(series) {
// float textures to shaders
//http://jsfiddle.net/greggman/upZ7V/
//http://jsfiddle.net/greggman/LMbhk/
// merge images if needed!
window.console.log('all parsed');
// those operations could be async too!
// prepare the texture!
var stack = series._stack[0];
window.console.log(stack);
// compute convenience vars (such as ijk2LPS matrix for the stack, re-order frames based on position)
stack.prepare();
// make a box!
var geometry = new THREE.BoxGeometry(896, 896, 60); // box is centered on 0,0,0
// we want first voxel of the box to be centered on 0,0,0
geometry.applyMatrix(new THREE.Matrix4().makeTranslation(448, 448, 30));
// go the LPS space
geometry.applyMatrix(stack._ijk2LPS);
var material = new THREE.MeshBasicMaterial({
wireframe: true,
color: 0x61F2F3
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// pass formated raw data from stack to webGL texture
var textures = [];
for (var m = 0; m < stack._rawData.length; m++) {
var tex = new THREE.DataTexture(stack._rawData[m], stack._textureSize, stack._textureSize, THREE.RGBAFormat, THREE.UnsignedByteType, THREE.UVMapping, THREE.ClampToEdgeWrapping, THREE.ClampToEdgeWrapping, THREE.NearestFilter, THREE.NearestFilter);
tex.needsUpdate = true;
textures.push(tex);
}
// update uniforms
var uniforms = VJS.shaders.data.parameters.uniforms;
uniforms.uTextureSize.value = stack._textureSize;
uniforms.uTextureContainer.value = textures;
uniforms.uDataDimensions.value = new THREE.Vector3(stack._columns, stack._rows, stack._numberOfFrames);
uniforms.uWorldToData.value = stack._lps2IJK;
uniforms.uNumberOfChannels.value = stack._numberOfChannels;
uniforms.uBitsAllocated.value = stack._bitsAllocated;
uniforms.uWindowLevel.value = stack._windowLevel;
uniforms.uInvert.value = stack._invert;
// create material
var sliceMaterial = new THREE.ShaderMaterial({
// 'wireframe': true,
'side': THREE.DoubleSide,
'transparency': true,
'uniforms': uniforms,
'vertexShader': glslify('../../src/shaders/shaders.data.vert'),
'fragmentShader': glslify('../../src/shaders/shaders.data.frag')
});
// create all the spheres with a "slice material" material
// get LPS BBox to know where to position the sphere
bboxMax = new THREE.Vector3(896, 896, 60).applyMatrix4(stack._ijk2LPS);
bboxMin = new THREE.Vector3(0, 0, 0).applyMatrix4(stack._ijk2LPS);
bbox = [
new THREE.Vector3(Math.min(bboxMin.x, bboxMax.x), Math.min(bboxMin.y, bboxMax.y), Math.min(bboxMin.z, bboxMax.z)),
new THREE.Vector3(Math.max(bboxMin.x, bboxMax.x), Math.max(bboxMin.y, bboxMax.y), Math.max(bboxMin.z, bboxMax.z))
];
var bboxCenter = new THREE.Vector3(
bbox[0].x + (bbox[1].x - bbox[0].x) / 2,
bbox[0].y + (bbox[1].y - bbox[0].y) / 2,
bbox[0].z + (bbox[1].z - bbox[0].z) / 2);
spheres = [];
directions = [];
steps = [];
for (var i = 0; i < testSpheres.nbSpheres; i++) {
createSphere(bboxCenter, sliceMaterial);
}
var gui = new dat.GUI({
autoPlace: false
});
var customContainer = document.getElementById('my-gui-container');
customContainer.appendChild(gui.domElement);
var ballsFolder = gui.addFolder('Spheres');
var numberOfSpheresUpdate = ballsFolder.add(testSpheres, 'nbSpheres', 1, 100).step(1);
ballsFolder.open();
numberOfSpheresUpdate.onChange(function(value) {
var diff = value - spheres.length;
if (diff > 0) {
for (var j = 0; j < diff; j++) {
createSphere(bboxCenter, sliceMaterial);
}
} else if (diff < 0) {
diff = Math.abs(diff);
for (var k = 0; k < diff; k++) {
scene.remove(spheres[0]);
spheres.shift();
directions.shift();
steps.shift();
}
}
});
},
// progress
function() {},
// error
function() {}
);
};
| pieper/vjs | examples/texture_data/texture_data.js | JavaScript | mit | 8,257 |
'use strict';
//npm imports
import $ from 'jquery';
//module imports
//import { example } from 'example/example';
const //hooks
_module = $('.JS-example'),
_target = $('.JS-example__target'),
_trigger = $('.JS-example__trigger');
const //classes
open_ = '-example--open';
//module functionality
class example {
constructor(elem){
const This = this;
this.elem = elem;
this.$elem = $(elem);
this.$elem.find(_trigger).click(function(e){
e.preventDefault();
//This.exampleMethod($(this));
})
}
//Description for example function
exampleMethod(_this){
//_this.doStuff();
}
}
//This function is called on page load unless the name of this file starts with an underscore
export default function() {
console.log('The example module javascript has loaded');
_module.each(function(e){
new example(this);
})
}
| Dan503/flexible-grid | src/_1_modules/example/_example.js | JavaScript | mit | 842 |
const minimax = (function () {
const winningPositions = [
'012', '036', '048', '147', '258', '345', '678', '246'
];
const winningDirections = {
'012': 'final-180',
'345': 'final-180',
'678': 'final-180',
'036': 'final-90',
'147': 'final-90',
'258': 'final-90',
'048': 'final-45',
'246': 'final-135'
};
const arrayToBoard = {
0: 'topLeft',
1: 'topMiddle',
2: 'topRight',
3: 'centerLeft',
4: 'centerMiddle',
5: 'centerRight',
6: 'bottomLeft',
7: 'bottomMiddle',
8: 'bottomRight'
};
const boardToArray = Object.keys(arrayToBoard).reduce((acc, key) => {
acc[arrayToBoard[key]] = key;
return acc;
}, {});
function all (arr, pred) {
let hasAll = true;
arr.forEach(elem => {
if (!pred(elem)) {
hasAll = false;
}
});
return hasAll;
}
const mini = {};
mini.choice = [];
mini.diff = function (oldBoard, newBoard) {
return newBoard.reduce((acc, curr, index) => {
if (curr !== oldBoard[index]) {
/*eslint-disable*/
acc = index;
/*eslint-enable*/
}
return acc;
}, -1);
};
mini.terminalState = function (board) {
const noOpenSquares = board.indexOf(0) === -1;
const winningPosition = winningPositions.reduce((acc, curr) => {
const positions = curr.split('').map(elem => ({position: board[elem], index: elem}));
acc.push(positions);
return acc;
}, []).filter(elem => {
return all(elem, item => item.position === 'O')
|| all(elem, item => item.position === 'X');
});
if (winningPosition.length) {
const winner = winningPosition.pop();
const winningTiles = winner.map(elem => arrayToBoard[elem.index]);
const winningDirection = winningDirections[winner.map(elem => elem.index).join('')];
return {
endState: true,
result: winner[0].position + '-won',
winningTiles: winningTiles,
winningDirection: winningDirection
};
}
if (noOpenSquares) {
return {endState: true, result: 'draw'};
}
return false;
};
mini.getMoves = function (board, player) {
let children = [];
board.map((elem, index) => ({elem, index}))
.filter(elem => elem.elem === 0)
.forEach(elem => {
const newBoard = board.slice();
newBoard[elem.index] = player;
children.push(newBoard);
});
return children;
};
mini.score = function (board, depth) {
const result = mini.terminalState(board);
if (result) {
if (result.result === 'X-won') {
return -10 + depth;
} else if (result.result === 'O-won') {
return 10 - depth;
} else {
return 0;
}
}
return 0 + depth;
};
mini.convertBoardToArray = function (board) {
return boardToArray(board);
};
mini.minimax = function (board, depth, player, alpha = -Infinity, beta = Infinity) {
let result = mini.terminalState(board);
if (result) {
return mini.score(board, depth);
}
let nextPlayer = player === 'O' ? 'X' : 'O';
let children = mini.getMoves(board, player);
let best;
let bestIndex;
if (player === 'O') {
best = -Infinity;
for (let i = 0; i < children.length; i++) {
let possible = mini.minimax(children[i],
depth + 1,
nextPlayer,
alpha,
beta);
if (possible > best) {
best = possible;
bestIndex = i;
}
/*eslint-disable*/
alpha = Math.max(alpha, best);
/*eslint-enable*/
if (beta <= alpha) {
break;
}
}
} else {
best = Infinity;
for (let i = 0; i < children.length; i++) {
let possible = mini.minimax(children[i],
depth + 1,
nextPlayer,
alpha,
beta);
if (possible < best) {
best = possible;
bestIndex = i;
}
/*eslint-disable*/
beta = Math.min(beta, best);
/*eslint-enable*/
if (beta <= alpha) {
break;
}
}
}
mini.choice = children[bestIndex];
return best;
};
return mini;
})();
export default minimax;
| terakilobyte/terakilobyte.github.io | src/projects/TicTacToe/minimax.js | JavaScript | mit | 4,447 |
var db = null;
var sql = window.SQL;
$(document).ready(function() {
db = new sql.Database();
var process = new Sheets2sqlite(db, '1jY9BZne07LoR1nvJm-PLsmQPY6jIKkkdYtuwcjMlQwA', ['department', 'employee']);
process.start(function() {
for(var i=0; i<process.tables.length; i++) {
var table = process.tables[i];
$('div#sql').append(table.createSQL() + '<br /><br />');
}
for(var i=0; i<process.tables.length; i++) {
var table = process.tables[i];
$('div#sql').append(table.insertSQL() + '<br /><br />');
}
var sql = 'SELECT * FROM department d, employee e WHERE d.id = e.id_department ORDER BY d.name ASC, e.name ASC';
var result = db.exec(sql);
var el = tableCreate()(result[0].columns, result[0].values);
$('div#sql').append(sql + '<br /><br />');
$('div#sql')[0].appendChild(el);
var table = $('div#sql table').DataTable({
paging: false,
ordering: false,
info: false
});
});
}); | lalkmim/sheets2sqlite | js/demo.js | JavaScript | mit | 1,105 |
import Transform from 'ember-stickler/transform';
export default Transform.create({
transform(value) {
return value.replace(/\D/g, '');
}
});
| sethpollack/ember-stickler | app/validations/digit.js | JavaScript | mit | 151 |
(function($) {
$.fn.GithubCommitHistory = function(options) {
var defaults = {
username: "halfdan",
repo: "github-commit-history",
branch: "master",
limit: 50,
offset: 0,
gravatar_size: 50
};
var options = $.extend(defaults, options);
return this.each(function() {
var obj = $(this);
var template;
$.get('_commit.html', function(data) {
template = data;
});
//
//jQuery.getJSON("http://github.com/api/v2/json/commits/list/" + options["username"] + "/" + options["repo"] + "/" + options["branch"] + "?callback=?", function(data) {
var apiUrl = "https://api.github.com/repos/" + options["username"] + "/" + options["repo"] + "/commits";
console.log(apiUrl);
$.getJSON(apiUrl, function(data) {
$.each(data, function(idx, commit) {
// Don't show the first "offset" entries.
if(idx < options["offset"]) {
return true;
}
// Break out of .each of we've reached our limit.
if(idx == options["limit"] + options["offset"]) {
return false;
}
commit = $.extend(commit, options);
commit.message = commit.commit.message;
commit.id = commit.sha;
commit.name = commit.commit.author.name;
var d = new Date(commit.commit.author.date);
commit.authored_date = d.toUTCString();
// Generate gravatar ID
commit.author.gravatar_id = $.md5(commit.commit.author.email.toLowerCase());
var html = Mustache.to_html(template, commit);
obj.append(html);
});
});
});
};
})(jQuery);
| dooglz/TemporalD3 | js/github-commit-history.js | JavaScript | mit | 1,536 |
import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
export default DS.RESTAdapter.extend(DataAdapterMixin, {
// namespace: 'api',
authorizer: 'authorizer:oauth2',
host: 'http://localhost:80/employees',
// host: 'http://localhost:80/intranet-api'
});
| msm-app-devs/intranet-app | app/adapters/file.js | JavaScript | mit | 312 |
module.exports = {
'url':'mongodb://Twick:1234567890@ds027505.mongolab.com:27505/passport-test'
} | PetarMetodiev/passport-test | test-app/config/db.js | JavaScript | mit | 101 |
// All code points in the NKo block as per Unicode v10.0.0:
[
0x7C0,
0x7C1,
0x7C2,
0x7C3,
0x7C4,
0x7C5,
0x7C6,
0x7C7,
0x7C8,
0x7C9,
0x7CA,
0x7CB,
0x7CC,
0x7CD,
0x7CE,
0x7CF,
0x7D0,
0x7D1,
0x7D2,
0x7D3,
0x7D4,
0x7D5,
0x7D6,
0x7D7,
0x7D8,
0x7D9,
0x7DA,
0x7DB,
0x7DC,
0x7DD,
0x7DE,
0x7DF,
0x7E0,
0x7E1,
0x7E2,
0x7E3,
0x7E4,
0x7E5,
0x7E6,
0x7E7,
0x7E8,
0x7E9,
0x7EA,
0x7EB,
0x7EC,
0x7ED,
0x7EE,
0x7EF,
0x7F0,
0x7F1,
0x7F2,
0x7F3,
0x7F4,
0x7F5,
0x7F6,
0x7F7,
0x7F8,
0x7F9,
0x7FA,
0x7FB,
0x7FC,
0x7FD,
0x7FE,
0x7FF
]; | mathiasbynens/unicode-data | 10.0.0/blocks/NKo-code-points.js | JavaScript | mit | 575 |
define('MAF.system.BaseView', function () {
var messagecenterlisteners = {};
var generateTransition = function (view, type) {
var eventType = 'on' + type.capitalize();
if (type === 'updateView') {
view.thaw();
}
if (view.transition && view.transition[type]) {
var animation = Object.merge({}, view.transition[type], {
events: {
onAnimationEnded: function () {
if ((type === 'hideView' || type === 'unselectView') && document.activeElement && view.element === document.activeElement.window) {
return;
}
if (view.fire(eventType)) {
view[type].call(view);
}
if (type === 'hideView') {
view.freeze();
}
}
}
});
view.animate(animation);
} else {
if (view.fire(eventType)) {
view[type].call(view);
}
if (type === 'hideView') {
view.freeze();
}
}
};
return new MAF.Class({
ClassName: 'BaseView',
Extends: MAF.element.Core,
Protected: {
initElement: function () {
this.parent();
var proto = this.constructor.prototype;
if (proto && proto.constructor) {
this.element.addClass(proto.constructor.prototype.ClassName);
}
},
onLoadView: function () {
if (this.fire('onCreateView')) {
if (MAF.Browser.webkit) {
this.thaw();
}
this.createView();
}
},
onUnloadView: function () {
if (this.fire('onDestroyView')) {
this.destroyView();
}
this.unregisterMessageCenterListeners();
this.cache = {};
this.controls = {};
this.elements = {};
messagecenterlisteners[this._classID] = [];
},
onShowView: function () {
generateTransition(this, 'updateView');
},
onHideView: function () {
generateTransition(this, 'hideView');
},
onSelectView: function () {
generateTransition(this, 'selectView');
},
onUnselectView: function () {
generateTransition(this, 'unselectView');
},
setInitialFocus: emptyFn,
unregisterMessageCenterListeners: function () {
if (messagecenterlisteners[this._classID].length > 0) {
var listener = false;
while (listener = messagecenterlisteners[this._classID].pop()) {
if (listener && listener.unsubscribeFrom && listener.unsubscribeFrom.call) {
listener.unsubscribeFrom(MAF.messages, MAF.messages.eventType);
}
}
}
},
getControlData: function (key, clear) {
if (this.persist && this.persist.___systemViewData___ && this.persist.___systemViewData___[key]) {
var value = this.persist.___systemViewData___[key];
if (clear) {
this.clearControlData(key);
}
return value;
}
},
setControlData: function (key, value) {
this.persist = this.persist || {};
this.persist.___systemViewData___ = this.persist.___systemViewData___ || {};
this.persist.___systemViewData___[key] = value;
},
clearControlData: function (key) {
delete this.persist.___systemViewData___[key];
},
getWindow: function () {
return this;
}
},
config: {
element: View
},
initialize: function () {
this.parent();
this.cache = {};
this.persist = {};
this.controls = {};
this.elements = {};
messagecenterlisteners[this._classID] = [];
this.rendered = false;
this.selected = false;
if (this.config.backParams) {
this.backParams = this.config.backParams;
this.config.backParams = null;
delete this.config.backParams;
}
if (this.config.persistParams) {
this.persist = this.config.persistParams;
this.config.persistParams = null;
delete this.config.persistParams;
}
this.initView();
},
// View initialization method to override in subclassed views.
initView: emptyFn,
createView: emptyFn,
updateView: emptyFn,
selectView: emptyFn,
unselectView: emptyFn,
destroyView: emptyFn,
hideView: emptyFn,
favbutton: emptyFn,
getView: function () {
return this;
},
registerMessageCenterListenerCallback: function (callback) {
if (callback && callback.subscribeTo) {
messagecenterlisteners[this._classID].push(callback.subscribeTo(MAF.messages, MAF.messages.eventType, this));
}
},
registerMessageCenterListenerControl: function (control) {
if (control && control.fire) {
messagecenterlisteners[this._classID].push(control.fire.subscribeTo(MAF.messages, MAF.messages.eventType, control));
}
},
suicide: function () {
delete messagecenterlisteners[this._classID];
delete this.persist;
delete this.cache;
delete this.viewBackParams;
delete this.transition;
Object.forEach(this.elements, function (key, obj) {
if (obj && obj.suicide) {
delete this.elements[key];
obj.suicide();
}
}, this);
delete this.elements;
Object.forEach(this.controls, function (key, obj) {
if (obj && obj.suicide) {
delete this.controls[key];
obj.suicide();
}
}, this);
delete this.controls;
this.parent();
}
});
});
| LibertyGlobal/maf3-test-runner | maf3-sdk/src/MAF/system/BaseView.js | JavaScript | mit | 4,942 |
cordova.define("jp.wizcorp.phonegap.plugin.wizAssetsPlugin", function(require, exports, module) {
/* Download and show, PhoneGap Example
*
* @author Ally Ogilvie
* @copyright WizCorp Inc. [ Incorporated Wizards ] 2011
* @file - wizAssets.js
* @about - JavaScript download and update asset example for PhoneGap
*
*
*/
var exec = require("cordova/exec");
var wizAssets = {
downloadFile: function(url, filePath, s, f) {
window.setTimeout(function () {
cordova.exec(s, f, "WizAssetsPlugin", "downloadFile", [url, filePath]);
}, 0);
},
deleteFile: function(uri, s, f) {
return cordova.exec(s, f, "WizAssetsPlugin", "deleteFile", [uri]);
},
deleteFiles: function(uris, s, f) {
return cordova.exec(s, f, "WizAssetsPlugin", "deleteFiles", uris );
},
getFileURIs: function(s, f) {
return cordova.exec(s, f, "WizAssetsPlugin", "getFileURIs", [] );
},
getFileURI: function(uri, s, f) {
return cordova.exec(s, f, "WizAssetsPlugin", "getFileURI", [uri] );
},
purgeEmptyDirectories: function(s, f) {
// todo
s();
}
};
module.exports = wizAssets;
});
| jrouault/phonegap-plugin-wizAssets | example/ios/www/phonegap/plugin/wizAssets/wizAssets.js | JavaScript | mit | 1,340 |
/*
The goal here is to minimize the last poll time, mostly.
It should be very small - perhaps as low as 1ms.
first poll, second poll,... full time
(500,2000,10) -> (5,87,7, 25165)
*/
var N = 5*100
var K = 2000
var OVERLAP = 10
var PLUSSED = (K*2-OVERLAP)*N
var minnow = require('./../../client/client')
var u = require('./../util')
u.reset(run)
function run(){
minnow.makeServer(u.config, function(){
console.log('made server')
minnow.makeClient(u.config.port, function(client){
console.log('made client')
var start = Date.now()
client.view('general', function(err, c){
if(err) throw err
//var readied = false
var h = setInterval(function(){
//console.log('v: '+ JSON.stringify(c.toJson()))//c.plussed.value())
//console.log(PLUSSED)
if(c.plussed.value() === PLUSSED){
//readied = true
c.make('container', {eId: 10, numbers: [10]}, function(){
c.make('container', {eId: 10, numbers: [10]}, function(){
clearInterval(h)
console.log('done: ' + (Date.now()-start))
console.log(PLUSSED)
process.exit(0)
})
})
}
},10)
for(var i=0;i<N;++i){
(function(i){
var a = []
for(var j=0;j<K;++j){
a.push(j)
}
var b = []
for(var j=0;j<K;++j){
b.push(j+(K-OVERLAP))
}
//console.log('genned: ' + JSON.stringify(genned))
var entity = c.make('entity', function(eId){
//console.log(entity.id())
c.make('container', {eId: entity.id(), numbers: a, more: b}, true)
})
})(i)
}
})
})
})
}
| lfdoherty/minnow | bench/bigsingleunion_withone/test.js | JavaScript | mit | 1,634 |
import connection from '../db'
import {exercises} from './exercises.json'
import {workouts} from './workouts.json'
// Seed the database with sample workouts and exercises
export async function seedDatabase(db = connection) {
try {
return Promise.all([createExercises(db), createWorkouts(db)])
} catch (err) {
console.error(`Unable to create database seed: ${err.message}`)
}
}
// Insert a bulk of sample exercises in DB. Return the number of inserted exercises if successful
export async function createExercises(db = connection) {
return db.exercises.bulkAdd(exercises.map(x => ({name: x})))
}
// Insert a bulk of sample workouts in DB. Return the number of inserted workouts if successful
export async function createWorkouts(db = connection) {
return db.workouts.bulkAdd(workouts)
}
| diegocasmo/workouter | src/api/seed/seed.js | JavaScript | mit | 807 |
/*
* src/ui/Button.js
* Author: H.Alper Tuna <halpertuna@gmail.com>
* Date: 08.08.2016
*/
'use strict'
define([
'../core/Utils',
'./ComponentContainer', './Element', './Icon',
'./utils/setTheme',
'./interfaces/iComponent'
], function (
Utils,
ComponentContainer, Element, Icon,
setTheme,
iComponent
) {
return ComponentContainer.extend(/** @lends ui/Button# */{
/**
* Button component class.
* @constructs
* @augments ui/ComponentContainer
* @implements iComponent
* @param {string} caption - Caption of button.
*/
'init': function (caption) {
/**
* Click event.
* @event ui/Button.ui/Button:click
*/
var component = Element.new('button')
.setAttr('type', 'button')
.addClass('jb-button')
this.super(component)
this.handle('click')
component.getDom().addEventListener('click', this.emit.bind(this, 'click'))
var captionElement = Element.new()
.addClass('jb-button-caption')
component.add(captionElement)
this.set('captionElement', captionElement)
if (!Utils.isSet(caption)) caption = ''
this.setCaption(caption)
},
/**
* Sets caption.
* @param {string} caption - Caption of button.
* @return {Object} Instance reference.
*/
'setCaption': function (caption) {
var captionElement = this.get('captionElement').clear()
if (caption === '') captionElement.hide()
else captionElement.add(caption).show()
return this.ref
},
/**
* Sets icon.
* @param {string} name - Icon name.
* @return {Object} Instance reference.
*/
'setIcon': function (name) {
var component = this.getComponent()
var iconElement = this.get('iconElement')
if (iconElement) {
if (name === this.get('iconName')) return this.ref
iconElement.remove()
}
iconElement = Icon.new(name).addClass('jb-button-icon')
component.prepend(iconElement)
this.set('iconElement', iconElement)
this.set('iconName', name)
return this.ref
},
// Inherited from iComponent interface
'setTheme': setTheme,
// Inherited from iComponent interface
'setDisabled': function (value) {
if (value) {
this.getComponent().setAttr('disabled', 'disabled')
} else {
this.getComponent().removeAttr('disabled')
}
return this.ref
},
// Inherited from iComponent interface
'focus': function () {
this.getComponent().getDom().focus()
return this.ref
}
}).implement(iComponent)
})
| alpertuna/burner | src/ui/Button.js | JavaScript | mit | 2,627 |
import { document } from '../seed/core'
export function VComment(text) {
this.nodeName = '#comment'
this.nodeValue = text
}
VComment.prototype = {
constructor: VComment,
toDOM: function() {
if (this.dom)
return this.dom
return this.dom = document.createComment(this.nodeValue)
},
toHTML: function() {
return '<!--' + this.nodeValue + '-->'
}
} | wangyongtan/H5 | common/avalon-2.2.7/avalon-2.2.7/src/vdom/VComment.js | JavaScript | mit | 408 |
version https://git-lfs.github.com/spec/v1
oid sha256:1e34042614ec5b0547393ad7143fe28f2557fae0652e65eb896ff008564e918b
size 4063
| yogeshsaroya/new-cdnjs | ajax/libs/extjs/4.2.1/src/grid/feature/GroupingSummary.js | JavaScript | mit | 129 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Alert from 'react-bootstrap/lib/Alert';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth /* , logout */ } from 'redux/modules/auth';
import { Notifs /* , InfoBar */ } from 'components';
import { push } from 'react-router-redux';
import config from 'config';
import { asyncConnect } from 'redux-connect';
@asyncConnect([
{
promise: ({ store: { dispatch, getState } }) => {
const promises = [];
if (!isAuthLoaded(getState())) {
promises.push(dispatch(loadAuth()));
}
if (!isInfoLoaded(getState())) {
promises.push(dispatch(loadInfo()));
}
return Promise.all(promises);
}
}
])
@connect(
state => ({
notifs: state.notifs,
user: state.auth.user
}),
{ /* logout, */ pushState: push }
)
export default class App extends Component {
static propTypes = {
children: PropTypes.element.isRequired,
router: PropTypes.shape({
location: PropTypes.object
}).isRequired,
user: PropTypes.shape({
email: PropTypes.string
}),
notifs: PropTypes.shape({
global: PropTypes.array
}).isRequired,
// logout: PropTypes.func.isRequired,
pushState: PropTypes.func.isRequired
};
static defaultProps = {
user: null
};
static contextTypes = {
store: PropTypes.object.isRequired
};
componentWillReceiveProps(nextProps) {
if (!this.props.user && nextProps.user) {
// login
const redirect = this.props.router.location.query && this.props.router.location.query.redirect;
this.props.pushState(redirect || '/loginSuccess');
} else if (this.props.user && !nextProps.user) {
// logout
this.props.pushState('/');
}
}
// handleLogout = event => {
// event.preventDefault();
// this.props.logout();
// };
render() {
const { notifs, children } = this.props;
const styles = require('./App.scss');
return (
<div className={styles.app}>
<Helmet {...config.app.head} />
<Navbar fixedTop>
<Navbar.Header>
<Navbar.Brand>
<IndexLink to="/" activeStyle={{ color: '#33e0ff' }}>
<div className={styles.brand} />
<span>
{config.app.title}
</span>
</IndexLink>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav navbar>
<LinkContainer to="/metacoin">
<NavItem>MetaCoin</NavItem>
</LinkContainer>
</Nav>
<Nav navbar pullRight>
<NavItem
target="_blank"
title="View on Github"
href="https://github.com/leopoldjoy/react-ethereum-dapp-example"
>
<i className="fa fa-github" />
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
<div className={styles.appContent}>
{notifs.global &&
<div className="container">
<Notifs
className={styles.notifs}
namespace="global"
NotifComponent={props =>
(<Alert bsStyle={props.kind}>
{props.message}
</Alert>)}
/>
</div>}
{children}
</div>
{/* <InfoBar /> */}
<div className="well text-center">
Have questions? Ask for help{' '}
<a
href="https://github.com/leopoldjoy/react-ethereum-example-dapp/issues"
target="_blank"
rel="noopener noreferrer"
>
on Github
</a>.
</div>
</div>
);
}
}
| leopoldjoy/react-ethereum-dapp-example | src/containers/App/App.js | JavaScript | mit | 4,211 |
function MockResponse() {
this._written = [];
this.headers = {};
this._closed = false;
}
// function _logMethodCall(name, args) {
// var argsArray = new Array(args.length);
// for (var i = 0; i < args.length; i++) {
// argsArray[i] = args[i];
// }
// console.log('[MockResponse] ' + name + ': ' + JSON.stringify(argsArray));
// }
MockResponse.prototype.write = function(data) {
// _logMethodCall('write', arguments);
if (this._closed) {
throw new Error('Response is closed');
}
this._written.push(data);
};
MockResponse.prototype.end = function(data, encoding) {
// _logMethodCall('end', arguments);
if (data) {
this._written.push(data);
}
this._closed = true;
};
MockResponse.prototype.setHeader = function(name, value) {
// _logMethodCall('setHeader', arguments);
if (this._closed) {
throw new Error('Response is closed');
}
this.headers[name.toLowerCase()] = value;
};
MockResponse.prototype.getHeader = function(name) {
// _logMethodCall('getHeader', arguments);
return this.headers[name.toLowerCase()];
};
MockResponse.prototype.mock_getWritten = function() {
return this._written.join('');
};
module.exports = MockResponse; | philidem/node-rest-handler | test/MockResponse.js | JavaScript | mit | 1,166 |
import React, { PropTypes } from 'react';
import { readableTime } from '../helpers/media';
const Timestamp = (
{},
{ media }
) => (
<span>
{ readableTime(media.currentTime) } / { readableTime(media.duration) }
</span>
);
Timestamp.contextTypes = {
media: PropTypes.shape({
currentTime: PropTypes.number.isRequired,
duration: PropTypes.number.isRequired,
}).isRequired,
};
export default Timestamp;
| Andreyco/react-video | src/components/Timestamp.js | JavaScript | mit | 425 |
import createWidgetsManager from '../createWidgetsManager';
describe('createWidgetsManager', () => {
describe('registerWidget', () => {
it('adds the widget to the widgets list', () => {
const wm = createWidgetsManager(() => null);
const widget = {};
wm.registerWidget(widget);
expect(wm.getWidgets()[0]).toBe(widget);
});
it('returns an unregister method', () => {
const wm = createWidgetsManager(() => null);
const unregister = wm.registerWidget({});
unregister();
expect(wm.getWidgets()).toHaveLength(0);
});
it('schedules an update', () => {
const onUpdate = jest.fn();
const wm = createWidgetsManager(onUpdate);
wm.registerWidget({});
return Promise.resolve().then(() => {
expect(onUpdate.mock.calls).toHaveLength(1);
});
});
});
describe('update', () => {
it('schedules an update', () => {
const onUpdate = jest.fn();
const wm = createWidgetsManager(onUpdate);
wm.update();
return Promise.resolve().then(() => {
expect(onUpdate.mock.calls).toHaveLength(1);
});
});
});
});
| algolia/react-instantsearch | packages/react-instantsearch-core/src/core/__tests__/createWidgetsManager.js | JavaScript | mit | 1,146 |
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-recess');
grunt.loadNpmTasks('grunt-react');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
copy: {
react: {
files: [
{
expand: true,
cwd: 'bower_components/react/',
src: ['react.js','JSXTransformer.js'],
dest: 'lib/hn_history/public/js/'
}
]
},
underscore: {
files: [
{
expand: true,
cwd: 'bower_components/underscore/',
src: ['underscore.js'],
dest: 'lib/hn_history/public/js/'
}
]
},
reqwest: {
files: [
{
expand: true,
cwd: 'bower_components/reqwest/',
src: ['reqwest.js'],
dest: 'lib/hn_history/public/js/'
}
]
},
purecss: {
files: [
{
expand: true,
cwd: 'bower_components/pure/',
src: ['pure.css'],
dest: 'lib/hn_history/public/css/'
}
]
},
d3: {
files: [
{
expand: true,
cwd: 'bower_components/d3/',
src: ['d3.js'],
dest: 'lib/hn_history/public/js/'
}
]
},
aviator: {
files: [
{
expand: true,
cwd: 'bower_components/aviator/',
src: ['aviator.js'],
dest: 'lib/hn_history/public/js/'
}
]
},
assets: {
files: [
{
expand: true,
cwd: 'assets/js/',
src: ['**/*.js'],
dest: 'tmp/js'
}
]
}
},
react: {
app: {
files: [
{
expand: true,
cwd: 'assets/jsx/',
src: ['**/*.jsx'],
dest: 'tmp/js',
ext: '.jsx'
}
]
}
},
concat: {
options: {
// define a string to put between each file in the concatenated output
separator: ';'
},
css: {
src: ['assets/less/**/*.less'],
dest: 'tmp/less/<%= pkg.name %>.less'
},
js: {
src: ['tmp/js/**/*.js', 'tmp/js/**/*.jsx'],
dest: 'lib/hn_history/public/js/hn_history.js'
}
},
watch: {
all: {
files: ['assets/js/**/*.js', 'assets/jsx/**/*.jsx', '<%= concat.css.src %>'],
tasks: ['copy:assets', 'react:app', 'concat:css', 'concat:js', 'recess:dist', 'recess:min', 'timestamp']
}
},
recess: {
dist: {
options: {
compile: true
},
files: {
'lib/hn_history/public/css/<%= pkg.name %>.css': 'tmp/less/*.less'
}
},
min: {
options: {
compress: true
},
files: {
'lib/hn_history/public/css/<%= pkg.name %>.min.css': 'lib/hn_history/public/css/<%= pkg.name %>.css'
}
}
}
});
grunt.registerTask('default', ['copy', 'react', 'concat', 'recess']);
grunt.registerTask('timestamp', function() {
grunt.log.subhead(Date());
});
};
| tlunter/hn_history | Gruntfile.js | JavaScript | mit | 3,333 |
import React from 'react'
import PropTypes from 'prop-types'
import cx from 'classnames'
import { mapToCssModules } from '../../lib/'
const propTypes = {
tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
className: PropTypes.string,
cssModule: PropTypes.object,
}
const defaultProps = {
tag: 'div',
}
const CardGroup = (props) => {
const {
className,
cssModule,
tag: Tag,
...attributes
} = props
const classes = mapToCssModules(cx(
className,
'card-group',
), cssModule)
return (
<Tag {...attributes} className={classes} />
)
}
CardGroup.propTypes = propTypes
CardGroup.defaultProps = defaultProps
export default CardGroup
| shengnian/shengnian-ui-react | src/views/BootCard/BootCardGroup.js | JavaScript | mit | 689 |
module.exports = function(Tipo) {
};
| pablohgm/asofac | common/models/tipo.js | JavaScript | mit | 38 |
function byPubDateDescending(a, b){
var dateA = new Date(a.pubDate);
var dateB = new Date(b.pubDate);
return dateB - dateA;
}
| podStation/podStation | src/reuse/comparison.js | JavaScript | mit | 129 |
define([
'jquery',
'underscore',
'backbone',
'app',
'text!scripts/main/templates/dashboard/todo/item.html',
], function($, _, Backbone, App, template) {
return Backbone.View.extend({
// Delegated events for creating new items, and clearing completed ones.
events: {
"click #view" : "view",
},
/**
*
*/
tagName : 'li',
/**
*
*/
className : 'list-group-item',
/**
*
*/
initialize: function() {
this.template = _.template(template || "");
},
/**
*
*/
render: function() {
var data = this.model.toJSON();
var format = "DD, HH:mm:ss";
var due = moment(this.model.get('end')).diff(moment());
if (due < 0){
data['due'] = 'Ended since ' + moment.utc(due).format(format);
}
else {
data['due'] = 'Left ' + moment.utc(due).format(format);
}
this.$el.html(this.template(data));
this.$el.find('.show-menu').on('click', function(event) {
event.preventDefault();
$(this).closest('ul').closest('li').toggleClass('open');
});
this.model.view = this;
return this;
},
/**
*
*/
view : function (event){
event.preventDefault();
Backbone.history.navigate(this.model.get('model') + '/' + this.model.get('id'), true);
},
/**
*
*/
close : function() {
this.remove ();
},
});
});
| houssemFat/MeeM-Dev | teacher/static/js/main/views/dashboard/todo/item.js | JavaScript | mit | 1,710 |
'use strict';
/* jasmine specs for directives go here */
describe('directives', function () {
beforeEach(module('myApp.directives'));
xdescribe('app-version', function () {
it('should print current version', function () {
module(function ($provide) {
$provide.value('version', 'TEST_VER');
});
inject(function ($compile, $rootScope) {
var element = $compile('<span app-version></span>')($rootScope);
expect(element.text()).toEqual('TEST_VER');
});
});
});
xdescribe('my-test', function () {
var element, scope;
it('should replace html', function () {
inject(function ($compile, $rootScope) {
scope = $rootScope.$new();
scope.bins = 100;
scope.histogramData = [3, 4, 5];
element = $compile('<span my-test bins="bins" histogram-data="histogramData"></span>')(scope);
scope.$digest();
expect(element.text()).toEqual('100--3');
});
});
});
describe('d3-histogram', function () {
var element, scope, datum = {
url: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference',
responseTimes: '1 2 3 5 4 3'
};
describe('for 20 bins', function () {
beforeEach(function () {
inject(function ($compile, $rootScope) {
scope = $rootScope.$new();
scope.bins = 20;
scope.datum = datum
element = $compile('<span d3-histogram bins="bins" histogram-data="datum"></span>')(scope);
scope.$digest();
});
});
it('should draw 20 bars and two axis', function () {
expect(element.children().length).toEqual(22);
});
it('should draw bars approximately 22px wide', function () {
expect(parseFloat(element.find('rect').eq(0).attr('width'))).toBeCloseTo(22.0);
});
});
describe('for 10 bins', function () {
beforeEach(function () {
inject(function ($compile, $rootScope) {
scope = $rootScope.$new();
scope.bins = 10;
scope.datum = datum;
element = $compile('<span d3-histogram bins="bins" histogram-data="datum"></span>')(scope);
scope.$digest();
});
});
it('should draw 10 bars and two axis', function () {
expect(element.children().length).toEqual(12);
});
it('should draw bars approximately 44px wide', function () {
expect(parseFloat(element.find('rect').eq(0).attr('width'))).toBeCloseTo(44.0);
});
});
describe('for undefined datum', function () {
beforeEach(function () {
inject(function ($compile, $rootScope) {
scope = $rootScope.$new();
scope.bins = 10;
element = $compile('<span d3-histogram bins="bins" histogram-data="datum"></span>')(scope);
scope.$digest();
});
});
it('should not draw anything', function () {
expect(element.children().length).toEqual(0);
});
});
describe('for undefined bins', function () {
beforeEach(function () {
inject(function ($compile, $rootScope) {
scope = $rootScope.$new();
scope.datum = datum;
element = $compile('<span d3-histogram bins="bins" histogram-data="datum"></span>')(scope);
scope.$digest();
});
});
it('should not draw anything', function () {
expect(element.children().length).toEqual(0);
});
});
});
});
| lucasprus/ncc_test | test/unit/directivesSpec.js | JavaScript | mit | 3,490 |
exports.config = {
allScriptsTimeout: 11000,
specs: [
'e2e/*.js'
],
// capabilities: {
// 'browserName': 'firefox',
// 'browserName': 'chrome'
// },
multiCapabilities: [
// {
// browserName: 'firefox'
// },
{
browserName: 'chrome'
}
],
baseUrl: 'http://localhost:8000/app/',
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
| tomwalker/glasgow_parking | test/protractor-conf.js | JavaScript | mit | 444 |
for(var number = 1; number<= 100; number++){
if(number % 15 === 0){
console.log("FizzBuzz")
}
else if(number% 5 === 0){
console.log("Buzz")
}
else if(number% 3 === 0){
console.log("Fizz")
}
else{
console.log(number)
}
} | hdngo/eloquent-js-notes | ch-2-program-structure/fizzbuzz.js | JavaScript | mit | 235 |
'use strict';
var YelpAPI = require('./lib/yelp-api');
var yelpAPI = new YelpAPI({
// To do: un-hard-code keys for Heroku
consumerKey: 'LF09pfePJ5IAB7MYcnRkaQ',
consumerSecret: '8QABPQRA-VZpVtCk6gXmPc-rojg',
token: 'dPrd7L96SseVYeQGvoyVtf1Dy9n3mmrT',
tokenSecret: 'W9Br5z5nKGHkScKBik9XljJEAoE',
});
module.exports = function(app) {
var api = '/api/0_0_1/:locations/:options';
app.get(api, function(req, res) {
var locations = JSON.parse(req.params.locations) || [{}];
var options = JSON.parse(req.params.options) || {};
var allBusinesses = []; // (Will hold master list of businesses)
locations.forEach(function(location) {
// Prepare a string version, to keep Yelp happy:
var stringLocation = location.lat + ',' + location.lon;
// Run each point through the Yelp API
yelpAPI.searchCoordinates(stringLocation, options, function(err, data) {
if (!err) {
allBusinesses.push(data);
} else {
console.log('Error in the Yelp callback!');
}
// When we're done, return master array to be parsed by business collection
if (allBusinesses.length === locations.length) {
return res.status(200).send(allBusinesses);
}
});
});
});
}; | Localhost3000/along-the-way | expressRoutes.js | JavaScript | mit | 1,198 |
// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').load();
// Require keystone
var keystone = require('keystone');
var handlebars = require('express-handlebars');
// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.
keystone.init({
'name': 'Keystone Content',
'brand': 'Keystone Content',
'less': 'public',
'static': 'public',
'favicon': 'public/favicon.ico',
'views': 'templates/views',
'view engine': 'hbs',
'custom engine': handlebars.create({
layoutsDir: 'templates/views/layouts',
partialsDir: 'templates/views/partials',
defaultLayout: 'default',
helpers: new require('./templates/views/helpers')(),
extname: '.hbs'
}).engine,
'emails': 'templates/emails',
'auto update': true,
'session': true,
'auth': true,
'user model': 'User'
});
// Load your project's Models
keystone.import('models');
// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js
keystone.set('locals', {
_: require('underscore'),
env: keystone.get('env'),
utils: keystone.utils,
editable: keystone.content.editable
});
// Load your project's Routes
keystone.set('routes', require('./routes'));
// Setup common locals for your emails. The following are required by Keystone's
// default email templates, you may remove them if you're using your own.
keystone.set('email locals', {
logo_src: '/images/logo-email.gif',
logo_width: 194,
logo_height: 76,
theme: {
email_bg: '#f9f9f9',
link_color: '#2697de',
buttons: {
color: '#fff',
background_color: '#2697de',
border_color: '#1a7cb7'
}
}
});
// Setup replacement rules for emails, to automate the handling of differences
// between development a production.
// Be sure to update this rule to include your site's actual domain, and add
// other rules your email templates require.
keystone.set('email rules', [{
find: '/images/',
replace: (keystone.get('env') == 'production') ? 'http://www.your-server.com/images/' : 'http://localhost:3000/images/'
}, {
find: '/keystone/',
replace: (keystone.get('env') == 'production') ? 'http://www.your-server.com/keystone/' : 'http://localhost:3000/keystone/'
}]);
// Load your project's email test routes
keystone.set('email tests', require('./routes/emails'));
// Configure the navigation bar in Keystone's Admin UI
keystone.set('nav', {
'contents': 'contents',
'posts': ['posts', 'post-categories'],
'galleries': 'galleries',
'enquiries': 'enquiries',
'users': 'users'
});
// Start Keystone to connect to your database and initialise the web server
keystone.start();
| steventux/keystone-content | keystone.js | JavaScript | mit | 2,865 |
/**
* @Author: Li'Zhuo
* @Date: 2016-04-07 13:05:02
* @Email: topgrd@outlook.com
* @Project: ES6
* @Last modified by: Li'Zhuo
* @Last modified time: 2016-06-11 23:09:03
*/
var app = angular.module(
'app', [
'ngRoute',
'ngMaterial',
'ngAnimate',
'ngRateIt'
]
).config(
[
'$routeProvider',
function($routeProvider) {
$routeProvider.when(
'/', {
templateUrl: './view/home/content.html'
}
);
$routeProvider.when(
'/login', {
templateUrl: './view/home/login.html',
controller: 'LoginCtrl'
}
);
$routeProvider.when(
'/register', {
templateUrl: './view/home/register.html',
controller: 'RegisterCtrl'
}
);
$routeProvider.when(
'/search', {
templateUrl: './view/home/search.html',
controller: 'ResultCtrl'
}
);
$routeProvider.when(
'/allItems', {
templateUrl: './view/home/allItems.html',
controller: 'AllItemsCtrl'
}
);
$routeProvider.when(
'/items/:itemId', {
templateUrl: './view/home/detail.html',
controller: 'DetailCtrl'
}
);
$routeProvider.otherwise({
redirectTo: '/'
});
}
]
);
| TopGrd/FilmApp | app.js | JavaScript | mit | 1,659 |
var SuiteFactory = require('../SuiteFactory');
var ImmutableListFactory = require('../../src/ImmutableListFactory');
var ImmutableModelFactory = require('../../src/ImmutableModelFactory');
var SimpleFrozenTextImmutableModel = ImmutableModelFactory.extend(function SimpleTextImmutableModel(text) {
this.text = text;
Object.freeze(this);
});
SuiteFactory.question(
'Should I use immutable if performance is critical?',
'ImmutableModelFactory.values.forEach(...) vs [].forEach()',
"You shouldn't base your applications requirements on any of these tests. "
)
.add('Yep', function() {
var items = [];
ImmutableListFactory.create([
new SimpleFrozenTextImmutableModel('one'),
new SimpleFrozenTextImmutableModel('two'),
new SimpleFrozenTextImmutableModel('three')
]).forEach(function(item) {
items.push(item);
});
})
.add('Nope', function() {
var items = [];
var enumerableUnfrozen = [
{
text: 'one'
},
{
text: 'two'
},
{
text: 'three'
}
].forEach(function(item) {
items.push(item);
});
})
.run(); | EnzoMartin/Minesweeper-React | client-src/js/modules/immutable/benchmark/questions/should-i-use-immutable-if-performance-is-critical.js | JavaScript | mit | 1,284 |
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');
/**
* Generate user schema.
* ::> Used as foundation for user model.
*/
var userSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true },
password: String,
facebook: String,
twitter: String,
google: String,
instagram: String,
tokens: Array,
profile: {
name: { type: String, default: '' },
gender: { type: String, default: '' },
location: { type: String, default: '' },
website: { type: String, default: '' },
picture: { type: String, default: '' }
},
resetPasswordToken: String,
resetPasswordExpires: Date
});
/**
* Hash the password for security.
* ::> "Pre" is a Mongoose middleware that executes before each user.save() call.
*/
userSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(5, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
/**
* Validate user's password.
* ::> Used by Passport-Local Strategy for password validation.
*/
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
/**
* Get URL to a user's gravatar.
* ::> Used in Navbar and Account Management page.
*/
userSchema.methods.gravatar = function(size) {
if (!size) size = 200;
if (!this.email) {
return 'https://gravatar.com/avatar/?s=' + size + '&d=retro';
}
var md5 = crypto.createHash('md5').update(this.email).digest('hex');
return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro';
};
module.exports = mongoose.model('User', userSchema);
| danXyu/bitely | models/User.js | JavaScript | mit | 1,940 |
'use strict';
var fs = require('fs');
var vm = require('vm');
var path = require('path');
var verify = require('adventure-verify');
var unpack = require('browser-unpack');
var concat = require('concat-stream');
var glob = require('glob');
var api = module.exports;
var fixtures = [{file:'<null>',text:null}].concat(glob.sync('problems/exporter_importer/fixture/*.txt').map(read));
var expectation = {
'<null>': 'That should take you approximately a few seconds to read',
'romeo-juliet': 'That should take you approximately an hour to read',
'quick-fox': 'That should take you approximately a few seconds to read',
'moby-dick': 'That should take you approximately 12 hours to read',
'hamlet-part': 'That should take you approximately 4 minutes to read'
};
function read (file) {
return {
text: fs.readFileSync(file), file: path.basename(file, '.txt')
};
}
api.problem = fs.createReadStream(__dirname + '/problem.txt');
api.solution = fs.createReadStream(__dirname + '/solution.txt');
api.verify = verify({ modeReset: true }, function (args, t) {
t.plan(fixtures.length + 1);
process.stdin.pipe(concat(function (body) {
var rows;
try {
rows = unpack(body);
} catch (err) {
return t.fail('The input had a syntax error!');
}
if (!rows) {
return t.fail('The input is not a browserify bundle!');
}
t.deepEqual(rows[0].deps, {}, 'shouldn\'t have any deps');
run(body.toString(), function (approximate) {
return function (fixture) {
t.equal(approximate(fixture.text), expectation[fixture.file], fixture.file + '? ' + expectation[fixture.file]);
};
});
}));
});
api.run = function (args) {
process.stdin.pipe(concat(function (body) {
run(body.toString(), function (approximate) {
return function (fixture) {
console.log(approximate(fixture.text));
};
});
}));
};
function run (body, cb) {
var glob = {};
vm.runInNewContext(body, glob, 'browserify-vm');
var approximate = glob.require('approximate');
fixtures.forEach(cb(approximate));
}
| bevacqua/learnyoubrowserify | problems/exporter_importer/index.js | JavaScript | mit | 2,074 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UxSelect = void 0;
var tslib_1 = require("tslib");
var aurelia_framework_1 = require("aurelia-framework");
var positioning_1 = require("@aurelia-ux/positioning");
var aurelia_logging_1 = require("aurelia-logging");
var core_1 = require("@aurelia-ux/core");
var ux_select_theme_1 = require("./ux-select-theme");
var util_1 = require("./util");
// tslint:disable-next-line: no-submodule-imports
require("@aurelia-ux/core/components/ux-input-component.css");
// tslint:disable-next-line: no-submodule-imports
require("@aurelia-ux/core/components/ux-input-component--outline.css");
var ux_default_select_configuration_1 = require("./ux-default-select-configuration");
var UP = 38;
// const RIGHT = 39;
var DOWN = 40;
// const LEFT = 37;
// const ESC = 27;
var ENTER = 13;
var SPACE = 32;
var logger = aurelia_logging_1.getLogger('ux-select');
var invalidMultipleValueMsg = 'Only null or Array instances can be bound to a multi-select';
var selectArrayContext = 'context:ux-select';
var UxSelect = /** @class */ (function () {
function UxSelect(element, styleEngine, observerLocator, taskQueue, defaultConfiguration, positioningFactory) {
this.element = element;
this.styleEngine = styleEngine;
this.observerLocator = observerLocator;
this.taskQueue = taskQueue;
this.positioningFactory = positioningFactory;
this.selectedOption = null;
this.variant = 'filled';
this.dense = false;
this.ignoreSelectEvent = true;
// Only chrome persist the element prototype when cloning with clone node
defineUxSelectElementApis(element);
if (defaultConfiguration.theme !== undefined) {
this.theme = defaultConfiguration.theme;
}
if (defaultConfiguration.dense !== undefined) {
this.dense = defaultConfiguration.dense;
}
if (defaultConfiguration.variant !== undefined) {
this.variant = defaultConfiguration.variant;
}
}
UxSelect.prototype.bind = function () {
if (util_1.bool(this.autofocus)) {
// setTimeout(focusEl, 0, this.button);
}
this.dense = core_1.normalizeBooleanAttribute('dense', this.dense);
if (this.isMultiple) {
if (!this.value) {
this.value = [];
}
else if (!Array.isArray(this.value)) {
throw new Error(invalidMultipleValueMsg);
}
}
if (!this.winEvents) {
this.winEvents = new aurelia_framework_1.ElementEvents(window);
}
this.themeChanged(this.theme);
// Initially Synchronize options with value of this element
this.taskQueue.queueMicroTask(this);
};
UxSelect.prototype.attached = function () {
this.resolveDisplayValue();
this.variantChanged(this.variant);
this.positioning = this.positioningFactory(this.element, this.optionWrapperEl, {
placement: 'bottom-start',
constraintElement: window,
offsetY: 0,
});
};
UxSelect.prototype.detached = function () {
this.unsetupListAnchor();
};
UxSelect.prototype.unbind = function () {
this.winEvents.disposeAll();
if (this.arrayObserver) {
this.arrayObserver.unsubscribe(selectArrayContext, this);
this.arrayObserver = null;
}
this.selectedOption = null;
};
UxSelect.prototype.resolveDisplayValue = function () {
var _this = this;
var values = this.options
.filter(function (option) {
return Array.isArray(_this.value) ?
_this.value.some(function (value) { return value === option.value; }) :
option.value === _this.value;
})
.map(function (t) { return t.innerText; });
this.displayValue = values.join(', ');
this.element.classList.toggle('ux-input-component--has-value', this.displayValue.length > 0);
};
UxSelect.prototype.synchronizeOptions = function () {
var value = this.value;
var isArray = Array.isArray(value);
var options = this.options;
var matcher = this.element.matcher || defaultMatcher;
var i = options.length;
this.ignoreSelectEvent = true;
var _loop_1 = function () {
var option = options[i];
var optionValue = option.value;
if (isArray) {
option.selected = value.findIndex(function (item) { return !!matcher(optionValue, item); }) !== -1;
return "continue";
}
option.selected = !!matcher(optionValue, value);
};
while (i--) {
_loop_1();
}
this.ignoreSelectEvent = false;
};
UxSelect.prototype.synchronizeValue = function () {
var options = this.options;
var ii = options.length;
var count = 0;
var optionValues = [];
// extract value from ux-option
for (var i = 0; i < ii; i++) {
var option = options[i];
if (!option.selected) {
continue;
}
optionValues.push(option.value);
count++;
}
if (this.isMultiple) {
// multi-select
if (Array.isArray(this.value)) {
var selectValues = this.value;
var matcher_1 = this.element.matcher || defaultMatcher;
// remove items that are no longer selected.
var i = 0;
var _loop_2 = function () {
var a = selectValues[i];
if (optionValues.findIndex(function (b) { return matcher_1(a, b); }) === -1) {
selectValues.splice(i, 1);
}
else {
i++;
}
};
while (i < selectValues.length) {
_loop_2();
}
// add items that have been selected.
i = 0;
var _loop_3 = function () {
var a = optionValues[i];
if (selectValues.findIndex(function (b) { return matcher_1(a, b); }) === -1) {
selectValues.push(a);
}
i++;
};
while (i < optionValues.length) {
_loop_3();
}
this.resolveDisplayValue();
return; // don't notify.
}
}
else {
// single-select
// tslint:disable-next-line:prefer-conditional-expression
if (count === 0) {
optionValues = null;
}
else {
optionValues = optionValues[0];
}
this.setValue(optionValues);
}
};
UxSelect.prototype.moveToBody = function () {
document.body.appendChild(this.optionWrapperEl);
};
UxSelect.prototype.moveToElement = function () {
this.element.appendChild(this.optionWrapperEl);
};
UxSelect.prototype.setupListAnchor = function () {
var _this = this;
this.moveToBody();
if (this.positioning) {
this.positioning.update();
}
this.winEvents.subscribe('wheel', function (e) {
if (_this.expanded) {
if (e.target === aurelia_framework_1.PLATFORM.global || !_this.optionWrapperEl.contains(e.target)) {
_this.collapse();
}
}
}, true);
};
UxSelect.prototype.unsetupListAnchor = function () {
this.moveToElement();
this.winEvents.disposeAll();
};
UxSelect.prototype.onKeyboardSelect = function () {
if (!this.expanded) {
return;
}
var focusedOption = this.focusedUxOption;
if (this.isMultiple) {
if (!focusedOption) {
return;
}
focusedOption.selected = !focusedOption.selected;
}
else {
this.collapse();
}
};
UxSelect.prototype.call = function () {
this.synchronizeOptions();
};
UxSelect.prototype.getValue = function () {
return this.value;
};
UxSelect.prototype.setValue = function (newValue) {
if (newValue !== null && newValue !== undefined && this.isMultiple && !Array.isArray(newValue)) {
throw new Error('Only null, undenfined or Array instances can be bound to a multi-select.');
}
if (this.value === newValue) {
return;
}
// unsubscribe from old array.
if (this.arrayObserver) {
this.arrayObserver.unsubscribe(selectArrayContext, this);
this.arrayObserver = null;
}
if (this.isMultiple) {
// subscribe to new array.
if (Array.isArray(newValue)) {
this.arrayObserver = this.observerLocator.getArrayObserver(newValue);
this.arrayObserver.subscribe(selectArrayContext, this);
}
}
if (newValue !== this.value) {
this.value = newValue;
this.resolveDisplayValue();
this.element.dispatchEvent(aurelia_framework_1.DOM.createCustomEvent('change', { bubbles: true }));
}
};
UxSelect.prototype.expand = function () {
var _this = this;
if (this.expanded) {
return;
}
if (this.isExpanding) {
return;
}
this.isExpanding = true;
this.optionWrapperEl.classList.add('ux-select__list-wrapper--open');
setTimeout(function () {
_this.optionCtEl.classList.add('ux-select__list-container--open');
_this.isExpanding = false;
_this.expanded = true;
_this.setFocusedOption(_this.selectedOption);
}, 0);
this.setupListAnchor();
};
UxSelect.prototype.collapse = function () {
var _this = this;
if (this.isCollapsing) {
return;
}
this.isCollapsing = true;
this.optionCtEl.classList.remove('ux-select__list-container--open');
var listTransitionString = getComputedStyle(this.element).getPropertyValue('--aurelia-ux--select-list-transition')
|| ux_select_theme_1.UxSelectTheme.DEFAULT_LIST_TRANSITION;
var listTransition = parseInt(listTransitionString.replace('ms', ''));
setTimeout(function () {
var _a;
(_a = _this.optionWrapperEl) === null || _a === void 0 ? void 0 : _a.classList.remove('ux-select__list-wrapper--open');
_this.isCollapsing = false;
_this.expanded = false;
_this.setFocusedOption(null);
_this.unsetupListAnchor();
}, listTransition);
};
UxSelect.prototype.setFocusedOption = function (focusedOption) {
var oldFocusedOption = this.focusedUxOption;
if (focusedOption !== oldFocusedOption) {
if (oldFocusedOption) {
oldFocusedOption.focused = false;
}
if (focusedOption) {
focusedOption.focused = true;
focusedOption.scrollIntoView({ block: 'nearest', inline: 'nearest' });
}
this.focusedUxOption = focusedOption;
}
};
UxSelect.prototype.moveSelectedIndex = function (offset) {
var currentIndex = 0;
var options = this.options;
if (this.focusedUxOption) {
currentIndex = options.indexOf(this.focusedUxOption);
}
else if (this.selectedOption) {
currentIndex = options.indexOf(this.selectedOption);
}
var nextIndex = currentIndex + offset;
if (nextIndex > options.length - 1) {
nextIndex = options.length - 1;
}
if (nextIndex < 0) {
nextIndex = 0;
}
var focusedOption = options[nextIndex];
if (focusedOption.disabled) {
if (offset > 0) {
if (nextIndex === options.length - 1) {
return;
}
this.moveSelectedIndex(offset + 1);
}
else {
if (nextIndex < 0) {
return;
}
this.moveSelectedIndex(offset - 1);
}
return;
}
this.setFocusedOption(focusedOption);
focusedOption.focused = true;
if (this.isMultiple) {
// empty
}
else {
this.ignoreSelectEvent = true;
if (this.selectedOption) {
this.selectedOption.selected = false;
}
this.selectedOption = focusedOption;
this.selectedOption.selected = true;
this.ignoreSelectEvent = false;
this.setValue(this.selectedOption.value);
}
};
UxSelect.prototype.onTriggerClick = function () {
if (!this.isDisabled) {
if (this.expanded) {
return;
}
this.expand();
}
};
UxSelect.prototype.onBlur = function () {
if (!this.element.contains(aurelia_framework_1.DOM.activeElement)) {
this.collapse();
}
};
UxSelect.prototype.onSelect = function (e) {
e.stopPropagation();
if (this.ignoreSelectEvent) {
return;
}
var newSelection = e.detail;
var lastSelection = this.selectedOption;
if (this.isMultiple) {
this.synchronizeValue();
}
else {
this.ignoreSelectEvent = true;
if (lastSelection) {
lastSelection.selected = false;
}
this.ignoreSelectEvent = false;
this.selectedOption = newSelection;
this.setValue(newSelection.value);
if (this.expanded) {
this.collapse();
}
}
};
UxSelect.prototype.onKeyDown = function (event) {
if (this.isDisabled) {
return;
}
// tslint:disable-next-line:switch-default
switch (event.which) {
case UP:
case DOWN:
this.moveSelectedIndex(event.which === UP ? -1 : 1);
event.preventDefault();
break;
case ENTER:
case SPACE:
this.onKeyboardSelect();
event.preventDefault();
break;
}
return true;
};
UxSelect.prototype.themeChanged = function (newValue) {
if (newValue && !newValue.themeKey) {
newValue.themeKey = 'select';
}
this.styleEngine.applyTheme(newValue, this.element);
};
UxSelect.prototype.multipleChanged = function (newValue, oldValue) {
newValue = util_1.bool(newValue);
oldValue = util_1.bool(oldValue);
var hasChanged = newValue !== oldValue;
if (hasChanged) {
this.ignoreSelectEvent = true;
for (var _i = 0, _a = this.options; _i < _a.length; _i++) {
var opt = _a[_i];
opt.selected = false;
}
this.ignoreSelectEvent = false;
this.selectedOption = null;
this.setValue(newValue
? [] // Changing from single to multiple = reset value to empty array
: null // Changing from multiple to single = reset value to null
);
}
};
UxSelect.prototype.variantChanged = function (newValue) {
this.element.style.backgroundColor = newValue === 'outline' ?
this.element.style.backgroundColor = core_1.getBackgroundColorThroughParents(this.element) :
'';
};
Object.defineProperty(UxSelect.prototype, "placeholderMode", {
get: function () {
return typeof this.label !== 'string' || this.label.length === 0;
},
enumerable: false,
configurable: true
});
Object.defineProperty(UxSelect.prototype, "options", {
get: function () {
if (!this.optionCtEl) {
return [];
}
var result = [];
var children = this.optionCtEl.children;
var ii = children.length;
for (var i = 0; ii > i; ++i) {
var element = children[i];
if (element.nodeName === 'UX-OPTION') {
result.push(element);
}
else if (element.nodeName === 'UX-OPTGROUP') {
var groupOptions = element.options;
var jj = groupOptions.length;
for (var j = 0; jj > j; ++j) {
result.push(groupOptions[j]);
}
}
}
return result;
},
enumerable: false,
configurable: true
});
UxSelect.prototype.getOptions = function () {
return this.options;
};
Object.defineProperty(UxSelect.prototype, "isMultiple", {
get: function () {
return util_1.bool(this.multiple);
},
enumerable: false,
configurable: true
});
Object.defineProperty(UxSelect.prototype, "isDisabled", {
get: function () {
return util_1.bool(this.disabled);
},
enumerable: false,
configurable: true
});
tslib_1.__decorate([
aurelia_framework_1.bindable()
], UxSelect.prototype, "theme", void 0);
tslib_1.__decorate([
aurelia_framework_1.bindable()
], UxSelect.prototype, "autofocus", void 0);
tslib_1.__decorate([
aurelia_framework_1.bindable({ defaultValue: false })
], UxSelect.prototype, "disabled", void 0);
tslib_1.__decorate([
aurelia_framework_1.bindable({ defaultValue: false })
], UxSelect.prototype, "multiple", void 0);
tslib_1.__decorate([
aurelia_framework_1.bindable
], UxSelect.prototype, "label", void 0);
tslib_1.__decorate([
aurelia_framework_1.bindable
], UxSelect.prototype, "placeholder", void 0);
tslib_1.__decorate([
aurelia_framework_1.bindable()
], UxSelect.prototype, "variant", void 0);
tslib_1.__decorate([
aurelia_framework_1.bindable
], UxSelect.prototype, "dense", void 0);
tslib_1.__decorate([
aurelia_framework_1.computedFrom('label')
], UxSelect.prototype, "placeholderMode", null);
tslib_1.__decorate([
aurelia_framework_1.computedFrom('multiple')
], UxSelect.prototype, "isMultiple", null);
tslib_1.__decorate([
aurelia_framework_1.computedFrom('disabled')
], UxSelect.prototype, "isDisabled", null);
UxSelect = tslib_1.__decorate([
aurelia_framework_1.inject(Element, core_1.StyleEngine, aurelia_framework_1.ObserverLocator, aurelia_framework_1.TaskQueue, ux_default_select_configuration_1.UxDefaultSelectConfiguration, aurelia_framework_1.Factory.of(positioning_1.UxPositioning)),
aurelia_framework_1.processContent(ensureUxOptionOrUxOptGroup),
aurelia_framework_1.customElement('ux-select'),
aurelia_framework_1.useView(aurelia_framework_1.PLATFORM.moduleName('./ux-select.html'))
], UxSelect);
return UxSelect;
}());
exports.UxSelect = UxSelect;
/**
* A View-compiler hook that will remove any element that is not `<ux-option>` or `<ux-optgroup/>`
* as child of this `<ux-select/>` element
*/
function ensureUxOptionOrUxOptGroup(_, __, node) {
if (node.hasAttribute('containerless')) {
logger.warn('Cannot use containerless on <ux-select/>. Consider using as-element instead.');
node.removeAttribute('containerless');
}
var currentChild = node.firstChild;
while (currentChild) {
var nextSibling = currentChild.nextSibling;
if (currentChild.nodeName === 'UX-OPTION' || currentChild.nodeName === 'UX-OPTGROUP') {
currentChild = nextSibling;
continue;
}
node.removeChild(currentChild);
currentChild = nextSibling;
}
return true;
}
var defineUxSelectElementApis = function (element) {
Object.defineProperties(element, {
value: {
get: function () {
return util_1.getAuViewModel(this).getValue();
},
set: function (v) {
util_1.getAuViewModel(this).setValue(v);
},
configurable: true
},
options: {
get: function () {
return util_1.getAuViewModel(this).getOptions();
},
configurable: true
}
});
};
function defaultMatcher(a, b) {
return a === b;
}
//# sourceMappingURL=ux-select.js.map | aurelia/ux | packages/select/dist/commonjs/ux-select.js | JavaScript | mit | 20,949 |
import React from 'react';
import { Col, FormGroup, FormControl } from 'react-bootstrap';
import Switch from '../../src/js/index';
export class LabelWidth extends React.Component {
constructor(props){
super(props);
this.state = {
width: 100
};
}
_onChange(e){
const width = parseInt(e.target.value, 10);
if(isNaN(width))
return;
this.setState({
width
});
}
render(){
return (
<Col xs={6} md={4}>
<h3>Label Width</h3>
<form>
<FormGroup>
<Switch labelWidth={this.state.width} />
</FormGroup>
<FormGroup>
<FormControl type="text" onChange={this._onChange.bind(this)} value={this.state.width} />
</FormGroup>
</form>
</Col>
);
}
} | Julusian/react-bootstrap-switch | example/src/label-width.js | JavaScript | mit | 802 |
import { createStore, applyMiddleware, compose } from "redux";
import { createLogger } from "redux-logger";
import thunkMiddleware from "redux-thunk";
import saqSearch from "./reducers";
const loggerMiddleware = createLogger();
let store = createStore(saqSearch, compose(applyMiddleware(thunkMiddleware)));
if (process.env.NODE_ENV !== "production") {
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const enhancer = composeEnhancers(
applyMiddleware(thunkMiddleware, loggerMiddleware)
);
store = createStore(saqSearch, enhancer);
}
export default store;
| TerrySmithDC/saqsearch | src/data/store.js | JavaScript | mit | 609 |
const assert = require('assert');
var _ = require('lodash');
describe('Common Test', () => {
describe('#Method Reg Test()', () => {
it('Match a method with order.*', async () => {
var root = '^' + 'order.*' + '$';
var method1 = 'order.add.dd';
var method2 = 'order.move';
var method3 = 'app.move';
var method4 = 'app.hh';
var method5 = 'app.dd';
var method6 = 'app.ff';
var reg = new RegExp(root);
assert(reg.test(method1))
assert(reg.test(method2))
assert(!reg.test(method3))
assert(!reg.test(method4))
assert(!reg.test(method5))
assert(!reg.test(method6))
});
it('Match a method with app.*', async () => {
var root = '^' + 'app.*' + '$';
var method1 = 'order.add.dd';
var method2 = 'order.move';
var method3 = 'app.move';
var method4 = 'app.hh';
var method5 = 'app.dd';
var method6 = 'app.ff';
var reg = new RegExp(root);
assert(!reg.test(method1))
assert(!reg.test(method2))
assert(reg.test(method3))
assert(reg.test(method4))
assert(reg.test(method5))
assert(reg.test(method6))
});
it('Match a method with (app|order).*', function (done) {
var root = '^' + '(app|order).*' + '$';
var method1 = 'order.add.dd';
var method2 = 'order.move';
var method3 = 'app.move';
var method4 = 'app.hh';
var method5 = 'app.dd';
var method6 = 'app.ff';
var reg = new RegExp(root);
assert(reg.test(method1))
assert(reg.test(method2))
assert(reg.test(method3))
assert(reg.test(method4))
assert(reg.test(method5))
assert(reg.test(method6))
});
});
}); | team4yf/yf-fpm-server | test/common.test.js | JavaScript | mit | 1,806 |
import makeGenericModelActions from '../utils/actions'
const actions = makeGenericModelActions({
commands: {
'Collection GET': {},
'Collection POST': {},
'DELETE': {
redirectionStrategy: 'toHome'
},
'GET': {},
'PUT': {}
},
pluralName: 'sites',
singularName: 'site'
})
export default actions
| conveyal/commute | client/actions/site.js | JavaScript | mit | 331 |
import {Mongo} from 'meteor/mongo';
export const Authors = new Mongo.Collection('cache_authors');
export const AuthorProfiles = new Mongo.Collection('cache_author_profiles');
export const Posts = new Mongo.Collection('cache_posts');
export const Groups = new Mongo.Collection('cache_groups');
export const Categories = new Mongo.Collection('cache_categories');
Authors.remove({});
AuthorProfiles.remove({});
Posts.remove({});
Groups.remove({});
Categories.remove({});
Posts.addLinks({
author: {
type: 'one',
collection: Authors,
field: 'authorId',
denormalize: {
field: 'authorCache',
body: {
name: 1,
address: 1,
}
}
},
categories: {
type: 'many',
metadata: true,
collection: Categories,
field: 'categoryIds',
denormalize: {
field: 'categoriesCache',
body: {
name: 1,
}
}
}
});
Authors.addLinks({
posts: {
collection: Posts,
inversedBy: 'author',
denormalize: {
field: 'postCache',
body: {
title: 1,
}
}
},
groups: {
type: 'many',
collection: Groups,
field: 'groupIds',
denormalize: {
field: 'groupsCache',
body: {
name: 1,
}
}
},
profile: {
type: 'one',
metadata: true,
collection: AuthorProfiles,
field: 'profileId',
unique: true,
denormalize: {
field: 'profileCache',
body: {
name: 1,
}
}
}
});
AuthorProfiles.addLinks({
author: {
collection: Authors,
inversedBy: 'profile',
unique: true,
denormalize: {
field: 'authorCache',
body: {
name: 1,
}
}
}
});
Groups.addLinks({
authors: {
collection: Authors,
inversedBy: 'groups',
denormalize: {
field: 'authorsCache',
body: {
name: 1,
}
}
}
});
Categories.addLinks({
posts: {
collection: Posts,
inversedBy: 'categories',
denormalize: {
field: 'postsCache',
body: {
title: 1,
}
}
}
});
| cult-of-coders/grapher | lib/query/testing/link-cache/collections.js | JavaScript | mit | 2,457 |
//{namespace name=backend/connect/view/main}
//{block name="backend/connect/view/export/stream/list"}
Ext.define('Shopware.apps.Connect.view.export.stream.List', {
extend: 'Ext.grid.Panel',
alias: 'widget.connect-export-stream-list',
border: false,
store: 'export.StreamList',
selModel: Ext.create('Shopware.apps.Connect.view.export.stream.CustomCheckboxModel', {
selectedAll: false, // you can add whatever normal configuration properties you want here
mode: 'MULTI',
listeners: {
selectall: function (scope) {
if (!scope.selectedAll) {
scope.selectedAll = true;
} else {
scope.deselectAll();
scope.selectedAll = false;
}
}
}
}),
/**
* Contains all snippets for the component
* @object
*/
snippets: {
streamInfoMessage: '{s name=export/stream/activate_cron_message}Activate the cron job to use this function{/s}'
},
initComponent: function() {
var me = this;
Ext.applyIf(me, {
dockedItems: [
me.getPagingToolbar()
],
features: [me.getGrouping()],
columns: me.getColumns()
});
me.callParent(arguments);
me.store.addListener('load', function (store, records) {
var hasInactiveRows = false;
Ext.Array.each(records, function (record) {
if (record.get('enableRow') == false) {
hasInactiveRows = true;
return false;
}
});
me.getView().features[0].groupHeaderTpl = me.getGroupHeaderTpl(hasInactiveRows);
me.getView().refresh();
});
},
listeners: {
beforeselect: function (sm, record) {
if (record.get('enableRow') == false ) return false;
},
selectionchange: function (sm, selected) {
// deselect disabled records
if (selected.length > 0) {
Ext.Array.each(selected, function (record) {
if (record.get('enableRow') == false) {
sm.deselect(record, true);
}
});
}
}
},
getColumns: function() {
var me = this;
return [{
header: '{s name=export/columns/name}Name{/s}',
dataIndex: 'name',
flex: 4,
renderer: function(value, metaData, record) {
if (record.get('enableRow') == false) {
return '<div class="sc-transparency-color">' + value + '</div>'
}
return value;
}
}, {
header: '{s name=export/columns/product_amount}Product amount{/s}',
dataIndex: 'productCount',
flex: 1
}, {
header: '{s name=export/columns/status}Status{/s}',
dataIndex: 'exportStatus',
flex: 1,
renderer: function(value, metaData, record) {
var className = '',
label;
if (!value) {
return;
}
if (me.iconMapping.hasOwnProperty(value)) {
className = me.iconMapping[value];
}
if (record.get('enableRow') == false) {
className += ' sc-transparency';
}
if(record.get('exportMessage')) {
metaData.tdAttr = 'data-qtip="' + record.get('exportMessage') + '"';
} else {
label = (value in me.iconLabelMapping) ? me.iconLabelMapping[value] : value;
metaData.tdAttr = 'data-qtip="' + label + '"';
}
return '<div class="' + className + '" style="width: 16px; height: 16px;"></div>';
}
}];
},
getGrouping: function() {
var me = this;
return Ext.create('Ext.grid.feature.Grouping', {
groupHeaderTpl: me.getGroupHeaderTpl(false),
hideGroupedHeader: true,
startCollapsed: false
});
},
/**
* Creates a paging toolbar with additional page size selector
*
* @returns Array
*/
getPagingToolbar: function() {
var me = this;
var pageSize = Ext.create('Ext.form.field.ComboBox', {
labelWidth: 120,
cls: Ext.baseCSSPrefix + 'page-size',
queryMode: 'local',
width: 180,
listeners: {
scope: me,
select: function(combo, records) {
var record = records[0],
me = this;
me.store.pageSize = record.get('value');
me.store.loadPage(1);
}
},
store: Ext.create('Ext.data.Store', {
fields: [ 'value' ],
data: [
{ value: '20' },
{ value: '40' },
{ value: '60' },
{ value: '80' },
{ value: '100' }
]
}),
displayField: 'value',
valueField: 'value',
editable: false,
emptyText: '20'
});
pageSize.setValue(me.store.pageSize);
var pagingBar = Ext.create('Ext.toolbar.Paging', {
store: me.store,
dock:'bottom',
displayInfo:true
});
pagingBar.insert(pagingBar.items.length - 2, [ { xtype: 'tbspacer', width: 6 }, pageSize ]);
return pagingBar;
},
getGroupHeaderTpl: function(hasInactiveRows) {
var me = this;
return [
'{literal}{name:this.formatName}{/literal}',
{
formatName: function(type) {
if (type == 2) {
return '{s name=export/selection_streams}Selection streams{/s}';
} else {
if (hasInactiveRows) {
return '{s name=export/condition_streams}Condition streams{/s}<div class="sc-stream-hint sprite-exclamation" data-qtip="'+ me.snippets.streamInfoMessage +'"></div>';
} else {
return '{s name=export/condition_streams}Condition streams{/s}';
}
}
}
}
]
}
});
//{/block}
| shopware/SwagConnect | Views/backend/connect/view/export/stream/list.js | JavaScript | mit | 6,599 |
/*global BigBlock */
/**
Button object
Creates clickable groups of blocks that carry functions to execute on events. Buttons must be static.
Creates a BlockAnim (render_static = true) while also populating a "map" property with x, y, width, height, and a function to run when clicked/touched.
Width and Height of the button graphic must be supplied.
Can also create hot spots without a graphic as long as x, y, width, height are passed and anim =
Rollovers currently not supported;
@author Vince Allen 01-06-2011
Big Block Framework
Copyright (C) 2011 Foldi, LLC
*/
BigBlock.Button = (function () {
return {
alias: 'button',
map: [],
/**
* Creates a BlockAnim (render_static = true) while also populating a "map" property with x, y, width, height, and a function to run when clicked/touched.
*
* @param {Object} key
*/
create: function (params) {
try {
if (typeof params === "undefined") {
throw new Error("Button.create(): params argument required");
}
if (typeof params.x === "undefined") {
throw new Error("Button.create(): params.x argument required");
}
if (typeof params.y === "undefined") {
throw new Error("Button.create(): params.y argument required");
}
if (typeof params.width === "undefined") {
throw new Error("Button.create(): params.width argument required");
}
if (typeof params.height === "undefined") {
throw new Error("Button.create(): params.height argument required");
}
if (typeof params.alias === "undefined") {
params.alias = "button"+BigBlock.Utils.getUniqueId(); // assign unique id if alias is not passed
}
if (typeof params.action_input === "undefined") {
params.action_input = false; // force an empty function if action_input is not passed
}
} catch(e) {
BigBlock.Log.display(e.name + ": " + e.message);
}
this.map[this.map.length] = { // add coords to map
alias: params.alias,
x: params.x,
y: params.y,
width: params.width,
height: params.height,
url: params.url,
action_input: params.action_input
};
params.render_static = true; // force static
params.className = "Button"; // force className
params.after_destroy = false;
/*
* This version of the Button class forces buttons to be static.
* Future versions will allow active buttons with rollovers, active states, etc. Uncomment the following for use with active buttons.
*/
/*params.destroy = function () {
if (typeof(callback) == 'function') { this.after_destroy = callback; }
this.render = 0; // prevents render manager from rendering this object's blocks
BigBlock.Timer.destroyObject(this);
BigBlock.removeStaticBlock(this.alias); // remove static blocks associated with this object
};*/
// if anim = "undefined", use width/height to draw button
if (typeof params.anim === "undefined") {
BigBlock.BlockBig.create(params); // create a BlockBig
} else {
BigBlock.BlockAnim.create(params); // create a BlockAnim
}
},
/**
* Removes an entry from Button.map. Typically used when removing buttons but not changing scenes.
*
* @param {String} alias
*/
deleteFromMap: function (alias) {
var i, max;
for (i = 0, max = BigBlock.Button.map.length; i < max; i++) {
if (BigBlock.Button.map[i].alias === alias) {
BigBlock.Button.map.splice(i,1);
return true;
}
}
return false;
},
destroy: function (alias) {
this.deleteFromMap(alias);
BigBlock.removeStaticBlock(alias);
}
};
}()); | foldi/Big-Block-Framework | lib/Button.js | JavaScript | mit | 3,663 |
'use strict'
const { stringify } = JSON
exports.connect = async function connect() {
return {
body: stringify({ foo: 'bar' }),
statusCode: 200,
}
}
exports.disconnect = async function disconnect() {
return {
body: stringify({ foo: 'bar' }),
statusCode: 200,
}
}
exports.default = async function _default() {
return {
body: stringify({ foo: 'bar' }),
statusCode: 200,
}
}
| dherault/serverless-offline | examples/events/websocket/handler.js | JavaScript | mit | 411 |
'use strict';
var Configuration = {
version: 1, // only whole numbers here! this increases the port number for both base and client sockets!
// MySQL Database Connection
//--------------------------
mySQL: {
HOST: '127.0.0.1',
USER: 'root',
PASS: '',
DB: 'ctrl_1v0',
},
// Base Socket Server related
//---------------------------
base: {
// Server Setup
srv: {
PORT: 8000, // starting port number. actual port number is this value + version!
MAX_CONN: 1000,
},
// Random IV Pool Size
randomIvPoolSize: 131072, // custom pool size, bigger = better, but not too big! lets try with 131072bytes (128kB), that will last us for 8192 encryptions. More in ../messages/baseMessage.js
// Socket Setup
sock: {
KEEPALIVE_MS: 5000, // keep-alive connection timeout
AUTH_TIMEOUT_MS: 3000, // authorization timeout after connection establishment (0 disables timeout)
SENDER_TASK_MS: 100, // task that writes data to Base on socket (timer exists only because we don't want to flush Base with pending data all at once)
ON_DATA_THROTTLING_MS: 50, // throttling of received commands
MAX_AUTH_ATTEMPTS: 10, // how many failed auth attempts are allowed?
MAX_AUTH_ATTEMPTS_MINUTES: 5, // ...in this duration (minutes)?
BACKOFF_MS: 2000, // initial backoff period (milliseconds) - will increment by *2 on each successive backoff reply from Base
MAXIMUM_BACKOFF_MS: 60000, // maximum backoff delay that can be achieved if Base backoffs on too many successive messages
OUT_OF_SYNC_CNT_MAX: 3, // how many out of sync messages should we receive before flushing the txserver2base queue and dropping the connection?
},
},
// Client Socket Server related
//-----------------------------
client: {
// Feature for localhost authentications - to bypass IP blocking after MAX_AUTH_ATTEMPTS wrong auths.
localIPs: ['127.0.0.1', '10.0.0.1', '78.47.48.138'],
// Server Setup
srv: {
PORT: 9000, // starting port number. actual port number is this value + version!
MAX_CONN: 3000,
},
// Socket Setup
sock: {
KEEPALIVE_MS: 10000, // keep-alive connection timeout
AUTH_TIMEOUT_MS: 3000, // authorization timeout after connection establishment (0 disables timeout)
SENDER_TASK_MS: 100, // task that writes data to Client on socket (timer exists only because we don't want to flush Client with pending data all at once)
ON_DATA_THROTTLING_MS: 50, // throttling of received commands
MAX_AUTH_ATTEMPTS: 5, // how many failed auth attempts are allowed?
MAX_AUTH_ATTEMPTS_MINUTES: 5, // ...in this duration (minutes)?
OUT_OF_SYNC_CNT_MAX: 3, // how many out of sync messages should we receive before flushing the txserver2client queue and dropping the connection?
},
},
// Tiny Status Server related
//---------------------------
tinyStatusServer: {
PORT: 7000, // starting port number. actual port number is this value + version!
},
};
module.exports = Configuration;
| elektronika-ba/ctrl-server | js/configuration/configuration.js | JavaScript | mit | 3,491 |
// @flow
/* eslint-disable */
import { type Fixed8 } from '@cityofzion/neon-js'
import {
ROUTES,
NOTIFICATION_LEVELS,
NOTIFICATION_POSITIONS,
MODAL_TYPES,
TX_TYPES,
ASSETS,
THEME,
NETWORK_LABELS,
MAIN_NETWORK_LABEL,
TEST_NETWORK_LABEL,
} from '../app/core/constants'
declare type ActionCreatorType = any
declare type DispatchType = (actionCreator: ActionCreatorType) => Promise<*>
declare type GetStateType = () => Object
declare type ReduxAction = () => {
type: string,
payload: Object,
meta?: Object,
error?: Object,
}
declare type SelectOption = {
label: string,
value: string,
}
declare type NetworkType = string
declare type NetworkLabelTypes = MAIN_NETWORK_LABEL | TEST_NETWORK_LABEL
declare type ExplorerType = $Values<Explorer>
declare type Explorer = {
NEO_TRACKER: string,
NEO_SCAN: string,
ANT_CHAIN: string,
}
declare type RouteType = $Values<typeof ROUTES>
declare type NotificationType = {
id: string,
level: $Values<typeof NOTIFICATION_LEVELS>,
title?: string,
message: string,
position: $Values<typeof NOTIFICATION_POSITIONS>,
dismissible: boolean,
autoDismiss: number,
}
declare type TransactionHistoryType = {
change: {
NEO: Fixed8,
GAS: Fixed8,
},
txid: string,
blockHeight: Fixed8,
}
declare type ModalType = $Values<typeof MODAL_TYPES>
declare type TxType = $Values<typeof TX_TYPES>
declare type TxEntryType = {
type: TxType,
txid: string,
to: string,
from?: string,
amount: number,
label: $Values<typeof ASSETS>,
time?: number,
isNetworkFee?: boolean,
image?: string,
}
type PendingTransactions = {
[address: string]: Array<any>,
}
type PendingTransaction = {
vout: Array<{ asset: string, address: string, value: string }>,
sendEntries: Array<SendEntryType>,
confirmations: number,
txid: string,
net_fee: string,
blocktime: number,
type: string,
}
type ParsedPendingTransaction = {
confirmations: number,
txid: string,
net_fee: string,
blocktime: number,
to: string,
amount: string,
asset: {
symbol: string,
image: string,
},
}
declare type SymbolType = string
declare type NetworkItemType = {
value: string,
id: string,
label: string,
network: NetworkType,
deprecatedLabel: string,
}
declare type TokenItemType = {
id: string,
scriptHash: string,
networkId: string,
isUserGenerated: boolean,
symbol?: string,
cryptocompareSymbol?: string,
totalSupply?: number,
decimals?: number,
image?: ?string,
isNotValidated?: boolean,
}
declare type TokenType = {
symbol: SymbolType,
balance: number,
totalSupply: number,
decimals: number,
name: string,
}
declare type TokenBalanceType = {
symbol: SymbolType,
image: string,
balance: string,
scriptHash: string,
totalSupply: number,
decimals: number,
name: string,
}
declare type SendEntryType = {
amount: string | number,
address: string,
symbol: SymbolType,
contractHash?: string,
}
declare type ThemeType = THEME.LIGHT | THEME.DARK
// polyfill flow's bom since Node does implement navigator.mediaDevices
declare interface Navigator extends Navigator {
mediaDevices: MediaDevicesType;
}
// https://mdn.io/MediaDevices
// https://mdn.io/MediaDevices/enumerateDevices
// https://mdn.io/MediaDevices/getUserMedia
declare type MediaDevicesType = {
enumerateDevices(): Promise<Array<MediaDeviceInfoType>>,
getUserMedia(MediaStreamConstraints): Promise<MediaStream>,
}
// https://mdn.io/MediaDeviceInfo
declare type MediaDeviceInfoType = {
deviceId: string,
groupId: string,
kind: 'videoinput' | 'audioinput' | 'audiooutput',
label: string,
}
// https://mdn.io/MediaStreamConstraints
declare type MediaStreamConstraints = {
['audio' | 'video']: Object | boolean,
}
| CityOfZion/neon-wallet | flow-typed/declarations.js | JavaScript | mit | 3,757 |
Ajax.Responders.register({
onCreate: function(request) {
Mojo.Log.info("ajax request started,", request.method, request.url)
},
onComplete: function(request) {
Mojo.Log.info("ajax request completed with status code", request.getStatus())
},
onException: function(request, exception) {
Mojo.Log.info("ajax exception -", exception.message)
}
})
Ajax.Request.prototype.success = function() {
var status = this.getStatus()
return (status >= 200 && status < 300)
} | darrinholst/webos-template | app/lib/ajax.js | JavaScript | mit | 489 |
define(['lazoCtl', 'async'], function (LazoCtl, async) {
'use strict';
return LazoCtl.extend({
index: function (options) {
var self = this;
async.parallel([
function (callback) {
self.loadCollection('collection-example', {
success: function (collection) {
self.ctx.collections['collection-example'] = collection;
callback(null);
},
error: function (err) {
callback(err);
}
});
},
function (callback) {
self.loadCollection('model-example', {
success: function (model) {
self.ctx.models['model-example'] = model;
callback(null);
},
error: function (err) {
callback(err);
}
});
}
], function (err, models) {
if (err) {
return options.error(err);
}
options.success('index');
});
}
});
}); | lazojs/lazo-react-view | example/components/home/controller.js | JavaScript | mit | 1,339 |
import should from "should";
import pushNonFalsy from "../../lib/array/pushNonFalsy";
describe("pushNonFalsy", () => {
it("Should works", () => {
const array = [true];
pushNonFalsy(true, array)
.should.equal(array).and.eql([true, true]);
});
it("Should works with a falsy value", () => {
const array = [true];
pushNonFalsy(undefined, array)
.should.equal(array).and.eql([true]);
});
it("Should works with no explicit array", () => {
pushNonFalsy(true).should.eql([true]);
});
it("Should works with no explicit array and a falsy value", () => {
should(pushNonFalsy(false)).be.undefined();
});
});
| yvele/poosh | packages/poosh-common/test/array/pushNonFalsy.js | JavaScript | mit | 654 |
/**
* iteration
*/
var iterate = (left, right) => (...y) => {
let leftResult = left.apply(undefined, y);
return new Promise((resolve, reject) => {
leftResult.then(preVs => {
let counter = 0;
let results = [];
for (let i = 0; i < preVs.length; i++) {
let item = preVs[i];
let v = right.apply(undefined, [item]);
v.then(result => {
results[i] = result;
counter++;
if (counter >= preVs.length) {
resolve(results);
}
}).catch(err => reject(err));
}
}).catch(err => reject(err));
});
}
export default iterate; | LoveKino/alleyway | src/iterate.js | JavaScript | mit | 751 |
var AppDispatcher = require('../dispatcher/AppDispatcher');
var AppConstants = require('../constants/AppConstants');
var ActionTypes = AppConstants.ActionTypes;
module.exports = {
clickConnection: function (key) {
AppDispatcher.handleViewAction({
type: ActionTypes.CLICK_CONNECTION,
key: key
});
},
clickTab: function (key) {
AppDispatcher.handleViewAction({
type: ActionTypes.CLICK_TAB,
key: key
});
}
};
| bitheater/beanstalk-admin | server/public/src/actions/ConnectionActionCreators.js | JavaScript | mit | 504 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define(["require","exports","../core/tsSupport/assignHelper","@dojo/framework/shim/WeakMap","./locale"],function(l,c,m,f,e){function g(a){var b=a||h;if(!d.has(b)){var c=e.getLocale(),c=k[e.getLocale()]||c;d.set(b,new Intl.NumberFormat(c,a))}return d.get(b)}Object.defineProperty(c,"__esModule",{value:!0});var k={ar:"ar-u-nu-latn"},d=new f.default,h={};e.onLocaleChange(function(){d=new f.default;h={}});c.getFormatter=g;c.convertNumberFormatToIntlOptions=function(a){void 0===a&&(a={});var b={};null!=
a.digitSeparator&&(b.useGrouping=a.digitSeparator);null!=a.places&&(b.minimumFractionDigits=b.maximumFractionDigits=a.places);return b};c.formatNumber=function(a,b){return g(b).format(a)}}); | ycabon/presentations | 2020-devsummit/arcgis-js-api-road-ahead/js-api/esri/intl/number.js | JavaScript | mit | 850 |
import ParseInitializer from "ember-parse-lib/initializers/parse";
export default {
name: "ember-parse-lib",
after: "ember-data",
initialize: ParseInitializer.initialize
};
| championswimmer/ember-parse-lib | app/initializers/parse.js | JavaScript | mit | 180 |
import CustomerIndexPage from '../components/pages/customers/CustomerIndexPage'
import CustomerUpdatePage from '../components/pages/customers/CustomerUpdatePage'
import CustomerShowPage from '../components/pages/customers/CustomerShowPage'
import CustomerCreatePage from '../components/pages/customers/CustomerCreatePage'
const NotFoundPage = { template: '<div>404</div>' }
export default [
{ path: '/customers', component: { template: '<router-view></router-view>' }, children: [
{
path: '', component: CustomerIndexPage
},
{
path: 'create', component: CustomerCreatePage
},
{
path: ':id', component: CustomerShowPage
},
{
path: ':id/edit', component: CustomerUpdatePage
}
] },
{ path: '/404', component: NotFoundPage },
{ path: '*', redirect: '/404' }
] | dvwzj/semi-vue-pos | vue/src/routes/main.js | JavaScript | mit | 885 |
var timed = require('../lib/timed')
var scheduler = require('./scheduler')
var toMidi = require('note-midi')
var toFreq = require('midi-freq')
function play (ac, player, obj) {
var e = timed.events(obj)
scheduler.schedule(ac, 0, e, function (time, note) {
console.log(time, note)
var freq = toFreq(440, toMidi(note.pitch))
if (freq) player(ac, freq, time, note.duration, note.velocity)
})
}
function synth (ac, freq, when, dur, vel) {
console.log('synth', freq, when, dur, vel)
var osc = ac.createOscillator()
var gain = ac.createGain()
osc.connect(gain)
gain.connect(ac.destination)
gain.gain.value = (vel || 80) / 100
osc.type = 'square'
osc.frequency.value = freq || 440
osc.start(when || 0)
osc.stop(when + (dur || 0.5))
}
module.exports = { play: play, synth: synth }
| danigb/scorejs | ext/player.js | JavaScript | mit | 815 |
/*jslint node: true */
"use strict";
const horoscope = require('horoscope');
const async = require('async');
const crypto = require('crypto');
const nodemailer = require('nodemailer');
const passport = require('passport');
const User = require('../models/User');
const Match = require('../models/Match');
const Message = require('../models/Message');
const Rating = require('../models/Rating');
const _ = require('lodash');
/**
* GET /login
* Login page.
*/
exports.getLogin = (req, res) => {
if (req.user) {
return res.redirect('/');
}
res.render('account/login', {
title: 'Login'
});
};
/**
* POST /login
* Sign in using email and password.
*/
exports.postLogin = (req, res, next) => {
req.assert('email', 'Email is not valid').isEmail();
req.assert('password', 'Password cannot be blank').notEmpty();
req.sanitize('email').normalizeEmail({remove_dots: false});
const errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/login');
}
passport.authenticate('local', (err, user, info) => {
if (err) {
return next(err);
}
if (!user) {
req.flash('errors', info);
return res.redirect('/login');
}
req.logIn(user, (err) => {
if (err) {
return next(err);
}
req.flash('success', {msg: 'Success! You are logged in.'});
res.redirect(req.session.returnTo || '/');
});
})(req, res, next);
};
/**
* GET /logout
* Log out.
*/
exports.logout = (req, res) => {
req.logout();
res.redirect('/');
};
/**
* GET /signup
* Signup page.
*/
exports.getSignup = (req, res) => {
if (req.user) {
return res.redirect('/');
}
res.render('account/signup', {
title: 'Create Account'
});
};
/**
* POST /signup
* Create a new local account.
*/
exports.postSignup = (req, res, next) => {
req.assert('email', 'Email is not valid').isEmail();
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);
req.sanitize('email').normalizeEmail({remove_dots: false});
const errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/signup');
}
const user = new User({
email: req.body.email,
password: req.body.password
});
User.findOne({email: req.body.email}, (err, existingUser) => {
if (err) {
return next(err);
}
if (existingUser) {
req.flash('errors', {msg: 'Account with that email address already exists.'});
return res.redirect('/signup');
}
user.save((err) => {
if (err) {
return next(err);
}
req.logIn(user, (err) => {
if (err) {
return next(err);
}
res.redirect('/');
});
});
});
};
/**
* GET /account
* Profile page.
*/
exports.getAccount = (req, res) => {
res.render('account/profile', {
title: 'Account Management'
});
};
/**
* Gets the astrological sign for a given user's birthday
* @param date
* @returns {string}
*/
function getAstrologicalSign(date){
var sign = '';
// Get the birthday from the user's profile
var birthday = new Date(date);
if (_.isDate(birthday)){
// Set the user's astrological sign based on the horoscope
sign = horoscope.getSign({month: birthday.getMonth(),
day: birthday.getDay()});
}
return sign;
}
/**
* Gets the age of the user from a given user's birthday
* @param date
* @returns {string}
*/
function getAgeFromBirthday(date){
var age = '';
// Get the birthday from the user's profile
var birthday = new Date(date);
if (_.isDate(birthday)){
// Set the user's astrological sign based on the horoscope
var currentTime = new Date(_.now());
console.log('currentTime' + currentTime);
console.log('currentTime.year' + currentTime.getYear());
console.log('current year=' + currentTime.getYear() + ' birthday year=' + birthday.getYear());
age = currentTime.getYear() - birthday.getYear();
}
return age;
}
/**
* POST /account/profile
* Update profile information.
*/
exports.postUpdateProfile = (req, res, next) => {
req.check('email', 'Please enter a valid email address.').isEmail();
req.check('zipcode', 'Please enter a valid ZIP code').len(4,5).isInt();
req.sanitize('email').normalizeEmail({remove_dots: false});
req.sanitizeBody('name');
req.sanitizeBody('birthday').toDate();
req.sanitizeBody('gender');
req.sanitizeBody('picture');
req.sanitizeBody('summary');
req.sanitizeBody('astrologicalSign');
req.sanitizeBody('eyeColor');
req.sanitizeBody('hairColor');
req.sanitizeBody('heightInches').toInt();
req.sanitizeBody('weightPounds').toInt();
req.sanitizeBody('fitnessLevel').toInt();
req.sanitizeBody('ethnicity');
req.sanitizeBody('language');
req.sanitizeBody('religion');
req.sanitizeBody('education');
req.sanitizeBody('diet');
req.sanitizeBody('caffeine').toBoolean();
req.sanitizeBody('alcohol').toBoolean();
req.sanitizeBody('tobacco').toBoolean();
req.sanitizeBody('weed').toBoolean();
req.sanitizeBody('otherDrugs').toBoolean();
req.sanitizeBody('cats').toBoolean();
req.sanitizeBody('dogs').toBoolean();
req.sanitizeBody('reptiles').toBoolean();
req.sanitizeBody('birds').toBoolean();
req.sanitizeBody('otherPets').toBoolean();
req.sanitizeBody('currentKids').toInt();
req.sanitizeBody('wantMoreKids').toBoolean();
req.sanitizeBody('messageMeIf');
req.sanitizeBody('doNotMessageIf');
req.sanitizeBody('genderInterests');
req.check({
'minAge': {
isInt: {
options: {
min: '18',
max: req.body.maxAge
},
errorMessage: 'Minimum age must be between 18 and the maximum age you entered.'
}
}
});
req.sanitizeBody('minAge').toInt();
req.check({
'maxAge': {
isInt: {
options: {
min: req.body.minAge,
max: '99'
},
errorMessage: 'Maximum age must be between the minimum age you entered and 99 (sorry old people, props for getting here though)'
}
}
});
req.sanitizeBody('maxAge').toInt();
req.sanitizeBody('relationshipTypes');
req.sanitizeBody('minDistanceMiles').toInt();
req.sanitizeBody('maxDistanceMiles').toInt();
req.sanitizeBody('minMatchPercent').toInt();
req.sanitizeBody('maxMatchPercent').toInt();
//TODO: we should have schemas for each one which maps to an enum or something
// religion enum - 1: christian, 2: jewish, etc.
const errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/account');
}
User.findById(req.user.id, (err, user) => {
if (err) {
return next(err);
}
//TODO: need to upload/manage profile pictures here too, maybe we could move it elsewhere
// General information
user.email = req.body.email || req.user.email || '';
user.profile.name = req.body.name || req.user.name || '';
user.profile.birthday = req.body.birthday || req.user.birthday || '';
user.profile.age = req.user.age || getAgeFromBirthday(user.profile.birthday) || '';
user.profile.gender = req.body.gender || req.user.gender || '';
//TODO: we might need zipcodes to get the locations, might be easier to do here rather than from the client side
//TODO: not sure what to do with the locations pulled from linkedin, facebook, etc.
user.profile.zipcode = req.body.zipcode || req.user.zipcode || '';
user.profile.summary = req.body.summary || req.user.summary || '';
user.profile.astrologicalSign = req.user.astrologicalSign || getAstrologicalSign(user.profile.birthday) || '';
// Physical appearance
user.profile.eyeColor = req.body.eyeColor || req.user.eyeColor || '';
user.profile.hairColor = req.body.hairColor || req.user.hairColor || '';
user.profile.heightInches = req.body.heightInches || req.user.heightInches || '';
user.profile.weightPounds = req.body.weightPounds || req.user.weightPounds || '';
user.profile.fitnessLevel = req.body.fitnessLevel || req.user.fitnessLevel || '';
// Culture
user.profile.ethnicity = req.body.ethnicity || req.user.ethnicity || '';
user.profile.language = req.body.language || req.user.language || '';
user.profile.religion = req.body.religion || req.user.religion || '';
user.profile.education = req.body.education || req.user.education || '';
// Dating Purpose
user.profile.messageMeIf = req.body.messageMeIf || req.user.messageMeIf || '';
user.profile.doNotMessageIf = req.body.doNotMessageIf || req.user.doNotMessageIf || '';
user.profile.genderInterests = req.body.genderInterests || req.user.genderInterests || '';
// Lifestyle
user.profile.diet = req.body.diet || req.user.diet || '';
user.profile.caffeine = req.body.caffeine || req.user.caffeine || '';
user.profile.alcohol = req.body.alcohol || req.user.alcohol || '';
user.profile.tobacco = req.body.tobacco || req.user.tobacco || '';
user.profile.weed = req.body.weed || req.user.weed || '';
user.profile.otherDrugs = req.body.otherDrugs || req.user.otherDrugs || '';
// Pets
user.profile.cats = req.body.cats || req.user.cats || '';
user.profile.dogs = req.body.dogs || req.user.dogs || '';
user.profile.reptiles = req.body.reptiles || req.user.reptiles || '';
user.profile.birds = req.body.birds || req.user.birds || '';
user.profile.otherPets = req.body.otherPets || req.user.otherPets || '';
// Kids
user.profile.currentKids = req.body.currentKids || req.user.currentKids || '';
user.profile.wantMoreKids = req.body.wantMoreKids || req.user.wantMoreKids || '';
// Logistics
user.profile.minAge = req.body.minAge || req.user.minAge || '';
user.profile.maxAge = req.body.maxAge || req.user.maxAge || '';
user.profile.relationshipTypes = req.body.relationshipTypes || req.user.relationshipTypes || '';
user.profile.minDistanceMiles = req.body.minDistanceMiles || req.user.minDistanceMiles || '';
user.profile.maxDistanceMiles = req.body.maxDistanceMiles || req.user.maxDistanceMiles || '';
user.profile.minMatchPercent = req.body.minMatchPercent || req.user.minMatchPercent || '';
user.profile.maxMatchPercent = req.body.maxMatchPercent || req.user.maxMatchPercent || '';
user.save((err) => {
if (err) {
if (err.code === 11000) {
req.flash('errors', {msg: 'The email address you have entered is already associated with an account.'});
return res.redirect('/account');
}
return next(err);
}
req.flash('success', {msg: 'Profile information has been updated.'});
res.redirect('/account');
});
});
};
/**
* POST /account/password
* Update current password.
*/
exports.postUpdatePassword = (req, res, next) => {
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);
const errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/account');
}
User.findById(req.user.id, (err, user) => {
if (err) {
return next(err);
}
user.password = req.body.password;
user.save((err) => {
if (err) {
return next(err);
}
req.flash('success', {msg: 'Password has been changed.'});
res.redirect('/account');
});
});
};
/**
* POST /account/delete
* Delete user account.
*/
exports.postDeleteAccount = (req, res, next) => {
User.remove({_id: req.user.id}, (err) => {
if (err) {
return next(err);
}
req.logout();
req.flash('info', {msg: 'Your account has been deleted.'});
res.redirect('/');
});
};
/**
* GET /account/unlink/:provider
* Unlink OAuth provider.
*/
exports.getOauthUnlink = (req, res, next) => {
const provider = req.params.provider;
User.findById(req.user.id, (err, user) => {
if (err) {
return next(err);
}
user[provider] = undefined;
user.tokens = user.tokens.filter(token => token.kind !== provider);
user.save((err) => {
if (err) {
return next(err);
}
req.flash('info', {msg: `${provider} account has been unlinked.`});
res.redirect('/account');
});
});
};
/**
* GET /reset/:token
* Reset Password page.
*/
exports.getReset = (req, res, next) => {
if (req.isAuthenticated()) {
return res.redirect('/');
}
User
.findOne({passwordResetToken: req.params.token})
.where('passwordResetExpires').gt(Date.now())
.exec((err, user) => {
if (err) {
return next(err);
}
if (!user) {
req.flash('errors', {msg: 'Password reset token is invalid or has expired.'});
return res.redirect('/forgot');
}
res.render('account/reset', {
title: 'Password Reset'
});
});
};
/**
* POST /reset/:token
* Process the reset password request.
*/
exports.postReset = (req, res, next) => {
req.assert('password', 'Password must be at least 4 characters long.').len(4);
req.assert('confirm', 'Passwords must match.').equals(req.body.password);
const errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('back');
}
async.waterfall([
function resetPassword(done) {
User
.findOne({passwordResetToken: req.params.token})
.where('passwordResetExpires').gt(Date.now())
.exec((err, user) => {
if (err) {
return next(err);
}
if (!user) {
req.flash('errors', {msg: 'Password reset token is invalid or has expired.'});
return res.redirect('back');
}
user.password = req.body.password;
user.passwordResetToken = undefined;
user.passwordResetExpires = undefined;
user.save((err) => {
if (err) {
return next(err);
}
req.logIn(user, (err) => {
done(err, user);
});
});
});
},
function sendResetPasswordEmail(user, done) {
const transporter = nodemailer.createTransport({
service: 'SendGrid',
auth: {
user: process.env.SENDGRID_USER,
pass: process.env.SENDGRID_PASSWORD
}
});
const mailOptions = {
to: user.email,
from: 'hackathon@starter.com',
subject: 'Your Hackathon Starter password has been changed',
text: `Hello,\n\nThis is a confirmation that the password for your account ${user.email} has just been changed.\n`
};
transporter.sendMail(mailOptions, (err) => {
req.flash('success', {msg: 'Success! Your password has been changed.'});
done(err);
});
}
], (err) => {
if (err) {
return next(err);
}
res.redirect('/');
});
};
/**
* GET /forgot
* Forgot Password page.
*/
exports.getForgot = (req, res) => {
if (req.isAuthenticated()) {
return res.redirect('/');
}
res.render('account/forgot', {
title: 'Forgot Password'
});
};
/**
* POST /forgot
* Create a random token, then the send user an email with a reset link.
*/
exports.postForgot = (req, res, next) => {
req.assert('email', 'Please enter a valid email address.').isEmail();
req.sanitize('email').normalizeEmail({remove_dots: false});
const errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/forgot');
}
async.waterfall([
function createRandomToken(done) {
crypto.randomBytes(16, (err, buf) => {
const token = buf.toString('hex');
done(err, token);
});
},
function setRandomToken(token, done) {
User.findOne({email: req.body.email}, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
req.flash('errors', {msg: 'Account with that email address does not exist.'});
return res.redirect('/forgot');
}
user.passwordResetToken = token;
user.passwordResetExpires = Date.now() + 3600000; // 1 hour
user.save((err) => {
done(err, token, user);
});
});
},
function sendForgotPasswordEmail(token, user, done) {
const transporter = nodemailer.createTransport({
service: 'SendGrid',
auth: {
user: process.env.SENDGRID_USER,
pass: process.env.SENDGRID_PASSWORD
}
});
const mailOptions = {
to: user.email,
from: 'support@fourthmouse.com',
subject: 'Reset your Fourth Mouse account password',
text: `You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n
Please click on the following link, or paste this into your browser to complete the process:\n\n
http://${req.headers.host}/reset/${token}\n\n
If you did not request this, please ignore this email and your password will remain unchanged.\n`
};
transporter.sendMail(mailOptions, (err) => {
req.flash('info', {msg: `An e-mail has been sent to ${user.email} with further instructions.`});
done(err);
});
}
], (err) => {
if (err) {
return next(err);
}
res.redirect('/forgot');
});
};
| Geroy/FourthMouse | controllers/user.js | JavaScript | mit | 19,383 |
/**
* @requires
*/
_import('components.worker.elements.websocketserver.WebsocketServer');
/**
* The httpsserver that attaches the convoy protocols
* @class HttpsServer
* @type {object}
*/
var _self = _class('components.worker.elements.httpsserver.HttpsServer');
/**
* @constructor
*/
_self.__construct = function() {
this.createServer();
};
/**
* Creates an HTTPS server
*/
_self.createServer = function() {
// TODO: make this specific files based on the project requested
var options = {
// default certs (these will be overridden using the SNICallback)
// TODO find a way to catch clients that don't support SNI (prehaps redirect to convoy.io?)
//ca: fs.readFileSync('cert/startssl_intermediate.pem'),
key: fs.readFileSync('cert/server.key'),
cert: fs.readFileSync('cert/server.crt'),
};
// workers can actually share the same port. awesome.
var httpsServer = spdy.createServer(options, function(req, res) {
_pubsub.publish("httpsserver.onRequest", {
req: req,
res: res
});
}.bind(this)).listen(convoy.config.https.port, "::"); // supports both IPv4 & IPv6
this.webSocketServer = _new('components.worker.elements.websocketserver.WebsocketServer', httpsServer);
console.log(this.namespace, 'https server listening');
};
| theundebruijn/convoy | backend/server/components/worker/elements/httpsserver/HttpsServer.js | JavaScript | mit | 1,300 |
import React from 'react';
import '../css/App.css';
class App extends React.Component {
constructor (...args) {
super(...args);
}
render() {
return <div className="font-c">Hello World !</div>;
}
}
export default App; | fengnovo/diary | seed/src/js/App.js | JavaScript | mit | 251 |
Toro.CandidatoController=Ember.ObjectController.extend({needs:"application",actions:{mostrar_mensagens:function(){var o=this.get("controllers.application");o.isShowingMessages?(o.set("isShowingMessages",!1),this.transitionToRoute("candidato")):(o.set("isShowingMessages",!this.isShowingMessages),this.transitionToRoute("mensagem"))},voto_favor:function(o,t){this.transitionToRoute("voto",o,t,"favor")},voto_contra:function(o,t){this.transitionToRoute("voto",o,t,"contra")}}}); | vedovelli/toro | js/controllers/candidato-min.js | JavaScript | mit | 476 |
import React, {Component} from 'react'
import {
View,
ScrollView,
Dimensions,
TextInput,
Switch,
Text,
} from 'react-native'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import * as serverActions from '../redux/actions/serverActions'
import * as authActions from '../redux/actions/authActions'
import * as accountSettingsActions from '../redux/actions/accountSettingsActions'
import {Actions} from '../../node_modules/react-native-router-flux'
import ActionsSettingsList from '../components/accountSettings/ActionsSettingsList'
import style, {COLOR_2, COLOR_3, COLOR_4, COLOR_5} from '../stylesheets/styles'
import ProgressView from '../components/ProgressView'
import HVTButton from '../components/HVTButton'
const deviceWidth = Dimensions.get('window').width
const deviceHeight = Dimensions.get('window').height
class AccountSettingsContainer extends Component {
constructor(props) {
super(props)
this.state = {
container: {
width: deviceWidth,
height: deviceHeight,
},
}
}
render() {
const {accountSettingsFieldChanged} = this.props
return (
<ScrollView {...style('container', [{padding: 20}])}>
<View style={{flex: 1, marginBottom: 240}}>
<View style={{backgroundColor: COLOR_4}}>
<Text {...style('text text.huge', [{color: COLOR_3, textAlign:'center'}])}>
Account Settings
</Text>
</View>
<TextInput
{...style('text.heading form.textInput', [{backgroundColor:COLOR_3, marginLeft: 0, marginRight: 0, marginBottom: 0}])}
placeholder={"Display Name"}
ref={(component) => this.textInputDisplayName = component}
returnKeyType="next"
onChangeText={(value) => accountSettingsFieldChanged({field: 'displayName', value})}
onKeyPress={(event) => {
if (event.nativeEvent.key === 'Enter') {
this.textInputDisplayName.blur()
}
}}
value={this.props.displayName}
/>
<View style={{flex: 1, marginTop: 8, marginBottom: 8, flexDirection: 'row'}}>
<View style={{flex : 1, justifyContent: 'center'}}>
<Text {...style('text', [{color: COLOR_5, padding: 0, margin: 0, paddingTop: 8, paddingBottom: 8}])} numberOfLines={2}>
Get an email when someone shares to me
</Text>
</View>
<Switch
style={{marginLeft: 0, width: 48}}
value={true}
/>
</View>
<Text {...style('text', [{color: COLOR_2, margin: 0, padding:0, marginLeft: 0, marginRight: 0, marginBottom: 0, marginTop: 0, textAlign:'center'}])}>-</Text>
<Text {...style('text', [{color: COLOR_2, margin: 0, marginLeft: 0, marginRight: 0, marginBottom: 8, marginTop: 6}])} numberOfLines={6}>
{`Using the IFTTT Maker API you can integrate a number of services by cloning our example recipe *here* and pasting the URL back into the 'IFTTT URL' field. Hint: you can use emoji 📌📷👻🌮⛱🎉 to make custom buttons!`}
</Text>
<View style={{backgroundColor: COLOR_4, marginTop: 8, marginBottom: 8}}>
<Text {...style('text text.huge', [{color: COLOR_3, textAlign:'center'}])}>
IFTTT Actions
</Text>
</View>
<ActionsSettingsList />
<HVTButton
text={"Update Account"}
onPress={() => {
this.props.updateCurrentUser()
}}
extraTouchableStyle={{marginTop: 10, marginBottom: 10, marginLeft: 10, marginRight: 10}}
/>
<HVTButton
text={"Log Out"}
onPress={() => {
this.props.logout()
Actions.Intro()
}}
extraTouchableStyle={{marginTop: 2, marginBottom: 10, marginLeft: 10, marginRight: 10}}
extraTextWrapperStyle={{backgroundColor: COLOR_3}}
extraTextStyle={{color: COLOR_2}}
/>
</View>
</ScrollView>
)
}
}
export default connect(
(state) => {
return state.accountSettings
},
(dispatch) => {
return {
...bindActionCreators(serverActions, dispatch),
...bindActionCreators(authActions, dispatch),
...bindActionCreators(accountSettingsActions, dispatch),
}
}
)(AccountSettingsContainer)
| gr4yscale/havit | src/containers/AccountSettingsContainer.js | JavaScript | mit | 4,517 |
'use strict';
var jwtTestHelper = require('../../config/auth/jwtTestHelper');
var app = require('../../app');
var seed = require('../../config/seed');
var request = require('supertest');
var BoardRepository = require('../../repositories/board.repository');
describe('Board Web API', function() {
before(function(done) {
seed()
.then(function() {
done();
});
});
it('criar uma nova combinação', function(done) {
request(app)
.post(jwtTestHelper.appendAccessTokenUrl('/api/board/create', 'mcarolina', 'facebook'))
.send({
'hiInt': 264,
'loInt': 6272
})
.expect(200)
.end(function(err, res) {
res.body.should.not.be.instanceOf(Array);
res.body.selectedTimes.should.be.equal(1);
if (err) return done(err);
done();
});
});
it('criar uma combinação existente', function(done) {
request(app)
.post(jwtTestHelper.appendAccessTokenUrl('/api/board/create', 'jsilva', 'facebook'))
.send({
'hiInt': 264,
'loInt': 6272
})
.expect(200)
.end(function(err, res) {
res.body.should.not.be.instanceOf(Array);
res.body.selectedTimes.should.be.equal(2);
if (err) return done(err);
done();
});
});
it('criar uma combinação inválida zerada para rejeitar', function(done) {
request(app)
.post(jwtTestHelper.appendAccessTokenUrl('/api/board/create', 'mcarolina', 'facebook'))
.send({
'hiInt': 0,
'loInt': 0
})
.expect(400)
.end(function(err, res) {
if (err) return done(err);
done();
});
});
it('criar uma combinação inválida completa para rejeitar', function(done) {
request(app)
.post(jwtTestHelper.appendAccessTokenUrl('/api/board/create', 'mcarolina', 'facebook'))
.send({
'hiInt': 4095,
'loInt': 8191
})
.expect(400)
.end(function(err, res) {
if (err) return done(err);
done();
});
});
}); | ericogr/jeco | server/api/board/board.spec.js | JavaScript | mit | 1,867 |
export default from './reducers';
| grxy/boilerplate | src/services/redux/reducers/index.js | JavaScript | mit | 34 |
/***********************************************************************
* retro-205/webUI D205ConsoleOutput.js
************************************************************************
* Copyright (c) 2014, Paul Kimpel.
* Licensed under the MIT License, see
* http://www.opensource.org/licenses/mit-license.php
************************************************************************
* ElectroData/Burroughs Datatron 205 Flexowriter printer and
* High-Speed Paper Tape Punch devices.
************************************************************************
* 2014-12-26 P.Kimpel
* Original version, from retro-B5500 B5500SPOUnit.js.
***********************************************************************/
"use strict";
/**************************************/
function D205ConsoleOutput(mnemonic, p) {
/* Constructor for the Console Output object */
this.config = p.config; // System configuration object
this.hasFlexowriter = p.config.getNode("ControlConsole.hasFlexowriter");
this.hasPaperTapePunch = p.config.getNode("ControlConsole.hasPaperTapePunch");
this.maxScrollLines = 15000; // Maximum amount of printer/punch scrollback
this.mnemonic = mnemonic; // Unit mnemonic
this.outTimer = 0; // output setCallback() token
this.punchPeriod = 1000/60; // Punch speed, ms/c (60 cps)
this.boundButton_Click = D205ConsoleOutput.prototype.button_Click.bind(this);
this.boundFlipSwitch = D205ConsoleOutput.prototype.flipSwitch.bind(this);
this.clear();
// Create the Flexowriter window and onload event
if (this.hasFlexowriter) {
this.flexUse204Codes = p.config.getNode("Flexowriter.use204FlexCodes") || false;
this.flexDoc = null;
this.flexWin = null;
this.flexPaper = null;
this.flexLine = null;
this.flexEOP = null;
this.flexCol = 0;
D205Util.openPopup(window, "../webUI/D205Flexowriter.html", "Flexowriter",
"location=no,scrollbars=no,resizable,width=668,height=370,left=0,top=0",
this, D205ConsoleOutput.prototype.flexOnload);
}
// Create the Paper Tape Punch window and onload event
if (this.hasPaperTapePunch) {
this.punchDoc = null;
this.punchWin = null;
this.punchTape = null;
this.punchEOP = null;
D205Util.openPopup(window, "../webUI/D205PaperTapePunch.html", "PaperTapePunch",
"location=no,scrollbars=no,resizable,width=290,height=100,left=0,top=430",
this, D205ConsoleOutput.prototype.punchOnload);
}
}
/**************************************/
D205ConsoleOutput.offSwitch = "./resources/ToggleDown.png";
D205ConsoleOutput.midSwitch = "./resources/ToggleMid.png";
D205ConsoleOutput.onSwitch = "./resources/ToggleUp.png";
D205ConsoleOutput.cardatronXlate = [ // translate internal Cardatron code to ANSI
" ", "|", "|", ".", "|", "|", "|", "|", "|", "|", // 00-09
"&", "|", "|", "$", "&", "|", "|", "$", "&", "|", // 10-19
"-", "/", "|", ",", "%", "|", "|", "|", "|", "|", // 20-29
"|", "|", "|", "|", "\t", "\n", "|", "|", "|", "|", // 30-39
"|", "A", "B", "C", "D", "E", "F", "G", "H", "I", // 40-49
"|", "J", "K", "L", "M", "N", "O", "P", "Q", "R", // 50-59
"|", "|", "S", "T", "U", "V", "W", "X", "Y", "Z", // 60-69
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", // 70-79
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", // 80-89
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; // 90-99
D205ConsoleOutput.flex204XlateLower = [ // translate lower-case 203/204 Flexowriter codes to ANSI
"|", "|", "|", "|", "\t","\n","|", "|", "|", "|", // 00-09
"|", "|", "|", "|", "|", "|", "|", "|", "|", "|", // 10-19
"a", "r", "s", "t", "+", "-", ";", "|", "|", "|", // 20-29
"|", ",", ".", "'", " ", "|", "l", "|", "|", "|", // 30-39
"0", "1", "2", "3", "4", "5", "6", "7", "|", "|", // 40-49
"8", "9", "u", "v", "w", "x", "y", "z", "|", "|", // 50-59
"|", "b", "c", "d", "e", "f", "g", "h", "|", "|", // 60-69
"i", "j", "k", "m", "n", "o", "p", "q", "|", "|", // 70-79
"|", "|", "|", "|", "|", "|", "|", "|", "|", "|", // 80-89
"|", "|", "|", "|", "|", "|", "|", "|", "|", "|"]; // 90-99
D205ConsoleOutput.flex204XlateUpper = [ // translate upper-case 203/204 Flexowriter codes to ANSI
"|", "|", "|", "|", "\t","\n","|", "|", "|", "|", // 00-09
"|", "|", "|", "|", "|", "|", "|", "|", "|", "|", // 10-19
"A", "R", "S", "T", "=", "_", ":", "|", "|", "|", // 20-29
"|", ",", ".", "\""," ", "|", "L", "|", "|", "|", // 30-39
")", "#", "&", "/", "$", "%", "?", "!", "|", "|", // 40-49
"*", "(", "U", "V", "W", "X", "Y", "Z", "|", "|", // 50-59
"|", "B", "C", "D", "E", "F", "G", "H", "|", "|", // 60-69
"I", "J", "K", "M", "N", "O", "P", "Q", "|", "|", // 70-79
"|", "|", "|", "|", "|", "|", "|", "|", "|", "|", // 80-89
"|", "|", "|", "|", "|", "|", "|", "|", "|", "|"]; // 90-99
/**************************************/
D205ConsoleOutput.prototype.clear = function clear() {
/* Initializes (and if necessary, creates) the SPO unit state */
this.ready = false; // ready status
this.busy = false; // busy status
this.formatDigit = 0; // format digit from PO or POF C8
this.alphaFirstDigit = 0; // first digit of an alpha pair
this.alphaLock = 0; // alpha translation enabled for format=4
this.zeroSuppress = 0; // currently suppressing leading zeroes
this.stopPrintout = 0; // idle processor if a printout command occurs
this.upperCase = 0; // current shift position (204 Flex encoding only)
this.printRed = 0; // print in red color (204 Flex encoding only)
this.wordCounter = 0; // grouping words/line counter
this.lineCounter = 0; // grouping lines/group counter
this.groupCounter = 0; // grouping groups/page counter
this.pendingSignalOK = null; // pending I/O-complete successor function
this.pendingOutputFcn = null; // pending output function that was stopped
this.pendingOutputUnit = 0; // pending output unit designator
this.pendingOutputDigit = 0; // pending output digit
};
/**************************************/
D205ConsoleOutput.prototype.resetCounters = function resetCounters() {
/* Resets the grouping counters and turns on the Reset lamp. If the carriage
is not at the left margin, a new-line is issued. If there is pending output
function that was stopped earlier, it is now called */
var outputFcn;
var signalOK;
this.wordCounter = 0;
this.lineCounter = 0;
this.groupCounter = 0;
this.stopPrintout = 0;
this.resetLamp.set(1);
if (this.flexCol > 0) {
this.flexEmptyLine();
}
if (this.pendingOutputFcn) {
outputFcn = this.pendingOutputFcn;
this.pendingOutputFcn = null;
signalOK = this.pendingSignalOK;
this.pendingSignalOK = null;
outputFcn.call(this, this.pendingOutputUnit, this.pendingOutputDigit, signalOK);
}
};
/**************************************/
D205ConsoleOutput.prototype.beforeUnload = function beforeUnload(ev) {
var msg = "Closing this window will make the device unusable.\n" +
"Suggest you stay on the page and minimize this window instead";
ev.preventDefault();
ev.returnValue = msg;
return msg;
};
/***********************************************************************
* Flexowriter Interface *
***********************************************************************/
/**************************************/
D205ConsoleOutput.prototype.flexSetMode = function flexSetMode(mode204) {
this.flex$$("FlexowriterMode").textContent =
(mode204 ? "203/204 CODES" : "CARDATRON CODES");
};
/**************************************/
D205ConsoleOutput.prototype.flex$$ = function flex$$(e) {
return this.flexDoc.getElementById(e);
};
/**************************************/
D205ConsoleOutput.prototype.flexEmptyPaper = function flexEmptyPaper() {
/* Empties the Flex output "paper" and initializes it for new output */
while (this.flexPaper.firstChild) {
this.flexPaper.removeChild(this.flexPaper.firstChild);
}
this.flexLine = this.flexDoc.createTextNode("");
this.flexPaper.appendChild(this.flexLine);
};
/**************************************/
D205ConsoleOutput.prototype.flexEmptyLine = function flexEmptyLine(text) {
/* Removes excess lines already output, then appends a new text node
to the <pre> element within the paper element */
var paper = this.flexPaper;
var line = text || "";
while (paper.childNodes.length > this.maxScrollLines) {
paper.removeChild(paper.firstChild);
}
this.flexLine.nodeValue += "\n"; // newline
paper = this.flexLine.parentNode;
this.flexLine = this.flexDoc.createTextNode(line);
paper.appendChild(this.flexLine);
this.flexCol = line.length;
this.flexEOP.scrollIntoView();
};
/**************************************/
D205ConsoleOutput.prototype.flexChar = function flexChar(c) {
/* Outputs the character "c" to the output device */
var line = this.flexLine.nodeValue;
var len = line.length;
if (len < 1) {
line = c;
++this.flexCol;
} else if (this.flexCol < 120) {
line += c;
++this.flexCol;
} else {
line = line.substring(0, len-1) + c;
}
this.flexLine.nodeValue = line;
};
/**************************************/
D205ConsoleOutput.prototype.flexPrintRed = function flexPrintRed(enable) {
/* Changes the printing color to/from red based on "enable" */
var e = null;
this.flexLine = this.flexDoc.createTextNode("");
if (enable) {
e = this.flexDoc.createElement("SPAN");
e.className = "red";
e.appendChild(this.flexLine);
this.flexPaper.appendChild(e);
} else {
this.flexPaper.appendChild(this.flexLine);
}
};
/**************************************/
D205ConsoleOutput.prototype.flexResizeWindow = function flexResizeWindow(ev) {
/* Handles the window onresize event by scrolling the "paper" so it remains at the end */
this.flexEOP.scrollIntoView();
};
/**************************************/
D205ConsoleOutput.prototype.flexCopyPaper = function flexCopyPaper(ev) {
/* Copies the text contents of the "paper" area of the device, opens a new
temporary window, and pastes that text into the window so it can be copied
or saved by the user */
var text = this.flexPaper.textContent;
var title = "D205 " + this.mnemonic + " Text Snapshot";
D205Util.openPopup(window, "./D205FramePaper.html", "",
"scrollbars,resizable,width=500,height=500",
this, function(ev) {
var doc = ev.target;
var win = doc.defaultView;
doc.title = title;
win.moveTo((screen.availWidth-win.outerWidth)/2, (screen.availHeight-win.outerHeight)/2);
doc.getElementById("Paper").textContent = text;
});
this.flexEmptyPaper();
this.flexEmptyLine();
ev.preventDefault();
ev.stopPropagation();
};
/**************************************/
D205ConsoleOutput.prototype.button_Click = function button_Click(ev) {
/* Handler for button clicks */
switch (ev.target.id) {
case "ResetBtn":
this.resetCounters();
break;
case "FlexowriterMode":
this.flexUse204Codes = !this.flexUse204Codes;
this.flexSetMode(this.flexUse204Codes);
break;
} // switch ev.target.id
ev.preventDefault();
ev.stopPropagation();
return false;
};
/**************************************/
D205ConsoleOutput.prototype.flipSwitch = function flipSwitch(ev) {
/* Handler for switch clicks */
switch (ev.target.id) {
case "ZeroSuppressSwitch":
this.zeroSuppressSwitch.flip();
this.config.putNode("Flexowriter.zeroSuppressSwitch", this.zeroSuppressSwitch.state);
break;
case "TabSpaceSwitch":
this.tabSpaceSwitch.flip();
this.config.putNode("Flexowriter.tabSpaceSwitch", this.tabSpaceSwitch.state);
break;
case "GroupingCountersSwitch":
this.groupingCountersSwitch.flip();
this.config.putNode("Flexowriter.groupingCountersSwitch", this.groupingCountersSwitch.state);
break;
case "AutoStopSwitch":
this.autoStopSwitch.flip();
this.config.putNode("Flexowriter.autoStopSwitch", this.autoStopSwitch.state);
break;
case "PowerSwitch":
this.powerSwitch.flip();
this.config.putNode("Flexowriter.powerSwitch", 1); // always force on
setCallback(null, this.powerSwitch, 250, this.powerSwitch.set, 1);
break;
case "WordsKnob":
this.config.putNode("Flexowriter.wordsKnob", ev.target.selectedIndex);
break;
case "LinesKnob":
this.config.putNode("Flexowriter.linesKnob", ev.target.selectedIndex);
break;
case "GroupsKnob":
this.config.putNode("Flexowriter.groupsKnob", ev.target.selectedIndex);
break;
}
ev.preventDefault();
return false;
};
/**************************************/
D205ConsoleOutput.prototype.flexOnload = function flexOnload(ev) {
/* Initializes the Flexowriter window and user interface */
var body;
var prefs = this.config.getNode("Flexowriter");
this.flexDoc = ev.target;
this.flexWin = this.flexDoc.defaultView;
this.flexDoc.title = "retro-205 - Flexowriter";
this.flexPaper = this.flex$$("Paper");
this.flexEOP = this.flex$$("EndOfPaper");
this.flexEmptyPaper();
this.flexEmptyLine();
this.flexSetMode(this.flexUse204Codes);
body = this.flex$$("FormatControlsDiv");
this.resetLamp = new ColoredLamp(body, null, null, "ResetLamp", "whiteLamp", "whiteLit");
this.zeroSuppressSwitch = new ToggleSwitch(body, null, null, "ZeroSuppressSwitch",
D205ConsoleOutput.offSwitch, D205ConsoleOutput.onSwitch);
this.zeroSuppressSwitch.set(prefs.zeroSuppressSwitch);
this.tabSpaceSwitch = new ThreeWaySwitch(body, null, null, "TabSpaceSwitch",
D205ConsoleOutput.midSwitch, D205ConsoleOutput.offSwitch, D205ConsoleOutput.onSwitch);
this.tabSpaceSwitch.set(prefs.tabSpaceSwitch);
this.groupingCountersSwitch = new ThreeWaySwitch(body, null, null, "GroupingCountersSwitch",
D205ConsoleOutput.midSwitch, D205ConsoleOutput.offSwitch, D205ConsoleOutput.onSwitch);
this.groupingCountersSwitch.set(prefs.groupingCountersSwitch);
this.autoStopSwitch = new ToggleSwitch(body, null, null, "AutoStopSwitch",
D205ConsoleOutput.offSwitch, D205ConsoleOutput.onSwitch);
this.autoStopSwitch.set(prefs.autoStopSwitch);
this.powerSwitch = new ToggleSwitch(body, null, null, "PowerSwitch",
D205ConsoleOutput.offSwitch, D205ConsoleOutput.onSwitch);
this.powerSwitch.set(prefs.powerSwitch);
this.wordsKnob = this.flex$$("WordsKnob");
this.wordsKnob.selectedIndex = prefs.wordsKnob;
this.linesKnob = this.flex$$("LinesKnob");
this.linesKnob.selectedIndex = prefs.linesKnob;
this.groupsKnob = this.flex$$("GroupsKnob");
this.groupsKnob.selectedIndex = prefs.groupsKnob;
this.flexWin.addEventListener("beforeunload",
D205ConsoleOutput.prototype.beforeUnload);
this.flexWin.addEventListener("resize",
D205ConsoleOutput.prototype.flexResizeWindow.bind(this));
this.flexPaper.addEventListener("dblclick",
D205ConsoleOutput.prototype.flexCopyPaper.bind(this));
this.flex$$("ResetBtn").addEventListener("click", this.boundButton_Click);
this.flex$$("FlexowriterMode").addEventListener("click", this.boundButton_Click);
this.flex$$("ZeroSuppressSwitch").addEventListener("click", this.boundFlipSwitch);
this.flex$$("TabSpaceSwitch").addEventListener("click", this.boundFlipSwitch);
this.flex$$("GroupingCountersSwitch").addEventListener("click", this.boundFlipSwitch);
this.flex$$("AutoStopSwitch").addEventListener("click", this.boundFlipSwitch);
this.flex$$("PowerSwitch").addEventListener("click", this.boundFlipSwitch);
this.wordsKnob.addEventListener("change", this.boundFlipSwitch);
this.linesKnob.addEventListener("change", this.boundFlipSwitch);
this.groupsKnob.addEventListener("change", this.boundFlipSwitch);
this.flexWin.focus();
};
/***********************************************************************
* Paper Tape Punch Interface *
***********************************************************************/
/**************************************/
D205ConsoleOutput.prototype.punch$$ = function punch$$(e) {
return this.punchDoc.getElementById(e);
};
/**************************************/
D205ConsoleOutput.prototype.punchEmptyPaper = function punchEmptyPaper() {
/* Empties the punch output "paper" and initializes it for new output */
while (this.punchTape.firstChild) {
this.punchTape.removeChild(this.punchTape.firstChild);
}
this.punchTape.appendChild(this.punchDoc.createTextNode(""));
};
/**************************************/
D205ConsoleOutput.prototype.punchEmptyLine = function punchEmptyLine(text) {
/* Removes excess lines already output, then appends a new text node
to the <pre> element within the paper element */
var paper = this.punchTape;
var line = text || "";
while (paper.childNodes.length > this.maxScrollLines) {
paper.removeChild(paper.firstChild);
}
paper.lastChild.nodeValue += "\n"; // newline
paper.appendChild(this.punchDoc.createTextNode(line));
};
/**************************************/
D205ConsoleOutput.prototype.punchChar = function punchChar(c) {
/* Outputs the character "c" to the output device */
var line = this.punchTape.lastChild.nodeValue;
var len = line.length;
if (len < 1) {
line = c;
} else {
line += c;
}
this.punchTape.lastChild.nodeValue = line;
};
/**************************************/
D205ConsoleOutput.prototype.punchResizeWindow = function punchResizeWindow(ev) {
/* Handles the window onresize event by scrolling the "paper" so it remains at the end */
this.punchEOP.scrollIntoView();
};
/**************************************/
D205ConsoleOutput.prototype.punchCopyTape = function punchCopyTape(ev) {
/* Copies the text contents of the "paper" area of the device, opens a new
temporary window, and pastes that text into the window so it can be copied
or saved by the user */
var text = this.punchTape.textContent;
var title = "D205 " + this.mnemonic + " Text Snapshot";
var win = null;
D205Util.openPopup(window, "./D205FramePaper.html", "",
"scrollbars,resizable,width=500,height=500",
this, function(ev) {
var doc = ev.target;
var win = doc.defaultView;
doc.title = title;
win.moveTo((screen.availWidth-win.outerWidth)/2, (screen.availHeight-win.outerHeight)/2);
doc.getElementById("Paper").textContent = text;
});
this.punchEmptyPaper();
ev.preventDefault();
ev.stopPropagation();
};
/**************************************/
D205ConsoleOutput.prototype.punchOnload = function punchOnload(ev) {
/* Initializes the Paper Tape Punch window and user interface */
this.punchDoc = ev.target;
this.punchWin = this.punchDoc.defaultView;
this.punchDoc.title = "retro-205 - Paper Tape Punch";
this.punchTape = this.punch$$("Paper");
this.punchEOP = this.punch$$("EndOfPaper");
this.punchEmptyPaper();
this.punchWin.addEventListener("beforeunload",
D205ConsoleOutput.prototype.beforeUnload);
this.punchWin.addEventListener("resize",
D205ConsoleOutput.prototype.punchResizeWindow.bind(this));
this.punchTape.addEventListener("dblclick",
D205ConsoleOutput.prototype.punchCopyTape.bind(this));
//this.punchWin.moveTo(screen.availWidth-this.punchWin.outerWidth,
// screen.availHeight-this.punchWin.outerHeight);
//this.punchWin.moveTo(0, 430);
this.punchWin.focus();
};
/***********************************************************************
* Output Entry Points *
***********************************************************************/
/**************************************/
D205ConsoleOutput.prototype.writeFormatDigit = function writeFormatDigit(
outputUnit, formatDigit, signalOK) {
/* Sets the format digit at the beginning of output for a word, or as the
result of a POF instruction. Delays for an appropriate amount of time, then
calls the Processor's signalOK function. */
var delay = 1000/14; // default character output delay, ms
var tabCol = 0; // tabulation column
if (this.stopPrintout) {
this.pendingOutputFcn = writeFormatDigit;
this.pendingOutputUnit = outputUnit;
this.pendingOutputDigit = formatDigit;
this.pendingSignalOK = signalOK;
} else {
switch (outputUnit) {
case 1: // Flexowriter
if (this.hasFlexowriter) {
switch (formatDigit) {
case 2: // suppress sign, print decimal point instead
case 3: // suppress sign, print space instead
case 4: // translate alphanumerically
this.alphaLock = 0;
delay = 120;
this.formatDigit = formatDigit;
break;
case 5: // actuate carriage return
delay = this.flexCol/120*55 + 70; // 70-125ms based on carriage position
this.flexEmptyLine();
break;
case 6: // actuate tab key
tabCol = Math.floor((this.flexCol + 8)/8)*8;
while (this.flexCol < tabCol) {
this.flexChar(" ");
}
break;
case 7: // set stop printout flag
this.stopPrintout = 1;
break;
case 8: // actuate space bar
this.flexChar(" ");
break;
} // switch formatDigit
setCallback(this.mnemonic, this, delay, signalOK);
}
break;
case 2: // Paper-tape punch
if (this.hasPaperTapePunch) {
// Format digit is used only to feed blank tape -- it isn't output by this implementation
switch (formatDigit) {
case 1:
delay = this.punchPeriod;
this.punchChar(" ");
break;
default:
break;
} // switch formatDigit
setCallback(this.mnemonic, this, delay, signalOK);
}
break;
} // switch outputUnit
}
};
/**************************************/
D205ConsoleOutput.prototype.writeSignDigit = function writeSignDigit(outputUnit, signDigit, signalOK) {
/* Outputs (or not) the sign digit of a word. Delays for an appropriate
amount of time, then calls the Processor's signalOK function */
var delay = 65; // default character output delay, ms
if (this.stopPrintout) {
this.pendingOutputFcn = writeSignDigit;
this.pendingOutputUnit = outputUnit;
this.pendingOutputDigit = signDigit;
this.pendingSignalOK = signalOK;
} else {
switch (outputUnit) {
case 1: // Flexowriter
if (this.hasFlexowriter) {
this.zeroSuppress = this.zeroSuppressSwitch.state;
switch (this.formatDigit) {
case 2: // suppress sign, print decimal point instead
this.zeroSuppress = 0;
this.flexChar(".");
break;
case 3: // suppress sign, print space instead
this.flexChar(" ");
break;
case 4: // translate alphanumerically -- ignore the sign
delay = 62;
break;
default:
this.flexChar((signDigit & 0x01) ? "-" : "+");
break;
} // switch formatDigit
setCallback(this.mnemonic, this, delay, signalOK);
}
break;
case 2: // Paper-tape punch
if (this.hasPaperTapePunch) {
delay = this.punchPeriod;
this.punchChar(signDigit.toString());
setCallback(this.mnemonic, this, delay, signalOK);
}
break;
} // switch outputUnit
}
};
/**************************************/
D205ConsoleOutput.prototype.writeNumberDigit = function writeNumberDigit(outputUnit, digit, signalOK) {
/* Sets the current digit in the translator and outputs it if appropriate */
var char = ""; // ASCII character to output
var delay = 70; // default delay
var tabCol = 0; // tabulation column
switch (outputUnit) {
case 1: // Flexowriter
if (this.hasFlexowriter) {
if (this.formatDigit == 4) { // translate alphanumerically
if (this.alphaLock) {
this.alphaLock = 0;
delay = 75;
digit += this.alphaFirstDigit*10;
if (!this.flexUse204Codes) {
char = D205ConsoleOutput.cardatronXlate[digit];
} else {
char = this.upperCase ? D205ConsoleOutput.flex204XlateUpper[digit]
: D205ConsoleOutput.flex204XlateLower[digit];
switch (digit) {
case 1: // backspace
if (this.flexCol > 0) {
--this.flexCol;
tabCol = this.flexLine.nodeValue.length;
if (tabCol > 0) {
this.flexLine.nodeValue =
this.flexLine.nodeValue.substring(0, tabCol-1);
}
}
break;
case 27: // lower case
this.upperCase = false;
break;
case 30: // upper case
this.upperCase = true;
break;
case 35: // color shift
this.printRed = 1 - this.printRed;
this.flexPrintRed(this.printRed);
break;
default:
break;
}
}
switch (char) {
case "|": // some characters are just ignored by the Flex
break;
case "\t": // tabulate
tabCol = Math.floor((this.flexCol + 8)/8)*8;
while (this.flexCol < tabCol) {
this.flexChar(" ");
}
break;
case "\n": // carriage return
delay = this.flexCol/120*55 + 70; // 70-125ms based on carriage position
this.flexEmptyLine();
break;
default: // all printable characters
this.flexChar(char);
break;
}
} else {
this.alphaLock = 1;
this.alphaFirstDigit = digit;
delay = 48;
}
} else if (digit == 0 && this.zeroSuppress) {
this.flexChar(" ");
} else {
this.zeroSuppress = 0;
this.flexChar(digit.toString());
}
setCallback(this.mnemonic, this, delay, signalOK);
}
break;
case 2: // Paper-tape punch
if (this.hasPaperTapePunch) {
delay = this.punchPeriod;
this.punchChar(digit.toString());
setCallback(this.mnemonic, this, delay, signalOK);
}
break;
} // switch outputUnit
};
/**************************************/
D205ConsoleOutput.prototype.writeFinish = function writeFinish(outputUnit, controlDigit, signalOK) {
/* Signals end of output for a word. Delays for an appropriate amount of
time, then calls the Processor's signalOK function */
var delay = 140; // default delay, ms
var tabCol = 0; // TCU tabulation column
switch (outputUnit) {
case 1: // Flexowriter
if (this.hasFlexowriter) {
this.formatDigit = this.alphaLock = 0;
if (controlDigit & 0x08) {
// suppress line/group counting
} else if (this.groupingCountersSwitch.state) {
// perform line/group counting -- note that .selectedIndex is zero-relative
this.resetLamp.set(0);
if (this.wordCounter < this.wordsKnob.selectedIndex) {
++this.wordCounter;
switch (this.tabSpaceSwitch.state) {
case 1: // output a tab
tabCol = Math.floor((this.flexCol + 8)/8)*8;
while (this.flexCol < tabCol) {
this.flexChar(" ");
}
break;
case 2: // output a space
this.flexChar(" ");
break;
} // switch this.tabSpaceSwitch.state
} else {
this.wordCounter = 0;
if (this.groupingCountersSwitch.state == 2) {
this.flexEmptyLine(); // end of line: do new line
}
if (this.lineCounter < this.linesKnob.selectedIndex) {
++this.lineCounter;
} else {
this.lineCounter = 0;
if (this.groupingCountersSwitch.state == 2) {
delay += 100; // end of group: do another new line
this.flexEmptyLine();
}
if (this.groupCounter < this.groupsKnob.selectedIndex) {
++this.groupCounter;
} else {
this.groupCounter = 0; // end of page
if (this.autoStopSwitch.state) {
this.stopPrintout = 1; // stop before next output
}
}
}
}
}
setCallback(this.mnemonic, this, delay, signalOK);
}
break;
case 2: // Paper-tape punch
if (this.hasPaperTapePunch) {
delay = this.punchPeriod;
this.punchEmptyLine();
this.punchEOP.scrollIntoView();
setCallback(this.mnemonic, this, delay, signalOK);
}
break;
} // switch outputUnit
};
/**************************************/
D205ConsoleOutput.prototype.shutDown = function shutDown() {
/* Shuts down the device */
if (this.outTimer) {
clearCallback(this.outTimer);
}
if (this.flexWin) {
this.flexWin.removeEventListener("beforeunload", D205ConsoleOutput.prototype.beforeUnload);
this.flexWin.close();
this.flexWin = null;
}
if (this.punchWin) {
this.punchWin.removeEventListener("beforeunload", D205ConsoleOutput.prototype.beforeUnload);
this.punchWin.close();
this.punchWin = null;
}
};
| pkimpel/retro-205 | webUI/D205ConsoleOutput.js | JavaScript | mit | 33,287 |
module.exports = {
dist: {
"devFile" : '<%= paths.src.assets %>/<%= grunt.config("design") %>/js/modernizr.dev.js',
"outputFile" : '<%= paths.src.assets %>/<%= grunt.config("design") %>/js/generic/modernizr.custom.js',
"extra" : {
"shiv" : true,
"printshiv" : false,
"load" : true,
"mq" : true,
"cssclasses" : true
},
"extensibility" : {
"addtest" : false,
"prefixed" : false,
"teststyles" : false,
"testprops" : false,
"testallprops" : false,
"hasevents" : false,
"prefixes" : false,
"domprefixes" : false,
"cssclassprefix": ""
},
"uglify" : false,
"tests" : [],
"parseFiles" : true,
"matchCommunityTests" : false,
"customTests" : []
}
};
| basecreative/barebase | tools/grunt/modernizr.js | JavaScript | mit | 905 |
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
sass: {
files: ['sass/*.scss'],
tasks: ['sass:dist', 'cssmin',]
},
// concat: {
// files: ['public/js/*.js'],
// tasks: ['concat']
// }
// uglify: {
// files: ['public/js/*.js'],
// tasks: ['uglify']
// }
},
sass: {
dist: {
files:{
'public/css/main.css' :'sass/style.scss'
},
options: {
// sourcemap: 'true'
}
}
},
cssmin: {
target: {
files: [{
expand: true,
cwd: 'public/css',
src: ['*.css', '!*.min.css'],
dest: 'public/css',
ext: '.min.css'
}]
}
},
concat: {
dist: {
src: ['public/js/*.js', '!public/js/built.js'],
dest: 'public/js/built.js',
}
},
uglify: {
options: {
},
my_target: {
files: {
'public/js/main.min.js': ['public/js/main.js'],
'public/js/react-dom.min.js': ['public/js/react-dom.js'],
'public/js/react.min.js': ['public/js/react.js'],
'public/js/browser.min.js': ['public/js/browser.min.js'],
}
}
},
browserSync: {
dev: {
bsFiles: {
src: 'public/**/*.{js,css}'
},
options: {
proxy: 'localhost:3000',
watchTask: true
}
}
}
});
grunt.registerTask('default', ['browserSync', 'watch']);
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-browser-sync');
}; | GarrettEstrin/windows.garrettestrin.com | Gruntfile.js | JavaScript | mit | 2,276 |
#!/usr/bin/env node
require('./index')();
| petemill/git-credentials-envvar | cli.js | JavaScript | mit | 42 |
import { expect } from 'chai';
import supertest from 'supertest';
import app from '../../routes/index';
import helpers from '../helpers/helpers';
const request = supertest.agent(app);
const users = helpers.legitUsers;
const invalidUser = helpers.invalidUsers;
describe('User Routes Spec', () => {
let adminUserToken;
let regularUserToken;
before((done) => {
request.post('/api/users/login')
.send({
email: users[0].email,
password: users[0].password
})
.end((error, response) => {
adminUserToken = response.body.token;
});
request.post('/api/users/login')
.send({
email: users[1].email,
password: users[1].password
})
.end((err, response) => {
regularUserToken = response.body.token;
done();
});
});
describe('Authenticate users', () => {
it('should successfully signup a user and generate a token', (done) => {
request.post('/api/users')
.send({
firstName: 'Blessing',
lastName: 'Herbert',
email: 'herbbliss@example.com',
userName: 'blissbert',
password: 'passion123'
})
.expect(201)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.token).to.exist;
expect(response.body.message).to.equal('User was successfully created');
expect(response.body.user.userName).to.equal('blissbert');
done();
});
});
it('should not register user if some fields are left empty', (done) => {
request.post('/api/users')
.send(invalidUser[1])
.expect(400)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal('The paramaters are incomplete');
done();
});
});
it('should not register user with an already existing email', (done) => {
request.post('/api/users')
.send(users[2])
.expect(409)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal(`There is a user already existing
with this email or userName`);
done();
});
});
it('should generate and return a token when user signin', (done) => {
request.post('/api/users/login')
.send({
email: users[2].email,
password: users[2].password
})
.expect(200)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal('You are successfully logged in');
expect(response.body.token).to.exist;
done();
});
});
it('should not sign in a user if required fields are missing', (done) => {
request.post('/api/users/login')
.send({
email: users[2].email
})
.expect(401)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to
.equal('There was a problem while logging in due to invalid credentials');
done();
});
});
it('should not sign in a non-registered user', (done) => {
request.post('/api/users/login')
.send({
email: 'notargistereduser@example.com',
password: '45thersa0'
})
.expect(403)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal('User was not found');
done();
});
});
it('should not sign in a user if password is invalid', (done) => {
request.post('/api/users/login')
.send({
email: users[2].email,
password: 'invalidpassword'
})
.expect(401)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal('Invalid password');
done();
});
});
});
describe('Get Users', () => {
it('should get a list of all users', () => {
request.get('/api/users')
.set('authorization', regularUserToken)
.expect(200)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal('Listing available users');
});
});
it('should require a token before listing available users', () => {
request.get('/api/users')
.expect(401)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal('No token was provided');
});
});
it(`should not allow access to the list of
users if the token is invalid`, () => {
request.get('/api/users')
.set('authorization', 'hdfhf743u43brf97dhewhurvgy382hch')
.expect(401)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal('Invalid token');
});
});
it('should search for a user by id', () => {
request.get('/api/users/2')
.set('authorization', adminUserToken)
.expect(200)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal('User found!');
expect(response.body.data).to.exist;
});
});
it('should return an error message if the user was not found', () => {
request.get('/api/users/4098')
.set('authorization', regularUserToken)
.expect(404)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to
.equal('User was not found');
});
});
});
describe('Updating user', () => {
it('should allow a user to update their data', () => {
request.put('/api/users/2')
.set('authorization', regularUserToken)
.send({
email: 'ikgrace@example.com'
})
.expect(200)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to
.equal('User information updated successfully');
expect(response.body.updateProfile).to.exist;
});
});
});
describe('User Deletion', () => {
it('should allow an admin to delete a user\'s account', () => {
request.delete('/api/users/5')
.set('authorization', adminUserToken)
.expect(200)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal('User was deleted successfully');
});
});
});
describe('User Logout', () => {
it('should log a user out', () => {
request.post('/api/users/logout')
.set('authorization', regularUserToken)
.expect(200)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal('You were logged out successfully');
});
});
it('should require a user to have a valid token to be logged out', () => {
request.post('/api/users/logout')
.expect(401)
.end((err, response) => {
expect(typeof response.body).to.equal('object');
expect(response.body.message).to.equal('No token was provided');
});
});
});
});
| andela-gike/Checkpoint-2 | server/tests/controllers/user.spec.js | JavaScript | mit | 7,650 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @format
*/
'use strict';
const path = require('path');
const NODE_MODULES = path.sep + 'node_modules' + path.sep;
class DependencyGraphHelpers {
constructor(_ref)
{let providesModuleNodeModules = _ref.providesModuleNodeModules,assetExts = _ref.assetExts;
this._providesModuleNodeModules = providesModuleNodeModules;
this._assetExts = assetExts;
}
isNodeModulesDir(file) {
const index = file.lastIndexOf(NODE_MODULES);
if (index === -1) {
return false;
}
const parts = file.substr(index + 14).split(path.sep);
const dirs = this._providesModuleNodeModules;
for (let i = 0; i < dirs.length; i++) {
if (parts.indexOf(dirs[i]) > -1) {
return false;
}
}
return true;
}
isAssetFile(file) {
return this._assetExts.indexOf(this.extname(file)) !== -1;
}
extname(name) {
return path.extname(name).substr(1);
}}
module.exports = DependencyGraphHelpers; | Dagers/React-Native-Differential-Updater | App/node_modules/metro-bundler/src/node-haste/DependencyGraph/DependencyGraphHelpers.js | JavaScript | mit | 1,267 |
import { ROW_ID, ON_CLICK_ROW, UPDATE_SELECTEDROWS } from '../constants'
export default {
props: {
selectedRows: {
type: Array,
default: () => []
},
rowSelectable: {
type: Boolean,
default: false
},
rowsSelectable: {
type: Boolean,
default: false
}
},
methods: {
selectRow (row) {
const id = row[ROW_ID]
if (this.rowSelectable) {
this.updateRowSelection([id])
return
}
const selectedRows = [...this.selectedRows]
selectedRows.push(id)
this.updateRowSelection(selectedRows)
},
unselectRow (row) {
const id = row[ROW_ID]
const index = this.selectedRows.indexOf(id)
const selectedRows = [...this.selectedRows]
selectedRows.splice(index, 1)
this.updateRowSelection(selectedRows)
},
toggleRowSelection (row) {
this.isRowSelected(row)
? this.unselectRow(row)
: this.selectRow(row)
},
toggleRowsSelection () {
let selectedRows = []
if (!this.allRowsSelected) {
selectedRows = this.rows.map(row => row[ROW_ID])
}
this.updateRowSelection(selectedRows)
},
isRowSelected (row) {
return Boolean(this.selectedRows
.filter(id => JSON.stringify(id) === JSON.stringify(row[ROW_ID])).length)
},
updateRowSelection (selectedRows) {
this.$emit(UPDATE_SELECTEDROWS, selectedRows)
}
},
computed: {
allRowsSelected () {
if (this.selectedRows && this.selectedRows.length < this.rows.length) {
return false
}
const selected = this.rows.filter(this.isRowSelected)
return selected.length === this.rows.length
}
},
created () {
if (this.rowsSelectable || this.rowSelectable) {
this.$on(ON_CLICK_ROW, this.toggleRowSelection)
}
}
}
| vuikit/vuikit | packages/vuikit/src/library/table/mixins/select.js | JavaScript | mit | 1,846 |
var cassowary = require('../deps/cassowary.js');
var Expression = require('./Expression.js');
function Addition(expression1, expression2) {
Expression.call(this);
this.addExpressions(expression1, expression2);
}
Addition.prototype = Object.create(Expression.prototype);
Addition.prototype.constructor = Addition;
Addition.prototype.construct = function () {
var left = this._left.construct();
var right = this._right.construct();
return left.plus(right);
};
function Subtraction(expression1, expression2) {
Expression.call(this);
this.addExpressions(expression1, expression2);
}
Subtraction.prototype = Object.create(Expression.prototype);
Subtraction.prototype.constructor = Subtraction;
Subtraction.prototype.construct = function () {
var left = this._left.construct();
var right = this._right.construct();
return left.minus(right);
};
function Multiplication(expression1, expression2) {
Expression.call(this);
this.addExpressions(expression1, expression2);
}
Multiplication.prototype = Object.create(Expression.prototype);
Multiplication.prototype.constructor = Multiplication;
Multiplication.prototype.construct = function () {
var left = this._left.construct();
var right = this._right.construct();
return left.times(right);
};
function Division(expression1, expression2) {
Expression.call(this);
this.addExpressions(expression1, expression2);
}
Division.prototype = Object.create(Expression.prototype);
Division.prototype.constructor = Division;
Division.prototype.construct = function () {
var left = this._left.construct();
var right = this._right.construct();
return left.divide(right);
};
var constraintCount = 0;
function Constraint(expression1, expression2, strength, weight) {
this._expression1 = expression1;
this._expression2 = expression2;
this._strength = strength;
this._weight = weight;
this._constraint = null;
this._id = (constraintCount++).toString();
this._registerToPrimitives();
}
Constraint.prototype._registerToPrimitives = function () {
var stack = [this._expression1, this._expression2];
while (stack.length !== 0) {
var expression = stack.pop();
if (expression._left === null) {
expression._register(this);
} else {
stack.push(expression._left);
stack.push(expression._right);
}
}
};
Constraint.prototype._unregisterFromPrimitives = function () {
var stack = [this._expression1, this._expression2];
while (stack.length !== 0) {
var expression = stack.pop();
if (expression._left === null) {
expression._unregister(this);
} else {
stack.push(expression._left);
stack.push(expression._right);
}
}
};
function LowerOrEqual(expression1, expression2, strength, weight) {
Constraint.call(this, expression1, expression2, strength, weight);
}
LowerOrEqual.prototype = Object.create(Constraint.prototype);
LowerOrEqual.prototype.constructor = LowerOrEqual;
LowerOrEqual.prototype.construct = function () {
this._constraint = new cassowary.Inequality(
this._expression1.construct(),
cassowary.LEQ,
this._expression2.construct(),
this._strength,
this._weight
);
return this._constraint;
};
function GreaterOrEqual(expression1, expression2, strength, weight) {
Constraint.call(this, expression1, expression2, strength, weight);
}
GreaterOrEqual.prototype = Object.create(Constraint.prototype);
GreaterOrEqual.prototype.constructor = GreaterOrEqual;
GreaterOrEqual.prototype.construct = function () {
this._constraint = new cassowary.Inequality(
this._expression1.construct(),
cassowary.GEQ,
this._expression2.construct(),
this._strength,
this._weight
);
return this._constraint;
};
function Equality(expression1, expression2, strength, weight) {
Constraint.call(this, expression1, expression2, strength, weight);
}
Equality.prototype = Object.create(Constraint.prototype);
Equality.prototype.constructor = Equality;
Equality.prototype.construct = function () {
this._constraint = new cassowary.Equation(
this._expression1.construct(),
this._expression2.construct(),
this._strength,
this._weight
);
return this._constraint;
};
module.exports = {
Addition: Addition,
Subtraction: Subtraction,
Multiplication: Multiplication,
Division: Division,
LowerOrEqual: LowerOrEqual,
GreaterOrEqual: GreaterOrEqual,
Equality: Equality
}; | Wizcorp/constrained | src/operators.js | JavaScript | mit | 4,450 |
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.3-4-62
description: >
Object.getOwnPropertyDescriptor returns data desc for functions on
built-ins (String.prototype.constructor)
includes: [runTestCase.js]
---*/
function testcase() {
var desc = Object.getOwnPropertyDescriptor(String.prototype, "constructor");
if (desc.value === String.prototype.constructor &&
desc.writable === true &&
desc.enumerable === false &&
desc.configurable === true) {
return true;
}
}
runTestCase(testcase);
| PiotrDabkowski/Js2Py | tests/test_cases/built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-62.js | JavaScript | mit | 864 |
/* global describe, it */
const assert = require('chai').assert
const PVec = require('../build/pvec.umd.js')
describe('angleBetween', function () {
let a, b
it('Maximum possible angle', function () {
a = new PVec(10, 0)
b = new PVec(-10, 0)
assert.approximately(PVec.angleBetween(a, b), Math.PI, 0.01)
})
it('Similar vectors', function () {
a = new PVec(3, 4)
b = new PVec(4, 3)
assert.approximately(PVec.angleBetween(a, b), 0.284, 0.01)
})
it('Different length vectors', function () {
a = new PVec(7, 1)
b = new PVec(5, 5)
assert.approximately(PVec.angleBetween(a, b), 0.644, 0.01)
})
it('Zero vector', function () {
a = new PVec()
b = new PVec(2, 4, 5)
assert.equal(PVec.angleBetween(a, b), 0)
})
})
| varbrad/pvec | test/angleBetween.js | JavaScript | mit | 773 |
var searchData=
[
['prefnameboolenum',['prefNameBoolEnum',['../_p_v_r_shell_8h.html#a3fa86f089e589b4785ebb9a217b9f8c5',1,'PVRShell.h']]],
['prefnameconstptrenum',['prefNameConstPtrEnum',['../_p_v_r_shell_8h.html#af13725186b1491b5d72cd42920b7bc73',1,'PVRShell.h']]],
['prefnamefloatenum',['prefNameFloatEnum',['../_p_v_r_shell_8h.html#a428ec8d292e36ac8dbc77044dc25075c',1,'PVRShell.h']]],
['prefnameintenum',['prefNameIntEnum',['../_p_v_r_shell_8h.html#a78ec4653192043575302f1448ae7054e',1,'PVRShell.h']]],
['prefnameptrenum',['prefNamePtrEnum',['../_p_v_r_shell_8h.html#a946b110b552f1d833e359e6517647330',1,'PVRShell.h']]],
['pvrshellkeyname',['PVRShellKeyName',['../_p_v_r_shell_8h.html#afe6e702981239131fb8bb06574e35159',1,'PVRShell.h']]],
['pvrshellkeyrotate',['PVRShellKeyRotate',['../_p_v_r_shell_8h.html#a0dd1e43d52218ef08cf887ac1657984a',1,'PVRShell.h']]]
];
| linuxaged/arena | Shell/Documentation/html/search/enums_70.js | JavaScript | mit | 880 |
import React from 'react'
import { Accordion, Button, Form, Segment } from 'shengnian-ui-react'
const panels = [
{
title: 'Optional Details',
content: {
as: Form.Input,
key: 'content',
label: 'Maiden Name',
placeholder: 'Maiden Name',
},
},
]
const AccordionExampleForm = () => (
<Segment>
<Form>
<Form.Group widths={2}>
<Form.Input label='First Name' placeholder='First Name' />
<Form.Input label='Last Name' placeholder='Last Name' />
</Form.Group>
<Accordion as={Form.Field} panels={panels} />
<Button secondary>Sign Up</Button>
</Form>
</Segment>
)
export default AccordionExampleForm
| shengnian/shengnian-ui-react | docs/app/Examples/modules/Accordion/Advanced/AccordionExampleForm.js | JavaScript | mit | 685 |
/*jslint browser: true, plusplus: true, sloppy: true*/
/*global $, jQuery, alert*/
/* Para crear mas entradas de Hosts y su boton correspondiente de calcular */
$(function () {
var cont = 0,
AltIP1 = 0,
AltIP2 = 0,
Diag = 9,
iPoct1 = 0,
iPoct2 = 0,
iPoct3 = 0,
iPoct4 = 0,
iPoct5 = 0,
IPf = 0,
Nodo = 0,
IPf2 = 0;
$("#Mas").click(function () {
var Host = (parseInt(document.getElementsByName("Hosts")[Nodo].value, 10)),
DiRed = "",
i = 0,
j = 0,
k = 0,
Msk = 0,
IPFin = 0,
Inicio = "",
Final = "",
Broad = "",
SubMsk = "",
Clase = "",
iPoct2f = 0,
iPoct4f = 0,
iPoct5f = 0,
iPoct3f = 0;
/*-----------Valor de Host--------- */
if (isNaN(Host) || Host <= 0) {
// alert("Debes introducir la cantidad de Hosts");
Materialize.toast('<span>Introduce un número valido de Hosts</span>', 5000);
} else {
if (Nodo === 0) {
iPoct1 = (parseInt(document.getElementsByName("IP")[0].value, 10)) + iPoct1;
AltIP1 = (parseInt(document.getElementsByName("IP")[0].value, 10));
iPoct2 = (parseInt(document.getElementsByName("IP")[1].value, 10)) + iPoct2;
AltIP2 = (parseInt(document.getElementsByName("IP")[1].value, 10));
iPoct3 = (parseInt(document.getElementsByName("IP")[2].value, 10)) + iPoct3;
iPoct4 = (parseInt(document.getElementsByName("IP")[3].value, 10)) + iPoct4;
} else {
// iPoct1 = iPoct1;
AltIP1 = iPoct1;
// iPoct2 = iPoct2;
AltIP2 = iPoct2;
// iPoct3 = iPoct3;
// iPoct4 = iPoct4;
}
Nodo = Nodo + 1;
if (iPoct1 >= 0 && iPoct1 <= 127) {
Clase = "A";
}
if (iPoct1 >= 128 && iPoct1 <= 191) {
Clase = "B";
} else {
Clase = "C";
}
DiRed = AltIP1 + "." + iPoct2 + "." + iPoct3 + "." + iPoct4;
if (Host > 32766 && Host <= 8388606) {
i = 8388606;
j = 128;
k = 0;
Msk = j;
Diag = 9;
while (j > 0) {
if (Host <= i && Host > i / 2 - 1) {
Msk = Msk + k;
iPoct2 = iPoct2 + j;
iPoct2f = iPoct2 - j;
iPoct4f = iPoct4 + 1;
IPFin = iPoct2 - 1;
j = 0;
} else {
Msk = Msk + k;
Diag = Diag + 1;
j = j / 2;
k = j;
i = i / 2 - 1;
}
}
Inicio = AltIP1 + "." + iPoct2f + "." + iPoct3 + "." + iPoct4f;
Final = AltIP1 + "." + IPFin + ".255.254";
Broad = AltIP1 + "." + IPFin + ".255.255";
SubMsk = "255." + Msk + ".0.0";
}
/*--------------------------------------------------------------------------------------------------------*/
if (Host > 126 && Host <= 32766) {
i = 32766;
j = 128;
k = 0;
Msk = j;
Diag = 17;
while (j > 0) {
if (Host <= i && Host > i / 2 - 1) {
Msk = Msk + k;
iPoct3 = iPoct3 + j;
iPoct3f = iPoct3 - j;
iPoct4f = iPoct4 + 1;
IPFin = iPoct3 - 1;
k = j;
j = 0;
} else {
Msk = Msk + k;
Diag = Diag + 1;
j = j / 2;
k = j;
i = i / 2 - 1;
}
}
if (iPoct3f > 255) {
iPoct2 = iPoct2 + 1;
iPoct3f = 0;
iPoct3 = 0;
i = 32766;
j = 128;
k = 0;
Msk = j;
Diag = 17;
while (j > 0) {
if (Host <= i && Host > i / 2 - 1) {
Msk = Msk + k;
iPoct3 = iPoct3 + j;
iPoct3f = iPoct3 - j;
iPoct4f = iPoct4 + 1;
IPFin = iPoct3 - 1;
k = j;
j = 0;
} else {
Msk = Msk + k;
Diag = Diag + 1;
j = j / 2;
k = j;
i = i / 2 - 1;
}
}
}
DiRed = AltIP1 + "." + iPoct2 + "." + iPoct3f + "." + iPoct4;
Inicio = AltIP1 + "." + iPoct2 + "." + iPoct3f + "." + iPoct4f;
Final = AltIP1 + "." + iPoct2 + "." + IPFin + ".254";
Broad = AltIP1 + "." + iPoct2 + "." + IPFin + ".255";
SubMsk = "255." + "255" + "." + Msk + ".0";
}
/*-------------------------------------------------------------------------------------------------*/
if (Host > 1 && Host <= 126) {
i = 126;
j = 128;
k = 0;
Msk = j;
Diag = 25;
while (j > 0) {
if (Host <= i && Host > i / 2 - 1) {
iPoct5 = iPoct4 + 1;
iPoct4 = iPoct4 + j;
iPoct5f = iPoct4 - j;
iPoct4f = iPoct4 - 2;
IPf = iPoct4;
IPFin = iPoct4 - 1;
Msk = Msk + k;
k = j;
j = 0;
} else {
Msk = Msk + k;
Diag = Diag + 1;
i = i / 2 - 1;
j = j / 2;
k = j;
}
}
if (iPoct4f > 255) {
iPoct3f = iPoct3f + 1;
iPoct3 = iPoct3 + 1;
iPoct5f = 0;
iPoct4 = 0;
iPoct4f = 0;
i = 126;
j = 128;
k = 0;
Msk = j;
Diag = 25;
while (j > 0) {
if (Host <= i && Host > i / 2 - 1) {
iPoct5 = iPoct4 + 1;
iPoct4 = iPoct4 + j;
iPoct5f = iPoct4 - j;
IPf2 = iPoct4 + 1;
iPoct4f = iPoct4 - 2;
IPf = iPoct4;
IPFin = iPoct4 - 1;
Msk = Msk + k;
k = j;
j = 0;
} else {
Msk = Msk + k;
Diag = Diag + 1;
i = i / 2 - 1;
j = j / 2;
k = j;
}
}
}
DiRed = AltIP1 + "." + iPoct2 + "." + iPoct3 + "." + iPoct5f;
Inicio = AltIP1 + "." + iPoct2 + "." + iPoct3 + "." + iPoct5;
Final = AltIP1 + "." + iPoct2 + "." + iPoct3 + "." + iPoct4f;
Broad = AltIP1 + "." + iPoct2 + "." + iPoct3 + "." + IPFin;
SubMsk = "255." + "255" + ".255" + "." + Msk;
}
/*--------------------------------------------------------------------------------------------------------*/
var c2 = 0,
table = document.createElement('table'),
thead = document.createElement('thead'),
tbody = document.createElement('tbody'),
tr = document.createElement('tr'),
th1 = document.createElement('th'),
th2 = document.createElement('th'),
th3 = document.createElement('th'),
th4 = document.createElement('th'),
th5 = document.createElement('th'),
tit1 = document.createTextNode('Dirección de Red'),
tit2 = document.createTextNode('Inicio'),
tit3 = document.createTextNode('Final'),
tit4 = document.createTextNode('BroadCast'),
tit5 = document.createTextNode('SubMask'),
trb = document.createElement('tr'),
td1 = document.createElement('td'),
td2 = document.createElement('td'),
td3 = document.createElement('td'),
td4 = document.createElement('td'),
td5 = document.createElement('td'),
col1 = document.createTextNode(DiRed + "/" + Diag),
col2 = document.createTextNode(Inicio),
col3 = document.createTextNode(Final),
col4 = document.createTextNode(Broad),
col5 = document.createTextNode(SubMsk);
table.setAttribute("class", "responsive-table");
table.setAttribute("name", "Result");
for (c2 = 1; c2 < 4; c2++) {
th1.appendChild(tit1);
th2.appendChild(tit2);
th3.appendChild(tit3);
th4.appendChild(tit4);
th5.appendChild(tit5);
tr.appendChild(th1);
tr.appendChild(th2);
tr.appendChild(th3);
tr.appendChild(th4);
tr.appendChild(th5);
td1.appendChild(col1);
td2.appendChild(col2);
td3.appendChild(col3);
td4.appendChild(col4);
td5.appendChild(col5);
trb.appendChild(td1);
trb.appendChild(td2);
trb.appendChild(td3);
trb.appendChild(td4);
trb.appendChild(td5);
thead.appendChild(tr);
tbody.appendChild(trb);
}
document.getElementById("Contenedor").appendChild(table);
document.getElementsByName("Result")[cont].appendChild(thead);
document.getElementsByName("Result")[cont].appendChild(tbody);
cont = cont + 1;
if (isNaN(AltIP1)) {
Materialize.toast('<span>BATMAN!!!!</span>', 2000);
}
}
});
});
/*--------------------------------------------------------------------------------------------------------------------*/
$(function () {
var i = 0,
idN = 0;
$("#Mas").click(function () {
var Row = document.createElement("div"),
Input = document.createElement("div"),
Texto = document.createElement("input"),
Etiqueta = document.createElement("label"),
Linea = document.createElement("li"),
Vinc = document.createElement("a"),
Host = (parseInt(document.getElementsByName("Hosts")[i].value, 10));
if (isNaN(Host) || Host <= 0) {
i = i;
} else {
idN = i + 1;
Etiqueta.innerHTML = "#Hosts";
Texto.type = "number";
Texto.className = "validate";
Texto.setAttribute("name", "Hosts");
Texto.setAttribute("onkeypress", "return isNumber(event)");
Input.setAttribute("class", "input-field col s3");
Input.setAttribute("name", "InputF");
Row.className = "row";
Row.setAttribute("name", "Fila");
Row.setAttribute("id", "Hosts" + idN);
document.getElementById("Contenedor").appendChild(Row);
document.getElementsByName("Fila")[i + 1].appendChild(Input);
document.getElementsByName("InputF")[i].appendChild(Texto);
document.getElementsByName("InputF")[i].appendChild(Etiqueta);
Linea.setAttribute("name", "Vinculo");
Vinc.setAttribute("name", "Texto");
Vinc.setAttribute("href", "#Hosts" + idN);
document.getElementById("nav-mobile").appendChild(Linea);
document.getElementsByName("Vinculo")[i + 1].appendChild(Vinc);
document.getElementsByName("Texto")[i].innerHTML = Host + " Hosts";
Materialize.toast('<span>Se agregaron  </span> ' + Host + ' <span>  Hosts</span>', 3000);
i = i + 1;
}
});
});
| anargoz/SuNec | js/calc.js | JavaScript | mit | 13,120 |
var utils = require('./utils'),
/**
* Our main in-memory storage,
* hidden from everyone by using
* cache instance ids at a top-level
* @type {Object{id:{}}}
*/
cache = {},
deepAccess = function(ref, keys) {
var idx = 0,
// don't want the last key,
// that's our value
length = keys.length - 1,
key;
for (; idx < length; idx++) {
key = keys[idx];
// ensure the chain exists
ref = ref[key] || (ref[key] = {});
}
return ref;
};
module.exports = {
ref: function(inst) {
return cache[inst._id] || (cache[inst._id] = {});
},
flush: function(inst) {
return (cache[inst._id] = {});
},
get: function(ref, key) {
// simple access
return ref[utils.safe(key)];
},
getDeep: function(ref, keys) {
keys = utils.safeDeep(keys);
ref = deepAccess(ref, keys);
// access the ref of the last key
return ref[keys[keys.length - 1]];
},
set: function(ref, key, value) {
return (ref[utils.safe(key)] = value);
},
setDeep: function(ref, keys, value) {
keys = utils.safeDeep(keys);
ref = deepAccess(ref, keys);
// save the value to the last key
return (ref[keys[keys.length - 1]] = value);
},
remove: function(ref, key) {
delete ref[utils.safe(key)];
},
removeDeep: function(ref, keys) {
keys = utils.safeDeep(keys);
ref = deepAccess(ref, keys);
var key = keys[keys.length - 1];
delete ref[key];
}
}; | JosephClay/stashe-js | src/store.js | JavaScript | mit | 1,384 |
var sanity = require(__dirname),
EventEmitter = require('eventemitter2').EventEmitter2;
var Process = function(controller) {
var self = this;
// Enable event API:
EventEmitter.call(this);
this.__proto__ = EventEmitter.prototype;
self.close = function() {
return controller.close();
};
self.isOpen = function() {
return controller.isOpen;
};
self.open = function() {
return controller.open();
};
self.getController = function() {
return controller;
};
};
module.exports.Process = Process;
module.exports.createProcess = function(controller) {
return new Process(controller);
}; | psychoticmeow/jack-sanity | lib/Process.js | JavaScript | mit | 605 |
class Graphics {
constructor() {
this.canvas = document.getElementById('main-canvas');
this.context = this.canvas.getContext('2d');
}
clear() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
drawRectangle(rect, color = new Color()) {
this.context.fillStyle = color.rgba;
this.context.fillRect(...rect.dimensions);
}
drawCircle(rect, color = new Color()) {
this.context.beginPath();
this.context.arc(...rect.center, rect.w / 2, 0, 2 * Math.PI, false);
this.context.fillStyle = color.rgba;
this.context.fill();
}
drawImage(rect, image) {
this.context.drawImage(image, ...rect.dimensions);
}
}
| samuelleeuwenburg/Orbitals | src/js/core/graphics.js | JavaScript | mit | 681 |
import React, { PropTypes } from 'react';
import {
Container,
Loader,
Group,
} from 'amazeui-touch';
import { MyFooter } from '../components';
export default class ApplyDetail extends React.Component {
componentWillMount() {
const { applys ,detailActions, id} = this.props;
if (! applys.loadState.success) {
//根据 id 请求
detailActions.getApplyById(id);
}
}
renderDetail = () => {
const {applys, detail} = this.props;
if (!(applys.loadState.success || detail.loadState.success)) {
return(
<Loader
className="cy-empty-loader"
amStyle="primary"/>
)
}
var obj;
if (applys.loadState.success) {
const {item} = this.props;
const objArr = applys.applyArray;
obj = objArr[item];
}else {
obj = detail.detailObj.data[0];
}
return (
<div>
<Group>
<p>职位: {obj.jobtype}</p>
<p>姓名: {obj.name}</p>
<p>工资: {obj.salary}</p>
<p>学历 {obj.educational}</p>
<p>工作经验: {obj.jobback}</p>
<p>地点: {obj.workplace}</p>
<p>发布日期: {obj.inputtime}</p>
<p>求职者自述: {obj.content}</p>
</Group>
<MyFooter />
</div>
)
};
render() {
return (
<Container>
{this.renderDetail()}
</Container>
);
}
}
ApplyDetail.propTypes = {
applys: PropTypes.object.isRequired,
detailActions: PropTypes.object.isRequired,
item:PropTypes.string,
id:PropTypes.string,
detail:PropTypes.object.isRequired,
};
| sgt39007/waji_redux | app/js/components/ApplyDetail.js | JavaScript | mit | 1,682 |
const bcrypt = require('bcryptjs');
exports.seed = (knex, Promise) => {
return knex('users').del()
.then(() => {
const salt = bcrypt.genSaltSync();
const hash = bcrypt.hashSync('test234', salt);
return Promise.join(
knex('users').insert({
username: 'test234',
password: hash
})
);
})
.then(() => {
const salt = bcrypt.genSaltSync();
const hash = bcrypt.hashSync('admintest', salt);
return Promise.join(
knex('users').insert({
username: 'admintest',
password: hash,
admin: true
})
);
});
};
| ctdao/shopme | src/server/db/seeds/users.js | JavaScript | mit | 597 |
export { default as Home } from './Home';
export { default as Main } from './Main';
export { default as Baani } from './Baani';
export { default as SGGS } from './SGGS';
export { default as Nitnem } from './Nitnem';
export { default as Calendar } from './Calendar';
export { default as Shabad } from './Shabad';
export { default as Shabads } from './Shabads';
export { default as Hukamnama } from './Hukamnama';
export { default as Bookmarks } from './Bookmarks';
export { default as Authors } from './Authors';
export { default as Raags } from './Raags';
export { default as Author } from './Author';
export { default as Raag } from './Raag';
export { default as NotFound } from './NotFound';
export { default as Settings } from './Settings';
| bogas04/SikhJS | src/pages/index.js | JavaScript | mit | 744 |
const webpackConfig = require('./webpack.conf.js')
webpackConfig.node = {
process: true
}
module.exports = function(config) {
config.set({
browsers: ['PhantomJS'],
frameworks: ['jasmine'],
reporters: ['spec'],
plugins: [
'karma-webpack',
'karma-jasmine',
'karma-sourcemap-loader',
'karma-phantomjs-launcher',
'karma-spec-reporter'
],
singleRun: process.env.SINGLE_RUN || false,
files: [
{pattern: '*-spec.js', watched: false}
],
preprocessors: {
'*-spec.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
stats: 'errors-only'
}
});
};
| tulios/mappersmith-redux-middleware | karma.conf.js | JavaScript | mit | 675 |
(function () {
'use strict';
var app = angular.module('demoApp', ['cedarjs']);
app.config(function (commandApiProvider) {
commandApiProvider.configure({
routePrefix: 'test/'
});
});
app.controller('DemoController', function ($scope, commandApi) {
$scope.result = '';
$scope.sendAcceptedCommand = function () {
sendCommand({
commandId: "90D552BE-9259-4081-BEE0-A972D0AFAC8C",
commandName: "CommandThatIsAccepted",
value: 'Data'
});
};
$scope.sendRejectedCommand = function () {
sendCommand({
commandId: "90D552BE-9259-4081-BEE0-A972D0AFAC8C",
commandName: "CommandThatThrowsProblemDetailsException"
});
};
function sendCommand(command) {
commandApi.execute(command)
.then(function () {
$scope.result = 'Command Is Accepted';
}, function (e) {
$scope.result = 'Command Is Not Accepted';
console.log(e);
});
}
});
}()); | damianh/Cedar.CommandHandling | src/Cedar.CommandHandling.Http.TestHost/wwwroot/AngularExample.js | JavaScript | mit | 1,186 |
const assert = require('chai').assert;
const Rock = require('../lib/rocks');
describe('Rock', function() {
context('Variable checking', function () {
it('Rock should be a function', function () {
assert.isFunction(Rock);
});
it('should create a new rock', function () {
var rock = new Rock({});
assert.isObject(rock);
});
it('should take the "y" property as defined in an object and apply to Rock', function () {
var rock = new Rock({y: 10});
assert.equal(rock.y, 10);
});
it('should take the "width" property as defined in an object and apply to Rock', function () {
var rock = new Rock({width: 30});
assert.equal(rock.width, 30);
});
it('should take the "height" property as defined in an object and apply to Rock', function () {
var rock = new Rock({height: 30});
assert.equal(rock.height, 30);
});
});
context('with default attributes', function() {
var rock = new Rock({});
it('has a default y value', function(){
assert.equal(rock.y, 190 - rock.height);
});
it('has a default width value', function(){
assert.equal(rock.width, 25);
});
it('has a default height value', function(){
assert.equal(rock.height, 25);
});
});
context('with an x value off-screen left', function() {
it('isOffScreenLeft() returns true', function() {
var rock = new Rock({width: 25, height: 25});
rock.x = -26;
rock.isOffScreenLeft();
assert.equal(true, rock.isOffScreenLeft());
});
});
context('with an x value on-screen', function() {
it('isOffScreenLeft() returns false', function() {
var rock = new Rock({width: 25, height: 25});
rock.x = 100;
rock.isOffScreenLeft();
assert.equal(false, rock.isOffScreenLeft());
});
});
context('Movement function "moveLeft()""', function () {
it('should have a method called "moveLeft()', function () {
var rock = new Rock({});
assert.isFunction(rock.moveLeft);
});
it('"moveLeft()" should decrement the "x" property by 6', function () {
var rock = new Rock({});
rock.speed = 6;
rock.x = 100;
rock.moveLeft();
assert.equal(94, rock.x);
});
});
context('Different sized rock', function () {
it('should have a method called "small"', function () {
var rock = new Rock({});
assert.isFunction(rock.small);
});
it('"small" should make a small Rock', function () {
var rock = new Rock({width: 25, height: 25});
rock.small();
assert.equal(rock.width, 25, rock.height, 25);
});
it('should have a method called "medium"', function () {
var rock = new Rock({});
assert.isFunction(rock.medium);
});
it('"medium" should make a medium Rock', function () {
var rock = new Rock({width: 35, height: 35});
rock.medium();
assert.equal(rock.width, 35, rock.height, 35);
});
it('should have a method called "large"', function () {
var rock = new Rock({});
assert.isFunction(rock.large);
});
it('"large" should make a large Rock', function () {
var rock = new Rock({width: 40, height: 40});
rock.large();
assert.equal(rock.width, 40, rock.height, 40);
});
});
});
| blakeworsley/surfs-up | test/rocks-test.js | JavaScript | mit | 3,315 |
'use strict';
var _ = require('lodash'),
mixins = require('ic-utils').mixins,
amqp = require('..');
_.mixin(mixins);
var helloService = {
sayHello: function (name, location, callback) {
callback(null, _.fmt('Hello %s, I am HelloService from %s', name, location));
},
getQuote: function (callback) {
callback(null, 'The quick brown fox jumped over the lazy dog!');
}
};
amqp.withConfig({
server: 'localhost',
port: 5672,
user: 'guest',
password: 'guest'
}).initializeRpc(function (err, rpcHelper) {
rpcHelper.buildService('hello', helloService);
});
| intuitivcloud/inturn | examples/simpleService.js | JavaScript | mit | 588 |
var Token = require("../token");
module.exports = function(stream) {
stream.each(function(token) {
Token.current_token = this
if(!token.operator) return
if(token.text == "||=")
var op = "|| "
else if(token.text == ".=")
var op = "."
else return
optoken = token.after(op)
token.text = "="
var lhs = ""
token.prev.findRev(function(token) {
if(token.whitespace || token.unknown) return true
lhs = token.text + lhs
})
var tokens = Token.ize(lhs)
if(op != "." ) tokens.tail().eaten.right.push(Token.ize(" "))
token.after(tokens, tokens.tail())
})
// extend
var inserted_merge = false
stream.each(function(token) {
Token.current_token = this
if(token.text != "<-" ) return
var arrow = this
var L = this.expressionStart()
var lhs = L.remove(arrow.prev).collectText()
var R = arrow.next.expressionEnd(function() {})
var rhs = arrow.next.remove(R).collectText()
var ret = arrow.prev
// if(token.text == "=>") {
// arrow.replaceWith("__merge(" + lhs + ", " + rhs + ")")
// if(inserted_merge) {
// var g = stream.block
// if(!g.global) throw "WTF!"
// g.matching.before(new Token.word(__merge))
// inserted_merge = true
// }
// }
// else {
xxx = arrow.prev
arrow.replaceWith("__merge(" + lhs + ", " + rhs + ")")
if(!inserted_merge) {
var g = stream.block
if(!g.global) throw "WTF!"
g.matching.before(new Token.word(__merge))
inserted_merge = true
}
//token.global.vars['__extend'] = __extend.toString()
return ret
})
}
// var __extend = "\nfunction __extend(a,b) {\n\
// var c = {}, i;\n\
// a = a || {};\n\
// for(i in a) c[i] = a[i];\n\
// for(i in b) c[i] = b[i];\n\
// return c;\n\
// }"
var __merge = "\nfunction __merge(a,b) {\n\
b = b || {};\n\
for(var k in b) a[k] = b[k];\n\
return a;\n\
}"
| weepy/kaffeine | lib/plugins/operators.js | JavaScript | mit | 1,953 |
(function () {
'use strict';
angular.module('mockify.log.directive.updateScroll', [
])
/**
* Each time the 'logs' change, update the scroll to bottom smootly.
*/
.directive('updateScroll', [function () {
return {
restrict: 'A',
link: function (scope, element) {
var e = element;
scope.$watch('logs', function () {
e.animate({scrollTop: e.prop('scrollHeight')}, 500);
}, true);
}
};
}]);
})();
| Gandi/mockify | www/js/logs/directive.update-scroll.js | JavaScript | mit | 473 |
/**
* @Author: philip
* @Date: 2017-05-30T07:26:23+00:00
* @Filename: PageHeading.js
* @Last modified by: philip
* @Last modified time: 2017-05-30T07:26:59+00:00
*/
import React from 'react';
const PageHeading = ({ category, title }) => (
<div className="row wrapper border-bottom white-bg page-heading">
<div className="col-lg-12">
<h2>{title}</h2>
<ol className="breadcrumb">
<li>
<a href="/dashboard">Home</a>
</li>
{category && <li><a>{category}</a></li>}
<li className="active">
<strong>{title}</strong>
</li>
</ol>
</div>
</div>
);
export default PageHeading;
| mondrus/meteor-starter | app/imports/ui/components/PageHeading.js | JavaScript | mit | 732 |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require_tree ./application
//= require bootstrap
| istickz/skype-chats | app/assets/javascripts/application.js | JavaScript | mit | 675 |
ig.module(
'plusplus.helpers.utilstile'
)
.requires(
'plusplus.core.config',
'plusplus.core.collision-map',
'plusplus.helpers.utils',
'plusplus.helpers.utilsintersection',
'plusplus.helpers.utilsvector2'
)
.defines(function () {
"use strict";
var _c = ig.CONFIG;
var _ut = ig.utils;
var _uti = ig.utilsintersection;
var _utv2 = ig.utilsvector2;
var TILE_ONE_WAY_UP = _c.COLLISION.TILE_ONE_WAY_UP;
var TILE_ONE_WAY_DOWN = _c.COLLISION.TILE_ONE_WAY_DOWN;
var TILE_ONE_WAY_RIGHT = _c.COLLISION.TILE_ONE_WAY_RIGHT;
var TILE_ONE_WAY_LEFT = _c.COLLISION.TILE_ONE_WAY_LEFT;
var TILE_CLIMBABLE_WITH_TOP = _c.COLLISION.TILE_CLIMBABLE_WITH_TOP;
var TILE_CLIMBABLE = _c.COLLISION.TILE_CLIMBABLE;
var TILE_CLIMBABLE_STAIRS_WITH_TOP = _c.COLLISION.TILE_STAIRS_WITH_TOP;
var TILE_CLIMBABLE_STAIRS = _c.COLLISION.TILE_STAIRS;
var HASH_WALKABLE = _c.COLLISION.TILES_HASH_WALKABLE;
var HASH_WALKABLE_STRICT = _c.COLLISION.TILES_HASH_WALKABLE_STRICT;
var HASH_ONE_WAY = _c.COLLISION.TILES_HASH_ONE_WAY;
var HASH_CLIMBABLE = _c.COLLISION.TILES_HASH_CLIMBABLE;
var HASH_CLIMBABLE_ONE_WAY = _c.COLLISION.TILES_HASH_CLIMBABLE_ONE_WAY;
var HASH_CLIMBABLE_STAIRS = _c.COLLISION.TILES_HASH_CLIMBABLE_STAIRS;
var SEGMENT_A = 1;
var SEGMENT_B = 2;
/**
* Static utilities for working with tiles and collision maps.
* <br>- shapes are extracted by {@link ig.GameExtended#loadLevel}, but the work is done by {@link ig.utilstile.shapesFromCollisionMap}
* <span class="alert alert-info"><strong>Tip:</strong> Impact++ can automatically convert collision maps into shapes (vertices, edges, etc).</span>
* @memberof ig
* @namespace ig.utilstile
* @author Collin Hover - collinhover.com
**/
ig.utilstile = {};
/**
* Definitions of tile types as vertices so we don't have to recalculate each tile.
* @type {Object}
* @readonly
*/
ig.utilstile.defaultTileVerticesDef = {};
/**
* Definitions of tile types as segments so we don't have to recalculate each tile.
* @type {Object}
* @readonly
*/
ig.utilstile.defaultTileSegmentsDef = {};
/**
* Gets if a tile is walkabke.
* @param {Number} tileId tile id.
* @returns {Boolean} whether tile is one-way
**/
ig.utilstile.isTileWalkable = function (tileId) {
return HASH_WALKABLE[ tileId ];
};
/**
* Gets if a tile is strictly walkabke.
* @param {Number} tileId tile id.
* @returns {Boolean} whether tile is one-way
**/
ig.utilstile.isTileWalkableStrict = function (tileId) {
return HASH_WALKABLE_STRICT[ tileId ];
};
/**
* Gets if a tile is one-way.
* @param {Number} tileId tile id.
* @returns {Boolean} whether tile is one-way
**/
ig.utilstile.isTileOneWay = function (tileId) {
return HASH_ONE_WAY[ tileId ];
};
/**
* Gets if a tile is climbable.
* @param {Number} tileId tile id.
* @returns {Boolean} whether tile is climbable
**/
ig.utilstile.isTileClimbable = function (tileId) {
return HASH_CLIMBABLE[ tileId ];
};
/**
* Gets if a tile is stairs.
* @param {Number} tileId tile id.
* @returns {Boolean} whether tile is stairs
**/
ig.utilstile.isTileClimbableStairs = function (tileId) {
return HASH_CLIMBABLE_STAIRS[ tileId ];
};
/**
* Gets if a tile is climbable and one way.
* @param {Number} tileId tile id.
* @returns {Boolean} whether tile is climbable and one way
**/
ig.utilstile.isTileClimbableOneWay = function (tileId) {
return HASH_CLIMBABLE_ONE_WAY[ tileId ];
};
/**
* Extracts all shapes from an impact collision map, with vertices in clockwise order.
* <br>- this method does its best to intelligently combine tiles into as big of shapes as it can
* <br>- shapes consist of an x and y position, and a settings object with an array of vertices and a size object
* @param {ig.CollisionMap} map map data object
* @param {Object} options options object
* @returns {Array} array of shapes including a list of oneWays, edges, and climbables
* @example
* // options is a plain object
* options = {};
* // we can ignore climbable tiles when extracting shapes
* options.ignoreClimbables = true;
* // we can ignore one way tiles when extracting shapes
* options.ignoreOneWays = true;
* // we can ignore solid tiles when extracting shapes
* options.ignoreSolids = true;
* // we can keep the outer boundary edge shape when converting a collision map
* // but by default, the outer boundary is thrown away
* // this is because it is unlikely the player will ever be outside the level
* // so the outer boundary edge is usually useless
* options.retainBoundaryOuter = true;
* // we can throw away the inner boundary edge shape
* // i.e. the edge shape on the inside of the outer boundary
* options.discardBoundaryInner = true;
* // we can also throw away any shapes inside the inner boundary edge shape
* options.discardBoundaryInner = true;
* // we can force rectangles to be created instead of contour shapes
* // this is useful when we may have concave shapes that don't play nice with bounding boxes
* options.rectangles = true;
* // we can force just climbables to be rectangles
* options.contourClimbables = false;
* // we can force just one ways to be rectangles
* options.contourOneWays = false;
* // we can force shapes to only be constructed by tiles of the same type / id
* options.groupByTileId = true;
* // we can throw away all collinear vertices to improve performance
* options.discardCollinear = true;
* // we can reverse the shape vertex order to counter-clockwise
* options.reverse = true;
**/
ig.utilstile.shapesFromCollisionMap = function (map, options) {
var shapes = {
oneWays: [],
solids: [],
climbables: []
};
if (map instanceof ig.CollisionMap) {
options = options || {};
// copy data so we can clear spots we've already visited and used
// data is edited as we go so we don't extract duplicates
var data = ig.copy(map.data);
// extract each tile shape from map
var tilesize = map.tilesize;
var width = map.width;
var height = map.height;
var solids = [];
var climbables = [];
var oneWays = [];
var vertices, scaledVertices, segments, segment;
var ix, iy, x, y;
var i, il, tile, shape;
for (iy = 0; iy < height; iy++) {
for (ix = 0; ix < width; ix++) {
shape = ig.utilstile.shapeFromTile(map, ix, iy);
tile = {
id: map.data[ iy ][ ix ],
ix: ix,
iy: iy,
x: ix * tilesize,
y: iy * tilesize,
width: tilesize,
height: tilesize,
shape: shape
};
// not empty
if (shape.vertices.length > 0) {
// copy, absolutely position, and scale vertices
scaledVertices = [];
vertices = shape.vertices;
segments = shape.segments;
for (i = 0, il = segments.length; i < il; i++) {
segment = segments[ i ];
var va = vertices[ segment.a ];
scaledVertices[ segment.a ] = { x: tile.x + va.x * tilesize, y: tile.y + va.y * tilesize };
}
shape.vertices = scaledVertices;
// add to list by type
if (HASH_CLIMBABLE[ tile.id ] && !options.ignoreClimbables) {
climbables.push(tile);
}
else if (HASH_ONE_WAY[ tile.id ] && !options.ignoreOneWays) {
oneWays.push(tile);
}
else if (!options.ignoreSolids) {
solids.push(tile);
}
}
// store in copied data so other tiles can compare
data[ iy ][ ix ] = tile;
}
}
// store original rectangles option
// we'll need to reset it with each shape type
var rectangles = options.rectangles;
// solid tiles to shapes
shapes.solids = shapes.solids.concat(ig.utilstile.shapedTilesToShapes(solids, data, options));
// climbable tiles to shapes
options.rectangles = typeof rectangles !== 'undefined' ? rectangles : !options.contourClimbables;
shapes.climbables = shapes.climbables.concat(ig.utilstile.shapedTilesToShapes(climbables, data, options));
// adjust climbable shapes by id
for (i = 0, il = shapes.climbables.length; i < il; i++) {
shape = shapes.climbables[ i ];
if (HASH_CLIMBABLE_ONE_WAY[ shape.id ] ) {
shape.settings.oneWay = true;
}
else {
shape.settings.sensor = true;
}
if ( HASH_CLIMBABLE_STAIRS[ shape.id ] ) {
shape.settings.climbableStairs = true;
}
}
// one-way tiles to shapes
options.rectangles = typeof rectangles !== 'undefined' ? rectangles : !options.contourOneWays;
shapes.oneWays = shapes.oneWays.concat(ig.utilstile.shapedTilesToShapes(oneWays, data, options));
// adjust one-way shapes by id
for (i = 0, il = shapes.oneWays.length; i < il; i++) {
shape = shapes.oneWays[ i ];
// one-way
if (HASH_ONE_WAY[ shape.id ]) {
shape.settings.oneWay = true;
// set one way facing (default up)
if (shape.id === TILE_ONE_WAY_DOWN) {
shape.settings.oneWayFacing = { x: 0, y: 1 };
}
else if (shape.id === TILE_ONE_WAY_RIGHT) {
shape.settings.oneWayFacing = { x: 1, y: 0 };
}
else if (shape.id === TILE_ONE_WAY_LEFT) {
shape.settings.oneWayFacing = { x: -1, y: 0 };
}
}
}
}
return shapes;
};
/**
* Converts a list of tiles with vertices into shapes.
* <span class="alert alert-info"><strong>Tip:</strong> when converting tiles to shapes, is usually better to call {@link ig.utilstile.shapesFromCollisionMap}.</span>
* @param {Array} tiles shaped tiles to convert
* @param {Array} data 2d list of all tiles in map
* @param {Object} options options object
* @returns {Array} list of shapes
**/
ig.utilstile.shapedTilesToShapes = function (tiles, data, options) {
options = options || {};
var shapes = [];
var vertices = [];
var contours = [];
var i, il, j, jl, index;
// create tile groups from tiles
if (options.groupByTileId) {
// lets avoid infinite recursion!
delete options.groupByTileId;
// group by id
var ids = [];
var id;
var groups = {};
var group;
for (i = 0, il = tiles.length; i < il; i++) {
var tile = tiles[ i ];
if (groups[ tile.id ]) {
groups[ tile.id ].push(tile);
}
else {
ids.push(tile.id);
groups[ tile.id ] = [ tile ];
}
}
// create shapes for each group
for (i = 0, il = ids.length; i < il; i++) {
id = ids[ i ];
group = groups[ id ];
options.id = id;
shapes = shapes.concat(ig.utilstile.shapedTilesToShapes(group, data, options));
}
}
else {
// rectangle shapes that may or may not be concave
if (options.rectangles) {
// step horizontal connected tiles
// add line if matches last, else create new rectangle
var tilePool = tiles.slice(0);
var rectangles = [];
var line, length, stepped, rectangle;
while (tilePool.length > 0) {
// get first horizontal line of tiles
line = ig.utilstile.findShapedTileLine(tilePool);
_ut.arrayCautiousRemoveMulti(tilePool, line);
length = line.length;
rectangle = line;
stepped = true;
// find as many matching length rows as possible
while (stepped) {
stepped = false;
var tileLast = line[ 0 ];
var tileFrom = data[ tileLast.iy ][ tileLast.ix + 1 ];
if (tileFrom) {
// get tile at start of next row and make sure it is part of tile pool
index = _ut.indexOfValue(tilePool, tileFrom);
if (index !== -1) {
line = ig.utilstile.findShapedTileLine(tilePool, false, index, length);
if (line.length === length) {
_ut.arrayCautiousRemoveMulti(tilePool, line);
rectangle = rectangle.concat(line);
stepped = true;
}
}
}
}
if (rectangle.length > 0) {
rectangles.push(rectangle);
}
}
for (j = 0, jl = rectangles.length; j < jl; j++) {
rectangle = rectangles[ j ];
// keep non-duplicate edge vertices
vertices = [];
for (i = 0, il = rectangle.length; i < il; i++) {
vertices = vertices.concat(ig.utilstile.getNonDuplicateSegmentVertices(rectangle[ i ], data, rectangle));
}
// vertices to contours
contours = contours.concat(ig.utilstile.verticesToContours(vertices, options));
}
}
// general shapes that may or may not be concave
else {
// keep non-duplicate edge vertices
for (i = 0, il = tiles.length; i < il; i++) {
vertices = vertices.concat(ig.utilstile.getNonDuplicateSegmentVertices(tiles[ i ], data, tiles));
}
// vertices to contours
contours = ig.utilstile.verticesToContours(vertices, options);
}
// contours to shapes
for (i = 0, il = contours.length; i < il; i++) {
var contour = contours[ i ];
shapes.push({
id: options.id,
x: contour.minX,
y: contour.minY,
settings: {
size: {
x: contour.width,
y: contour.height
},
vertices: contour.vertices
}
});
}
}
return shapes;
};
/**
* Finds the first line in either horizontal or vertical direction from tiles.
* <span class="alert alert-info"><strong>Tip:</strong> when converting tiles to shapes, is usually better to call {@link ig.utilstile.shapesFromCollisionMap}.</span>
* @param {Array} tiles shaped tiles to search.
* @param {Boolean} [horizontal=false] line is horizontal, else vertical.
* @param {Number} [indexFrom=0] index in tiles to start from.
* @param {Number} [length=0] max length of line.
* @returns {Array} list of tiles in line.
**/
ig.utilstile.findShapedTileLine = function (tiles, horizontal, indexFrom, length) {
indexFrom = indexFrom || 0;
length = length || 0;
var tileFrom = tiles[ indexFrom ];
var line = [];
var stepped = true;
var i, il;
while (stepped) {
stepped = false;
// add tile to line
line.push(tileFrom);
if (line.length === length) {
break;
}
// step to next in line
var tileNext = horizontal ? ig.utilstile.stepShapedTileHorizontally(tiles, tileFrom) : ig.utilstile.stepShapedTileVertically(tiles, tileFrom);
if (tileFrom !== tileNext) {
stepped = true;
tileFrom = tileNext;
}
}
return line;
};
/**
* Attempts to step to the next tile horizontally.
* <span class="alert alert-info"><strong>Tip:</strong> when converting tiles to shapes, is usually better to call {@link ig.utilstile.shapesFromCollisionMap}.</span>
* @param {Array} tiles shaped tiles to search
* @param {Object} tileFrom tile stepping from
* @returns {Object} next tile, or current tile if next not found
**/
ig.utilstile.stepShapedTileHorizontally = function (tiles, tileFrom) {
for (var i = 0, il = tiles.length; i < il; i++) {
var tileNext = tiles[ i ];
if (tileFrom.iy === tileNext.iy && tileFrom.ix + 1 === tileNext.ix) {
return tileNext;
}
}
return tileFrom;
};
/**
* Attempts to step to the next tile vertically.
* <span class="alert alert-info"><strong>Tip:</strong> when converting tiles to shapes, is usually better to call {@link ig.utilstile.shapesFromCollisionMap}.</span>
* @param {Array} tiles shaped tiles to search
* @param {Object} tileFrom tile stepping from
* @returns {Object} next tile, or current tile if next not found
**/
ig.utilstile.stepShapedTileVertically = function (tiles, tileFrom) {
for (var i = 0, il = tiles.length; i < il; i++) {
var tileNext = tiles[ i ];
if (tileFrom.ix === tileNext.ix && tileFrom.iy + 1 === tileNext.iy) {
return tileNext;
}
}
return tileFrom;
};
/**
* Converts a list of vertices into contours.
* <span class="alert alert-info"><strong>Tip:</strong> when converting tiles to shapes, is usually better to call {@link ig.utilstile.shapesFromCollisionMap}.</span>
* @param {Array} vertices list of vertices
* @param {Object} options options object
* @returns {Array} list of contours
**/
ig.utilstile.verticesToContours = function (vertices, options) {
var contours = [];
if (vertices.length > 1) {
options = options || {};
// find each contour within vertices
var vertexPool = vertices.slice(0);
var contour = {
vertices: [],
minX: Number.MAX_VALUE,
minY: Number.MAX_VALUE,
maxX: -Number.MAX_VALUE,
maxY: -Number.MAX_VALUE
};
var contourVertices = contour.vertices;
var vb = vertexPool.pop();
var va = vertexPool.pop();
var pva, pvb;
var sva, svb;
var i, il, j, jl;
// length > -2 because we need 1 extra loop for final segment/contour
while (vertexPool.length > -2) {
var stepped = false;
// if we haven't looped around, try to step to next
sva = contourVertices[ 0 ];
svb = contourVertices[ 1 ];
if (contourVertices.length <= 2 || vb.x !== sva.x || vb.y !== sva.y) {
for (i = 0, il = vertexPool.length; i < il; i += 2) {
pva = vertexPool[ i ];
pvb = vertexPool[ i + 1 ];
if (vb.x === pva.x && vb.y === pva.y) {
stepped = true;
break;
}
}
}
// only add the second vector of each pair
contourVertices.push(vb);
// update contour min/max
if (vb.x < contour.minX) contour.minX = vb.x;
if (vb.x > contour.maxX) contour.maxX = vb.x;
if (vb.y < contour.minY) contour.minY = vb.y;
if (vb.y > contour.maxY) contour.maxY = vb.y;
if (stepped === true) {
vertexPool.splice(i, 2);
va = pva;
vb = pvb;
}
else {
if ( contour.vertices.length >= 3 ) {
contours.push(contour);
}
if (vertexPool.length > 0) {
contour = {
vertices: []
};
contour.minX = contour.minY = Number.MAX_VALUE;
contour.maxX = contour.maxY = -Number.MAX_VALUE;
contourVertices = contour.vertices;
vb = vertexPool.pop();
va = vertexPool.pop();
}
else {
break;
}
}
}
// set contour size
for (i = 0, il = contours.length; i < il; i++) {
contour = contours[ i ];
contour.width = contour.maxX - contour.minX;
contour.height = contour.maxY - contour.minY;
}
// sort contours by largest up
contours.sort(function (a, b) {
return ( b.width * b.width + b.height * b.height ) - ( a.width * a.width + a.height * a.height );
});
// test each contour to find containing contours
// if shape's AABB is fully contained by another shape, make chain ordered from smallest to largest
var contourPool = contours.slice(0);
var containerChains = [];
var containerChain = [];
var containingContour, contained;
contour = contourPool.pop();
while (contourPool.length > -1) {
contained = false;
if (contour) {
// search contours instead of contour pool so we can find all containers
for (i = contours.length - 1; i > -1; i--) {
containingContour = contours[ i ];
if (contour !== containingContour && _uti.AABBContains(contour.minX, contour.minY, contour.maxX, contour.maxY, containingContour.minX, containingContour.minY, containingContour.maxX, containingContour.maxY)) {
contained = true;
break;
}
}
containerChain.push(contour);
}
if (contained) {
contourPool.erase(containingContour);
contour = containingContour;
}
else {
if (containerChain.length > 1) {
containerChains.push(containerChain);
}
if (contourPool.length > 0) {
containerChain = [];
contour = contourPool.pop();
}
else {
break;
}
}
}
// check each container chain
var contoursReversed = [];
var contoursRemoved = [];
for (i = 0, il = containerChains.length; i < il; i++) {
containerChain = containerChains[ i ];
var outerBoundary = containerChain[ containerChain.length - 1 ];
var innerBoundary = containerChain[ containerChain.length - 2 ];
// reverse vertices of every other contour to avoid creating ccw contours
// this happens because converting tiles to vertices cannot control the direction of the segments
// even length chain, start with first
if (containerChain.length % 2 === 0) {
j = 0;
}
// odd length chain, start with second
else {
j = 1;
}
for (jl = containerChain.length; j < jl; j += 2) {
contour = containerChain[ j ];
if (_ut.indexOfValue(contoursReversed, contour) === -1) {
contour.vertices.reverse();
contoursReversed.push(contour);
}
}
// discard outer boundary contour
// generally, we know that the tiles have edges on both sides
// so there should always be a container at the end of the chain that wraps the outside
// we don't need these edges/vertices as it is unlikely the player will ever walk outside the map
if (!options.retainBoundaryOuter && _ut.indexOfValue(contoursRemoved, outerBoundary) === -1) {
contoursRemoved.push(outerBoundary);
_ut.arrayCautiousRemove(contours, outerBoundary);
}
// discard inner boundary contour
if (options.discardBoundaryInner && _ut.indexOfValue(contoursRemoved, innerBoundary) === -1) {
contoursRemoved.push(innerBoundary);
_ut.arrayCautiousRemove(contours, innerBoundary);
}
// discard anything beyond inner boundary contour
if (options.discardEdgesInner && containerChain.length > 2) {
var otherContours = containerChain.slice(2);
contoursRemoved = contoursRemoved.concat(otherContours);
_ut.arrayCautiousRemoveMulti(contours, otherContours);
}
}
// finalize contours
for (i = 0, il = contours.length; i < il; i++) {
contour = contours[ i ];
contourVertices = contour.vertices;
// optimization (default): find and remove all intermediary collinear vertices
if (!options.discardCollinear) {
sva = contourVertices[ 0 ];
for (j = contourVertices.length - 1; j > 0; j--) {
va = contourVertices[ j ];
vb = contourVertices[ j - 1 ];
if (_utv2.pointsCW(sva, va, vb) === 0) {
contourVertices.splice(j, 1);
}
else {
sva = va;
}
va = vb;
}
// do one extra collinear check with first vertex as target for removal
if (_utv2.pointsCW(contourVertices[ j + 1 ], contourVertices[ j ], contourVertices[ contourVertices.length - 1 ]) === 0) {
contourVertices.splice(0, 1);
}
}
// if vertices should be in reverse order
if (options.reverse) {
contourVertices.reverse();
}
// make vertices relative
var minX = contour.minX;
var minY = contour.minY;
var width = contour.width;
var height = contour.height;
for (j = 0, jl = contourVertices.length; j < jl; j++) {
va = contourVertices[ j ];
va.x -= minX + width * 0.5;
va.y -= minY + height * 0.5;
}
}
}
return contours;
};
/**
* Generates boolean for empty or, if solid, vertices and segments in clockwise order from a tile.
* <span class="alert alert-info"><strong>Tip:</strong> when converting tiles to shapes, is usually better to call {@link ig.utilstile.shapesFromCollisionMap}.</span>
* @param {Object} map collision Map
* @param {Number} ix x position
* @param {Number} iy y Position
* @returns {Object} object with array of 0 to 5 vertices and array of 0 to 5 segments
**/
ig.utilstile.shapeFromTile = function (map, ix, iy) {
var i, il;
var tileId = map.data[ iy ][ ix ];
var vertices = ig.utilstile.verticesFromTile(map, ix, iy);
var segments;
if (vertices) {
// get or compute segments from tile
if (ig.utilstile.defaultTileSegmentsDef[ tileId ]) {
segments = ig.utilstile.defaultTileSegmentsDef[ tileId ];
}
else {
ig.utilstile.defaultTileSegmentsDef[ tileId ] = segments = [];
for (i = 0, il = vertices.length; i < il; i++) {
var va = vertices[ i ];
var indexB = i === il - 1 ? 0 : i + 1;
var vb = vertices[ indexB ];
// store segment with pre-computed normal for later use
// normal should be facing out and normalized between 0 and 1
var dx = vb.x - va.x;
var dy = vb.y - va.y;
var l = Math.sqrt(dx * dx + dy * dy);
var nx = dy / l;
var ny = -dx / l;
segments.push({ a: i, b: indexB, normal: { x: nx, y: ny } });
}
}
}
return {
vertices: vertices,
segments: segments || []
};
};
/**
* Generates boolean for empty or, if solid, vertices in clockwise order from a tile.9
* <br>- this function makes some assumptions about tiles, such as being either 3, 4, or 5 sided, always having a corner, and being convex
* <span class="alert alert-info"><strong>Tip:</strong> when converting tiles to shapes, is usually better to call {@link ig.utilstile.shapesFromCollisionMap}.</span>
* @param {Object} map Collision Map
* @param {Number} ix x position
* @param {Number} iy y Position
* @returns {Array} array of 0 to 5 vertices
**/
ig.utilstile.verticesFromTile = function (map, ix, iy) {
var tileId = map.data[ iy ][ ix ];
var vertices;
// get or compute shape from tile
if (ig.utilstile.defaultTileVerticesDef[ tileId ]) {
vertices = ig.utilstile.defaultTileVerticesDef[ tileId ];
}
else {
// solid square (1) or climbable (100/111)
if (tileId === 1 || HASH_CLIMBABLE[ tileId ]) {
vertices = [
{ x: 0, y: 0 },
{ x: 1, y: 0 },
{ x: 1, y: 1 },
{ x: 0, y: 1 }
];
}
// solid sloped
else {
vertices = [];
// find vertices
var def = map.tiledef[ tileId ];
if (def) {
var va = vertices[ 0 ] = { x: def[0], y: def[1] };
var vb = vertices[ 1 ] = { x: def[2], y: def[3] };
var ax = va.x;
var ay = va.y;
var bx = vb.x;
var by = vb.y;
var fx = bx - ax;
var fy = by - ay;
// we have two points and the slope's facing direction
// find remaining points
// corner
var vc = vertices[ 2 ] = { x: ( fy < 0 ? 1 : 0 ), y: ( fx > 0 ? 1 : 0 ) };
var cx = vc.x;
var cy = vc.y;
var vd, ve, dax, day, dbx, dby;
// check if 5 sided
var fiveSided = false;
if (Math.abs(fx) < 1 && Math.abs(fy) < 1) {
var quadrantA = _utv2.pointQuadrant(ax, ay, 0.5, 0.5);
var quadrantB = _utv2.pointQuadrant(bx, by, 0.5, 0.5);
var quadrantC = _utv2.pointQuadrant(cx, cy, 0.5, 0.5);
if (!( quadrantA & quadrantC ) && !( quadrantB & quadrantC )) {
fiveSided = true;
}
}
if (fiveSided === true) {
// generate vertices in both directions from corner
if (cx !== cy) {
dax = cx;
dby = cy;
if (cx == 1) {
day = 1;
dbx = 0;
}
else {
day = 0;
dbx = 1;
}
}
else {
day = cy;
dbx = cx;
if (cx == 1) {
dax = 0;
dby = 0;
}
else {
dax = 1;
dby = 1;
}
}
vd = vertices[ 3 ] = { x: dax, y: day };
ve = vertices[ 4 ] = { x: dbx, y: dby };
}
else {
// check from corner to connected points
// generate d vertices in both directions for testing against a and b
if (cx !== cy) {
dax = cx;
dby = cy;
if (cx == 1) {
day = Math.max(ay, by);
dbx = Math.min(ax, bx);
}
else {
day = Math.min(ay, by);
dbx = Math.max(ax, bx);
}
}
else {
day = cy;
dbx = cx;
if (cx == 1) {
dax = Math.min(ax, bx);
dby = Math.min(ay, by);
}
else {
dax = Math.max(ax, bx);
dby = Math.max(ay, by);
}
}
// da is duplicate of a
if (( dax === ax && day === ay ) || ( dax === bx && day === by )) {
// db is not duplicate of b
if (!( ( dbx === ax && dby === ay ) || ( dbx === bx && dby === by ) )) {
vd = vertices[ 3 ] = { x: dbx, y: dby };
}
}
else {
vd = vertices[ 3 ] = { x: dax, y: day };
}
}
vertices = _utv2.pointsToConvexHull(vertices);
}
// store so we don't compute again
ig.utilstile.defaultTileVerticesDef[ tileId ] = vertices;
}
}
return vertices;
};
/**
* Checks and returns all of a tile's non-duplicate segment vertices.
* <span class="alert alert-info"><strong>Tip:</strong> when converting tiles to shapes, is usually better to call {@link ig.utilstile.shapesFromCollisionMap}.</span>
* @param {Object} tile shaped tile
* @param {Array} tileData tiles data (2D array).
* @param {Array} tilesAllowed tiles allowed to check against (flat array)
* @returns {Array} list of vertices
**/
ig.utilstile.getNonDuplicateSegmentVertices = function (tile, tileData, tilesAllowed) {
var ix = tile.ix;
var iy = tile.iy;
var shape = tile.shape;
var vertices = shape.vertices;
var segments = shape.segments;
var nonDuplicates = [];
// add segment vertices in clockwise order while checking for duplicates
var i, il;
var j, jl;
for (i = 0, il = segments.length; i < il; i++) {
var segment = segments[ i ];
var va = vertices[ segment.a ];
var vb = vertices[ segment.b ];
var normal = segment.normal;
var overlap = false;
// if normal is axis aligned to x/y
// compare segment to touching tiles from normal direction
if (( normal.x === 0 && normal.y !== 0 ) || ( normal.x !== 0 && normal.y === 0 )) {
var touchingTiles = ig.utilstile.getTouchingTilesByDirection(tile, normal, tileData, tilesAllowed);
// check each touching for overlap
for (j = 0, jl = touchingTiles.length; j < jl; j++) {
var touchingTile = touchingTiles[ j ];
if (touchingTile.shape.vertices.length > 0) {
overlap = ig.utilstile.getSegmentOverlapWithTile(va, vb, normal, touchingTile);
if (overlap) break;
}
}
}
// no overlap at all
if (overlap === false) {
nonDuplicates.push(va, vb);
}
// partial overlap found, use returned non-overlapping segment
else if (overlap.segmentA) {
nonDuplicates.push(overlap.segmentA.va, overlap.segmentA.vb);
}
}
return nonDuplicates;
};
/**
* Gets touching tiles based on a direction.
* <span class="alert alert-info"><strong>Tip:</strong> when converting tiles to shapes, is usually better to call {@link ig.utilstile.shapesFromCollisionMap}.</span>
* @param {Object} tile shaped tile
* @param {Object} direction direction to look (normalized)
* @param {Array} tileData tiles data (2D array)
* @param {Array} tilesAllowed tiles allowed to check against (flat array)
* @returns {Array} all tiles directly touching a tile based on direction
**/
ig.utilstile.getTouchingTilesByDirection = function (tile, direction, tileData, tilesAllowed) {
var ix = tile.ix;
var iy = tile.iy;
var nx = direction.x;
var ny = direction.y;
var touchingTiles = [];
var touchingTile;
var row;
if (nx !== 0) {
row = tileData[ iy ];
if (nx > 0) {
if (ix < row.length - 1) {
touchingTile = row[ ix + 1 ];
if (!tilesAllowed || _ut.indexOfValue(tilesAllowed, touchingTile) !== -1) {
touchingTiles.push(touchingTile);
}
}
}
else {
if (ix > 0) {
touchingTile = row[ ix - 1 ];
if (!tilesAllowed || _ut.indexOfValue(tilesAllowed, touchingTile) !== -1) {
touchingTiles.push(touchingTile);
}
}
}
}
if (ny !== 0) {
if (ny > 0) {
if (iy < tileData.length - 1) {
touchingTile = tileData[ iy + 1 ][ ix ];
if (!tilesAllowed || _ut.indexOfValue(tilesAllowed, touchingTile) !== -1) {
touchingTiles.push(touchingTile);
}
}
}
else {
if (iy > 0) {
touchingTile = tileData[ iy - 1 ][ ix ];
if (!tilesAllowed || _ut.indexOfValue(tilesAllowed, touchingTile) !== -1) {
touchingTiles.push(touchingTile);
}
}
}
}
return touchingTiles;
};
/**
* Gets if a segment overlaps a tile edge.
* <span class="alert alert-info"><strong>Tip:</strong> when converting tiles to shapes, is usually better to call {@link ig.utilstile.shapesFromCollisionMap}.</span>
* @param {Number} vaA segment vertex a
* @param {Number} vbA segment vertex b
* @param {Vector2|Object} normalCompare facing normal of segment
* @param {Object} tile shaped tile to compare segment to
* @returns {Boolean|Object} no overlap = false, full overlap = true, partial overlap = object with area not overlapped
**/
ig.utilstile.getSegmentOverlapWithTile = function (vaA, vbA, normalCompare, tile) {
var overlap = false;
var shape = tile.shape;
var vertices = shape.vertices;
var segments = shape.segments;
var i, il;
var segmentPotential, normal, segment;
// find overlapping segment, assuming no more than 1 overlap can occur in a tile
for (i = 0, il = segments.length; i < il; i++) {
segmentPotential = segments[ i ];
normal = segmentPotential.normal;
// for any overlap to occur, normals must be pointing in opposite directions
if (normalCompare.x === -normal.x && normalCompare.y === -normal.y) {
segment = segmentPotential;
break;
}
}
if (segment) {
var vaB = vertices[ segment.a ];
var vbB = vertices[ segment.b ];
var xaA = vaA.x;
var yaA = vaA.y;
var xbA = vbA.x;
var ybA = vbA.y;
var xaB = vaB.x;
var yaB = vaB.y;
var xbB = vbB.x;
var ybB = vbB.y;
var xlA = xbA - xaA;
var ylA = ybA - yaA;
var lenA = Math.sqrt(xlA * xlA + ylA * ylA);
var xnA = xlA / lenA;
var ynA = ylA / lenA;
var xlB = xaB - xbB;
var ylB = yaB - ybB;
var lenB = Math.sqrt(xlB * xlB + ylB * ylB);
var xnB = xlB / lenB;
var ynB = ylB / lenB;
var cross = xnA * ynB - ynA * xnB;
// if cross product = 0, lines are parallel
// no need to check for collinearity
if (cross === 0) {
var saebMin, saebMax, easbMin, easbMax, normal;
var minCompare, maxCompare, property;
// horizontal lines
if (xnA !== 0) {
saebMin = Math.min(xaA, xbB);
saebMax = Math.max(xaA, xbB);
easbMin = Math.min(xbA, xaB);
easbMax = Math.max(xbA, xaB);
normal = xnA;
minCompare = xaA;
maxCompare = xbA;
property = 'x';
}
// vertical lines
else {
saebMin = Math.min(yaA, ybB);
saebMax = Math.max(yaA, ybB);
easbMin = Math.min(ybA, yaB);
easbMax = Math.max(ybA, yaB);
normal = ynA;
minCompare = yaA;
maxCompare = ybA;
property = 'y';
}
// fully overlapping
if (saebMin === saebMax && easbMin === easbMax) {
overlap = true;
}
// partial or no overlap
else {
var overlappingBy = normal < 0 ? saebMin - easbMax : easbMin - saebMax;
// find edges outside partial overlap
if (overlappingBy > 0) {
// duplicate will be new edges instead of boolean
overlap = {
segmentA: { va: { x: vaA.x, y: vaA.y }, vb: { x: vbA.x, y: vbA.y } },
segmentB: { va: { x: vaB.x, y: vaB.y }, vb: { x: vbB.x, y: vbB.y } }
};
var min, max;
var wipeout = true;
if (normal < 0) {
min = saebMin === saebMax ? 0 : ( saebMin === minCompare ? SEGMENT_B : SEGMENT_A );
max = easbMin === easbMax ? 0 : ( easbMax === maxCompare ? SEGMENT_B : SEGMENT_A );
if (min === SEGMENT_A) {
overlap.segmentA.vb[ property ] += overlappingBy;
wipeout = false;
}
else if (min === SEGMENT_B) {
overlap.segmentB.va[ property ] += overlappingBy;
}
if (max === SEGMENT_A) {
overlap.segmentA.va[ property ] -= overlappingBy;
wipeout = false;
}
else if (max === SEGMENT_B) {
overlap.segmentB.vb[ property ] -= overlappingBy;
}
// other edge may be bigger and fully overlapping this one
if (wipeout === true) {
overlap = true;
}
}
else {
min = saebMin === saebMax ? 0 : ( saebMin === minCompare ? SEGMENT_A : SEGMENT_B );
max = easbMin === easbMax ? 0 : ( easbMax === maxCompare ? SEGMENT_A : SEGMENT_B );
if (min === SEGMENT_A) {
overlap.segmentA.vb[ property ] -= overlappingBy;
wipeout = false;
}
else if (min === SEGMENT_B) {
overlap.segmentB.va[ property ] -= overlappingBy;
}
if (max === SEGMENT_A) {
overlap.segmentA.va[ property ] += overlappingBy;
wipeout = false;
}
else if (max === SEGMENT_B) {
overlap.segmentB.vb[ property ] += overlappingBy;
}
// other edge may be bigger and fully overlapping this one
if (wipeout === true) {
overlap = true;
}
}
}
}
}
}
return overlap;
};
}); | Tempus35/impactJSChocolate | lib/plusplus/helpers/utilstile.js | JavaScript | mit | 52,582 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sequelize = undefined;
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _sequelize = require('sequelize');
var _sequelize2 = _interopRequireDefault(_sequelize);
var _config = require('../config');
var _config2 = _interopRequireDefault(_config);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var sequelize = exports.sequelize = new _sequelize2.default(_config2.default.db.database, _config2.default.db.user, _config2.default.db.pass, _config2.default.db.options);
var db = {};
_fs2.default.readdirSync(__dirname).filter(function (file) {
return file !== 'index.js';
}).forEach(function (file) {
var model = sequelize.import(_path2.default.join(__dirname, file));
db[model.name] = model;
});
db.sequelize = sequelize;
db.Sequelize = _sequelize2.default;
db.invoice.belongsTo(db.class_enum, {
foreignKey: 'class'
});
db.invoice.belongsTo(db.currency_enum, {
foreignKey: 'currency'
});
db.invoice.belongsTo(db.product_enum, {
foreignKey: 'product'
});
db.invoice.belongsTo(db.revenue_type_enum, {
foreignKey: 'revenueType'
});
db.invoice.belongsTo(db.status_enum, {
foreignKey: 'status'
});
db.invoice.belongsTo(db.subscription_enum, {
foreignKey: 'subscriptionType'
});
db.invoice.belongsTo(db.type_enum, {
foreignKey: 'type'
});
db.invoice.belongsTo(db.country_enum, {
foreignKey: 'country'
});
db.invoice.hasMany(db.income, {
foreignKey: 'invoiceId',
onDelete: 'cascade'
});
db.invoice.hasMany(db.deferred_balance, {
foreignKey: 'invoiceId',
onDelete: 'cascade'
});
db.user.hasMany(db.user_permission, {
foreignKey: 'username',
onDelete: 'cascade'
});
db.income.belongsTo(db.invoice, {
foreignKey: 'invoiceId',
onDelete: 'cascade'
});
db.income.belongsTo(db.month_enum, {
foreignKey: 'month'
});
db.deferred_balance.belongsTo(db.invoice, {
foreignKey: 'invoiceId',
onDelete: 'cascade'
});
db.deferred_balance.belongsTo(db.month_enum, {
foreignKey: 'month'
});
module.exports = db; | superdada2/AccountingManager | server/dist/models/index.js | JavaScript | mit | 2,173 |
var q = require('q');
var fs = require('fs');
var path = require('path');
var async = require('async');
var modbusMap = require('ljswitchboard-modbus_map').getConstants();
var driver_const = require('ljswitchboard-ljm_driver_constants');
var DEBUG_STARTUP_CONFIG_OPS = false;
var DEBUG_READ_CONFIG_OP = false;
var DEBUG_WRITE_CONFIG_OP = false;
var ENABLE_ERROR_OUTPUT = true;
// Set to true to perform device writes. If it is false
// the write functions will automatically resolve and not execute to prevent
// un-necessary flash chip wear.
var ENABLE_DEVICE_WRITES = true;
function getLogger(bool) {
return function logger() {
if(bool) {
console.log.apply(console, arguments);
}
};
}
var debugSC = getLogger(DEBUG_STARTUP_CONFIG_OPS);
var debugRC = getLogger(DEBUG_READ_CONFIG_OP);
var debugWC = getLogger(DEBUG_WRITE_CONFIG_OP);
var errorLog = getLogger(ENABLE_ERROR_OUTPUT);
/*
* Basic flash address keys, locations (offsets), and lengths are
* documented on this basecamp page:
* https://basecamp.com/1764385/projects/34645/documents/767398
*
* Information that might be relevant to saving/restoring device settings:
* StartupPowerSettings
* Address: 0x3BF000
* Startup Settings
* Description:
* Key: 0x0D08CAEA
* Address: 0x3C0000
* Length: 0x001000
* Device Config Settings
* Description:
* Key: 0x9CDD28F7
* Address: 0x3C1000
* Length: 0x001000
* Comm Settings
* Description:
* Key: 0x2C69E1CE
* Address: 0x3C2000
* Length: 0x001000
* Device Info
* Description:
* Key: 0x552684BA
* Address: 0x3C3000
* Length: 0x001000
*
*/
var validConfigOptions = [
'RequiredInfo', // power_x_default registers
'StartupSettings', // DIO states & directions, DIO_EF clock configs, DIO_EF configs, AIN settings, DAC Voltages
'CommSettings', // Ethernet, WiFi, SSID settings.
'AIN_EF_Settings', // AIN_EF settings.
];
var KEY_REGISTERS = {
'T7': {
'RequiredInfo': { 'registers': ['PRODUCT_ID', 'FIRMWARE_VERSION']},
'StartupPowerSettings': { 'registers': ['POWER_ETHERNET_DEFAULT', 'POWER_WIFI_DEFAULT', 'POWER_AIN_DEFAULT', 'POWER_LED_DEFAULT']},
},
'T4': {
'RequiredInfo': { 'registers': ['PRODUCT_ID', 'FIRMWARE_VERSION']},
'StartupPowerSettings': { 'registers': ['POWER_ETHERNET_DEFAULT', 'POWER_WIFI_DEFAULT', 'POWER_AIN_DEFAULT', 'POWER_LED_DEFAULT']},
}
};
var FLASH_ADDRESSES = {
'T7': {
'UserAndWebSpace': { 'address': 0x000000, 'key': 0x6615E336, 'length': 0x200000, },
'ExtFirmwareImage': { 'address': 0x200000, 'key': 0x6A0902B5, 'length': 0x080000, },
'ExtFirmwareImgInfo': { 'address': 0x380000, 'key': 0xDCA6AD50, 'length': 0x001000, },
'IntFirmwareImgInfo': { 'address': 0x381000, 'key': 0xF0B17AC5, 'length': 0x001000, },
'EmerFirmwareImgInfo': { 'address': 0x382000, 'key': 0xB6337A1E, 'length': 0x001000, },
'UpgradeLog': { 'address': 0x383000, 'key': 0x5877D2EF, 'length': 0x001000, },
// 'StartupPowerSettings': { 'address': 0x3BF000, 'key': 0x0, 'length': 0x001000, }, // Not writeable via standard flash writes.
'StartupSettings': { 'address': 0x3C0000, 'key': 0x0D08CAEA, 'length': 0x001000, },
'DeviceConfig': { 'address': 0x3C1000, 'key': 0x9CDD28F7, 'length': 0x001000, },
'CommSettings': { 'address': 0x3C2000, 'key': 0x2C69E1CE, 'length': 0x001000, },
'DeviceInfo': { 'address': 0x3C3000, 'key': 0x552684BA, 'length': 0x001000, },
'CalValues': { 'address': 0x3C4000, 'key': 0xA7863777, 'length': 0x001000, },
'SWDTSettings': { 'address': 0x3C5000, 'key': 0x94D42492, 'length': 0x001000, },
'ManufacturingInfo': { 'address': 0x3C6000, 'key': 0x258E3701, 'length': 0x001000, }, // 8*8 ints. Only uses 0x100.
'CalibrationInfo': { 'address': 0x3C7000, 'key': 0x43A24C42, 'length': 0x001000, },
// 'DeviceName': { 'address': 0x3C8000, 'key': 0x1CE2FB72, 'length': 0x001000, }, // Not writeable via standard flash writes.
//S1W_DEV_Settings
'NTP_Settings': { 'address': 0x3CC000, 'key': 0x6D9DFA03, 'length': 0x001000, },
'AIN_EF_Settings': { 'address': 0x3CD000, 'key': 0x27EB26E7, 'length': 0x002000, },
// 'Lua_Script': { 'address': 0x3D0000, 'key': 0x0, 'length': 0x010000, }, // Not writeable via standard flash writes.
'EmerFirmwareImage': { 'address': 0x3E0000, 'key': 0xCD3D7F15, 'length': 0x020000, },
},
'T4': {
'UserAndWebSpace': { 'address': 0x000000, 'key': 0x6615E336, 'length': 0x200000, },
'ExtFirmwareImage': { 'address': 0x200000, 'key': 0x6A0902B5, 'length': 0x080000, },
'ExtFirmwareImgInfo': { 'address': 0x380000, 'key': 0xDCA6AD50, 'length': 0x001000, },
'IntFirmwareImgInfo': { 'address': 0x381000, 'key': 0xF0B17AC5, 'length': 0x001000, },
'EmerFirmwareImgInfo': { 'address': 0x382000, 'key': 0xB6337A1E, 'length': 0x001000, },
'UpgradeLog': { 'address': 0x383000, 'key': 0x5877D2EF, 'length': 0x001000, },
// 'StartupPowerSettings': { 'address': 0x3BF000, 'key': 0x0, 'length': 0x001000, }, // Not writeable via standard flash writes.
'StartupSettings': { 'address': 0x3C0000, 'key': 0x0D08CAEA, 'length': 0x001000, },
'DeviceConfig': { 'address': 0x3C1000, 'key': 0x9CDD28F7, 'length': 0x001000, },
'CommSettings': { 'address': 0x3C2000, 'key': 0x2C69E1CE, 'length': 0x001000, },
'DeviceInfo': { 'address': 0x3C3000, 'key': 0x552684BA, 'length': 0x001000, },
'CalValues': { 'address': 0x3C4000, 'key': 0xA7863777, 'length': 0x001000, },
'SWDTSettings': { 'address': 0x3C5000, 'key': 0x94D42492, 'length': 0x001000, },
'ManufacturingInfo': { 'address': 0x3C6000, 'key': 0x258E3701, 'length': 0x001000, },
'CalibrationInfo': { 'address': 0x3C7000, 'key': 0x43A24C42, 'length': 0x001000, },
// 'DeviceName': { 'address': 0x3C8000, 'key': 0x1CE2FB72, 'length': 0x001000, },
//S1W_DEV_Settings
'NTP_Settings': { 'address': 0x3CC000, 'key': 0x6D9DFA03, 'length': 0x001000, },
'AIN_EF_Settings': { 'address': 0x3CD000, 'key': 0x27EB26E7, 'length': 0x002000, },
// 'Lua_Script': { 'address': 0x3D0000, 'key': 0x0, 'length': 0x010000, }, // Not writeable via standard flash writes.
'EmerFirmwareImage': { 'address': 0x3E0000, 'key': 0xCD3D7F15, 'length': 0x020000, },
}
};
function calcNumPagesFromLength (length) {
var numPages = Math.ceil(length/driver_const.T7_FLASH_PAGE_SIZE);
return numPages;
}
function getStartupConfigOperations(self) {
function getReadOptionOperation(option) {
debugRC('in getReadOptionOperation', self.savedAttributes.deviceTypeName);
var dt = self.savedAttributes.deviceTypeName;
var isValid = false;
if(validConfigOptions.indexOf(option) >= 0) {
isValid = true;
}
// readFlash(startAddress, length)
// iRead(address)
// iReadMany(addresses)
var operation = {
'isValid': isValid,
'operationName': option,
'type': '',
'functionName': '',
'args': [],
'isError': false,
'error': undefined,
'errorCode': 0,
'result': undefined,
};
if(isValid) {
// Check to see if the option should be read from/written to using flash operations.
if(typeof(FLASH_ADDRESSES[dt][option]) !== 'undefined') {
operation.type = 'flash';
operation.functionName = 'readFlash';
var flashAddress = FLASH_ADDRESSES[dt][option].address;
var flashLength = FLASH_ADDRESSES[dt][option].length/4;
operation.args = [flashAddress, flashLength];
} else if(typeof(KEY_REGISTERS[dt][option]) !== 'undefined') {
operation.type = 'registers';
operation.functionName = 'iReadMany';
operation.args = [KEY_REGISTERS[dt][option].registers];
} else {
operation.isValid = false;
}
}
return operation;
}
function createReadConfigsBundle(options) {
var bundle = {
'readOperations': [],
'validResults': [],
'isError': false,
'errorStep': '',
'error': undefined,
'errorCode': 0,
};
if(typeof(options) !== 'undefined') {
options.forEach(function(option) {
var readOperation = getReadOptionOperation(option);
if(readOperation.isValid) {
bundle.readOperations.push(readOperation);
}
});
}
debugRC('read operations:', bundle.readOperations.length);
bundle.readOperations.forEach(function(op) {
debugRC(' - ', op.operationName);
});
return bundle;
}
function innerReadConfigs(bundle) {
var defered = q.defer();
debugRC(' in innerReadConfigs');
async.eachSeries(
bundle.readOperations,
function executeReadOps (operation, cb) {
debugRC('Executing operation', operation.operationName, operation.type, operation.isValid);
var func = operation.functionName;
var args = operation.args;
function onSuccess(data) {
if(func === 'readFlash') {
debugRC('Executed operation (flash)', operation.operationName, func);
operation.result = data.results;
} else if(func === 'iReadMany') {
debugRC('Executed operation (regs)', operation.operationName, func);
var results = data;
var dataToSave = [];
results.forEach(function(result) {
dataToSave.push({'reg': result.name, 'res': result.val});
});
operation.result = dataToSave;
}
cb();
}
function onError(err) {
debugRC('! Error Executing operation', operation.operationName);
operation.isError = true;
operation.error = err;
bundle.errorStep = 'executingWriteOperations-' + operation.operationName;
// TODO: Populate operation.errorCode to be a non-zero value.
cb();
}
try{
self[func].apply(undefined, args)
.then(onSuccess)
.catch(onError);
} catch(err) {
console.error('Error executing function...', err);
bundle.isError = true;
bundle.errorStep = 'executeWriteOperations-funcExec';
bundle.error = err;
bundle.errorCode = 0;
cb();
}
},
function finishedReadOps (err) {
// debugRC('Executed all operations', bundle.readOperations);
// Organize results and determine if overall operation was successful.
bundle.readOperations.forEach(function(operation) {
if(operation.isError) {
// We detected an error. Indicate that the overall operation failed.
bundle.isError = true;
bundle.errorStep = operation.operationName;
bundle.error = operation.error;
bundle.errorCode = operation.errorCode;
} else {
bundle.validResults.push({
'group': operation.operationName,
'type': operation.type,
'data': operation.result,
});
}
});
var numOperations = bundle.readOperations.length;
var numSuccessOperations = bundle.validResults.length;
debugRC('Executed all operations % successful:', (numSuccessOperations/numOperations*100).toFixed(2));
defered.resolve(bundle);
}
);
return defered.promise;
}
/*
* Options: Array of strings. Each string is a flash address name that correlates to what needs to be read
* from flash.
*
* ex: var options = ['UserAndWebSpace', 'DeviceConfig, 'DeviceInfo'];
*/
this.readConfigs = function(userOptions) {
debugSC('in readConfigs');
var defered = q.defer();
var options = ['RequiredInfo'];
userOptions.forEach(function(userOption) {
if(userOption !== 'RequiredInfo') {
options.push(userOption);
}
});
var bundle = createReadConfigsBundle(options);
function onSuccess(resBundle) {
debugSC('in readConfigs onSuccess');
if(resBundle.isError) {
defered.reject({
'isError': resBundle.isError,
'errorStep': resBundle.errorStep,
'error': resBundle.error,
'errorCode': resBundle.errorCode,
})
} else {
defered.resolve(resBundle.validResults);
}
}
function onError(errBundle) {
debugSC('in readConfigs onError');
defered.reject({
'isError': errBundle.isError,
'errorStep': errBundle.errorStep,
'error': errBundle.error,
'errorCode': errBundle.errorCode,
})
}
innerReadConfigs(bundle)
.then(onSuccess)
.catch(onError);
return defered.promise;
};
/*
* option is an object with three properties (ref: "finishedReadOps"):
* group: (string) that indicates the operation name reference these defined variables:
* validConfigOptions, KEY_REGISTERS, FLASH_ADDRESSES
* type: (string) that indicates the operation type "flash" or "registers".
* Ref. function "getReadOptionOperation"
* data: array of numbers (uint32 sized) or object that is: {'reg': result.name, 'res': result.val}
*/
function getWriteOptionOperation(option) {
debugWC('in getWriteOptionOperation', self.savedAttributes.deviceTypeName);
var dt = self.savedAttributes.deviceTypeName;
var isValid = false;
if(validConfigOptions.indexOf(option.group) >= 0) {
isValid = true;
}
var operationName = option.group;
var operationType = option.type;
var operationData = option.data;
// writeFlash(startAddress, length, size, key, data)
// iWrite(address, value)
// iWriteMany(addresses, values)
// eraseFlash(startAddress, numPages, key)
var operation = {
'isValid': isValid,
'operationName': option.group,
'type': '',
'functionName': '',
'args': [],
'executeEraseOp': false,
'eraseFuncName': '',
'eraseArgs': [],
'isError': false,
'error': undefined,
'errorCode': 0,
'result': undefined,
};
if(isValid) {
// Check to see if the option should be read from/written to using flash operations.
if(typeof(FLASH_ADDRESSES[dt][operationName]) !== 'undefined') {
debugWC('Detected a flash write operation');
operation.type = 'flash';
operation.functionName = 'writeFlash';
var flashAddress = FLASH_ADDRESSES[dt][operationName].address;
var flashWriteSize = driver_const.T7_FLASH_BLOCK_WRITE_SIZE;
var flashKey = FLASH_ADDRESSES[dt][operationName].key;
var expectedLength = FLASH_ADDRESSES[dt][operationName].length/4;
var actualLength = operationData.length;
if(expectedLength != actualLength) {
console.log('HERE!!!',expectedLength, actualLength);
// If the expected length isn't the actual length of the data being
// written then we likely have issues with this data....
operation.isValid = false;
operation.isError = true;
operation.error = 'Data being written to "' + operationName + '" is invalid. ';
operation.error += 'Expected Length: ' + expectedLength.toString() + '. ';
operation.error += 'Actual Length: ' + actualLength.toString() + '. ';
}
operation.args = [flashAddress, expectedLength, flashWriteSize, flashKey, option.data];
// Add data for flash erase operation.
operation.executeEraseOp = true;
operation.eraseFuncName = 'eraseFlash';
var numPages = calcNumPagesFromLength(expectedLength);
operation.eraseArgs = [flashAddress, numPages, flashKey];
debugWC('Created a flash write operation', flashAddress.toString(16), expectedLength, flashWriteSize, flashKey.toString(16), option.data.length);
} else if(typeof(KEY_REGISTERS[dt][operationName]) !== 'undefined') {
debugWC('Detected a register write operation');
operation.type = 'registers';
operation.functionName = 'iWriteMany';
var registers = [];
var values = [];
operationData.forEach(function(registerObj) {
registers.push(registerObj.reg);
values.push(registerObj.res);
});
operation.args = [registers, values];
debugWC('Created a register write operation');
} else {
debugWC('Operation is not found!', dt, operationName);
operation.isValid = false;
}
}
debugWC('Created a write operation', operation.operationName, operation.type, operation.isValid);
if(!operation.isValid) {
debugWC('Error info', operation.isError, operation.error);
}
return operation;
}
function getEraseFlashOperation(writeFlashOperation) {
var operation = {
'isValid': writeFlashOperation.isValid,
'operationName': writeFlashOperation.operationName,
'type': writeFlashOperation.type,
'functionName': writeFlashOperation.eraseFuncName,
'args': writeFlashOperation.eraseArgs,
'isError': false,
'error': undefined,
'errorCode': 0,
'result': undefined,
};
return operation;
}
function createWriteConfigsBundle(deviceConfigs) {
debugWC('in createWriteConfigsBundle', self.savedAttributes.deviceTypeName);
var bundle = {
// Variables used to determine if data should be written to device.
'requiredProductID': 0,
'requiredFirmwareVersion': 0,
'currentProductID': 99,
'currentFirmwareVersion': 99,
'writeDataToDevice': false,
// Variables used to store data being written to device & results.
'writeOperations': [],
'validResults': [],
// Variables used to determine if write was successful.
'isError': false,
'errorStep': '',
'error': undefined,
'errorCode': 0,
};
if(typeof(deviceConfigs) !== 'undefined') {
deviceConfigs.forEach(function(config) {
// check to see if the config is 'RequiredInfo' which contains the
// required Product ID and FW version.
if(config.group === 'RequiredInfo') {
debugWC('Organizing required info');
config.data.forEach(function(registerData) {
if(registerData.reg === 'FIRMWARE_VERSION') {
bundle.requiredFirmwareVersion = registerData.res;
} else if(registerData.reg === 'PRODUCT_ID') {
bundle.requiredProductID = registerData.res;
}
});
} else {
debugWC('Executing getWriteOptionOperation');
// Parse the configuration into a write operation & make sure it is valid.
var writeOperation = getWriteOptionOperation(config);
// Only add the operation if it is valid.
if(writeOperation.isValid) {
if(writeOperation.type === 'flash') {
var eraseOperation = getEraseFlashOperation(writeOperation);
bundle.writeOperations.push(eraseOperation);
}
bundle.writeOperations.push(writeOperation);
}
}
});
}
debugWC('Write Operations:', bundle.writeOperations.length);
bundle.writeOperations.forEach(function(op) {
debugWC(' - op.operationName');
});
return bundle;
}
function readRequiredDeviceInfo(bundle) {
var defered = q.defer();
debugWC('in readRequiredDeviceInfo');
function onSuccess(registers) {
registers.forEach(function(register) {
if(register.name === 'FIRMWARE_VERSION') {
bundle.currentFirmwareVersion = register.val;
} else if(register.name === 'PRODUCT_ID') {
bundle.currentProductID = register.val;
}
});
defered.resolve(bundle);
}
function onError(err) {
bundle.isError = true;
bundle.errorStep = 'readRequiredDeviceInfo';
bundle.error = err;
bundle.errorCode = 0;
defered.resolve(bundle);
}
var dt = self.savedAttributes.deviceTypeName;
var requiredRegisters = KEY_REGISTERS[dt].RequiredInfo.registers;
self.iReadMany(requiredRegisters)
.then(onSuccess)
.catch(onError);
return defered.promise;
}
function validateProductIDAndFirmware(bundle) {
var defered = q.defer();
var infoIsValid = true;
debugWC('in validateProductIDAndFirmware');
if(bundle.currentFirmwareVersion != bundle.requiredFirmwareVersion) {
infoIsValid = false;
bundle.error = 'Configs are intended for FW version: ' + bundle.requiredFirmwareVersion.toString();
}
if(bundle.currentProductID != bundle.requiredProductID) {
infoIsValid = false;
bundle.error = 'Configs are intended for PRODUCT_ID version: ' + bundle.requiredProductID.toString();
}
if(!infoIsValid) {
bundle.isError = true;
bundle.errorStep = 'validateProductIDAndFirmware-funcExec';
bundle.errorCode = 0;
}
bundle.writeDataToDevice = infoIsValid;
defered.resolve(bundle);
return defered.promise;
}
function executeWriteOperations(bundle) {
var defered = q.defer();
debugWC('in executeWriteOperations');
if(bundle.writeDataToDevice) {
debugWC('Device Info',
bundle.currentFirmwareVersion,
bundle.requiredFirmwareVersion,
bundle.currentProductID,
bundle.requiredProductID
);
async.eachSeries(
bundle.writeOperations,
function executeWriteOps (operation, cb) {
var func = operation.functionName;
var args = operation.args;
debugWC('Executing write operation', operation.operationName, func);
function onSuccess(data) {
debugWC('Finished write operation', operation.operationName);
bundle.validResults.push({
'operation': operation.operationName,
'result': data
});
cb();
}
function onError(err) {
debugWC('Failed write operation', operation.operationName, err);
errorLog('Failed write operation', operation.operationName, err);
bundle.isError = true;
bundle.errorStep = 'executingWriteOperations-' + operation.operationName;
bundle.error = err;
cb();
}
try {
if(!ENABLE_DEVICE_WRITES) {
console.log('NOT WRITING DATA, TEST MODE!! will call func:', func);
onSuccess({'testResult': 1});
} else {
self[func].apply(undefined, args)
.then(onSuccess)
.catch(onError);
// if(func === 'writeFlash') {
// self.writeFlash(args[0], args[1], args[2], args[3], args[4])
// .then(onSuccess)
// .catch(onError);
// } else {
// self[func].apply(undefined, args)
// .then(onSuccess)
// .catch(onError);
// }
}
} catch(err) {
console.error('Error executing function...', err);
bundle.isError = true;
bundle.errorStep = 'executeWriteOperations-funcExec';
bundle.error = err;
bundle.errorCode = 0;
cb();
}
},
function finishedWriteOps (err) {
debugWC('Finished All Write Operations');
var numSuccessfulOperations = bundle.validResults.length;
var numOperations = bundle.writeOperations.length;
debugWC('Executed all operations % successful:', (numSuccessfulOperations/numOperations*100).toFixed(2));
defered.resolve(bundle);
}
);
} else {
debugWC('Invalid Required Device Info',
bundle.currentFirmwareVersion,
bundle.requiredFirmwareVersion,
bundle.currentProductID,
bundle.requiredProductID
);
defered.resolve(bundle);
}
return defered.promise;
}
function innerWriteConfigs(bundle) {
debugWC('in innerWriteConfigs', self.savedAttributes.deviceTypeName);
/*
* In order to write data we must do the following:
* 1. Read the device to check its Product ID and FW currentFirmwareVersion.
* 2. Check to make sure that the P-ID & FW are the same as saved in the data being
* uploaded.
* 3. Write data to the device.
*/
return readRequiredDeviceInfo(bundle)
.then(validateProductIDAndFirmware)
.then(executeWriteOperations);
}
/*
* data: Array of objects that need to be written to the device.
* [{'group': [groupName], 'type': 'flash'/'registers', 'data': [array of ints]/[array of objects Reg & value]}]
*/
this.writeConfigs = function(deviceConfigs) {
debugSC('in writeConfigs');
var defered = q.defer();
var bundle = createWriteConfigsBundle(deviceConfigs);
function onSuccess(resBundle) {
debugSC('in writeConfigs onSuccess');
if(resBundle.isError) {
defered.reject({
'isError': resBundle.isError,
'errorStep': resBundle.errorStep,
'error': resBundle.error,
'errorCode': resBundle.errorCode,
});
} else {
defered.resolve(resBundle.validResults);
}
}
function onError(errBundle) {
debugSC('in writeConfigs onError');
defered.reject({
'isError': errBundle.isError,
'errorStep': errBundle.errorStep,
'error': errBundle.error,
'errorCode': errBundle.errorCode,
})
}
innerWriteConfigs(bundle)
.then(onSuccess)
.catch(onError);
return defered.promise;
};
}
module.exports.get = getStartupConfigOperations; | chrisJohn404/ljswitchboard-ljm_device_curator | lib/startup_config_operations.js | JavaScript | mit | 23,758 |
'use strict';
var app_mo_static = require('../index');
// To know the usage of `assert`, see: http://nodejs.org/api/assert.html
var assert = require('assert');
describe("description", function(){
it("should has a method `my_method`", function(){
assert.ok('my_method' in app_mo_static);
});
}); | mo-doc/mo-static | test/app-mo-static.js | JavaScript | mit | 305 |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.11.0-master-3e34e02
*/
!function(t,n,i){"use strict";n.module("material.components.backdrop",["material.core"]).directive("mdBackdrop",["$mdTheming","$animate","$rootElement","$window","$log","$$rAF","$document",function(t,n,i,e,o,r,a){function p(p,d,s){var m=e.getComputedStyle(a[0].body);if("fixed"==m.position){var l=parseInt(m.height,10)+Math.abs(parseInt(m.top,10));d.css({height:l+"px"})}n.pin&&n.pin(d,i),r(function(){var n=d.parent()[0];if(n){var i=e.getComputedStyle(n);"static"==i.position&&o.warn(c)}t.inherit(d,d.parent())})}var c="<md-backdrop> may not work properly in a scrolled, static-positioned parent container.";return{restrict:"E",link:p}}])}(window,window.angular); | jzucadi/bower-material | modules/js/backdrop/backdrop.min.js | JavaScript | mit | 780 |
'use strict';
import MainCtrl from './main/main.controller';
import NavbarCtrl from '../app/components/navbar/navbar.controller';
angular.module('clashPlanner', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngResource', 'ui.router', 'ngMaterial'])
.controller('MainCtrl', MainCtrl)
.controller('NavbarCtrl', NavbarCtrl)
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('/');
})
;
| jarekb84/ClashPlanner | src/app/index.js | JavaScript | mit | 583 |
import { leftSidebarViews } from '../../../constants';
import { __ } from '~/locale';
export const templateTypes = () => [
{
name: '.gitlab-ci.yml',
key: 'gitlab_ci_ymls',
},
{
name: '.gitignore',
key: 'gitignores',
},
{
name: __('LICENSE'),
key: 'licenses',
},
{
name: __('Dockerfile'),
key: 'dockerfiles',
},
{
name: '.metrics-dashboard.yml',
key: 'metrics_dashboard_ymls',
},
];
export const showFileTemplatesBar = (_, getters, rootState) => name =>
getters.templateTypes.find(t => t.name === name) &&
rootState.currentActivityView === leftSidebarViews.edit.name;
| mmkassem/gitlabhq | app/assets/javascripts/ide/stores/modules/file_templates/getters.js | JavaScript | mit | 633 |
(function() {
describe('daemon', function() {
return it('simple daemon', function() {});
});
}).call(this);
| esdrasedu/node-daemon | test/daemon.js | JavaScript | mit | 117 |
import {UPDATE_ROUTES, UPDATE_ACTIVE_PATHNAME, REDIRECT_ROUTE,} from '../types';
import {getPathname,} from '../util';
import {browserHistory,} from 'react-router';
const initialState = {
routes: [],
visibleRoutes: [],
activePathname: getPathname(),
defaultPathname: '/',
};
export default(state = initialState, action) => {
switch (action.type) {
case UPDATE_ROUTES:
return {...state, routes: action.routes, visibleRoutes: action.visibleRoutes,};
case UPDATE_ACTIVE_PATHNAME:
return {...state, activePathname: action.activePathname,};
case REDIRECT_ROUTE:
if (!state.routes.some(route => route.pathname === state.activePathname)) {
requestAnimationFrame(browserHistory.push.bind(browserHistory, initialState.defaultPathname));
}
return state;
default:
return state;
}
}; | ChenH0ng/blog | client/src/store/router.js | JavaScript | mit | 808 |