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
|
---|---|---|---|---|---|
var JudeteRomania = function () {
this.suceava = {color: '#FFFFFF', name: 'suceava'};
this.botosani = {color: '#FFFFFF', name: 'botosani'};
this.iasi = {color: '#FFFFFF', name: 'iasi'};
this.neamt = {color: '#FFFFFF', name: 'neamt'};
this.bacau = {color: '#FFFFFF', name: 'bacau'};
this.vaslui = {color: '#FFFFFF', name: 'vaslui'};
this.galati = {color: '#FFFFFF', name: 'galati'};
this.vrancea = {color: '#FFFFFF', name: 'vrancea'};
this.buzau = {color: '#FFFFFF', name: 'buzau'};
this.braila = {color: '#FFFFFF', name: 'braila'};
this.constanta = {color: '#FFFFFF', name: 'constanta'};
this.tulcea = {color: '#FFFFFF', name: 'tulcea'};
this.mehedinti = {color: '#FFFFFF', name: 'mehedinti'};
this.dolj = {color: '#FFFFFF', name: 'dolj'};
this.gorj = {color: '#FFFFFF', name: 'gorj'};
this.valcea = {color: '#FFFFFF', name: 'valcea'};
this.olt = {color: '#FFFFFF', name: 'olt'};
this.arges = {color: '#FFFFFF', name: 'arges'};
this.teleorman = {color: '#FFFFFF', name: 'teleorman'};
this.dambovita = {color: '#FFFFFF', name: 'dambovita'};
this.giurgiu = {color: '#FFFFFF', name: 'giurgiu'};
this.ialomita = {color: '#FFFFFF', name: 'ialomita'};
this.calarasi = {color: '#FFFFFF', name: 'calarasi'};
this.prahova = {color: '#FFFFFF', name: 'prahova'};
this.bucuresti = {color: '#FFFFFF', name: 'bucuresti'};
this.satu_mare = {color: '#FFFFFF', name: 'satu_mare'};
this.maramures = {color: '#FFFFFF', name: 'maramures'};
this.bihor = {color: '#FFFFFF', name: 'bihor'};
this.arad = {color: '#FFFFFF', name: 'arad'};
this.timis = {color: '#FFFFFF', name: 'timis'};
this.caras_severin = {color: '#FFFFFF', name: 'caras_severin'};
this.hunedoara = {color: '#FFFFFF', name: 'hunedoara'};
this.alba = {color: '#FFFFFF', name: 'alba'};
this.sibiu = {color: '#FFFFFF', name: 'sibiu'};
this.brasov = {color: '#FFFFFF', name: 'brasov'};
this.covasna = {color: '#FFFFFF', name: 'covasna'};
this.harghita = {color: '#FFFFFF', name: 'harghita'};
this.mures = {color: '#FFFFFF', name: 'mures'};
this.bistrita_nasaud = {color: '#FFFFFF', name: 'bistrita_nasaud'};
this.cluj = {color: '#FFFFFF', name: 'cluj'};
this.salaj = {color: '#FFFFFF', name: 'salaj'};
this.suceava.vecini = [
this.maramures,
this.bistrita_nasaud,
this.mures,
this.harghita,
this.neamt,
this.iasi,
this.botosani
];
this.botosani.vecini = [
this.suceava,
this.iasi
];
this.iasi.vecini = [
this.botosani,
this.suceava,
this.neamt,
this.vaslui
];
this.neamt.vecini = [
this.suceava,
this.harghita,
this.bacau,
this.vaslui,
this.iasi
];
this.bacau.vecini = [
this.neamt,
this.harghita,
this.covasna,
this.vrancea,
this.vaslui
];
this.vaslui.vecini = [
this.iasi,
this.neamt,
this.bacau,
this.vrancea,
this.galati
];
this.galati.vecini = [
this.vaslui,
this.vrancea,
this.braila,
this.tulcea
];
this.vrancea.vecini = [
this.bacau,
this.covasna,
this.buzau,
this.braila,
this.galati,
this.vaslui
];
this.buzau.vecini = [
this.vrancea,
this.covasna,
this.brasov,
this.prahova,
this.ialomita,
this.braila
];
this.braila.vecini = [
this.vrancea,
this.buzau,
this.ialomita,
this.constanta,
this.tulcea,
this.galati
];
this.constanta.vecini = [
this.tulcea,
this.braila,
this.ialomita,
this.calarasi
];
this.tulcea.vecini = [
this.galati,
this.braila,
this.constanta
];
this.mehedinti.vecini = [
this.caras_severin,
this.gorj,
this.dolj
];
this.dolj.vecini = [
this.mehedinti,
this.gorj,
this.valcea,
this.olt
];
this.gorj.vecini = [
this.caras_severin,
this.hunedoara,
this.valcea,
this.dolj,
this.mehedinti
];
this.valcea.vecini = [
this.sibiu,
this.alba,
this.hunedoara,
this.gorj,
this.dolj,
this.olt,
this.arges
];
this.olt.vecini = [
this.dolj,
this.valcea,
this.arges,
this.teleorman
];
this.arges.vecini = [
this.sibiu,
this.valcea,
this.olt,
this.teleorman,
this.dambovita,
this.brasov
];
this.teleorman.vecini = [
this.olt,
this.arges,
this.dambovita,
this.giurgiu
];
this.dambovita.vecini = [
this.brasov,
this.arges,
this.teleorman,
this.giurgiu,
this.bucuresti,
this.prahova
];
this.giurgiu.vecini = [
this.teleorman,
this.dambovita,
this.bucuresti,
this.calarasi
];
this.ialomita.vecini = [
this.buzau,
this.prahova,
this.bucuresti,
this.calarasi,
this.constanta,
this.braila
];
this.calarasi.vecini = [
this.giurgiu,
this.bucuresti,
this.ialomita,
this.constanta
];
this.prahova.vecini = [
this.brasov,
this.dambovita,
this.bucuresti,
this.ialomita,
this.buzau
];
this.bucuresti.vecini = [
this.prahova,
this.dambovita,
this.giurgiu,
this.calarasi,
this.ialomita
];
this.satu_mare.vecini = [
this.bihor,
this.salaj,
this.maramures
];
this.maramures.vecini = [
this.satu_mare,
this.salaj,
this.cluj,
this.bistrita_nasaud,
this.suceava
];
this.bihor.vecini = [
this.satu_mare,
this.salaj,
this.cluj,
this.alba,
this.arad
];
this.arad.vecini = [
this.bihor,
this.alba,
this.hunedoara,
this.timis
];
this.timis.vecini = [
this.arad,
this.hunedoara,
this.caras_severin
];
this.caras_severin.vecini = [
this.timis,
this.hunedoara,
this.gorj,
this.mehedinti
];
this.hunedoara.vecini = [
this.arad,
this.timis,
this.caras_severin,
this.gorj,
this.valcea,
this.alba
];
this.alba.vecini = [
this.cluj,
this.bihor,
this.arad,
this.hunedoara,
this.valcea,
this.sibiu,
this.mures
];
this.sibiu.vecini = [
this.mures,
this.alba,
this.valcea,
this.arad,
this.brasov
];
this.brasov.vecini = [
this.harghita,
this.mures,
this.sibiu,
this.arges,
this.dambovita,
this.prahova,
this.buzau,
this.covasna
];
this.covasna.vecini = [
this.harghita,
this.brasov,
this.buzau,
this.vrancea,
this.bacau
];
this.harghita.vecini = [
this.mures,
this.brasov,
this.covasna,
this.bacau,
this.neamt,
this.suceava
];
this.mures.vecini = [
this.bistrita_nasaud,
this.cluj,
this.alba,
this.sibiu,
this.brasov,
this.harghita,
this.suceava
];
this.bistrita_nasaud.vecini = [
this.maramures,
this.cluj,
this.mures,
this.suceava
];
this.cluj.vecini = [
this.salaj,
this.bihor,
this.alba,
this.mures,
this.bistrita_nasaud,
this.maramures
];
this.salaj.vecini = [
this.satu_mare,
this.bihor,
this.cluj,
this.maramures
];
}; | ggbt/UniProjects | Map Coloring with Genetic Algorithm/src/judete.js | JavaScript | mit | 7,036 |
'use strict';
var mc = require('./');
var assert = require('assert');
if(process.argv.length < 4 || process.argv.length > 6) {
console.log("Usage : node echo.js <host> <port> [<name>] [<password>]");
process.exit(1);
}
var host = process.argv[2];
var port = parseInt(process.argv[3]);
var username = process.argv[4] ? process.argv[4] : "echo";
var password = process.argv[5];
mc.createClientAsync({host, port, username, password}, function(err, client) {
if (err) {
console.log('failed to create client', err);
throw err;
}
client.on('connect', function() {
console.info('connected');
});
client.on('disconnect', function(packet) {
console.log('disconnected: '+ packet.reason);
});
client.on('end', function(err) {
console.log('Connection lost');
});
client.on('chat', function(packet) {
console.log('received chat',packet);
});
client.on('forgeMods', function(mods) {
console.log('Received forgeMods event:',mods);
});
});
| deathcap/node-minecraft-protocol-auto | demo.js | JavaScript | mit | 987 |
"use strict";
var vsStore = module.exports,
promise = require('node-promise'),
fs = require('fs-extra'),
moment = require('moment'),
_s4 = function _s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
},
_getGuid = function _getGuid() {
return _s4() + _s4() + '-' + _s4() + '-' + _s4() + '-' + _s4() + '-' + _s4() + _s4() + _s4();
},
initParams = {
dataFolder: ''
};
/**
* Initialize set up and store parameters during runtime
* @param {Object} data Any common storage parameters, currently the data folder is mandatory for proper working.
* @return Boolean True if the process was successful
* @example
* ```javascript
*
* vsStore.init({
* dataFolder: './datastore'
* });
* ```
*/
vsStore.init = function init(setup) {
if (setup === undefined) {
return false;
}
initParams.dataFolder = setup.dataFolder;
return true;
};
/**
* Show the pre-defined init parameters - currently only the data folder
* @return Object Object with pre-defined parameters
* @example
* ```javascript
*
* vsStore.getInitParams();
* ```
*/
vsStore.getInitParams = function getInitParams() {
return initParams;
};
/**
* Read all existing keys
* @return {Promise} Array with all keys
* @example
* ```javascript
*
* vsStore.getKeys().then(function(result){
* console.info('keys:', result);
* });
* ```
*/
vsStore.getKeys = function getKeys() {
var deferred = new promise.Promise();
if (initParams.dataFolder === '') {
deferred.resolve({
success: false,
message: 'Data storing folder is not set'
});
} else {
fs.readdir(initParams.dataFolder, function(err, keys) {
deferred.resolve({
success: true,
data: keys
});
});
}
return deferred;
};
/**
* Storing data with guid key. If the key is provided, it will change and version will bump with one
* @param {Object} data Any kind of standard javascript object which can be stringified and need to be placed into the data file
* @param {String} key Standard key for the data object
* @return {Promise} Object with stored key
* @example
* ```javascript
*
* vsStore.store({
* foo: 'bar'
* }).then(function(data) {
* console.info('resolved', data);
* });
* ```
*/
vsStore.store = function store(data, key) {
var deferred = new promise.Promise(),
guid = (key !== undefined) ? key : _getGuid(),
contentData = data,
filePath = initParams.dataFolder + '/' + guid,
newContent = {
_version: 0,
_modified: null,
_history: {},
content: {}
};
if (data === undefined || data === '') {
deferred.resolve({
success: false,
message: new Error('"data" is not defined')
});
} else {
fs.readJson(filePath, function(err, data) {
if (!err) {
newContent = data;
newContent._history[data._modified + '_' + _s4()] = {
_version: data._version,
_modified: data._modified,
content: data.content
};
}
newContent._version += 1;
newContent._modified = moment().format();
newContent.content = contentData;
newContent.content._key = guid;
fs.outputFile(filePath, JSON.stringify(newContent), function() {
deferred.resolve({
success: true,
data: guid
});
});
});
}
return deferred;
};
/**
* Read data by it's GUID. If `history` is `true`, the whole object going to send
* @param {String} key Standard key for the data object
* @param {Boolean} history If true the whole object will read, not just the current version
* @return {Promise} Object with read data
* @example
* ```javascript
*
* vsStore.read('aaa-bbb-ccc-ddd', true).then(function(data){
* console.info('resolved:', data);
* });
* ```
*/
vsStore.read = function read(key, history) {
var deferred = new promise.Promise(),
result = null;
if (key === undefined || key === '') {
deferred.resolve({
success: false,
message: new Error('"key" is not defined')
});
} else {
fs.readJson(initParams.dataFolder + '/' + key, function(err, data) {
try {
result = (history === true) ? data : data.content;
deferred.resolve({
success: true,
data: result,
key: key
});
} catch (err) {
deferred.resolve({
success: false,
message: err
});
}
});
}
return deferred;
};
/**
* Delete a data object. This process is undoable
* @param {String} key Standard key for the data object
* @return {Promise} Boolean
* @example
* ```javascript
*
* vsStore.del('aaa-bbb-ccc-ddd');
* ```
*/
vsStore.del = function del(key) {
var deferred = new promise.Promise();
if (key === undefined || key === '') {
deferred.resolve({
success: false,
message: new Error('"key" is not defined')
});
} else {
fs.remove(initParams.dataFolder + '/' + key, function() {
deferred.resolve({
success: true
});
});
}
return deferred;
};
/**
* Show if the requested data object is exist or not
* @param {String} key Standard key for the data object
* @return {Promise} Boolean
* @example
* ```javascript
*
* vsStore.exists('aaa-bbb-ccc-ddd');
* ```
*/
vsStore.exists = function exists(key) {
var deferred = new promise.Promise();
if (key === undefined || key === '') {
deferred.resolve({
success: false,
message: new Error('"key" is not defined')
});
} else {
fs.exists(initParams.dataFolder + '/' + key, function(exists) {
if (!exists) {
deferred.resolve({
success: false
});
} else {
deferred.resolve({
success: true
});
}
});
}
return deferred;
};
/**
* Set multiple object at the same time. Currently not supporting overwrites, just creation
* @param {Array} data Array of data, each will placed into a new object
* @return {Promise} Array with stored keys
* @example
* ```javascript
*
* vsStore.mset(array);
* ```
*/
vsStore.mset = function mset(array) {
var deferred = new promise.Promise(),
setMList = function setMList(list) {
var deferred = new promise.Promise(),
mList = [];
list.forEach(function(item) {
mList.push(vsStore.store(item));
});
deferred.resolve(mList);
return deferred;
};
try {
setMList(array).then(function(mList) {
promise.all(mList).then(function(keys) {
deferred.resolve({
success: true,
data: keys
});
});
});
} catch (err) {
deferred.resolve({
success: false,
message: err
});
}
return deferred;
};
/**
* Get multiple object at the same time
* @param {Array} data Array of keys
* @param {Boolean} history If true the whole object will read, not just the current version
* @return {Promise} Array with read data
* @example
* ```javascript
*
* vsStore.mget(array, true);
* ```
*/
vsStore.mget = function mget(array, history) {
var deferred = new promise.Promise(),
setGList = function setGList(list) {
var deferred = new promise.Promise(),
gList = [];
list.forEach(function(item) {
gList.push(vsStore.read(item, history));
});
deferred.resolve(gList);
return deferred;
};
history = (history === true) ? true : undefined;
try {
setGList(array).then(function(gList) {
promise.all(gList).then(function(dataItems) {
deferred.resolve({
success: true,
data: dataItems
});
});
});
} catch (err) {
deferred.resolve({
success: false,
message: err
});
}
return deferred;
};
/**
* Roll back a data file into a given version. The rollback process also will generate a new version and not change the meta data, only the content
* @param {String} key Standard key for the data object
* @param {Int} version Previous number of version (should be exists)
* @return {Promise} Object, with the requested version of data
* @example
* ```javascript
*
* vsStore.rollback('aaa-bbb-ccc-ddd', 2);
* ```
*/
vsStore.rollback = function rollback(key, version) {
var deferred = new promise.Promise();
if (key === undefined || key === '' || version === undefined || version === '') {
deferred.resolve({
success: false,
message: new Error('"key" and "version" also need to be defined')
});
} else {
vsStore.read(key, true).then(function(dataFile) {
if (dataFile.data._version < version) {
deferred.resolve({
success: false,
message: new Error('There is no such a version number')
});
} else if (dataFile.data._version == version) {
deferred.resolve({
success: false,
message: new Error('The selected version is the current one')
});
} else {
var history = dataFile.data._history;
for (var prop in history) {
if (history.hasOwnProperty(prop)) {
if (history[prop]._version === version) {
var copy = history[prop].content;
vsStore.store(copy, key).then(function(stored) {
if (stored.success === true) {
deferred.resolve({
success: true,
data: copy
});
}
});
}
}
}
}
});
}
return deferred;
};
/**
* Create a dump object from the whole data folder
* @return {Promise} Array
* @example
* ```javascript
*
* vsStore.dump();
* ```
*/
vsStore.dump = function dump() {
var dumplist = [],
deferred = new promise.Promise();
vsStore.getKeys()
.then(function(response) {
vsStore.mget(response.data, true, true)
.then(function(response) {
var data = response.data;
data.forEach(function(item) {
dumplist.push({
key: item.key,
value: item.data
});
});
deferred.resolve({
success: true,
data: dumplist
});
});
});
return deferred;
};
/**
* Restore a previously dumped data folder
* @param {Array} data Each contained object should be a key/value pair, where the key will be the name of the data file
* @param {String} folder The folder where the restore will happen
* @param {Boolean} clear If true, the found folder will wipe out before restoring
* @return {Promise} Success:true
* @example
* ```javascript
*
* vsStore.restore(array, './datafolder', true);
* ```
*/
vsStore.restore = function restore(dumpfile, folder, clear) {
var deferred = new promise.Promise();
if (dumpfile === undefined || dumpfile === '' && folder === undefined || folder === '') {
deferred.resolve({
success: false,
message: new Error('"dumpfile" or "folder" is not defined')
});
} else {
if (clear === true) {
fs.removeSync(folder);
}
fs.ensureDir(folder, function() {
for (var prop in dumpfile) {
if (dumpfile.hasOwnProperty(prop)) {
fs.outputJsonSync(folder + '/' + dumpfile[prop].key, dumpfile[prop].value);
}
}
deferred.resolve({
success: true
});
});
}
return deferred;
}; | jrmitty/vc-storage | lib-vcs/index.js | JavaScript | mit | 10,597 |
/*global define*/
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define({
"units": {
"miles": {
"displayText": "מיילים",
"acronym": "מיילים"
},
"kilometers": {
"displayText": "קילומטרים",
"acronym": "ק\"מ"
},
"feet": {
"displayText": "רגל",
"acronym": "רגל"
},
"meters": {
"displayText": "מטרים",
"acronym": "מ'"
}
},
"searchSourceSetting": {
"searchSourceSettingTabTitle": "חפש הגדרות מקור",
"searchSourceSettingTitle": "חפש הגדרות מקור",
"searchSourceSettingTitleHintText": "הוסף והגדר שירותי עיגון כתובות או שכבות ישויות כמקורות חיפוש. מקורות אלה שמצוינים קובעים מה ניתן לחיפוש בתוך תיבת החיפוש",
"addSearchSourceLabel": "הוסף מקור חיפוש",
"featureLayerLabel": "שכבת ישות",
"geocoderLabel": "מעגן כתובות",
"nameTitle": "שם",
"generalSettingLabel": "הגדרה כללית",
"allPlaceholderLabel": "טקסט Placeholder לחיפוש מלא:",
"allPlaceholderHintText": "רמז: הקלד טקסט שיוצג כממלא מקום בעת חיפוש בכל השכבות ומעגן הכתובות",
"generalSettingCheckboxLabel": "הצג חלון קופץ עבור הישות או המיקום שנמצאו",
"countryCode": "קוד/ים של ארצות או אזורים",
"countryCodeEg": "לדוגמה ",
"countryCodeHint": "השארת הערך הזה ריק תפעיל חיפוש בכל הארצות והאזורים",
"questionMark": "?",
"searchInCurrentMapExtent": "חפש רק בתיחום המפה הנוכחי",
"zoomScale": "קנה מידה להתמקדות",
"locatorUrl": "URL של מעגן הכתובות",
"locatorName": "שם מעגן הכתובות",
"locatorExample": "דוגמה",
"locatorWarning": "גרסה זו של שירות עיגון הכתובות אינה נתמכת. הווידג'ט תומך בשירות עיגון הכתובות בגרסה 10.0 ואילך.",
"locatorTips": "אין הצעות זמינות מפני ששירות עיגון הכתובות אינו תומך ביכולת הצעה.",
"layerSource": "מקור שכבה",
"setLayerSource": "הגדר מקור שכבה",
"setGeocoderURL": "הגדר URL של מעגן הכתובות",
"searchLayerTips": "אין הצעות זמינות מפני ששירות התמיכה אינו תומך ביכולת עימוד.",
"placeholder": "טקסט מציין מיקום (Placeholder)",
"searchFields": "שדות חיפוש",
"displayField": "שדה תצוגה",
"exactMatch": "התאמה מדויקת",
"maxSuggestions": "מקסימום הצעות",
"maxResults": "מקסימום תוצאות",
"enableLocalSearch": "הפעל חיפוש מקומי",
"minScale": "קנ\"מ מינימלי",
"minScaleHint": "כאשר קנה המידה גדול יותר מקנה מידה זה, החיפוש המקומי יבוצע",
"radius": "רדיוס",
"radiusHint": "מציין את רדיוס האזור מסביב למרכז המפה הנוכחית שמשמש להגדלת הדירוג של מועמדים לעיגון כתובות, כך שהמועמדים הקרובים ביותר למיקום יוחזרו ראשונים.",
"meters": "מטרים",
"setSearchFields": "הגדר שדות חיפוש",
"set": "הגדר",
"fieldName": "שם",
"invalidUrlTip": "ה-URL ${URL} שגוי או אינו נגיש."
},
"searchSetting": {
"searchSettingTabTitle": "הגדרות חיפוש",
"defaultBufferDistanceLabel": "הגדר ברירת מחדל של מרחק חיץ",
"maxResultCountLabel": "הגבל את מספר התוצאות",
"maxResultCountHintLabel": "רמז: קבע את המספר המרבי של תוצאות נראות. הערך של 1 יחזיר את הישות הקרובה ביותר",
"maxBufferDistanceLabel": "הגדר מרחק חיץ מקסימלי",
"bufferDistanceUnitLabel": "יחידות מרחק חיץ",
"defaultBufferHintLabel": "רמז: הגדר ערך ברירת מחדל עבור מחוון החיץ",
"maxBufferHintLabel": "רמז: הגדר ערך מקסימום עבור מחוון החיץ",
"bufferUnitLabel": "רמז: הגדר יחידה ליצירת אזור חיץ",
"selectGraphicLocationSymbol": "סמל כתובת או מיקום",
"graphicLocationSymbolHintText": "רמז: סמל עבור כתובת שחיפשת או מיקום שלחצת עליו",
"addressLocationPolygonHintText": "רמז: הסמל של שכבת הפוליגונים המוגדרת לשימוש בחיפוש באזור הסמוך.",
"popupTitleForPolygon": "בחר פוליגון עבור מיקום כתובת שנבחר",
"popupTitleForPolyline": "בחר קו עבור מיקום כתובת",
"addressLocationPolylineHintText": "רמז: הסמל של שכבת הקווים המוגדרת לשימוש בחיפוש באזור הסמוך.",
"fontColorLabel": "בחר צבע גופן עבור תוצאות החיפוש",
"fontColorHintText": "רמז: צבע גופן של תוצאות החיפוש",
"highlightColorLabel": "הגדר את צבע הבחירה",
"highlightColorHintText": "רמז: צבע בחירה",
"zoomToSelectedFeature": "התמקד לישות שנבחרה",
"zoomToSelectedFeatureHintText": "רמז: התמקד לישות שנבחרה במקום לחיץ",
"intersectSearchLocation": "החזר פוליגונים מצטלבים",
"intersectSearchLocationHintText": "רמז: החזר פוליגונים שמכילים את המיקום שבו נערך החיפוש במקום פוליגונים בתוך החיץ",
"enableProximitySearch": "הפעל חיפוש באזור הסמוך",
"enableProximitySearchHintText": "רמז: הפעל את היכולת לחפש מיקומים שנמצאים באזור הסמוך לתוצאה שבחרת",
"bufferVisibilityLabel": "הגדר ניראות של חיץ",
"bufferVisibilityHintText": "רמז: החיץ יוצג על המפה",
"bufferColorLabel": "הגדר סמל חיץ",
"bufferColorHintText": "רמז: בחר צבע ושקיפות עבור החיץ",
"searchLayerResultLabel": "צייר רק את תוצאות השכבה שנבחרה",
"searchLayerResultHint": "רמז: רק השכבה שנבחרה בתוצאות החיפוש תצויר על המפה",
"showToolToSelectLabel": "הגדר לחצן מיקום",
"showToolToSelectHintText": "רמז: מספק לחצן כדי להגדיר מיקום במפה במקום להגדיר תמיד את המיקום כאשר מתבצעת לחיצה על המפה",
"geoDesicParamLabel": "השתמש בחיץ גיאודזי",
"geoDesicParamHintText": "רמז: השתמש בחיץ גיאודזי במקום בחיץ אקלידיאני (מישורי)",
"showImageGalleryLabel": "הצג את גלריית התמונות",
"showImageGalleryHint": "עצה: הצג גלריית תמונות בפאנל הווידג'ט אם תיבת הסימון מסומנת, אם לא היא לא תופיע",
"showResultCountOfLayerLabel": "הצג ספירה של תוצאות חיפוש לכל שכבה",
"showResultCountOfLayerHint": "רמז: הצג את מספר תוצאות החיפוש אחרי כל שם שכבה",
"editDescription": "טקסט של הקדמה",
"editDescriptionTip": "טקסט שמופיע בווידג'ט מעל לתיבת החיפוש.",
"noResultsFound": "הודעה שמופיעה אם אין תוצאות",
"noResultFoundHint": "רמז: הגדר את ההודעה שתופיע כאשר אין תוצאות באזור החיפוש",
"noFeatureFoundText": "לא נמצאו תוצאות ",
"searchHeaderText": "חפש כתובת או אתר כתובת במפה",
"setCurrentLocationLabel": "הגדר לחצן מיקום נוכחי",
"setCurrentLocationHintText": "רמז: ספק לחצן לצורך שימוש במיקום הנוכחי של המשתמש",
"bufferDistanceSliderLabel": "מחוון מרחק חיץ",
"bufferDistanceTextboxLabel": "תיבת טקסט של חיץ",
"bufferDistanceSliderandTextboxLabel": "מחוון מרחק ותיבת טקסט של חיץ",
"bufferItemOptionLegend": "אפשרויות קלט של חיץ"
},
"layerSelector": {
"selectLayerLabel": "בחר שכבות חיפוש",
"layerSelectionHint": "רמז: השתמש בלחצן ההגדרה לבחירת שכבות",
"addLayerButton": "הגדר"
},
"routeSetting": {
"routeSettingTabTitle": "הגדרות הוראות נסיעה",
"routeServiceUrl": "שירות מסלול",
"buttonSet": "הגדר",
"routeServiceUrlHintText": "רמז: לחץ על 'הגדר' כדי לנווט לשירות מסלול ולבחור אותו",
"directionLengthUnit": "יחידות אורך של הוראות נסיעה",
"unitsForRouteHintText": "רמז: משמש להצגת יחידות עבור מסלול",
"selectRouteSymbol": "בחר סמל להצגת מסלול",
"routeSymbolHintText": "רמז: משמש להצגת סמל קווי של המסלול",
"routingDisabledMsg": "כדי לאפשר הוראות נסיעה, ודא שניתוב מופעל בפריט בהגדרות האפליקציה.",
"enableDirectionLabel": "הפעל כיוונים",
"enableDirectionText": "רמז: סמן כדי להפעיל כיוונים בווידג'ט"
},
"symbologySetting": {
"symbologySettingTabTitle": "הגדרות סימבולוגיה",
"addSymbologyBtnLabel": "הוסף סמלים חדשים",
"layerNameTitle": "שם שכבה",
"fieldTitle": "שדה",
"valuesTitle": "ערכים",
"symbolTitle": "סמל",
"actionsTitle": "פעולות",
"invalidConfigMsg": "שדה כפול : ${fieldName} עבור שכבה : ${layerName}"
},
"filterSetting": {
"filterSettingTabTitle": "הגדרות סינון",
"addTaskTip": "הוסף מסנן אחד או יותר לשכבות החיפוש שנבחרו והגדר פרמטרים לכל מסנן.",
"enableMapFilter": "הסר מהמפה את פילטר השכבות שהוגדר מראש.",
"newFilter": "סינון חדש",
"filterExpression": "ביטוי סינון",
"layerDefaultSymbolTip": "השתמש בסימול ברירת המחדל של השכבה",
"uploadImage": "טען תמונה",
"selectLayerTip": "בחר שכבה.",
"setTitleTip": "הגדר כותרת.",
"noTasksTip": "לא הוגדרו מסננים. לחץ על \"${newFilter}\" להוספת מסנן חדש.",
"collapseFiltersTip": "כווץ את ביטויי המסנן (אם קיימים) כאשר הווידג'ט פתוח",
"groupFiltersTip": "קבץ מסננים לפי שכבה",
"infoTab": "מידע",
"expressionsTab": "ביטויים",
"optionsTab": "אפשרויות",
"autoApplyWhenWidgetOpen": "החל מסנן זה לאחר פתיחת הווידג'ט",
"expandFiltersOnLoad": "הרחב מסננים בטעינת וידג'ט"
},
"networkServiceChooser": {
"arcgislabel": "הוסף מ-ArcGIS Online",
"serviceURLabel": "הוסף כתובת URL של שירות",
"routeURL": "URL של המסלול",
"validateRouteURL": "אמת",
"exampleText": "דוגמה",
"hintRouteURL1": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/",
"hintRouteURL2": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
"invalidRouteServiceURL": "ציין שירות מסלול חוקי.",
"rateLimitExceeded": "עברת את מגבלת השיעור. נסה שוב מאוחר יותר.",
"errorInvokingService": "שם משתמש או סיסמה שגויים."
},
"errorStrings": {
"bufferErrorString": "הזן ערך מספרי חוקי.",
"selectLayerErrorString": "בחר שכבה/ות לחיפוש.",
"invalidDefaultValue": "מרחק החיץ המוגדר כברירת מחדל לא יכול להיות ריק. ציין את מרחק החיץ",
"invalidMaximumValue": "מרחק החיץ המקסימלי לא יכול להיות ריק. ציין את מרחק החיץ",
"defaultValueLessThanMax": "ציין את מרחק החיץ המוגדר כברירת מחדל בטווח האפשרי עד לגבול המקסימלי",
"defaultBufferValueGreaterThanOne": "מרחק חיץ ברירת מחדל לא יכול להיות פחות מ-0",
"maximumBufferValueGreaterThanOne": "ציין את מרחק החיץ המקסימלי כשהוא גדול מ-0",
"invalidMaximumResultCountValue": "ציין ערך חוקי ספציפי עבור ספירת התוצאה המקסימלית",
"invalidSearchSources": "הגדרות חיפוש מקור לא חוקיות"
},
"symbolPickerPreviewText": "תצוגה מקדימה:"
}); | tmcgee/cmv-wab-widgets | wab/2.15/widgets/NearMe/setting/nls/he/strings.js | JavaScript | mit | 13,738 |
'use strict'
const awsServerlessExpress = require('./aws-serverless-express/index.js')
const app = require('./server')
const server = awsServerlessExpress.createServer(app)
exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context) | TCEES-NTI/SAPO | lambda.js | JavaScript | mit | 261 |
import React from 'react';
const LoaderComponent = () =>
<div className="spinner-center">
<i className="fa fa-circle-o-notch fa-spin"></i>
</div>;
export default LoaderComponent;
| jimmymintzer/reacter-news | src/components/LoaderComponent.js | JavaScript | mit | 189 |
import React, { Component } from 'react';
import shallowEqual from 'shallowequal';
import throttle from './utils/throttle';
import pick from './utils/pick';
function pickState(pickProperties, stateToPickFrom) {
if (!pickProperties.length) return stateToPickFrom;
return pick(stateToPickFrom, ...pickProperties);
}
export default function createMatchMediaConnect(queryMap = {}, options = {}) {
const { matchMediaFn = window.matchMedia } = options;
const mqls = {};
const listeners = [];
let state = {};
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
function createState() {
const nextState = {};
for (const key in mqls) {
if (!mqls.hasOwnProperty(key)) continue;
const mql = mqls[key];
const { matches } = mql;
nextState[key] = matches;
}
return nextState;
}
const handleChange = throttle(() => {
const nextState = createState();
if (shallowEqual(state, nextState)) return;
state = nextState;
for (let i = 0, l = listeners.length; i < l; i++) {
const listener = listeners[i];
if (!listener) continue;
listener(nextState);
}
});
if (matchMediaFn) {
for (const key in queryMap) {
if (!queryMap.hasOwnProperty(key)) continue;
const query = queryMap[key];
const mql = matchMediaFn(query);
mql.addListener(handleChange);
mqls[key] = mql;
}
}
function destroy() {
listeners.length = 0;
for (const key in mqls) {
if (!mqls.hasOwnProperty(key)) continue;
const mql = mqls[key];
mql.removeListener(handleChange);
mqls[key] = undefined;
}
}
state = createState();
function connect(pickProperties = []) {
return function wrapWithConnect(WrappedComponent) {
return class WrapWithConnect extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = pickState(pickProperties, state);
}
componentDidMount() {
this.unsubscribe = subscribe(this.handleChange);
}
componentWillUnmount() {
this.unsubscribe();
}
handleChange(nextState) {
const nextPickedState = pickState(
pickProperties,
nextState
);
if (shallowEqual(this.state, nextPickedState)) {
return;
}
this.setState(nextPickedState);
}
render() {
return <WrappedComponent {...this.props} {...this.state} />;
}
};
};
}
// For testing
connect.destroy = destroy;
connect.listeners = listeners;
return connect;
}
| malte-wessel/react-matchmedia-connect | src/createMatchMediaConnect.js | JavaScript | mit | 3,270 |
'use strict';
var TruliaError = require('./trulia_error');
var request = require('./request');
var qs = require('querystring');
var _ = require('lodash');
var TRULIA_API_URL = 'http://api.trulia.com/webservices.php';
var LOCATION_INFO_DEFAULT = {
library: 'LocationInfo'
};
// var TRULIA_STATS_DEFAULT = {
// library: 'TruliaStats'
// };
var Trulia = function (apiKey) {
if (!_.isString(apiKey)) {
throw new TruliaError('Must pass an API key');
}
this.apiKey = apiKey;
};
Trulia.prototype.request = request;
Trulia.prototype.get = function (querystring, cb) {
var url = [TRULIA_API_URL, '?', querystring].join('');
return this.request.get.call(this.request, url, cb);
};
Trulia.prototype.getNeighborhoodsInCity = function (opts, cb) {
opts = _.defaults(opts || {}, LOCATION_INFO_DEFAULT, {
function: 'getNeighborhoodsInCity',
state: 'CA',
city: 'San Francisco'
});
var querystring = qs.stringify(opts);
return this.get(querystring, cb).promise();
};
module.exports = Trulia;
| kmiyashiro/trulia-node | lib/trulia.js | JavaScript | mit | 1,024 |
/*
* Tell the server to gracefully prepare for shutdown, but do not end the process.
*/
console.log("Instructing server to prepare for shutdown");
var http = require("http");
config = require('../configs/server.js');
var configs = config.configs;
// Port
if(typeof configs.server_port === 'undefined'){
var server_port = process.env.PORT || 14080;
}
else {
var server_port = configs.server_port;
}
var options = {
host: "localhost",
port: server_port,
path: "/prepareForShutdown",
method: "HEAD"
};
var request = http.request(options, function(response) {
console.log("Server completed preparations for shutdown");
});
request.end();
request.on("error", function(error) {
console.log("An error occurred when trying to shutdown server.");
throw error;
}); | vanHeemstraSystems/core | OLD-servers/prepareForStop.js | JavaScript | mit | 779 |
/*
* This file is part of the serializerjs package.
*
* (c) HAIRCVT <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import SerializerAware from './../../src/Serializer/SerializerAware';
import { ADMIN_TYPE, ANONYMOUS_TYPE, CUSTOMER_TYPE } from './UserType';
export default class UserTypeSerializer extends SerializerAware {
constructor() {
super();
/**
* @type {Map.<number, Symbol>} Key and value as respectively the raw and deserialized value
* @private
*/
this._mapping = new Map([
[0, ADMIN_TYPE],
[1, ANONYMOUS_TYPE],
[2, CUSTOMER_TYPE],
]);
}
/**
* @inheritDoc
*
* @param {Symbol} userType
*
* @return {number}
*/
serialize(userType, format, context) {
return this._getKeyOfType(userType);
}
/**
* @inheritDoc
*/
supportsSerialize(data, format = null) {
return null !== this._getKeyOfType(data);
}
/**
* @param {*} userType
*
* @return {?number}
* @private
*/
_getKeyOfType(userType) {
for (const [key, type] of this._mapping.entries()) {
if (userType === type) {
return key;
}
}
return null;
}
/**
* @inheritDoc
*
* @param {number} key
*
* @return {ADMIN_TYPE|ANONYMOUS_TYPE|CUSTOMER_TYPE}
*/
deserialize(key, className, format = null, context = null) {
return this._mapping.get(key);
}
/**
* @inheritDoc
*/
supportsDeserialize(data, className, format = null) {
return 'UserType' === className && this._mapping.has(data);
}
}
| haircvt/serializerjs | tests/Fixtures/UserTypeSerializer.js | JavaScript | mit | 1,816 |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["RFA"] = factory(require("react"));
else
root["RFA"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
module.exports = {
Accordion: __webpack_require__(1),
ActionSheet: __webpack_require__(4),
Iconic: __webpack_require__(10),
Interchange: __webpack_require__(11),
Modal: __webpack_require__(17),
Notification: __webpack_require__(22),
OffCanvas: __webpack_require__(26),
Panel: __webpack_require__(27),
Popup: __webpack_require__(28),
Tabs: __webpack_require__(30),
Trigger: __webpack_require__(32),
};
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var Accordion = React.createClass({
displayName: 'Accordion',
getInitialState: function getInitialState() {
return { sections: [] };
},
getDefaultProps: function getDefaultProps() {
return {
autoOpen: true,
multiOpen: false,
collapsible: false
};
},
componentWillMount: function componentWillMount() {
var sections = [];
React.Children.forEach(this.props.children, function (child, index) {
sections.push({ active: false });
});
if (this.props.autoOpen) {
sections[0].active = true;
}
this.setState({ sections: sections });
},
select: function select(selectSection) {
var sections = this.state.sections;
sections.forEach((function (section, index) {
if (this.props.multiOpen) {
if (index === selectSection) {
section.active = !section.active;
}
} else {
if (index === selectSection) {
section.active = this.props.collapsible === true ? !section.active : true;
} else {
section.active = false;
}
}
}).bind(this));
this.setState({ sections: sections });
},
render: function render() {
var children = React.Children.map(this.props.children, (function (child, index) {
return React.cloneElement(child, {
active: this.state.sections[index] ? this.state.sections[index].active : false,
activate: this.select.bind(this, index)
});
}).bind(this));
return React.createElement(
'div',
{ className: 'accordion' },
children
);
}
});
module.exports = Accordion;
Accordion.Item = __webpack_require__(3);
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var classnames = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"classnames\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var AccordionItem = React.createClass({
displayName: 'AccordionItem',
render: function render() {
var itemClasses = {
'accordion-item': true,
'is-active': this.props.active
};
return React.createElement(
'div',
{ className: classnames(itemClasses) },
React.createElement(
'div',
{ className: 'accordion-title', onClick: this.props.activate },
this.props.title
),
React.createElement(
'div',
{ className: 'accordion-content' },
this.props.children
)
);
}
});
module.exports = AccordionItem;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var foundationApi = __webpack_require__(5);
var ActionSheet = React.createClass({
displayName: 'ActionSheet',
getInitialState: function getInitialState() {
return { active: false };
},
setActiveState: function setActiveState(active) {
this.setState({ active: active });
},
onBodyClick: function onBodyClick(e) {
var el = e.target;
var insideActionSheet = false;
do {
if (el.classList && el.classList.contains('action-sheet-container') && el.id === this.props.id) {
insideActionSheet = true;
break;
}
} while (el = el.parentNode);
if (!insideActionSheet) {
this.setActiveState(false);
}
},
componentDidMount: function componentDidMount() {
if (this.props.id) {
foundationApi.subscribe(this.props.id, (function (name, msg) {
if (msg === 'open') {
this.setState({ active: true });
} else if (msg === 'close') {
this.setState({ active: false });
} else if (msg === 'toggle') {
this.setState({ active: !this.state.active });
}
}).bind(this));
}
document.body.addEventListener('click', this.onBodyClick);
},
componentWillUnmount: function componentWillUnmount() {
if (this.props.id) foundationApi.unsubscribe(this.props.id);
document.body.removeEventListener('click', this.onBodyClick);
},
render: function render() {
var children = React.Children.map(this.props.children, (function (child, index) {
var extraProps = { active: this.state.active };
if (child.type.displayName === 'ActionSheetButton') {
extraProps.setActiveState = this.setActiveState;
}
return React.cloneElement(child, extraProps);
}).bind(this));
return React.createElement(
'div',
{ id: this.props.id, 'data-closable': true, className: 'action-sheet-container' },
children
);
}
});
module.exports = ActionSheet;
ActionSheet.Button = __webpack_require__(8);
ActionSheet.Content = __webpack_require__(9);
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
//From https://github.com/zurb/foundation-apps/blob/master/js/angular/common/common.services.js
'use strict';
var PubSub = __webpack_require__(6);
var assign = __webpack_require__(7);
var listeners = [];
var settings = {};
var uniqueIds = [];
var foundationApi = {
subscribe: PubSub.subscribe,
publish: PubSub.publish,
unsubscribe: PubSub.unsubscribe,
closeActiveElements: function closeActiveElements(options) {
var self = this;
options = options || {};
var activeElements = document.querySelectorAll('.is-active[data-closable]');
Array.prototype.forEach.call(activeElements, function (el) {
if (options.exclude !== el.id) {
self.publish(el.id, 'close');
}
});
},
getSettings: function getSettings() {
return settings;
},
modifySettings: function modifySettings(tree) {
settings = assign(settings, tree);
return settings;
},
generateUuid: function generateUuid() {
var uuid = '';
//little trick to produce semi-random IDs
do {
uuid += 'zf-uuid-';
for (var i = 0; i < 15; i++) {
uuid += Math.floor(Math.random() * 16).toString(16);
}
} while (!uniqueIds.indexOf(uuid));
uniqueIds.push(uuid);
return uuid;
}
};
module.exports = foundationApi;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*
Copyright (c) 2010,2011,2012,2013,2014 Morgan Roderick http://roderick.dk
License: MIT - http://mrgnrdrck.mit-license.org
https://github.com/mroderick/PubSubJS
*/
(function (root, factory){
'use strict';
if (true){
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports === 'object'){
// CommonJS
factory(exports);
}
// Browser globals
var PubSub = {};
root.PubSub = PubSub;
factory(PubSub);
}(( typeof window === 'object' && window ) || this, function (PubSub){
'use strict';
var messages = {},
lastUid = -1;
function hasKeys(obj){
var key;
for (key in obj){
if ( obj.hasOwnProperty(key) ){
return true;
}
}
return false;
}
/**
* Returns a function that throws the passed exception, for use as argument for setTimeout
* @param { Object } ex An Error object
*/
function throwException( ex ){
return function reThrowException(){
throw ex;
};
}
function callSubscriberWithDelayedExceptions( subscriber, message, data ){
try {
subscriber( message, data );
} catch( ex ){
setTimeout( throwException( ex ), 0);
}
}
function callSubscriberWithImmediateExceptions( subscriber, message, data ){
subscriber( message, data );
}
function deliverMessage( originalMessage, matchedMessage, data, immediateExceptions ){
var subscribers = messages[matchedMessage],
callSubscriber = immediateExceptions ? callSubscriberWithImmediateExceptions : callSubscriberWithDelayedExceptions,
s;
if ( !messages.hasOwnProperty( matchedMessage ) ) {
return;
}
for (s in subscribers){
if ( subscribers.hasOwnProperty(s)){
callSubscriber( subscribers[s], originalMessage, data );
}
}
}
function createDeliveryFunction( message, data, immediateExceptions ){
return function deliverNamespaced(){
var topic = String( message ),
position = topic.lastIndexOf( '.' );
// deliver the message as it is now
deliverMessage(message, message, data, immediateExceptions);
// trim the hierarchy and deliver message to each level
while( position !== -1 ){
topic = topic.substr( 0, position );
position = topic.lastIndexOf('.');
deliverMessage( message, topic, data, immediateExceptions );
}
};
}
function messageHasSubscribers( message ){
var topic = String( message ),
found = Boolean(messages.hasOwnProperty( topic ) && hasKeys(messages[topic])),
position = topic.lastIndexOf( '.' );
while ( !found && position !== -1 ){
topic = topic.substr( 0, position );
position = topic.lastIndexOf( '.' );
found = Boolean(messages.hasOwnProperty( topic ) && hasKeys(messages[topic]));
}
return found;
}
function publish( message, data, sync, immediateExceptions ){
var deliver = createDeliveryFunction( message, data, immediateExceptions ),
hasSubscribers = messageHasSubscribers( message );
if ( !hasSubscribers ){
return false;
}
if ( sync === true ){
deliver();
} else {
setTimeout( deliver, 0 );
}
return true;
}
/**
* PubSub.publish( message[, data] ) -> Boolean
* - message (String): The message to publish
* - data: The data to pass to subscribers
* Publishes the the message, passing the data to it's subscribers
**/
PubSub.publish = function( message, data ){
return publish( message, data, false, PubSub.immediateExceptions );
};
/**
* PubSub.publishSync( message[, data] ) -> Boolean
* - message (String): The message to publish
* - data: The data to pass to subscribers
* Publishes the the message synchronously, passing the data to it's subscribers
**/
PubSub.publishSync = function( message, data ){
return publish( message, data, true, PubSub.immediateExceptions );
};
/**
* PubSub.subscribe( message, func ) -> String
* - message (String): The message to subscribe to
* - func (Function): The function to call when a new message is published
* Subscribes the passed function to the passed message. Every returned token is unique and should be stored if
* you need to unsubscribe
**/
PubSub.subscribe = function( message, func ){
if ( typeof func !== 'function'){
return false;
}
// message is not registered yet
if ( !messages.hasOwnProperty( message ) ){
messages[message] = {};
}
// forcing token as String, to allow for future expansions without breaking usage
// and allow for easy use as key names for the 'messages' object
var token = 'uid_' + String(++lastUid);
messages[message][token] = func;
// return token for unsubscribing
return token;
};
/* Public: Clears all subscriptions
*/
PubSub.clearAllSubscriptions = function clearAllSubscriptions(){
messages = {};
};
/*Public: Clear subscriptions by the topic
*/
PubSub.clearSubscriptions = function clearSubscriptions(topic){
var m;
for (m in messages){
if (messages.hasOwnProperty(m) && m.indexOf(topic) === 0){
delete messages[m];
}
}
};
/* Public: removes subscriptions.
* When passed a token, removes a specific subscription.
* When passed a function, removes all subscriptions for that function
* When passed a topic, removes all subscriptions for that topic (hierarchy)
*
* value - A token, function or topic to unsubscribe.
*
* Examples
*
* // Example 1 - unsubscribing with a token
* var token = PubSub.subscribe('mytopic', myFunc);
* PubSub.unsubscribe(token);
*
* // Example 2 - unsubscribing with a function
* PubSub.unsubscribe(myFunc);
*
* // Example 3 - unsubscribing a topic
* PubSub.unsubscribe('mytopic');
*/
PubSub.unsubscribe = function(value){
var isTopic = typeof value === 'string' && messages.hasOwnProperty(value),
isToken = !isTopic && typeof value === 'string',
isFunction = typeof value === 'function',
result = false,
m, message, t;
if (isTopic){
delete messages[value];
return;
}
for ( m in messages ){
if ( messages.hasOwnProperty( m ) ){
message = messages[m];
if ( isToken && message[value] ){
delete message[value];
result = value;
// tokens are unique, so we can just stop here
break;
}
if (isFunction) {
for ( t in message ){
if (message.hasOwnProperty(t) && message[t] === value){
delete message[t];
result = true;
}
}
}
}
}
return result;
};
}));
/***/ },
/* 7 */
/***/ function(module, exports) {
'use strict';
function ToObject(val) {
if (val == null) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
module.exports = Object.assign || function (target, source) {
var from;
var keys;
var to = ToObject(target);
for (var s = 1; s < arguments.length; s++) {
from = arguments[s];
keys = Object.keys(Object(from));
for (var i = 0; i < keys.length; i++) {
to[keys[i]] = from[keys[i]];
}
}
return to;
};
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var ActionSheetButton = React.createClass({
displayName: 'ActionSheetButton',
toggle: function toggle() {
this.props.setActiveState(!this.props.active);
},
render: function render() {
var Title = null;
if (this.props.title.length > 0) {
Title = React.createElement(
'a',
{ className: 'button' },
this.props.title
);
}
return React.createElement(
'div',
{ onClick: this.toggle },
Title,
React.createElement(
'div',
null,
this.props.children
)
);
}
});
module.exports = ActionSheetButton;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var classnames = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"classnames\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var ActionSheetContent = React.createClass({
displayName: 'ActionSheetContent',
getDefaultProps: function getDefaultProps() {
return { position: 'bottom' };
},
render: function render() {
var classes = {
'action-sheet': true,
'is-active': this.props.active
};
return React.createElement(
'div',
{ className: classnames(classes) },
this.props.children
);
}
});
module.exports = ActionSheetContent;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"react-dom\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var ExecutionEnvironment = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"react/lib/ExecutionEnvironment\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var IconicJs = ExecutionEnvironment.canUseDOM && __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"../vendor/iconic.min\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var Iconic = React.createClass({
displayName: 'Iconic',
inject: function inject() {
var ico = IconicJs();
ico.inject(ReactDOM.findDOMNode(this));
},
componentDidMount: function componentDidMount() {
this.inject();
},
componentDidUpdate: function componentDidUpdate() {
this.inject();
},
render: function render() {
return React.Children.only(this.props.children);
}
});
module.exports = Iconic;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var ResponsiveMixin = __webpack_require__(12);
var namedQueries = {
// small: '(min-width: 0) and (max-width: 640px)',
// medium: '(min-width: 641px) and (max-width: 1200px)',
// large: '(min-width: 1201px) and (max-width: 1440px)',
// 'default' : 'only screen',
// landscape : 'only screen and (orientation: landscape)',
// portrait : 'only screen and (orientation: portrait)',
// retina : 'only screen and (-webkit-min-device-pixel-ratio: 2),' +
// 'only screen and (min--moz-device-pixel-ratio: 2),' +
// 'only screen and (-o-min-device-pixel-ratio: 2/1),' +
// 'only screen and (min-device-pixel-ratio: 2),' +
// 'only screen and (min-resolution: 192dpi),' +
// 'only screen and (min-resolution: 2dppx)'
};
var Interchange = React.createClass({
displayName: 'Interchange',
mixins: [ResponsiveMixin],
getInitialState: function getInitialState() {
return { matchedMedia: 'large' };
},
componentDidMount: function componentDidMount() {
// for (var name in namedQueries) {
// this.media(namedQueries[name], function () {
// this.setState({matchedMedia: name});
// }.bind(this));
// }
this.media({ minWidth: 0, maxWidth: 640 }, (function () {
this.setState({ matchedMedia: 'small' });
}).bind(this));
this.media({ minWidth: 641, maxWidth: 1200 }, (function () {
this.setState({ matchedMedia: 'medium' });
}).bind(this));
this.media({ minWidth: 1200, maxWidth: 1440 }, (function () {
this.setState({ matchedMedia: 'large' });
}).bind(this));
},
render: function render() {
var matchedNode = null;
React.Children.forEach(this.props.children, (function (child) {
if (child.props.media === this.state.matchedMedia) {
matchedNode = child;
}
}).bind(this));
return matchedNode;
}
});
module.exports = Interchange;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
var canUseDOM = __webpack_require__(13);
var enquire = canUseDOM && __webpack_require__(14);
var json2mq = __webpack_require__(15);
var ResponsiveMixin = {
media: function (query, handler) {
query = json2mq(query);
if (typeof handler === 'function') {
handler = {
match: handler
};
}
enquire.register(query, handler);
// Queue the handlers to unregister them at unmount
if (! this._responsiveMediaHandlers) {
this._responsiveMediaHandlers = [];
}
this._responsiveMediaHandlers.push({query: query, handler: handler});
},
componentWillUnmount: function () {
if (this._responsiveMediaHandlers) {
this._responsiveMediaHandlers.forEach(function(obj) {
enquire.unregister(obj.query, obj.handler);
});
}
}
};
module.exports = ResponsiveMixin;
/***/ },
/* 13 */
/***/ function(module, exports) {
var canUseDOM = !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
module.exports = canUseDOM;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*!
* enquire.js v2.1.1 - Awesome Media Queries in JavaScript
* Copyright (c) 2014 Nick Williams - http://wicky.nillia.ms/enquire.js
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
*/
;(function (name, context, factory) {
var matchMedia = window.matchMedia;
if (typeof module !== 'undefined' && module.exports) {
module.exports = factory(matchMedia);
}
else if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
return (context[name] = factory(matchMedia));
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
else {
context[name] = factory(matchMedia);
}
}('enquire', this, function (matchMedia) {
'use strict';
/*jshint unused:false */
/**
* Helper function for iterating over a collection
*
* @param collection
* @param fn
*/
function each(collection, fn) {
var i = 0,
length = collection.length,
cont;
for(i; i < length; i++) {
cont = fn(collection[i], i);
if(cont === false) {
break; //allow early exit
}
}
}
/**
* Helper function for determining whether target object is an array
*
* @param target the object under test
* @return {Boolean} true if array, false otherwise
*/
function isArray(target) {
return Object.prototype.toString.apply(target) === '[object Array]';
}
/**
* Helper function for determining whether target object is a function
*
* @param target the object under test
* @return {Boolean} true if function, false otherwise
*/
function isFunction(target) {
return typeof target === 'function';
}
/**
* Delegate to handle a media query being matched and unmatched.
*
* @param {object} options
* @param {function} options.match callback for when the media query is matched
* @param {function} [options.unmatch] callback for when the media query is unmatched
* @param {function} [options.setup] one-time callback triggered the first time a query is matched
* @param {boolean} [options.deferSetup=false] should the setup callback be run immediately, rather than first time query is matched?
* @constructor
*/
function QueryHandler(options) {
this.options = options;
!options.deferSetup && this.setup();
}
QueryHandler.prototype = {
/**
* coordinates setup of the handler
*
* @function
*/
setup : function() {
if(this.options.setup) {
this.options.setup();
}
this.initialised = true;
},
/**
* coordinates setup and triggering of the handler
*
* @function
*/
on : function() {
!this.initialised && this.setup();
this.options.match && this.options.match();
},
/**
* coordinates the unmatch event for the handler
*
* @function
*/
off : function() {
this.options.unmatch && this.options.unmatch();
},
/**
* called when a handler is to be destroyed.
* delegates to the destroy or unmatch callbacks, depending on availability.
*
* @function
*/
destroy : function() {
this.options.destroy ? this.options.destroy() : this.off();
},
/**
* determines equality by reference.
* if object is supplied compare options, if function, compare match callback
*
* @function
* @param {object || function} [target] the target for comparison
*/
equals : function(target) {
return this.options === target || this.options.match === target;
}
};
/**
* Represents a single media query, manages it's state and registered handlers for this query
*
* @constructor
* @param {string} query the media query string
* @param {boolean} [isUnconditional=false] whether the media query should run regardless of whether the conditions are met. Primarily for helping older browsers deal with mobile-first design
*/
function MediaQuery(query, isUnconditional) {
this.query = query;
this.isUnconditional = isUnconditional;
this.handlers = [];
this.mql = matchMedia(query);
var self = this;
this.listener = function(mql) {
self.mql = mql;
self.assess();
};
this.mql.addListener(this.listener);
}
MediaQuery.prototype = {
/**
* add a handler for this query, triggering if already active
*
* @param {object} handler
* @param {function} handler.match callback for when query is activated
* @param {function} [handler.unmatch] callback for when query is deactivated
* @param {function} [handler.setup] callback for immediate execution when a query handler is registered
* @param {boolean} [handler.deferSetup=false] should the setup callback be deferred until the first time the handler is matched?
*/
addHandler : function(handler) {
var qh = new QueryHandler(handler);
this.handlers.push(qh);
this.matches() && qh.on();
},
/**
* removes the given handler from the collection, and calls it's destroy methods
*
* @param {object || function} handler the handler to remove
*/
removeHandler : function(handler) {
var handlers = this.handlers;
each(handlers, function(h, i) {
if(h.equals(handler)) {
h.destroy();
return !handlers.splice(i,1); //remove from array and exit each early
}
});
},
/**
* Determine whether the media query should be considered a match
*
* @return {Boolean} true if media query can be considered a match, false otherwise
*/
matches : function() {
return this.mql.matches || this.isUnconditional;
},
/**
* Clears all handlers and unbinds events
*/
clear : function() {
each(this.handlers, function(handler) {
handler.destroy();
});
this.mql.removeListener(this.listener);
this.handlers.length = 0; //clear array
},
/*
* Assesses the query, turning on all handlers if it matches, turning them off if it doesn't match
*/
assess : function() {
var action = this.matches() ? 'on' : 'off';
each(this.handlers, function(handler) {
handler[action]();
});
}
};
/**
* Allows for registration of query handlers.
* Manages the query handler's state and is responsible for wiring up browser events
*
* @constructor
*/
function MediaQueryDispatch () {
if(!matchMedia) {
throw new Error('matchMedia not present, legacy browsers require a polyfill');
}
this.queries = {};
this.browserIsIncapable = !matchMedia('only all').matches;
}
MediaQueryDispatch.prototype = {
/**
* Registers a handler for the given media query
*
* @param {string} q the media query
* @param {object || Array || Function} options either a single query handler object, a function, or an array of query handlers
* @param {function} options.match fired when query matched
* @param {function} [options.unmatch] fired when a query is no longer matched
* @param {function} [options.setup] fired when handler first triggered
* @param {boolean} [options.deferSetup=false] whether setup should be run immediately or deferred until query is first matched
* @param {boolean} [shouldDegrade=false] whether this particular media query should always run on incapable browsers
*/
register : function(q, options, shouldDegrade) {
var queries = this.queries,
isUnconditional = shouldDegrade && this.browserIsIncapable;
if(!queries[q]) {
queries[q] = new MediaQuery(q, isUnconditional);
}
//normalise to object in an array
if(isFunction(options)) {
options = { match : options };
}
if(!isArray(options)) {
options = [options];
}
each(options, function(handler) {
queries[q].addHandler(handler);
});
return this;
},
/**
* unregisters a query and all it's handlers, or a specific handler for a query
*
* @param {string} q the media query to target
* @param {object || function} [handler] specific handler to unregister
*/
unregister : function(q, handler) {
var query = this.queries[q];
if(query) {
if(handler) {
query.removeHandler(handler);
}
else {
query.clear();
delete this.queries[q];
}
}
return this;
}
};
return new MediaQueryDispatch();
}));
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
var camel2hyphen = __webpack_require__(16);
var isDimension = function (feature) {
var re = /[height|width]$/;
return re.test(feature);
};
var obj2mq = function (obj) {
var mq = '';
var features = Object.keys(obj);
features.forEach(function (feature, index) {
var value = obj[feature];
feature = camel2hyphen(feature);
// Add px to dimension features
if (isDimension(feature) && typeof value === 'number') {
value = value + 'px';
}
if (value === true) {
mq += feature;
} else if (value === false) {
mq += 'not ' + feature;
} else {
mq += '(' + feature + ': ' + value + ')';
}
if (index < features.length-1) {
mq += ' and '
}
});
return mq;
};
var json2mq = function (query) {
var mq = '';
if (typeof query === 'string') {
return query;
}
// Handling array of media queries
if (query instanceof Array) {
query.forEach(function (q, index) {
mq += obj2mq(q);
if (index < query.length-1) {
mq += ', '
}
});
return mq;
}
// Handling single media query
return obj2mq(query);
};
module.exports = json2mq;
/***/ },
/* 16 */
/***/ function(module, exports) {
var camel2hyphen = function (str) {
return str
.replace(/[A-Z]/g, function (match) {
return '-' + match.toLowerCase();
})
.toLowerCase();
};
module.exports = camel2hyphen;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var Animation = __webpack_require__(18);
var foundationApi = __webpack_require__(5);
var Modal = React.createClass({
displayName: 'Modal',
getInitialState: function getInitialState() {
return { open: false };
},
getDefaultProps: function getDefaultProps() {
return {
overlay: true,
overlayClose: true,
animationIn: 'fadeIn',
animationOut: 'fadeOut'
};
},
componentDidMount: function componentDidMount() {
this.subscribe(this.props.id);
},
componentWillUnmount: function componentWillUnmount() {
foundationApi.unsubscribe(this.props.id);
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.id !== this.props.id) {
foundationApi.unsubscribe(this.props.id);
this.subscribe(nextProps.id);
}
},
hideOverlay: function hideOverlay(e) {
e.preventDefault();
if (this.props.overlayClose) {
this.setState({ open: false });
}
},
stopClickPropagation: function stopClickPropagation(e) {
e.preventDefault();
e.stopPropagation();
},
subscribe: function subscribe(id) {
foundationApi.subscribe(id, (function (name, msg) {
if (msg === 'open') {
this.setState({ open: true });
} else if (msg === 'close') {
this.setState({ open: false });
} else if (msg === 'toggle') {
this.setState({ open: !this.state.open });
}
}).bind(this));
},
render: function render() {
var overlayStyle = {};
if (!this.props.overlay) {
overlayStyle.background = 'transparent';
}
return React.createElement(
Animation,
{ active: this.state.open, animationIn: 'fadeIn', animationOut: 'fadeOut' },
React.createElement(
'div',
{ className: 'modal-overlay', style: overlayStyle, onClick: this.hideOverlay },
React.createElement(
Animation,
{
active: this.state.open,
animationIn: this.props.animationIn,
animationOut: this.props.animationOut
},
React.createElement(
'div',
{ id: this.props.id, 'data-closable': true, className: 'modal', onClick: this.stopClickPropagation },
this.props.children
)
)
)
);
}
});
module.exports = Modal;
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
// some parts of code from react/lib/ReactCSSTransitionGroupChild.js
'use strict';
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"react-dom\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var ReactTransitionEvents = __webpack_require__(19);
var CSSCore = __webpack_require__(21);
var classnames = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"classnames\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var TICK = 17;
var Animation = React.createClass({
displayName: 'Animation',
getInitialState: function getInitialState() {
return {};
},
getDefaultProps: function getDefaultProps() {
return {
active: false,
animationIn: '',
animationOut: ''
};
},
reflow: function reflow(node) {
return node.offsetWidth;
},
reset: function reset(node) {
node.style.transitionDuration = 0;
CSSCore.removeClass(node, 'ng-enter');
CSSCore.removeClass(node, 'ng-leave');
CSSCore.removeClass(node, 'ng-enter-active');
CSSCore.removeClass(node, 'ng-leave-active');
CSSCore.removeClass(node, this.props.animationIn);
CSSCore.removeClass(node, this.props.animationOut);
},
finishAnimation: function finishAnimation() {
var node = ReactDOM.findDOMNode(this);
this.reset(node);
CSSCore.removeClass(node, this.props.active ? '' : 'is-active');
this.reflow(node);
ReactTransitionEvents.removeEndEventListener(node, this.finishAnimation);
},
animate: function animate(animationClass, animationType) {
var node = ReactDOM.findDOMNode(this);
var initClass = 'ng-' + animationType;
var activeClass = initClass + '-active';
this.reset(node);
CSSCore.addClass(node, animationClass);
CSSCore.addClass(node, initClass);
CSSCore.addClass(node, 'is-active');
//force a "tick"
this.reflow(node);
//activate
node.style.transitionDuration = '';
CSSCore.addClass(node, activeClass);
ReactTransitionEvents.addEndEventListener(node, this.finishAnimation);
},
componentDidUpdate: function componentDidUpdate(prevProps) {
if (prevProps.active !== this.props.active) {
var animationClass = this.props.active ? this.props.animationIn : this.props.animationOut;
var animationType = this.props.active ? 'enter' : 'leave';
this.animate(animationClass, animationType);
}
},
render: function render() {
var child = React.Children.only(this.props.children);
var extraProps = {};
return React.cloneElement(child, extraProps);
}
});
module.exports = Animation;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactTransitionEvents
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(20);
/**
* EVENT_NAME_MAP is used to determine which event fired when a
* transition/animation ends, based on the style property used to
* define that event.
*/
var EVENT_NAME_MAP = {
transitionend: {
'transition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'mozTransitionEnd',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd'
},
animationend: {
'animation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd',
'MozAnimation': 'mozAnimationEnd',
'OAnimation': 'oAnimationEnd',
'msAnimation': 'MSAnimationEnd'
}
};
var endEvents = [];
function detectEvents() {
var testEl = document.createElement('div');
var style = testEl.style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are useable, and if not remove them
// from the map
if (!('AnimationEvent' in window)) {
delete EVENT_NAME_MAP.animationend.animation;
}
if (!('TransitionEvent' in window)) {
delete EVENT_NAME_MAP.transitionend.transition;
}
for (var baseEventName in EVENT_NAME_MAP) {
var baseEvents = EVENT_NAME_MAP[baseEventName];
for (var styleName in baseEvents) {
if (styleName in style) {
endEvents.push(baseEvents[styleName]);
break;
}
}
}
}
if (ExecutionEnvironment.canUseDOM) {
detectEvents();
}
// We use the raw {add|remove}EventListener() call because EventListener
// does not know how to remove event listeners and we really should
// clean up. Also, these events are not triggered in older browsers
// so we should be A-OK here.
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var ReactTransitionEvents = {
addEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
// If CSS transitions are not supported, trigger an "end animation"
// event immediately.
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function (endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
removeEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function (endEvent) {
removeEventListener(node, endEvent, eventListener);
});
}
};
module.exports = ReactTransitionEvents;
/***/ },
/* 20 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ExecutionEnvironment
*/
'use strict';
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
/***/ },
/* 21 */
/***/ function(module, exports) {
'use strict';
var SPACE = ' ';
var RE_CLASS = /[\n\t\r]/g;
var norm = function norm(elemClass) {
return (SPACE + elemClass + SPACE).replace(RE_CLASS, SPACE);
};
module.exports = {
addClass: function addClass(elem, className) {
elem.className += ' ' + className;
},
removeClass: function removeClass(elem, needle) {
var elemClass = elem.className.trim();
var className = norm(elemClass);
needle = needle.trim();
needle = SPACE + needle + SPACE;
while (className.indexOf(needle) >= 0) {
className = className.replace(needle, SPACE);
}
elem.className = className.trim();
}
};
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = {
Set: __webpack_require__(23),
Static: __webpack_require__(25)
};
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(2);
var foundationApi = __webpack_require__(5);
var Notification = __webpack_require__(24);
var Animation = __webpack_require__(18);
var NotificationSet = React.createClass({
displayName: 'NotificationSet',
getInitialState: function getInitialState() {
return { notifications: [] };
},
componentDidMount: function componentDidMount() {
foundationApi.subscribe(this.props.id, (function (name, msg) {
if (msg === 'clearall') {
this.clearAll();
} else {
this.addNotification(msg);
}
}).bind(this));
},
addNotification: function addNotification(notification) {
notification.id = foundationApi.generateUuid();
var notifications = this.state.notifications.concat(notification);
this.setState({
notifications: notifications
});
},
removeNotifcation: function removeNotifcation(id) {
return (function (e) {
var notifications = [];
this.state.notifications.forEach(function (notification) {
if (notification.id !== id) {
notifications.push(notification);
}
});
this.setState({
notifications: notifications
});
e.preventDefault();
}).bind(this);
},
clearAll: function clearAll() {
this.setState({ notifications: [] });
},
render: function render() {
var notifications = this.state.notifications.map((function (notification) {
return React.createElement(
Notification,
_extends({ key: notification.id }, notification, { closeHandler: this.removeNotifcation(notification.id), className: 'is-active' }),
notification.content
);
}).bind(this));
return React.createElement(
'div',
null,
notifications
);
}
});
module.exports = NotificationSet;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var Notification = React.createClass({
displayName: 'Notification',
getDefaultProps: function getDefaultProps() {
return {
position: 'top-right',
color: 'success',
title: null,
image: null,
content: null,
wrapperElement: "p"
};
},
render: function render() {
var classes = 'notification ' + this.props.position + ' ' + this.props.color;
classes += ' ' + (this.props.className || '');
var imageNode = null;
if (this.props.image) {
imageNode = React.createElement(
'div',
{ className: 'notification-icon' },
React.createElement('img', { src: '{{ image }}' })
);
}
return React.createElement(
'div',
{ id: this.props.id, 'data-closable': true, className: classes },
React.createElement(
'a',
{ href: '#', className: 'close-button', onClick: this.props.closeHandler },
'×'
),
imageNode,
React.createElement(
'div',
{ className: 'notification-content' },
React.createElement(
'h1',
null,
this.props.title
),
React.createElement(this.props.wrapperElement, null, this.props.children)
)
);
}
});
module.exports = Notification;
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(2);
var classnames = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"classnames\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var foundationApi = __webpack_require__(5);
var Animation = __webpack_require__(18);
var Notification = __webpack_require__(24);
var NotificationStatic = React.createClass({
displayName: 'NotificationStatic',
getInitialState: function getInitialState() {
return { open: false };
},
componentDidMount: function componentDidMount() {
foundationApi.subscribe(this.props.id, (function (name, msg) {
if (msg === 'open') {
this.setState({ open: true });
} else if (msg === 'close') {
this.setState({ open: false });
}
}).bind(this));
},
componentWillUnmount: function componentWillUnmount() {
foundationApi.unsubscribe(this.props.id);
},
closeHandler: function closeHandler(e) {
this.setState({ open: false });
e.preventDefault();
e.stopPropagation();
},
render: function render() {
return React.createElement(
Animation,
{ active: this.state.open, animationIn: 'fadeIn', animationOut: 'fadeOut' },
React.createElement(
Notification,
_extends({}, this.props, { closeHandler: this.closeHandler }),
this.props.children
)
);
}
});
module.exports = NotificationStatic;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var classnames = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"classnames\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
// var LayerMixin = require('react-layer-mixin');
var foundationApi = __webpack_require__(5);
var Offcanvas = React.createClass({
displayName: 'Offcanvas',
// mixins: [LayerMixin],
getInitialState: function getInitialState() {
return { open: false };
},
getDefaultProps: function getDefaultProps() {
return {
position: 'left'
};
},
componentDidMount: function componentDidMount() {
foundationApi.subscribe(this.props.id, (function (name, msg) {
if (msg === 'open') {
this.setState({ open: true });
} else if (msg === 'close') {
this.setState({ open: false });
} else if (msg === 'toggle') {
this.setState({ open: !this.state.open });
}
}).bind(this));
},
componentWillUnmount: function componentWillUnmount() {
foundationApi.unsubscribe(this.props.id);
},
render: function render() {
var classes = {
'off-canvas': true,
'is-active': this.state.open
};
classes[this.props.position] = true;
if (this.props.className) {
classes[this.props.className] = true;
}
return React.createElement(
'div',
{ id: this.props.id, 'data-closable': true, className: classnames(classes) },
this.props.children
);
}
});
module.exports = Offcanvas;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var classnames = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"classnames\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var Animation = __webpack_require__(18);
var foundationApi = __webpack_require__(5);
var Panel = React.createClass({
displayName: 'Panel',
getInitialState: function getInitialState() {
return { open: false };
},
getDefaultProps: function getDefaultProps() {
return {
position: 'left'
};
},
componentDidMount: function componentDidMount() {
foundationApi.subscribe(this.props.id, (function (name, msg) {
if (msg === 'open') {
this.setState({ open: true });
} else if (msg === 'close') {
this.setState({ open: false });
} else if (msg === 'toggle') {
this.setState({ open: !this.state.open });
}
}).bind(this));
},
componentWillUnmount: function componentWillUnmount() {
foundationApi.unsubscribe(this.props.id);
},
render: function render() {
var animationIn, animationOut;
var classes = 'panel panel-' + this.props.position;
if (this.props.className) {
classes += ' ' + this.props.className;
}
if (this.props.position === 'left') {
animationIn = this.props.animationIn || 'slideInRight';
animationOut = this.props.animationOut || 'slideOutLeft';
} else if (this.props.position === 'right') {
animationIn = this.props.animationIn || 'slideInLeft';
animationOut = this.props.animationOut || 'slideOutRight';
} else if (this.props.position === 'top') {
animationIn = this.props.animationIn || 'slideInDown';
animationOut = this.props.animationOut || 'slideOutUp';
} else if (this.props.position === 'bottom') {
animationIn = this.props.animationIn || 'slideInUp';
animationOut = this.props.animationOut || 'slideOutBottom';
}
return React.createElement(
Animation,
{ active: this.state.open, animationIn: animationIn, animationOut: animationOut },
React.createElement(
'div',
{ 'data-closable': true, id: this.props.id, className: classes },
this.props.children
)
);
}
});
module.exports = Panel;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"react-dom\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var classnames = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"classnames\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var ExecutionEnvironment = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"react/lib/ExecutionEnvironment\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var foundationApi = __webpack_require__(5);
var Tether = ExecutionEnvironment.canUseDOM && __webpack_require__(29);
var Popup = React.createClass({
displayName: 'Popup',
getInitialState: function getInitialState() {
return {
active: false,
tetherInit: false
};
},
getDefaultProps: function getDefaultProps() {
return {
pinTo: 'top center',
pinAt: ''
};
},
componentDidMount: function componentDidMount() {
this.tether = {};
foundationApi.subscribe(this.props.id, (function (name, msg) {
if (msg[0] === 'toggle') {
this.toggle(msg[1]);
}
}).bind(this));
},
toggle: function toggle(target) {
var active = !this.state.active;
this.setState({ active: active }, (function () {
if (active) {
this.tetherElement(target);
} else {
this.tether.destroy();
}
}).bind(this));
},
tetherElement: function tetherElement(target) {
var targetElement = document.getElementById(target);
var attachment = 'top center';
this.tether = new Tether({
element: ReactDOM.findDOMNode(this),
target: targetElement,
attachment: attachment
});
},
render: function render() {
var classes = {
popup: true,
'is-active': this.state.active
};
return React.createElement(
'div',
{ id: this.props.id, className: classnames(classes), 'data-closable': 'popup' },
this.props.children
);
}
});
module.exports = Popup;
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! tether 0.6.5 */
(function(root, factory) {
if (true) {
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports === 'object') {
module.exports = factory(require,exports,module);
} else {
root.Tether = factory();
}
}(this, function(require,exports,module) {
(function() {
var Evented, addClass, defer, deferred, extend, flush, getBounds, getClassName, getOffsetParent, getOrigin, getScrollBarSize, getScrollParent, hasClass, node, removeClass, setClassName, uniqueId, updateClasses, zeroPosCache,
__hasProp = {}.hasOwnProperty,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
__slice = [].slice;
if (this.Tether == null) {
this.Tether = {
modules: []
};
}
getScrollParent = function(el) {
var parent, position, scrollParent, style, _ref;
position = getComputedStyle(el).position;
if (position === 'fixed') {
return el;
}
scrollParent = void 0;
parent = el;
while (parent = parent.parentNode) {
try {
style = getComputedStyle(parent);
} catch (_error) {}
if (style == null) {
return parent;
}
if (/(auto|scroll)/.test(style['overflow'] + style['overflowY'] + style['overflowX'])) {
if (position !== 'absolute' || ((_ref = style['position']) === 'relative' || _ref === 'absolute' || _ref === 'fixed')) {
return parent;
}
}
}
return document.body;
};
uniqueId = (function() {
var id;
id = 0;
return function() {
return id++;
};
})();
zeroPosCache = {};
getOrigin = function(doc) {
var id, k, node, v, _ref;
node = doc._tetherZeroElement;
if (node == null) {
node = doc.createElement('div');
node.setAttribute('data-tether-id', uniqueId());
extend(node.style, {
top: 0,
left: 0,
position: 'absolute'
});
doc.body.appendChild(node);
doc._tetherZeroElement = node;
}
id = node.getAttribute('data-tether-id');
if (zeroPosCache[id] == null) {
zeroPosCache[id] = {};
_ref = node.getBoundingClientRect();
for (k in _ref) {
v = _ref[k];
zeroPosCache[id][k] = v;
}
defer(function() {
return zeroPosCache[id] = void 0;
});
}
return zeroPosCache[id];
};
node = null;
getBounds = function(el) {
var box, doc, docEl, k, origin, v, _ref;
if (el === document) {
doc = document;
el = document.documentElement;
} else {
doc = el.ownerDocument;
}
docEl = doc.documentElement;
box = {};
_ref = el.getBoundingClientRect();
for (k in _ref) {
v = _ref[k];
box[k] = v;
}
origin = getOrigin(doc);
box.top -= origin.top;
box.left -= origin.left;
if (box.width == null) {
box.width = document.body.scrollWidth - box.left - box.right;
}
if (box.height == null) {
box.height = document.body.scrollHeight - box.top - box.bottom;
}
box.top = box.top - docEl.clientTop;
box.left = box.left - docEl.clientLeft;
box.right = doc.body.clientWidth - box.width - box.left;
box.bottom = doc.body.clientHeight - box.height - box.top;
return box;
};
getOffsetParent = function(el) {
return el.offsetParent || document.documentElement;
};
getScrollBarSize = function() {
var inner, outer, width, widthContained, widthScroll;
inner = document.createElement('div');
inner.style.width = '100%';
inner.style.height = '200px';
outer = document.createElement('div');
extend(outer.style, {
position: 'absolute',
top: 0,
left: 0,
pointerEvents: 'none',
visibility: 'hidden',
width: '200px',
height: '150px',
overflow: 'hidden'
});
outer.appendChild(inner);
document.body.appendChild(outer);
widthContained = inner.offsetWidth;
outer.style.overflow = 'scroll';
widthScroll = inner.offsetWidth;
if (widthContained === widthScroll) {
widthScroll = outer.clientWidth;
}
document.body.removeChild(outer);
width = widthContained - widthScroll;
return {
width: width,
height: width
};
};
extend = function(out) {
var args, key, obj, val, _i, _len, _ref;
if (out == null) {
out = {};
}
args = [];
Array.prototype.push.apply(args, arguments);
_ref = args.slice(1);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
obj = _ref[_i];
if (obj) {
for (key in obj) {
if (!__hasProp.call(obj, key)) continue;
val = obj[key];
out[key] = val;
}
}
}
return out;
};
removeClass = function(el, name) {
var className, cls, _i, _len, _ref, _results;
if (el.classList != null) {
_ref = name.split(' ');
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
cls = _ref[_i];
if (cls.trim()) {
_results.push(el.classList.remove(cls));
}
}
return _results;
} else {
className = getClassName(el).replace(new RegExp("(^| )" + (name.split(' ').join('|')) + "( |$)", 'gi'), ' ');
return setClassName(el, className);
}
};
addClass = function(el, name) {
var cls, _i, _len, _ref, _results;
if (el.classList != null) {
_ref = name.split(' ');
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
cls = _ref[_i];
if (cls.trim()) {
_results.push(el.classList.add(cls));
}
}
return _results;
} else {
removeClass(el, name);
cls = getClassName(el) + (" " + name);
return setClassName(el, cls);
}
};
hasClass = function(el, name) {
if (el.classList != null) {
return el.classList.contains(name);
} else {
return new RegExp("(^| )" + name + "( |$)", 'gi').test(getClassName(el));
}
};
getClassName = function(el) {
if (el.className instanceof SVGAnimatedString) {
return el.className.baseVal;
} else {
return el.className;
}
};
setClassName = function(el, className) {
return el.setAttribute('class', className);
};
updateClasses = function(el, add, all) {
var cls, _i, _j, _len, _len1, _results;
for (_i = 0, _len = all.length; _i < _len; _i++) {
cls = all[_i];
if (__indexOf.call(add, cls) < 0) {
if (hasClass(el, cls)) {
removeClass(el, cls);
}
}
}
_results = [];
for (_j = 0, _len1 = add.length; _j < _len1; _j++) {
cls = add[_j];
if (!hasClass(el, cls)) {
_results.push(addClass(el, cls));
} else {
_results.push(void 0);
}
}
return _results;
};
deferred = [];
defer = function(fn) {
return deferred.push(fn);
};
flush = function() {
var fn, _results;
_results = [];
while (fn = deferred.pop()) {
_results.push(fn());
}
return _results;
};
Evented = (function() {
function Evented() {}
Evented.prototype.on = function(event, handler, ctx, once) {
var _base;
if (once == null) {
once = false;
}
if (this.bindings == null) {
this.bindings = {};
}
if ((_base = this.bindings)[event] == null) {
_base[event] = [];
}
return this.bindings[event].push({
handler: handler,
ctx: ctx,
once: once
});
};
Evented.prototype.once = function(event, handler, ctx) {
return this.on(event, handler, ctx, true);
};
Evented.prototype.off = function(event, handler) {
var i, _ref, _results;
if (((_ref = this.bindings) != null ? _ref[event] : void 0) == null) {
return;
}
if (handler == null) {
return delete this.bindings[event];
} else {
i = 0;
_results = [];
while (i < this.bindings[event].length) {
if (this.bindings[event][i].handler === handler) {
_results.push(this.bindings[event].splice(i, 1));
} else {
_results.push(i++);
}
}
return _results;
}
};
Evented.prototype.trigger = function() {
var args, ctx, event, handler, i, once, _ref, _ref1, _results;
event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if ((_ref = this.bindings) != null ? _ref[event] : void 0) {
i = 0;
_results = [];
while (i < this.bindings[event].length) {
_ref1 = this.bindings[event][i], handler = _ref1.handler, ctx = _ref1.ctx, once = _ref1.once;
handler.apply(ctx != null ? ctx : this, args);
if (once) {
_results.push(this.bindings[event].splice(i, 1));
} else {
_results.push(i++);
}
}
return _results;
}
};
return Evented;
})();
this.Tether.Utils = {
getScrollParent: getScrollParent,
getBounds: getBounds,
getOffsetParent: getOffsetParent,
extend: extend,
addClass: addClass,
removeClass: removeClass,
hasClass: hasClass,
updateClasses: updateClasses,
defer: defer,
flush: flush,
uniqueId: uniqueId,
Evented: Evented,
getScrollBarSize: getScrollBarSize
};
}).call(this);
(function() {
var MIRROR_LR, MIRROR_TB, OFFSET_MAP, Tether, addClass, addOffset, attachmentToOffset, autoToFixedAttachment, defer, extend, flush, getBounds, getOffsetParent, getOuterSize, getScrollBarSize, getScrollParent, getSize, now, offsetToPx, parseAttachment, parseOffset, position, removeClass, tethers, transformKey, updateClasses, within, _Tether, _ref,
__slice = [].slice,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
if (this.Tether == null) {
throw new Error("You must include the utils.js file before tether.js");
}
Tether = this.Tether;
_ref = Tether.Utils, getScrollParent = _ref.getScrollParent, getSize = _ref.getSize, getOuterSize = _ref.getOuterSize, getBounds = _ref.getBounds, getOffsetParent = _ref.getOffsetParent, extend = _ref.extend, addClass = _ref.addClass, removeClass = _ref.removeClass, updateClasses = _ref.updateClasses, defer = _ref.defer, flush = _ref.flush, getScrollBarSize = _ref.getScrollBarSize;
within = function(a, b, diff) {
if (diff == null) {
diff = 1;
}
return (a + diff >= b && b >= a - diff);
};
transformKey = (function() {
var el, key, _i, _len, _ref1;
el = document.createElement('div');
_ref1 = ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform'];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
key = _ref1[_i];
if (el.style[key] !== void 0) {
return key;
}
}
})();
tethers = [];
position = function() {
var tether, _i, _len;
for (_i = 0, _len = tethers.length; _i < _len; _i++) {
tether = tethers[_i];
tether.position(false);
}
return flush();
};
now = function() {
var _ref1;
return (_ref1 = typeof performance !== "undefined" && performance !== null ? typeof performance.now === "function" ? performance.now() : void 0 : void 0) != null ? _ref1 : +(new Date);
};
(function() {
var event, lastCall, lastDuration, pendingTimeout, tick, _i, _len, _ref1, _results;
lastCall = null;
lastDuration = null;
pendingTimeout = null;
tick = function() {
if ((lastDuration != null) && lastDuration > 16) {
lastDuration = Math.min(lastDuration - 16, 250);
pendingTimeout = setTimeout(tick, 250);
return;
}
if ((lastCall != null) && (now() - lastCall) < 10) {
return;
}
if (pendingTimeout != null) {
clearTimeout(pendingTimeout);
pendingTimeout = null;
}
lastCall = now();
position();
return lastDuration = now() - lastCall;
};
_ref1 = ['resize', 'scroll', 'touchmove'];
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
event = _ref1[_i];
_results.push(window.addEventListener(event, tick));
}
return _results;
})();
MIRROR_LR = {
center: 'center',
left: 'right',
right: 'left'
};
MIRROR_TB = {
middle: 'middle',
top: 'bottom',
bottom: 'top'
};
OFFSET_MAP = {
top: 0,
left: 0,
middle: '50%',
center: '50%',
bottom: '100%',
right: '100%'
};
autoToFixedAttachment = function(attachment, relativeToAttachment) {
var left, top;
left = attachment.left, top = attachment.top;
if (left === 'auto') {
left = MIRROR_LR[relativeToAttachment.left];
}
if (top === 'auto') {
top = MIRROR_TB[relativeToAttachment.top];
}
return {
left: left,
top: top
};
};
attachmentToOffset = function(attachment) {
var _ref1, _ref2;
return {
left: (_ref1 = OFFSET_MAP[attachment.left]) != null ? _ref1 : attachment.left,
top: (_ref2 = OFFSET_MAP[attachment.top]) != null ? _ref2 : attachment.top
};
};
addOffset = function() {
var left, offsets, out, top, _i, _len, _ref1;
offsets = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
out = {
top: 0,
left: 0
};
for (_i = 0, _len = offsets.length; _i < _len; _i++) {
_ref1 = offsets[_i], top = _ref1.top, left = _ref1.left;
if (typeof top === 'string') {
top = parseFloat(top, 10);
}
if (typeof left === 'string') {
left = parseFloat(left, 10);
}
out.top += top;
out.left += left;
}
return out;
};
offsetToPx = function(offset, size) {
if (typeof offset.left === 'string' && offset.left.indexOf('%') !== -1) {
offset.left = parseFloat(offset.left, 10) / 100 * size.width;
}
if (typeof offset.top === 'string' && offset.top.indexOf('%') !== -1) {
offset.top = parseFloat(offset.top, 10) / 100 * size.height;
}
return offset;
};
parseAttachment = parseOffset = function(value) {
var left, top, _ref1;
_ref1 = value.split(' '), top = _ref1[0], left = _ref1[1];
return {
top: top,
left: left
};
};
_Tether = (function() {
_Tether.modules = [];
function _Tether(options) {
this.position = __bind(this.position, this);
var module, _i, _len, _ref1, _ref2;
tethers.push(this);
this.history = [];
this.setOptions(options, false);
_ref1 = Tether.modules;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
module = _ref1[_i];
if ((_ref2 = module.initialize) != null) {
_ref2.call(this);
}
}
this.position();
}
_Tether.prototype.getClass = function(key) {
var _ref1, _ref2;
if ((_ref1 = this.options.classes) != null ? _ref1[key] : void 0) {
return this.options.classes[key];
} else if (((_ref2 = this.options.classes) != null ? _ref2[key] : void 0) !== false) {
if (this.options.classPrefix) {
return "" + this.options.classPrefix + "-" + key;
} else {
return key;
}
} else {
return '';
}
};
_Tether.prototype.setOptions = function(options, position) {
var defaults, key, _i, _len, _ref1, _ref2;
this.options = options;
if (position == null) {
position = true;
}
defaults = {
offset: '0 0',
targetOffset: '0 0',
targetAttachment: 'auto auto',
classPrefix: 'tether'
};
this.options = extend(defaults, this.options);
_ref1 = this.options, this.element = _ref1.element, this.target = _ref1.target, this.targetModifier = _ref1.targetModifier;
if (this.target === 'viewport') {
this.target = document.body;
this.targetModifier = 'visible';
} else if (this.target === 'scroll-handle') {
this.target = document.body;
this.targetModifier = 'scroll-handle';
}
_ref2 = ['element', 'target'];
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
key = _ref2[_i];
if (this[key] == null) {
throw new Error("Tether Error: Both element and target must be defined");
}
if (this[key].jquery != null) {
this[key] = this[key][0];
} else if (typeof this[key] === 'string') {
this[key] = document.querySelector(this[key]);
}
}
addClass(this.element, this.getClass('element'));
addClass(this.target, this.getClass('target'));
if (!this.options.attachment) {
throw new Error("Tether Error: You must provide an attachment");
}
this.targetAttachment = parseAttachment(this.options.targetAttachment);
this.attachment = parseAttachment(this.options.attachment);
this.offset = parseOffset(this.options.offset);
this.targetOffset = parseOffset(this.options.targetOffset);
if (this.scrollParent != null) {
this.disable();
}
if (this.targetModifier === 'scroll-handle') {
this.scrollParent = this.target;
} else {
this.scrollParent = getScrollParent(this.target);
}
if (this.options.enabled !== false) {
return this.enable(position);
}
};
_Tether.prototype.getTargetBounds = function() {
var bounds, fitAdj, hasBottomScroll, height, out, scrollBottom, scrollPercentage, style, target;
if (this.targetModifier != null) {
switch (this.targetModifier) {
case 'visible':
if (this.target === document.body) {
return {
top: pageYOffset,
left: pageXOffset,
height: innerHeight,
width: innerWidth
};
} else {
bounds = getBounds(this.target);
out = {
height: bounds.height,
width: bounds.width,
top: bounds.top,
left: bounds.left
};
out.height = Math.min(out.height, bounds.height - (pageYOffset - bounds.top));
out.height = Math.min(out.height, bounds.height - ((bounds.top + bounds.height) - (pageYOffset + innerHeight)));
out.height = Math.min(innerHeight, out.height);
out.height -= 2;
out.width = Math.min(out.width, bounds.width - (pageXOffset - bounds.left));
out.width = Math.min(out.width, bounds.width - ((bounds.left + bounds.width) - (pageXOffset + innerWidth)));
out.width = Math.min(innerWidth, out.width);
out.width -= 2;
if (out.top < pageYOffset) {
out.top = pageYOffset;
}
if (out.left < pageXOffset) {
out.left = pageXOffset;
}
return out;
}
break;
case 'scroll-handle':
target = this.target;
if (target === document.body) {
target = document.documentElement;
bounds = {
left: pageXOffset,
top: pageYOffset,
height: innerHeight,
width: innerWidth
};
} else {
bounds = getBounds(target);
}
style = getComputedStyle(target);
hasBottomScroll = target.scrollWidth > target.clientWidth || 'scroll' === [style.overflow, style.overflowX] || this.target !== document.body;
scrollBottom = 0;
if (hasBottomScroll) {
scrollBottom = 15;
}
height = bounds.height - parseFloat(style.borderTopWidth) - parseFloat(style.borderBottomWidth) - scrollBottom;
out = {
width: 15,
height: height * 0.975 * (height / target.scrollHeight),
left: bounds.left + bounds.width - parseFloat(style.borderLeftWidth) - 15
};
fitAdj = 0;
if (height < 408 && this.target === document.body) {
fitAdj = -0.00011 * Math.pow(height, 2) - 0.00727 * height + 22.58;
}
if (this.target !== document.body) {
out.height = Math.max(out.height, 24);
}
scrollPercentage = this.target.scrollTop / (target.scrollHeight - height);
out.top = scrollPercentage * (height - out.height - fitAdj) + bounds.top + parseFloat(style.borderTopWidth);
if (this.target === document.body) {
out.height = Math.max(out.height, 24);
}
return out;
}
} else {
return getBounds(this.target);
}
};
_Tether.prototype.clearCache = function() {
return this._cache = {};
};
_Tether.prototype.cache = function(k, getter) {
if (this._cache == null) {
this._cache = {};
}
if (this._cache[k] == null) {
this._cache[k] = getter.call(this);
}
return this._cache[k];
};
_Tether.prototype.enable = function(position) {
if (position == null) {
position = true;
}
addClass(this.target, this.getClass('enabled'));
addClass(this.element, this.getClass('enabled'));
this.enabled = true;
if (this.scrollParent !== document) {
this.scrollParent.addEventListener('scroll', this.position);
}
if (position) {
return this.position();
}
};
_Tether.prototype.disable = function() {
removeClass(this.target, this.getClass('enabled'));
removeClass(this.element, this.getClass('enabled'));
this.enabled = false;
if (this.scrollParent != null) {
return this.scrollParent.removeEventListener('scroll', this.position);
}
};
_Tether.prototype.destroy = function() {
var i, tether, _i, _len, _results;
this.disable();
_results = [];
for (i = _i = 0, _len = tethers.length; _i < _len; i = ++_i) {
tether = tethers[i];
if (tether === this) {
tethers.splice(i, 1);
break;
} else {
_results.push(void 0);
}
}
return _results;
};
_Tether.prototype.updateAttachClasses = function(elementAttach, targetAttach) {
var add, all, side, sides, _i, _j, _len, _len1, _ref1,
_this = this;
if (elementAttach == null) {
elementAttach = this.attachment;
}
if (targetAttach == null) {
targetAttach = this.targetAttachment;
}
sides = ['left', 'top', 'bottom', 'right', 'middle', 'center'];
if ((_ref1 = this._addAttachClasses) != null ? _ref1.length : void 0) {
this._addAttachClasses.splice(0, this._addAttachClasses.length);
}
add = this._addAttachClasses != null ? this._addAttachClasses : this._addAttachClasses = [];
if (elementAttach.top) {
add.push("" + (this.getClass('element-attached')) + "-" + elementAttach.top);
}
if (elementAttach.left) {
add.push("" + (this.getClass('element-attached')) + "-" + elementAttach.left);
}
if (targetAttach.top) {
add.push("" + (this.getClass('target-attached')) + "-" + targetAttach.top);
}
if (targetAttach.left) {
add.push("" + (this.getClass('target-attached')) + "-" + targetAttach.left);
}
all = [];
for (_i = 0, _len = sides.length; _i < _len; _i++) {
side = sides[_i];
all.push("" + (this.getClass('element-attached')) + "-" + side);
}
for (_j = 0, _len1 = sides.length; _j < _len1; _j++) {
side = sides[_j];
all.push("" + (this.getClass('target-attached')) + "-" + side);
}
return defer(function() {
if (_this._addAttachClasses == null) {
return;
}
updateClasses(_this.element, _this._addAttachClasses, all);
updateClasses(_this.target, _this._addAttachClasses, all);
return _this._addAttachClasses = void 0;
});
};
_Tether.prototype.position = function(flushChanges) {
var elementPos, elementStyle, height, left, manualOffset, manualTargetOffset, module, next, offset, offsetBorder, offsetParent, offsetParentSize, offsetParentStyle, offsetPosition, ret, scrollLeft, scrollTop, scrollbarSize, side, targetAttachment, targetOffset, targetPos, targetSize, top, width, _i, _j, _len, _len1, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6,
_this = this;
if (flushChanges == null) {
flushChanges = true;
}
if (!this.enabled) {
return;
}
this.clearCache();
targetAttachment = autoToFixedAttachment(this.targetAttachment, this.attachment);
this.updateAttachClasses(this.attachment, targetAttachment);
elementPos = this.cache('element-bounds', function() {
return getBounds(_this.element);
});
width = elementPos.width, height = elementPos.height;
if (width === 0 && height === 0 && (this.lastSize != null)) {
_ref1 = this.lastSize, width = _ref1.width, height = _ref1.height;
} else {
this.lastSize = {
width: width,
height: height
};
}
targetSize = targetPos = this.cache('target-bounds', function() {
return _this.getTargetBounds();
});
offset = offsetToPx(attachmentToOffset(this.attachment), {
width: width,
height: height
});
targetOffset = offsetToPx(attachmentToOffset(targetAttachment), targetSize);
manualOffset = offsetToPx(this.offset, {
width: width,
height: height
});
manualTargetOffset = offsetToPx(this.targetOffset, targetSize);
offset = addOffset(offset, manualOffset);
targetOffset = addOffset(targetOffset, manualTargetOffset);
left = targetPos.left + targetOffset.left - offset.left;
top = targetPos.top + targetOffset.top - offset.top;
_ref2 = Tether.modules;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
module = _ref2[_i];
ret = module.position.call(this, {
left: left,
top: top,
targetAttachment: targetAttachment,
targetPos: targetPos,
attachment: this.attachment,
elementPos: elementPos,
offset: offset,
targetOffset: targetOffset,
manualOffset: manualOffset,
manualTargetOffset: manualTargetOffset,
scrollbarSize: scrollbarSize
});
if ((ret == null) || typeof ret !== 'object') {
continue;
} else if (ret === false) {
return false;
} else {
top = ret.top, left = ret.left;
}
}
next = {
page: {
top: top,
left: left
},
viewport: {
top: top - pageYOffset,
bottom: pageYOffset - top - height + innerHeight,
left: left - pageXOffset,
right: pageXOffset - left - width + innerWidth
}
};
if (document.body.scrollWidth > window.innerWidth) {
scrollbarSize = this.cache('scrollbar-size', getScrollBarSize);
next.viewport.bottom -= scrollbarSize.height;
}
if (document.body.scrollHeight > window.innerHeight) {
scrollbarSize = this.cache('scrollbar-size', getScrollBarSize);
next.viewport.right -= scrollbarSize.width;
}
if (((_ref3 = document.body.style.position) !== '' && _ref3 !== 'static') || ((_ref4 = document.body.parentElement.style.position) !== '' && _ref4 !== 'static')) {
next.page.bottom = document.body.scrollHeight - top - height;
next.page.right = document.body.scrollWidth - left - width;
}
if (((_ref5 = this.options.optimizations) != null ? _ref5.moveElement : void 0) !== false && (this.targetModifier == null)) {
offsetParent = this.cache('target-offsetparent', function() {
return getOffsetParent(_this.target);
});
offsetPosition = this.cache('target-offsetparent-bounds', function() {
return getBounds(offsetParent);
});
offsetParentStyle = getComputedStyle(offsetParent);
elementStyle = getComputedStyle(this.element);
offsetParentSize = offsetPosition;
offsetBorder = {};
_ref6 = ['Top', 'Left', 'Bottom', 'Right'];
for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) {
side = _ref6[_j];
offsetBorder[side.toLowerCase()] = parseFloat(offsetParentStyle["border" + side + "Width"]);
}
offsetPosition.right = document.body.scrollWidth - offsetPosition.left - offsetParentSize.width + offsetBorder.right;
offsetPosition.bottom = document.body.scrollHeight - offsetPosition.top - offsetParentSize.height + offsetBorder.bottom;
if (next.page.top >= (offsetPosition.top + offsetBorder.top) && next.page.bottom >= offsetPosition.bottom) {
if (next.page.left >= (offsetPosition.left + offsetBorder.left) && next.page.right >= offsetPosition.right) {
scrollTop = offsetParent.scrollTop;
scrollLeft = offsetParent.scrollLeft;
next.offset = {
top: next.page.top - offsetPosition.top + scrollTop - offsetBorder.top,
left: next.page.left - offsetPosition.left + scrollLeft - offsetBorder.left
};
}
}
}
this.move(next);
this.history.unshift(next);
if (this.history.length > 3) {
this.history.pop();
}
if (flushChanges) {
flush();
}
return true;
};
_Tether.prototype.move = function(position) {
var css, elVal, found, key, moved, offsetParent, point, same, transcribe, type, val, write, writeCSS, _i, _len, _ref1, _ref2,
_this = this;
if (this.element.parentNode == null) {
return;
}
same = {};
for (type in position) {
same[type] = {};
for (key in position[type]) {
found = false;
_ref1 = this.history;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
point = _ref1[_i];
if (!within((_ref2 = point[type]) != null ? _ref2[key] : void 0, position[type][key])) {
found = true;
break;
}
}
if (!found) {
same[type][key] = true;
}
}
}
css = {
top: '',
left: '',
right: '',
bottom: ''
};
transcribe = function(same, pos) {
var xPos, yPos, _ref3;
if (((_ref3 = _this.options.optimizations) != null ? _ref3.gpu : void 0) !== false) {
if (same.top) {
css.top = 0;
yPos = pos.top;
} else {
css.bottom = 0;
yPos = -pos.bottom;
}
if (same.left) {
css.left = 0;
xPos = pos.left;
} else {
css.right = 0;
xPos = -pos.right;
}
css[transformKey] = "translateX(" + (Math.round(xPos)) + "px) translateY(" + (Math.round(yPos)) + "px)";
if (transformKey !== 'msTransform') {
return css[transformKey] += " translateZ(0)";
}
} else {
if (same.top) {
css.top = "" + pos.top + "px";
} else {
css.bottom = "" + pos.bottom + "px";
}
if (same.left) {
return css.left = "" + pos.left + "px";
} else {
return css.right = "" + pos.right + "px";
}
}
};
moved = false;
if ((same.page.top || same.page.bottom) && (same.page.left || same.page.right)) {
css.position = 'absolute';
transcribe(same.page, position.page);
} else if ((same.viewport.top || same.viewport.bottom) && (same.viewport.left || same.viewport.right)) {
css.position = 'fixed';
transcribe(same.viewport, position.viewport);
} else if ((same.offset != null) && same.offset.top && same.offset.left) {
css.position = 'absolute';
offsetParent = this.cache('target-offsetparent', function() {
return getOffsetParent(_this.target);
});
if (getOffsetParent(this.element) !== offsetParent) {
defer(function() {
_this.element.parentNode.removeChild(_this.element);
return offsetParent.appendChild(_this.element);
});
}
transcribe(same.offset, position.offset);
moved = true;
} else {
css.position = 'absolute';
transcribe({
top: true,
left: true
}, position.page);
}
if (!moved && this.element.parentNode.tagName !== 'BODY') {
this.element.parentNode.removeChild(this.element);
document.body.appendChild(this.element);
}
writeCSS = {};
write = false;
for (key in css) {
val = css[key];
elVal = this.element.style[key];
if (elVal !== '' && val !== '' && (key === 'top' || key === 'left' || key === 'bottom' || key === 'right')) {
elVal = parseFloat(elVal);
val = parseFloat(val);
}
if (elVal !== val) {
write = true;
writeCSS[key] = css[key];
}
}
if (write) {
return defer(function() {
return extend(_this.element.style, writeCSS);
});
}
};
return _Tether;
})();
Tether.position = position;
this.Tether = extend(_Tether, Tether);
}).call(this);
(function() {
var BOUNDS_FORMAT, MIRROR_ATTACH, defer, extend, getBoundingRect, getBounds, getOuterSize, getSize, updateClasses, _ref,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
_ref = this.Tether.Utils, getOuterSize = _ref.getOuterSize, getBounds = _ref.getBounds, getSize = _ref.getSize, extend = _ref.extend, updateClasses = _ref.updateClasses, defer = _ref.defer;
MIRROR_ATTACH = {
left: 'right',
right: 'left',
top: 'bottom',
bottom: 'top',
middle: 'middle'
};
BOUNDS_FORMAT = ['left', 'top', 'right', 'bottom'];
getBoundingRect = function(tether, to) {
var i, pos, side, size, style, _i, _len;
if (to === 'scrollParent') {
to = tether.scrollParent;
} else if (to === 'window') {
to = [pageXOffset, pageYOffset, innerWidth + pageXOffset, innerHeight + pageYOffset];
}
if (to === document) {
to = to.documentElement;
}
if (to.nodeType != null) {
pos = size = getBounds(to);
style = getComputedStyle(to);
to = [pos.left, pos.top, size.width + pos.left, size.height + pos.top];
for (i = _i = 0, _len = BOUNDS_FORMAT.length; _i < _len; i = ++_i) {
side = BOUNDS_FORMAT[i];
side = side[0].toUpperCase() + side.substr(1);
if (side === 'Top' || side === 'Left') {
to[i] += parseFloat(style["border" + side + "Width"]);
} else {
to[i] -= parseFloat(style["border" + side + "Width"]);
}
}
}
return to;
};
this.Tether.modules.push({
position: function(_arg) {
var addClasses, allClasses, attachment, bounds, changeAttachX, changeAttachY, cls, constraint, eAttachment, height, left, oob, oobClass, p, pin, pinned, pinnedClass, removeClass, side, tAttachment, targetAttachment, targetHeight, targetSize, targetWidth, to, top, width, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8,
_this = this;
top = _arg.top, left = _arg.left, targetAttachment = _arg.targetAttachment;
if (!this.options.constraints) {
return true;
}
removeClass = function(prefix) {
var side, _i, _len, _results;
_this.removeClass(prefix);
_results = [];
for (_i = 0, _len = BOUNDS_FORMAT.length; _i < _len; _i++) {
side = BOUNDS_FORMAT[_i];
_results.push(_this.removeClass("" + prefix + "-" + side));
}
return _results;
};
_ref1 = this.cache('element-bounds', function() {
return getBounds(_this.element);
}), height = _ref1.height, width = _ref1.width;
if (width === 0 && height === 0 && (this.lastSize != null)) {
_ref2 = this.lastSize, width = _ref2.width, height = _ref2.height;
}
targetSize = this.cache('target-bounds', function() {
return _this.getTargetBounds();
});
targetHeight = targetSize.height;
targetWidth = targetSize.width;
tAttachment = {};
eAttachment = {};
allClasses = [this.getClass('pinned'), this.getClass('out-of-bounds')];
_ref3 = this.options.constraints;
for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
constraint = _ref3[_i];
if (constraint.outOfBoundsClass) {
allClasses.push(constraint.outOfBoundsClass);
}
if (constraint.pinnedClass) {
allClasses.push(constraint.pinnedClass);
}
}
for (_j = 0, _len1 = allClasses.length; _j < _len1; _j++) {
cls = allClasses[_j];
_ref4 = ['left', 'top', 'right', 'bottom'];
for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) {
side = _ref4[_k];
allClasses.push("" + cls + "-" + side);
}
}
addClasses = [];
tAttachment = extend({}, targetAttachment);
eAttachment = extend({}, this.attachment);
_ref5 = this.options.constraints;
for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) {
constraint = _ref5[_l];
to = constraint.to, attachment = constraint.attachment, pin = constraint.pin;
if (attachment == null) {
attachment = '';
}
if (__indexOf.call(attachment, ' ') >= 0) {
_ref6 = attachment.split(' '), changeAttachY = _ref6[0], changeAttachX = _ref6[1];
} else {
changeAttachX = changeAttachY = attachment;
}
bounds = getBoundingRect(this, to);
if (changeAttachY === 'target' || changeAttachY === 'both') {
if (top < bounds[1] && tAttachment.top === 'top') {
top += targetHeight;
tAttachment.top = 'bottom';
}
if (top + height > bounds[3] && tAttachment.top === 'bottom') {
top -= targetHeight;
tAttachment.top = 'top';
}
}
if (changeAttachY === 'together') {
if (top < bounds[1] && tAttachment.top === 'top') {
if (eAttachment.top === 'bottom') {
top += targetHeight;
tAttachment.top = 'bottom';
top += height;
eAttachment.top = 'top';
} else if (eAttachment.top === 'top') {
top += targetHeight;
tAttachment.top = 'bottom';
top -= height;
eAttachment.top = 'bottom';
}
}
if (top + height > bounds[3] && tAttachment.top === 'bottom') {
if (eAttachment.top === 'top') {
top -= targetHeight;
tAttachment.top = 'top';
top -= height;
eAttachment.top = 'bottom';
} else if (eAttachment.top === 'bottom') {
top -= targetHeight;
tAttachment.top = 'top';
top += height;
eAttachment.top = 'top';
}
}
if (tAttachment.top === 'middle') {
if (top + height > bounds[3] && eAttachment.top === 'top') {
top -= height;
eAttachment.top = 'bottom';
} else if (top < bounds[1] && eAttachment.top === 'bottom') {
top += height;
eAttachment.top = 'top';
}
}
}
if (changeAttachX === 'target' || changeAttachX === 'both') {
if (left < bounds[0] && tAttachment.left === 'left') {
left += targetWidth;
tAttachment.left = 'right';
}
if (left + width > bounds[2] && tAttachment.left === 'right') {
left -= targetWidth;
tAttachment.left = 'left';
}
}
if (changeAttachX === 'together') {
if (left < bounds[0] && tAttachment.left === 'left') {
if (eAttachment.left === 'right') {
left += targetWidth;
tAttachment.left = 'right';
left += width;
eAttachment.left = 'left';
} else if (eAttachment.left === 'left') {
left += targetWidth;
tAttachment.left = 'right';
left -= width;
eAttachment.left = 'right';
}
} else if (left + width > bounds[2] && tAttachment.left === 'right') {
if (eAttachment.left === 'left') {
left -= targetWidth;
tAttachment.left = 'left';
left -= width;
eAttachment.left = 'right';
} else if (eAttachment.left === 'right') {
left -= targetWidth;
tAttachment.left = 'left';
left += width;
eAttachment.left = 'left';
}
} else if (tAttachment.left === 'center') {
if (left + width > bounds[2] && eAttachment.left === 'left') {
left -= width;
eAttachment.left = 'right';
} else if (left < bounds[0] && eAttachment.left === 'right') {
left += width;
eAttachment.left = 'left';
}
}
}
if (changeAttachY === 'element' || changeAttachY === 'both') {
if (top < bounds[1] && eAttachment.top === 'bottom') {
top += height;
eAttachment.top = 'top';
}
if (top + height > bounds[3] && eAttachment.top === 'top') {
top -= height;
eAttachment.top = 'bottom';
}
}
if (changeAttachX === 'element' || changeAttachX === 'both') {
if (left < bounds[0] && eAttachment.left === 'right') {
left += width;
eAttachment.left = 'left';
}
if (left + width > bounds[2] && eAttachment.left === 'left') {
left -= width;
eAttachment.left = 'right';
}
}
if (typeof pin === 'string') {
pin = (function() {
var _len4, _m, _ref7, _results;
_ref7 = pin.split(',');
_results = [];
for (_m = 0, _len4 = _ref7.length; _m < _len4; _m++) {
p = _ref7[_m];
_results.push(p.trim());
}
return _results;
})();
} else if (pin === true) {
pin = ['top', 'left', 'right', 'bottom'];
}
pin || (pin = []);
pinned = [];
oob = [];
if (top < bounds[1]) {
if (__indexOf.call(pin, 'top') >= 0) {
top = bounds[1];
pinned.push('top');
} else {
oob.push('top');
}
}
if (top + height > bounds[3]) {
if (__indexOf.call(pin, 'bottom') >= 0) {
top = bounds[3] - height;
pinned.push('bottom');
} else {
oob.push('bottom');
}
}
if (left < bounds[0]) {
if (__indexOf.call(pin, 'left') >= 0) {
left = bounds[0];
pinned.push('left');
} else {
oob.push('left');
}
}
if (left + width > bounds[2]) {
if (__indexOf.call(pin, 'right') >= 0) {
left = bounds[2] - width;
pinned.push('right');
} else {
oob.push('right');
}
}
if (pinned.length) {
pinnedClass = (_ref7 = this.options.pinnedClass) != null ? _ref7 : this.getClass('pinned');
addClasses.push(pinnedClass);
for (_m = 0, _len4 = pinned.length; _m < _len4; _m++) {
side = pinned[_m];
addClasses.push("" + pinnedClass + "-" + side);
}
}
if (oob.length) {
oobClass = (_ref8 = this.options.outOfBoundsClass) != null ? _ref8 : this.getClass('out-of-bounds');
addClasses.push(oobClass);
for (_n = 0, _len5 = oob.length; _n < _len5; _n++) {
side = oob[_n];
addClasses.push("" + oobClass + "-" + side);
}
}
if (__indexOf.call(pinned, 'left') >= 0 || __indexOf.call(pinned, 'right') >= 0) {
eAttachment.left = tAttachment.left = false;
}
if (__indexOf.call(pinned, 'top') >= 0 || __indexOf.call(pinned, 'bottom') >= 0) {
eAttachment.top = tAttachment.top = false;
}
if (tAttachment.top !== targetAttachment.top || tAttachment.left !== targetAttachment.left || eAttachment.top !== this.attachment.top || eAttachment.left !== this.attachment.left) {
this.updateAttachClasses(eAttachment, tAttachment);
}
}
defer(function() {
updateClasses(_this.target, addClasses, allClasses);
return updateClasses(_this.element, addClasses, allClasses);
});
return {
top: top,
left: left
};
}
});
}).call(this);
(function() {
var defer, getBounds, updateClasses, _ref;
_ref = this.Tether.Utils, getBounds = _ref.getBounds, updateClasses = _ref.updateClasses, defer = _ref.defer;
this.Tether.modules.push({
position: function(_arg) {
var abutted, addClasses, allClasses, bottom, height, left, right, side, sides, targetPos, top, width, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref1, _ref2, _ref3, _ref4, _ref5,
_this = this;
top = _arg.top, left = _arg.left;
_ref1 = this.cache('element-bounds', function() {
return getBounds(_this.element);
}), height = _ref1.height, width = _ref1.width;
targetPos = this.getTargetBounds();
bottom = top + height;
right = left + width;
abutted = [];
if (top <= targetPos.bottom && bottom >= targetPos.top) {
_ref2 = ['left', 'right'];
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
side = _ref2[_i];
if ((_ref3 = targetPos[side]) === left || _ref3 === right) {
abutted.push(side);
}
}
}
if (left <= targetPos.right && right >= targetPos.left) {
_ref4 = ['top', 'bottom'];
for (_j = 0, _len1 = _ref4.length; _j < _len1; _j++) {
side = _ref4[_j];
if ((_ref5 = targetPos[side]) === top || _ref5 === bottom) {
abutted.push(side);
}
}
}
allClasses = [];
addClasses = [];
sides = ['left', 'top', 'right', 'bottom'];
allClasses.push(this.getClass('abutted'));
for (_k = 0, _len2 = sides.length; _k < _len2; _k++) {
side = sides[_k];
allClasses.push("" + (this.getClass('abutted')) + "-" + side);
}
if (abutted.length) {
addClasses.push(this.getClass('abutted'));
}
for (_l = 0, _len3 = abutted.length; _l < _len3; _l++) {
side = abutted[_l];
addClasses.push("" + (this.getClass('abutted')) + "-" + side);
}
defer(function() {
updateClasses(_this.target, addClasses, allClasses);
return updateClasses(_this.element, addClasses, allClasses);
});
return true;
}
});
}).call(this);
(function() {
this.Tether.modules.push({
position: function(_arg) {
var left, result, shift, shiftLeft, shiftTop, top, _ref;
top = _arg.top, left = _arg.left;
if (!this.options.shift) {
return;
}
result = function(val) {
if (typeof val === 'function') {
return val.call(this, {
top: top,
left: left
});
} else {
return val;
}
};
shift = result(this.options.shift);
if (typeof shift === 'string') {
shift = shift.split(' ');
shift[1] || (shift[1] = shift[0]);
shiftTop = shift[0], shiftLeft = shift[1];
shiftTop = parseFloat(shiftTop, 10);
shiftLeft = parseFloat(shiftLeft, 10);
} else {
_ref = [shift.top, shift.left], shiftTop = _ref[0], shiftLeft = _ref[1];
}
top += shiftTop;
left += shiftLeft;
return {
top: top,
left: left
};
}
});
}).call(this);
return this.Tether;
}));
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var Tabs = React.createClass({
displayName: 'Tabs',
getInitialState: function getInitialState() {
return {
selectedTab: 0
};
},
selectTab: function selectTab(options) {
this.setState(options);
},
render: function render() {
var content = null;
var children = React.Children.map(this.props.children, (function (child, index) {
if (index === this.state.selectedTab) content = child.props.children;
return React.cloneElement(child, {
active: index === this.state.selectedTab,
index: index,
selectTab: this.selectTab
});
}).bind(this));
return React.createElement(
'div',
null,
React.createElement(
'div',
{ className: 'tabs' },
children
),
React.createElement(
'div',
{ className: 'content' },
content
)
);
}
});
module.exports = Tabs;
Tabs.Tab = __webpack_require__(31);
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var classnames = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"classnames\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var Tab = React.createClass({
displayName: 'Tab',
select: function select() {
var options = {
selectedTab: this.props.index
};
this.props.selectTab(options);
},
render: function render() {
var classes = {
'tab-item': true,
'is-active': this.props.active
};
return React.createElement(
'div',
{ className: classnames(classes), onClick: this.select },
this.props.title
);
}
});
module.exports = Tab;
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"react-dom\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
var foundationApi = __webpack_require__(5);
var PopupToggle = __webpack_require__(33);
var Trigger = React.createClass({
displayName: 'Trigger',
getDefaultProps: function getDefaultProps() {
return {
open: null,
close: null,
toggle: null,
hardToggle: null,
popupToggle: null,
notify: null
};
},
getCloseId: function getCloseId() {
if (this.props.close) {
return this.props.close;
} else {
var parentElement = false;
var tempElement = ReactDOM.findDOMNode(this).parentNode;
while (parentElement === false) {
if (tempElement.nodeName == 'BODY') {
parentElement = '';
}
if (typeof tempElement.getAttribute('data-closable') !== 'undefined' && tempElement.getAttribute('data-closable') !== false) {
parentElement = tempElement;
}
tempElement = tempElement.parentNode;
}
return parentElement.getAttribute('id');
}
},
clickHandler: function clickHandler(e) {
e.preventDefault();
if (this.props.open) {
foundationApi.publish(this.props.open, 'open');
} else if (this.props.close !== null) {
foundationApi.publish(this.getCloseId(), 'close');
} else if (this.props.toggle) {
foundationApi.publish(this.props.toggle, 'toggle');
} else if (this.props.hardToggle) {
foundationApi.closeActiveElements({ exclude: this.props.hardToggle });
foundationApi.publish(this.props.hardToggle, 'toggle');
} else if (this.props.notify) {
foundationApi.publish(this.props.notify, {
title: this.props.title,
content: this.props.content,
position: this.props.position,
color: this.props.color,
image: this.props.image
});
}
},
render: function render() {
if (this.props.popupToggle) {
return React.createElement(PopupToggle, this.props);
} else {
var child = React.Children.only(this.props.children);
return React.cloneElement(child, {
onClick: this.clickHandler
});
}
}
});
module.exports = Trigger;
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(2);
var foundationApi = __webpack_require__(5);
var PopupToggle = React.createClass({
displayName: 'PopupToggle',
clickHandler: function clickHandler(id, e) {
e.preventDefault();
foundationApi.publish(this.props.popupToggle, ['toggle', id]);
},
render: function render() {
var child = React.Children.only(this.props.children);
var id = this.props.id || foundationApi.generateUuid();
return React.cloneElement(child, {
id: id,
onClick: this.clickHandler.bind(this, id)
});
}
});
module.exports = PopupToggle;
/***/ }
/******/ ])
});
; | valzav/react-foundation-apps | dist/react-foundation-apps.js | JavaScript | mit | 111,888 |
'use strict';
//noinspection JSUnresolvedVariable,JSUnresolvedFunction,JSHint
define([ 'jquery',
'knockout',
'../../../assets/js/views/smartDetailsViewmodel.js',
'../../../assets/js/views/style.js',
'../../../assets/js/support/settings.js',
'../../../assets/js/biz/diskHelper.js'
], function ($, ko, SmartDetailsViewModel, Style, Settings, DiskHelper) {
//noinspection JSHint,JSUnresolvedFunction,JSUnusedGlobalSymbols
return {
refreshing: ko.observable(false),
refreshFrequency: ko.observable('?'),
refreshIntervalId: 0,
disks: ko.observableArray([]),
// Called from timer
fetch: function (DiskListViewModel) {
DiskListViewModel.refreshing(true);
//Requests disk list
//noinspection JSUnresolvedFunction
$.getJSON(Settings.get().webServicesUrl + 'esxi/disks.json', function (diskListData) {
//Builds disk list for SMART request
var diskIds = '';
diskListData.disks.forEach(function (disk, i, disks) {
var diskId = i + 1;
diskIds = diskIds.concat(diskId);
if (diskId < disks.length) {
diskIds = diskIds.concat(',');
}
});
if (diskIds !== '') {
//Requests SMART data for these disks
//noinspection JSUnresolvedFunction
$.getJSON(Settings.get().webServicesUrl + 'esxi/disks/' + diskIds + '/smart.json', function (diskSmartData) {
//noinspection JSUnresolvedFunction
DiskListViewModel.disks.removeAll();
//noinspection JSHint,JSUnresolvedFunction
/** @namespace diskSmartData.disks_smart */
diskSmartData.disks_smart.forEach(function (smartData, i) {
var disk = diskListData.disks[i];
disk.smart = smartData.smart;
//Updates model with disk list
DiskListViewModel.disks.push(disk);
});
});
}
DiskListViewModel.refreshing(false);
});
},
bindSubView: function () {
//noinspection JSUnresolvedFunction
ko.applyBindings(SmartDetailsViewModel, $('#smartPopup')[0]);
},
// Called from binding: click on row
showSmartDetails: function (disk) {
//noinspection JSUnresolvedVariable,JSUnresolvedFunction
//noinspection JSUnresolvedFunction
if (disk) {
SmartDetailsViewModel.get(disk);
//noinspection JSUnresolvedFunction
$('#smartPopup').modal('show');
}
},
// Called from binding: computed
temperature: function (diskId) {
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
return ko.computed({
read: function () {
var temperatureCelsius = DiskHelper.getTemperatureCelsius(this, diskId);
if (temperatureCelsius !== DiskHelper.NOT_AVAILABLE_VALUE) {
var temperatureFahrenheit = DiskHelper.getTemperatureFahrenheit(this, diskId);
return Math.floor(temperatureCelsius) + '°C / ' + Math.floor(temperatureFahrenheit) + '°F';
}
return DiskHelper.NOT_AVAILABLE_VALUE;
}
}, this);
},
// Called from binding: computed
brand: function (driveModel) {
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
return ko.computed({
read: function () {
return DiskHelper.extractBrand(driveModel);
}
}, this);
},
// Called from binding: computed
global_status: function (diskId) {
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
return ko.computed({
read: function () //noinspection JSHint
{
var disk = this.disks()[diskId - 1];
// To handle case of empty disk list in model (when refreshing).
if (!disk) {
return '';
}
/** @namespace disk.smart.i_status */
return disk.smart.i_status;
}
}, this);
},
// Called from binding: computed
tempStatus: function (diskId) {
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
return ko.computed({
read: function () {
var disk = this.disks()[diskId - 1];
// To handle case of empty disk list in model (when refreshing).
if (!disk) {
return '';
}
/** @namespace disk.smart.items[].status */
return disk.smart.items[8].status;
}
}, this);
},
// Called from binding: computed
statusCssClass: function (status) {
return Style.getStatusLabelCssClass(status);
}
};
}); | djey47/smartX | web-ui/app/assets/js/views/diskListViewmodel.js | JavaScript | mit | 4,587 |
/* eslint-disable */
process.env.NODE_ENV = 'production'
const webpack = require('webpack')
const ora = require('ora')
const builds = require('./config.dist').getAllBuilds()
const spinner = ora('building for production...')
// const stylus = require('stylus')
// const fs = require('fs')
// const path = require('path')
// const resolve = file => path.resolve(__dirname, file)
// const styles = fs.readFileSync(resolve('../src/style/main.styl'), 'utf8')
// stylus(styles)
// .include(resolve('../src/style'))
// .set('compress', true)
// .render((err, css) => {
// fs.writeFileSync(resolve('../dist/rubik.min.css'), css)
// })
function build (builds) {
builds.forEach(config => {
spinner.start()
webpack(config, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n')
})
})
}
build(builds)
| packjs/pallas | build/build.dist.js | JavaScript | mit | 1,024 |
import React from 'react';
import {
PanelGroup,
Panel,
} from '../AMUIReact';
export class PanelDemo extends React.Component {
render() {
return (
<div>
<h2>Panel</h2>
<h3>可折叠面板组</h3>
<PanelGroup defaultActiveKey="2" accordion>
<Panel header="面板 1" eventKey="1">面板 1 内容</Panel>
<Panel header="面板 2" eventKey="2">面板 2 内容</Panel>
</PanelGroup>
</div>
);
}
}
| amazeui/amazeui-react | examples/server-rendering/shared/components/demos/Panel.js | JavaScript | mit | 474 |
function TraceablePeerConnection(ice_config, constraints) {
var self = this;
var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
this.peerconnection = new RTCPeerconnection(ice_config, constraints);
this.updateLog = [];
this.stats = {};
this.statsinterval = null;
this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
var Interop = require('sdp-interop').Interop;
this.interop = new Interop();
var Simulcast = require('sdp-simulcast');
this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
// override as desired
this.trace = function (what, info) {
//console.warn('WTRACE', what, info);
self.updateLog.push({
time: new Date(),
type: what,
value: info || ""
});
};
this.onicecandidate = null;
this.peerconnection.onicecandidate = function (event) {
self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
if (self.onicecandidate !== null) {
self.onicecandidate(event);
}
};
this.onaddstream = null;
this.peerconnection.onaddstream = function (event) {
self.trace('onaddstream', event.stream.id);
if (self.onaddstream !== null) {
self.onaddstream(event);
}
};
this.onremovestream = null;
this.peerconnection.onremovestream = function (event) {
self.trace('onremovestream', event.stream.id);
if (self.onremovestream !== null) {
self.onremovestream(event);
}
};
this.onsignalingstatechange = null;
this.peerconnection.onsignalingstatechange = function (event) {
self.trace('onsignalingstatechange', self.signalingState);
if (self.onsignalingstatechange !== null) {
self.onsignalingstatechange(event);
}
};
this.oniceconnectionstatechange = null;
this.peerconnection.oniceconnectionstatechange = function (event) {
self.trace('oniceconnectionstatechange', self.iceConnectionState);
if (self.oniceconnectionstatechange !== null) {
self.oniceconnectionstatechange(event);
}
};
this.onnegotiationneeded = null;
this.peerconnection.onnegotiationneeded = function (event) {
self.trace('onnegotiationneeded');
if (self.onnegotiationneeded !== null) {
self.onnegotiationneeded(event);
}
};
self.ondatachannel = null;
this.peerconnection.ondatachannel = function (event) {
self.trace('ondatachannel', event);
if (self.ondatachannel !== null) {
self.ondatachannel(event);
}
};
if (!navigator.mozGetUserMedia && this.maxstats) {
this.statsinterval = window.setInterval(function() {
self.peerconnection.getStats(function(stats) {
var results = stats.result();
for (var i = 0; i < results.length; ++i) {
//console.log(results[i].type, results[i].id, results[i].names())
var now = new Date();
results[i].names().forEach(function (name) {
var id = results[i].id + '-' + name;
if (!self.stats[id]) {
self.stats[id] = {
startTime: now,
endTime: now,
values: [],
times: []
};
}
self.stats[id].values.push(results[i].stat(name));
self.stats[id].times.push(now.getTime());
if (self.stats[id].values.length > self.maxstats) {
self.stats[id].values.shift();
self.stats[id].times.shift();
}
self.stats[id].endTime = now;
});
}
});
}, 1000);
}
};
dumpSDP = function(description) {
if (typeof description === 'undefined' || description == null) {
return '';
}
return 'type: ' + description.type + '\r\n' + description.sdp;
};
if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
var desc = this.peerconnection.localDescription;
this.trace('getLocalDescription::preTransform', dumpSDP(desc));
// if we're running on FF, transform to Plan B first.
if (navigator.mozGetUserMedia) {
desc = this.interop.toPlanB(desc);
this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
}
return desc;
});
TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
var desc = this.peerconnection.remoteDescription;
this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
// if we're running on FF, transform to Plan B first.
if (navigator.mozGetUserMedia) {
desc = this.interop.toPlanB(desc);
this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
}
return desc;
});
}
TraceablePeerConnection.prototype.addStream = function (stream) {
this.trace('addStream', stream.id);
try
{
this.peerconnection.addStream(stream);
}
catch (e)
{
console.error(e);
return;
}
};
TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
this.trace('removeStream', stream.id);
if(stopStreams) {
stream.getAudioTracks().forEach(function (track) {
track.stop();
});
stream.getVideoTracks().forEach(function (track) {
track.stop();
});
}
try {
// FF doesn't support this yet.
this.peerconnection.removeStream(stream);
} catch (e) {
console.error(e);
}
};
TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
this.trace('createDataChannel', label, opts);
return this.peerconnection.createDataChannel(label, opts);
};
TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
this.trace('setLocalDescription::preTransform', dumpSDP(description));
// if we're running on FF, transform to Plan A first.
if (navigator.mozGetUserMedia) {
description = this.interop.toUnifiedPlan(description);
this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
}
var self = this;
this.peerconnection.setLocalDescription(description,
function () {
self.trace('setLocalDescriptionOnSuccess');
successCallback();
},
function (err) {
self.trace('setLocalDescriptionOnFailure', err);
failureCallback(err);
}
);
/*
if (this.statsinterval === null && this.maxstats > 0) {
// start gathering stats
}
*/
};
TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
this.trace('setRemoteDescription::preTransform', dumpSDP(description));
// TODO the focus should squeze or explode the remote simulcast
description = this.simulcast.mungeRemoteDescription(description);
this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
// if we're running on FF, transform to Plan A first.
if (navigator.mozGetUserMedia) {
description = this.interop.toUnifiedPlan(description);
this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
}
var self = this;
this.peerconnection.setRemoteDescription(description,
function () {
self.trace('setRemoteDescriptionOnSuccess');
successCallback();
},
function (err) {
self.trace('setRemoteDescriptionOnFailure', err);
failureCallback(err);
}
);
/*
if (this.statsinterval === null && this.maxstats > 0) {
// start gathering stats
}
*/
};
TraceablePeerConnection.prototype.close = function () {
this.trace('stop');
if (this.statsinterval !== null) {
window.clearInterval(this.statsinterval);
this.statsinterval = null;
}
this.peerconnection.close();
};
TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
var self = this;
this.trace('createOffer', JSON.stringify(constraints, null, ' '));
this.peerconnection.createOffer(
function (offer) {
self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
// if we're running on FF, transform to Plan B first.
// NOTE this is not tested because in meet the focus generates the
// offer.
if (navigator.mozGetUserMedia) {
offer = self.interop.toPlanB(offer);
self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
}
if (config.enableSimulcast && self.simulcast.isSupported()) {
offer = self.simulcast.mungeLocalDescription(offer);
self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
}
successCallback(offer);
},
function(err) {
self.trace('createOfferOnFailure', err);
failureCallback(err);
},
constraints
);
};
TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
var self = this;
this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
this.peerconnection.createAnswer(
function (answer) {
self.trace('createAnswerOnSuccess::preTransfom', dumpSDP(answer));
// if we're running on FF, transform to Plan A first.
if (navigator.mozGetUserMedia) {
answer = self.interop.toPlanB(answer);
self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
}
if (config.enableSimulcast && self.simulcast.isSupported()) {
answer = self.simulcast.mungeLocalDescription(answer);
self.trace('createAnswerOnSuccess::postTransfom (simulcast)', dumpSDP(answer));
}
successCallback(answer);
},
function(err) {
self.trace('createAnswerOnFailure', err);
failureCallback(err);
},
constraints
);
};
TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
var self = this;
this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
this.peerconnection.addIceCandidate(candidate);
/* maybe later
this.peerconnection.addIceCandidate(candidate,
function () {
self.trace('addIceCandidateOnSuccess');
successCallback();
},
function (err) {
self.trace('addIceCandidateOnFailure', err);
failureCallback(err);
}
);
*/
};
TraceablePeerConnection.prototype.getStats = function(callback, errback) {
if (navigator.mozGetUserMedia) {
// ignore for now...
if(!errback)
errback = function () {
}
this.peerconnection.getStats(null,callback,errback);
} else {
this.peerconnection.getStats(callback);
}
};
module.exports = TraceablePeerConnection;
| NxTec/jitsi-meet | modules/xmpp/TraceablePeerConnection.js | JavaScript | mit | 12,032 |
export default function (arr, cb) {
var len = arr.length;
while (len--) {
cb(arr[len], len, arr) || arr.splice(len, 1);
}
return arr;
}
| lukeed/arr | packages/filter.mutate/module.js | JavaScript | mit | 144 |
(function (module, undefined) {
module.factory('mgPut', function () {
return {
as: 'put',
init: 'put.model=edit.model',
method: 'put',
service: 'mgHttp',
before: 'mgBeforeHttpFactory',
success: 'mgSuccessFactoryCreate',
error: 'mgErrorHttpFactory',
cmd: 'mgCommandCreate',
ajaxCmd: 'accept'
};
});
})(angular.module('mgCrud'));
| MagicCrudAngular/mgCrud | src/factories/mgPutFactory.js | JavaScript | mit | 481 |
webpackJsonp([0x7ecaebe5ee9f],{573:function(t,o){t.exports={data:{markdownRemark:{html:'<p>Always nice to see something working out of the box.</p>\n<p>Big ups shout out mad respect honor from most high Jah Rastafari to this excellent resource <a href="https://www.gatsbyjs.org/blog/2017-07-19-creating-a-blog-with-gatsby/">Creating a Blog with Gatsby</a> by Dustin Schau.</p>\n<p>All previous posts have been migrated over from my old Jekyll blog.</p>\n<p>I love you.</p>',frontmatter:{date:"January 28, 2018",path:"/blog/hello-world/",title:"Gatsby Post No.1",type:"blog"}}},pathContext:{}}}});
//# sourceMappingURL=path---blog-hello-world-ea22df2bfa5f8194dcfd.js.map | russellschmidt/russellschmidt.github.io | path---blog-hello-world-ea22df2bfa5f8194dcfd.js | JavaScript | mit | 669 |
var Hapi = require('hapi');
'use strict';
var server = new Hapi.Server();
server.register({
register: require('good'),
options: {
reporters: [
new GoodWinston({
ops: '*',
request: '*',
response: '*',
log: '*',
error: '*'
}, winston)
]
}
}, function(err) {
if(err) {
return server.log(['error'],'good load error: ' + err);
}
});
if( process.env.PORT ) {
server.connection({ port: process.env.PORT });
}
else {
server.connection({ port: 1337 });
}
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello, world!');
}
});
server.route({
method : "GET",
path : '/assets/{param*}',
handler : {
directory : {
path : '/bower_components',
listing : true
}
}
});
server.route({
method : "GET",
path : '/{param*}',
handler : {
directory : {
path : '/public',
listing : true
}
}
});
server.route({
method: 'GET',
path: '/{name}',
handler: function (request, reply) {
reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
}
});
server.start(function () {
console.log('Server running at:', server.info.uri);
});
var GoodWinston = require('good-winston');
var winston = require('winston');
| mike1337/elekta | server.js | JavaScript | mit | 1,301 |
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _transducerBase = require('../transducer/Base');
var _functionalCurry = require('../functional/curry');
var _typeIsTransformer = require('../type/isTransformer');
var _reduce = require('./reduce');
var _slice = require('./slice');
var LastWhileTaker = (function (_Base) {
_inherits(LastWhileTaker, _Base);
function LastWhileTaker(fn, xf) {
_classCallCheck(this, LastWhileTaker);
_get(Object.getPrototypeOf(LastWhileTaker.prototype), 'constructor', this).call(this);
this.fn = fn;
this.storage = [];
this.xf = xf;
}
_createClass(LastWhileTaker, [{
key: '@@transducer/step',
value: function transducerStep(result, input) {
if (this.fn(input)) {
this.storage[this.storage.length] = input;
} else {
this.storage.length = 0;
}
return result;
}
}, {
key: '@@transducer/result',
value: function transducerResult(result) {
var step = this.xf['@@transducer/step'].bind(this);
return (0, _reduce.reduce)(step, result, this.storage);
}
}, {
key: 'lastElements',
value: function lastElements() {
return this.moreThanN ? [].concat(_toConsumableArray((0, _slice.slice)(this.pos, this.n, this.storage)), _toConsumableArray((0, _slice.slice)(0, this.pos, this.storage))) : (0, _slice.slice)(0, this.pos, this.storage);
}
}]);
return LastWhileTaker;
})(_transducerBase.Base);
var _takeLastWhile = function _takeLastWhile(_x4, _x5, _x6) {
var _again2 = true;
_function2: while (_again2) {
var fn = _x4,
xs = _x5,
pos = _x6;
_again2 = false;
if (pos === -1) {
return xs;
} else {
if (fn(xs[pos])) {
_x4 = fn;
_x5 = xs;
_x6 = pos - 1;
_again2 = true;
continue _function2;
} else {
return xs.slice(pos + 1, Infinity);
}
}
}
};
var takeLastWhile = (0, _functionalCurry.curry)(function (fn, xf) {
return (0, _typeIsTransformer.isTransformer)(xf) ? new LastWhileTaker(fn, xf) : _takeLastWhile(fn, xf, xf && xf.length - 1);
});
exports.takeLastWhile = takeLastWhile; | gonzaloruizdevilla/alicates | lib/modules/list/takeLastWhile.js | JavaScript | mit | 4,266 |
import path from 'path';
import fs from 'fs';
import { introspectSchema } from '@graphql-tools/wrap';
import { printSchema } from 'graphql/utilities';
import executor from '../graphql/cofactsSchemaExecutor';
const PATH_PREFIX = '../graphql';
const OUTPUT = path.join(__dirname, `${PATH_PREFIX}/cofacts-api.graphql`);
introspectSchema(executor)
.then(schema => {
const sdl = printSchema(schema);
fs.writeFileSync(
OUTPUT,
'# Generated from `npm run cofactsapi`\n\n' + sdl,
{
encoding: 'utf-8',
}
);
console.log('Cofacts API schema written to', OUTPUT);
})
.catch(console.error);
| cofacts/rumors-line-bot | src/scripts/introspectCofactsApi.js | JavaScript | mit | 635 |
// https://www.reddit.com/r/dailyprogrammer/comments/pihtx/intermediate_challenge_1/
"use strict"
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let events = [];
let lastIndex = 0;
const clearTerminal = () => {
//rl.write('\x1Bc');
rl.write(null, {ctrl: true, name:"l"});
}
const chooseMainCommand = () => {
rl.write(`Available commands:
a - Add a new event
d - Delete an existing event
e - Edit an existing event
q - Quit the program\n`);
rl.question("Which command do you choose? - ", (command) => {
switch (command) {
case "a":
showAddMenu();
break;
case "d":
showDeleteMenu();
break;
case "e":
showEditMenu();
break;
case "q":
rl.close();
break;
default:
rl.write("Unknown command. Please select another.\n");
chooseMainCommand();
break;
}
})
}
const validEventFormat = (eventString) => {
let data = eventString.split(" ");
if (isNaN(data[1]) || parseInt(data[1] < 0 || parseInt(data[1] > 23)))
return false;
if (isNaN(data[2]) || parseInt(data[2] < 0 || parseInt(data[2] > 59)))
return false;
return true;
}
const sortEvents = () => {
events.sort((a,b) => {
return (a.hour*60+b.minute)-(b.hour*60+b.minute);
})
}
const showEditMenu = () => {
clearTerminal();
rl.question("What event do you want to edit? Give me its id - ", id => {
let found = events.some(element => {
return element.id == id;
})
if (!found) {
rl.question("The given id couldn't be found. Returning to the main menu.",() => {
showMainMenu();
})
}
rl.question("Please enter the edited data for the event (format: 'name hour minute')! - ", event => {
if (validEventFormat(event)) {
let data = event.split(" ");
events = events.map(element => {
if (element.id == id) {
return {
id: id,
title: data[0],
hour: parseInt(data[1]),
minute: parseInt(data[2])
}
} else {
return element;
}
});
sortEvents();
showMainMenu();
} else {
rl.question("Invalid format. Returning to main menu.",() => {
showMainMenu();
})
}
});
})
}
const showDeleteMenu = () => {
clearTerminal();
rl.question("What event do you want to be deleted? Give me its id - ", id => {
events = events.filter(element => {
return element.id != id;
});
showMainMenu();
});
}
const showAddMenu = () => {
clearTerminal();
rl.question("What event do you want to add (format: 'name hour minute')? - ", event => {
if (validEventFormat(event)) {
let data = event.split(" ");
events.push({
id: lastIndex++,
title: data[0],
hour: parseInt(data[1]),
minute: parseInt(data[2])
});
sortEvents();
showMainMenu();
} else {
rl.question("Invalid format. Returning to main menu.",() => {
showMainMenu();
})
}
});
}
const showMainMenu = () => {
clearTerminal();
rl.write("Welcome to this simple and small event organizer.\n");
rl.write(`
List of existing events
#######################
`);
if (events.length == 0) {
rl.write("There are currently no events available.\n")
} else {
events.forEach(event => {
rl.write(`${event.id} - ${event.hour}:${event.minute} "${event.title}"\n`);
})
}
rl.write("\n");
chooseMainCommand();
}
showMainMenu(); | Nuri0/dailyprogrammer | challenges/001/intermediate.js | JavaScript | mit | 4,225 |
import { StyleSheet } from 'react-native';
import { colors } from '../../config/styles';
export default styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: colors.background,
},
});
| abhaytalreja/react-native-telescope | RNApp/app/components/Loading/styles.js | JavaScript | mit | 267 |
delete process.env.BROWSER
const env = process.env.NODE_ENV || 'development'
const path = require('path')
const modulePath = require('app-module-path')
modulePath.addPath(path.join(__dirname, '../../'))
if (env !== 'production') {
modulePath.addPath(path.join(__dirname, '../../src'))
} else {
modulePath.addPath(path.join(__dirname, '../../lib'))
}
modulePath.addPath(path.join(__dirname, '../../styles'))
require('babel-core/register');
require('babel-polyfill');
const app = require('./koa.js')
module.exports = app
| lancetw/react-isomorphic-bundle | src/server/index.js | JavaScript | mit | 530 |
/**
* Created by Martin on 2017/11/10.
*/
class MXRResponseModel
{
constructor() {
this.header = new MXRResponseHeaderModel();
this.body = '';
this.notCoder = 1;
this.type = '';
}
isSuccess() {
return this.header.errCode == 0;
}
toMXRString() {
const json = {Header:{ErrCode:this.header.errCode, ErrMsg:this.header.errMsg}, Body: this.body, notCoder: this.notCoder, type: this.type};
return JSON.stringify(json);
}
}
class MXRResponseHeaderModel{
constructor() {
this.errCode = 0;
this.errMsg = '';
}
setErrCode(errCode) {
this.errCode = errCode;
}
}
module.exports = MXRResponseModel; | liulongdev/MyNodeServerPro | server/models/mxr_response_model.js | JavaScript | mit | 712 |
const simpleboard = require('../');
const assert = require('assert');
// putCells and clear
{
const board = simpleboard.createBoard();
const content1 = { color: 1 };
const content2 = { color: 2 };
const content3 = { color: 1 };
board.put(0, 0, content1);
board.put(1, 1, content2);
board.put(2, 1, content3);
board.remove(1, 1);
const positions = board.getPositions();
assert.ok(positions);
assert.equal(positions.length, 2);
assert.equal(positions[0].x, 0);
assert.equal(positions[0].y, 0);
assert.equal(positions[0].content, content1);
assert.equal(positions[1].x, 2);
assert.equal(positions[1].y, 1);
assert.equal(positions[1].content, content3);
}
| ajlopez/SimpleBoard | test/clear.js | JavaScript | mit | 762 |
'use strict';
module.exports = {
/////////////////////
// MUTABLE OPTIONS ////////////////////////////////
// YOU CAN CHANGE THIS OPTIONS ALL THE TIME //
// //
// You need to restart builder to apply options. //
///////////////////////////////////////////////////
/**
* Postprocessors for TARS
* @type {Array}
* Example:
*
* postcss: [
* {
* name: 'postcss-short',
* options: {
* deny: ['text']
* }
* }
* ]
*/
postcss: [],
svg: {
active: true,
// symbols, sprite
workflow: 'sprite',
symbolsConfig: {
// separate-file, separate-file-with-link, inject
loadingType: 'inject',
usePolyfillForExternalSymbols: true,
pathToExternalSymbolsFile: ''
}
},
css: {
// concat, manual
workflow: 'manual'
},
js: {
// concat, modular
workflow: 'modular',
// Only webpack is available right now
bundler: 'webpack',
/**
* Use linting of js-files
* @type {Boolean}
*/
lint: false,
/**
* Use babel for ES6(ES7-ESNext) syntax support
* @type {Boolean}
*/
useBabel: true,
/**
* Use TypeScript for ES6(ES7-ESNext) syntax support
* @type {Boolean}
*/
useTypeScript: false,
/**
* Remove console.log and debugger from js code in release mode
* @type {Boolean}
*/
removeConsoleLog: false,
// Special config for webpack
webpack: {
useHMR: false,
/**
* Automatically loaded modules.
* Module (value) is loaded when the identifier (key) is used as free variable in a module.
* The identifier is filled with the exports of the loaded module.
* Example: {$: "jquery"} or {React: 'react'}
* @type {Object}
*/
providePlugin: {}
},
/**
* Path-strings to js-files, which have to be included before modules' js-files
* Example: ['./markup/controller/** /*.js']
* @type {Array}
*/
jsPathsToConcatBeforeModulesJs: [],
/**
* Lint additional js before modules
* @type {Boolean}
*/
lintJsCodeBeforeModules: false,
/**
* Path-strings to js-files, which have to be included before modules' js-files
* @type {Array}
*/
jsPathsToConcatAfterModulesJs: [],
/**
* Lint additional js after modules
* @type {Boolean}
*/
lintJsCodeAfterModules: false
},
/**
* Write sourcemaps
* @type {Object}
*
* active – is sourcemaps active
* inline – use inline sourcemaps or in separate file
*/
sourcemaps: {
js: {
active: true,
inline: true
},
css: {
active: true,
inline: true
}
},
/**
* Config for Notify module
* @type {Object}
*/
notifyConfig: {
/**
* Do you need to use notify?
* @type {Boolean}
*/
useNotify: false,
/**
* Title for notifier
* @type {String}
*/
title: 'TARS notification',
/**
* Sounds notifactions
* String (name of system sound) or undefined, if you don't need to hear any sounds
* @type {Object}
*/
sounds: {
/**
* Sound after successfull finishing of task
* @type {String, undefined}
* For example 'Glass' in OS X
*/
onSuccess: undefined,
/**
* Sound after failed finishing of task
* @type {String, undefined}
* For example 'Glass' in OS X
*/
onError: undefined
},
/**
* Label for timestamp of task finishing time
* @type {String}
*/
taskFinishedText: 'Task finished at: '
},
/**
* Minify result html in build version
* If is set to false, compiled html will be prettified
* @type {Boolean}
*/
minifyHtml: false,
/**
* TARS will generate relative path from current page
* to static files in case of true value
* @type {Boolean}
*/
generateStaticPath: true,
/**
* Path to build version of project
* Could be like '../../../build' or absolute path
* @type {String}
*/
buildPath: './builds/',
/**
* Use build versioning
* Build version is a date ot building
* @type {Boolean}
*/
useBuildVersioning: false,
/**
* Use archiver for your build
* @type {Boolean}
*/
useArchiver: false,
/**
* Set ulimit. Topical for Linux-family OS and OSX.
* @type {Number}
*/
ulimit: 4096,
//////////////////////////////////////////////
//////////////////////////////////////////////
////////////////////////////////////////////////////////
// YOU CAN CHANGE THIS OPTIONS AND USE REINIT //
// //
// Options for technologies, which you'd like to use. //
////////////////////////////////////////////////////////
/**
* Templater
* Available 'pug', 'jade' and 'handlebars'
* @type {String}
*/
templater: 'handlebars',
/**
* Css-preprocessor
* Available 'scss', 'less' or 'stylus'
* .sass extension is supported if cssPreprocessor is 'scss'
* @type {String}
*/
cssPreprocessor: 'scss',
/**
* What kind of size of images are you going to use.
* 96 — 1 dppx (regular)
* 192 — 2 dppx (retina)
* 288 — 3 dppx (nexus 5, for example)
* 384 - 4 dppx (nexus 6, for example)
* Example if using for all displays: usePpi: [96, 192, 288, 384]
* You can change with options not only on init or reinit,
* but at with time you have to create new directories
* and delete unused.
* @type {Array}
*/
useImagesForDisplayWithDpi: [96],
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////////////
// You have to change with options after manually //
// renaming static and img folder //
// //
// Do not rename these dirs before reinit //
////////////////////////////////////////////////////////
/**
* File structure settings
* @type {Object}
*/
fs: {
/**
* Name of folder with static files, such *.css, *.js and so on
* 'static' by default
* @type {String}
*/
staticFolderName: 'assets',
/**
* Name of folder with images
* 'img' by default
* @type {String}
*/
imagesFolderName: 'img',
/**
* Name of folder with modules
* 'modules' by default
* @type {String}
*/
componentsFolderName: 'components'
}
////////////////////////////////////////////////////
////////////////////////////////////////////////////
};
| dmytrous/xim | tars-config.js | JavaScript | mit | 7,576 |
import React from 'react';
const VideoDetail = ({video})=> {
if (!video) {
return <div> Loading ... </div>;
}
const videoId = video.id.videoId;
const url = `http://www.youtube.com/embed/${videoId}`;
return (
<div className="video-detail col-md-8">
<div className="embed-responsive embed-responsive-16by9">
<iframe className="embed-responsive-item" src={url}></iframe>
</div>
<div className="details">
<div>{video.snippet.title}</div>
<div>{video.snippet.description}</div>
</div>
</div>
);
}
export default VideoDetail;
| yongliu2001/ReduxExample | src/components/video_detail.js | JavaScript | mit | 595 |
/**
*
* Asynchronously loads the component for Navigation
*
*/
import Loadable from 'react-loadable';
export default Loadable({
loader: () => import('./index'),
loading: () => null,
});
| dreamweaver1231/react-project | app/components/Navigation/Loadable.js | JavaScript | mit | 196 |
'use strict'
const assert = require('chai').assert
const uuid = require('uuid').v4
const getStatus = require('../../src/selectors/getStatus')
describe('getStatus()', function() {
it('should return null when config is missing', function() {
const component = {
data: []
}
const status = getStatus(component)
assert.strictEqual(status, null)
})
it('should return null when config data is missing', function() {
const component = {
data: [
{
id: 'config'
}
]
}
const status = getStatus(component)
assert.strictEqual(status, null)
})
it('should return null when status is missing', function() {
const component = {
data: [
{
id: 'config',
data: {}
}
]
}
const status = getStatus(component)
assert.strictEqual(status, null)
})
it('should return status', function() {
const component = {
data: [
{
id: 'config',
data: {
status: uuid()
}
}
]
}
const status = getStatus(component)
assert.strictEqual(status, component.data[0].data.status)
})
}) | comwrap/rosid-handler-components | test/selectors/getStatus.js | JavaScript | mit | 1,080 |
/**
* @fileoverview Enforce all aria-* properties are valid.
* @author Ethan Cohen
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
import { aria } from 'aria-query';
import { propName } from 'jsx-ast-utils';
import { generateObjSchema } from '../util/schemas';
import getSuggestion from '../util/getSuggestion';
const ariaAttributes = [...aria.keys()];
const errorMessage = (name) => {
const suggestions = getSuggestion(name, ariaAttributes);
const message = `${name}: This attribute is an invalid ARIA attribute.`;
if (suggestions.length > 0) {
return `${message} Did you mean to use ${suggestions}?`;
}
return message;
};
const schema = generateObjSchema();
export default {
meta: {
docs: {
url: 'https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/tree/HEAD/docs/rules/aria-props.md',
},
schema: [schema],
},
create: (context) => ({
JSXAttribute: (attribute) => {
const name = propName(attribute);
// `aria` needs to be prefix of property.
if (name.indexOf('aria-') !== 0) {
return;
}
const isValid = ariaAttributes.indexOf(name) > -1;
if (isValid === false) {
context.report({
node: attribute,
message: errorMessage(name),
});
}
},
}),
};
| evcohen/eslint-plugin-jsx-a11y | src/rules/aria-props.js | JavaScript | mit | 1,427 |
var Books = require('./../models/Books.js');
exports.bookAdd = function(req, res) {
console.log('------------req.params.name:'+ req.params.name);
if(req.params.name){ //update
return res.render('admin_add', {
title:req.params.name+'|书籍|管理|1',
label:'编辑书籍:'+req.params.name,
book:req.params.name
});
} else {
return res.render('admin_add',{
title:'新增加|书籍|管理| 2',
label:'新增书籍',
book:false
});
}
};
exports.doBookAdd = function(req, res) {
var obj = req.body
var catId = obj.category
var catName = obj.categoryName
var _book = new Books(obj)
_book.save(function(err, data){
if(err){
console.log(err)
}
console.log(data)
})
/*
Books.findOne({name: obj.name}, function(err, book){
console.log('111');
});
Books.term_save(obj, function(err, tmer){
if(err) {
console.log(err);
} else {
var _id = tmer._id;
obj.category = _id;
Books.save(obj, function(err, book){
if(err) {
res.redirect('/');
} else {
res.redirect('/detail/'+ book.bId);
}
});
}
});
*/
};
/*
exports.bookJSON = function(req, res) {
Books.findByName(req.params.name,function(err, obj){
res.send(obj);
});
}
*/
exports.detail = function(req, res) {
console.log('req.params.bId:' + req.params.bId);
Books.findByBid(req.params.bId, function(err, obj){
if(err){
console.log('读取失败');
}else {
console.log('读取成功');
}
//res.send(obj);
//res.render('/detail', { title: '详情页', data: obj });
//return obj;
res.render('detail', { title: obj.name + ' | 天天书屋' , json: obj });
});
}
exports.bookHomePage = function(req, res){
console.log('req:' + req);
console.log('res:' + res);
Books.findNewTen(function(err, obj){
if(err){
console.log('读取失败');
}else {
console.log('读取成功22');
}
res.render('', { title: '首页 | 天天书屋' , json: obj });
});
}
| leeggco/node-books | routes/books.js | JavaScript | mit | 2,358 |
net = require('net');
http = require('http');
// global variables
clientList = [];
// Autogenerated with DRAKON Editor 1.22
function Main() {
// item 4
console.log("DRAKON-Javascript chat server");
console.log("=============================");
// item 13
var server = net.createServer( handleConnection ),
port = Number(process.env.PORT || 8080);
// item 30
server.listen(port);
console.log("listening on port " + port);
}
function addClient(socket) {
// item 170
clientList.push(socket);
}
function broadcastToRoom(room, message) {
// item 53
if (room) {
// item 58
var clients = clientsInRoom(room),
i = 0,
length = clients.length;
// item 560001
i = 0
while (true) {
// item 560002
if (i < length) {
} else {
break;
}
// item 59
sendMessage(clients[i], message);
// item 560003
i +=1
}
} else {
}
}
function catfactHandler(socket, data) {
// item 268
http.get("http://catfacts-api.appspot.com/api/facts?number=1", function(res) {
res.on('data', function(chunk) {
var fact = JSON.parse(chunk)['facts'][0];
sendMessage(socket, fact);
});
});
}
function chomp(str) {
// item 155
return str.replace(/\r?\n|\r/, "");
}
function clientsInRoom(room) {
// item 172
var length = clientList.length,
clients = [],
client;
// item 2480001
i = 0
while (true) {
// item 2480002
if (i < length) {
} else {
break;
}
// item 252
if (room == clientList[i].room) {
// item 250
clients.push(clientList[i])
} else {
}
// item 2480003
i+=1
}
// item 251
return clients;
}
function findClientByName(name) {
// item 210
var client;
// item 2550001
var i = 0
while (true) {
// item 2550002
if (i < length) {
} else {
break;
}
// item 258
if (clientList[i].name == name) {
// item 261
client = clientList[i];
break;
} else {
}
// item 2550003
i+=1
}
// item 262
return client;
}
function handleConnection(socket) {
// item 19
console.log('connection established');
sendMessage(socket, "Welcome to the XYZ chat server");
sendMessage(socket, "Login Name?");
addClient(socket);
socket.on('data', function(data) { onDataReceived(socket, data) });
socket.on('end', function() { onSocketEnd(socket) });
}
function isUniqueName(name) {
// item 198
if (!name) {
return false;
}
var client;
for (var idx in clientList) {
client = clientList[idx];
if (client.name == name) {
return false;
}
}
return true;
}
function joinHandler(socket, data) {
// item 164
if (!data) {
sendMessage(socket, "Invalid room name");
return;
}
broadcastToRoom(data, "* new user joined chat: " + socket.name);
var clients = clientsInRoom(data),
names = [],
client, msg, name;
for (var idx in clients) {
client = clients[idx];
names.push(client.name);
}
msg = "entering room: " + data;
if (names.length) {
for (var idx in names) {
name = names[idx];
msg += "\n * " + name;
}
msg += "\nend of list";
}
sendMessage(socket, msg);
socket.room = data;
}
function leaveHandler(socket, data) {
// item 192
leaveRoom(socket, data);
}
function leaveRoom(socket, data) {
// item 234
if (socket.room) {
// item 191
broadcastToRoom(socket.room, "user has left chat: " + socket.name);
delete(socket.room);
} else {
}
}
function messageHandler(socket, data) {
// item 244
if (socket.room) {
// item 171
msg = socket.name + ': ' + data;
broadcastToRoom(socket.room, msg)
} else {
// item 247
msg = "Nobody hears you. (Try joining a room: `/join <room>`!)";
sendMessage(socket, msg);
}
}
function onDataReceived(socket, data) {
// item 89
packetHandler(socket, chomp(data.toString()));
}
function onSocketEnd(socket) {
// item 39
leaveRoom(socket, null);
removeClient(socket);
}
function packetHandler(socket, data) {
// item 215
if (socket.name) {
} else {
// item 216
setNameHandler(socket, data);
return;
}
// item 240
if (data.toString()[0] != "/") {
} else {
// item 241
var split = data.indexOf(' ');
if (split == -1) {
split = data.length;
}
var keyword = data.substr(1, split - 1);
var args = data.substr(split + 1);
try {
//eval? DEAL WITH IT (╯°□°)╯︵ ┻━┻)
eval(keyword + 'Handler(socket, args)');
} catch(e) { }
return;
}
// item 222
messageHandler(socket, data);
return;
}
function quitHandler(socket, data) {
// item 185
leaveRoom(socket, data);
sendMessage(socket, "BYE");
removeClient(socket);
try {
socket.destroy();
} catch(e) {}
}
function removeClient(socket) {
// item 65
clientList.splice(clientList.indexOf(socket), 1);
}
function roomNames() {
// item 157
var names = [];
var room;
for (var client in clientList) {
room = clientList[client].room;
if (room != null) {
if (names[room]) {
names[room] = names[room] + 1;
} else {
names[room] = 1;
}
}
}
var resp = [];
for (var name in names) {
resp.push(name + ' (' + names[name] + ')');
}
return resp;
}
function roomsHandler(socket, data) {
// item 156
var names = roomNames();
var msg = "";
// item 159
if (names.length == 0) {
// item 158
msg = "There are no active rooms. `/join <name>` one!";
} else {
// item 163
msg = "Active rooms are:\n"
var length = names.length;
for (var i = 0; i < length; i += 1) {
msg += " * " + names[i];
}
msg += "\nend of list.";
}
// item 162
sendMessage(socket, msg);
}
function sendMessage(client, message) {
// item 77
try {
client.write(message + "\n");
} catch (e) {
console.log("Socket write exception: " + e);
removeClient(client);
}
}
function setName(socket, data) {
// item 272
var name = data.replace(/\s/g, '_');
// item 269
if (isUniqueName(name)) {
// item 173
socket.name = name;
} else {
}
// item 273
return socket.name;
}
function setNameHandler(socket, data) {
// item 229
if (setName(socket, data)) {
// item 232
sendMessage(socket, "Welcome " + socket.name + "!");
} else {
// item 233
sendMessage(socket, "Sorry, name taken.");
sendMessage(socket, "Login Name?");
}
}
function whisperHandler(socket, data) {
// item 204
var split = data.indexOf(' ');
if (split == -1) {
split = data.length;
}
var name = data.substr(0, split);
var client = findClientByName(name);
if (client != socket) {
var message = socket.name + ': ' + data.substr(split + 1);
if (client) {
sendMessage(socket, '(whisper to ' + client.name + ') ' + message);
sendMessage(client, '(whisper)' + socket.name + ') ' + message);
} else {
sendMessage(socket, "That user cannot be found.");
}
} else {
sendMessage(socket, "You whisper to yourself.");
}
}
Main();
| stavro/drakon-node-chat | chat.js | JavaScript | mit | 8,165 |
import React from 'react';
import CreatePhoto from './CreatePhoto';
import { mount } from 'enzyme';
describe('CreatePhoto', () => {
let sut,
getPicture;
const image = {};
beforeEach(() => {
getPicture = env.spy();
});
it('should open gallery pop-up on click', () => {
sut = mount(<CreatePhoto image={image} />);
sut.find('.create-photo').simulate('click');
const checkAssertion = () => getPicture.should.not.been.called;
checkAssertion();
});
describe('On Device', () => {
const DATA_URL = 'DATA_URL';
const PHOTOLIBRARY = 'PHOTOLIBRARY';
beforeEach(() => {
getPicture = env.spy();
window.navigator.camera = {
getPicture,
DestinationType: {
DATA_URL
},
PictureSourceType: {
PHOTOLIBRARY
}
};
sut = mount(<CreatePhoto image={image} />);
});
it('should return image in base-64 format', () => {
sut.find('.create-photo').simulate('click');
const cameraOptions = getPicture.lastCall.args[2];
cameraOptions.destinationType.should.equal(DATA_URL);
});
it('should return image from Gallery', () => {
sut.find('.create-photo').simulate('click');
const cameraOptions = getPicture.lastCall.args[2];
cameraOptions.sourceType.should.equal(PHOTOLIBRARY);
});
it('should set image to form data', () => {
sut.find('.create-photo').simulate('click');
const onSuccessCallBack = getPicture.lastCall.args[0];
const imageData = 'imageData';
onSuccessCallBack(imageData);
sut.find('.create-photo').get(0).value.should.equal(imageData);
});
});
});
| travel-and-help/start-kit | src/front/app/common/components/create/CreatePhoto.spec.js | JavaScript | mit | 1,898 |
version https://git-lfs.github.com/spec/v1
oid sha256:689ac19a07a12cbde782eecd200457f2e48553cb7fdb81a33d076d889344d0c8
size 112554
| yogeshsaroya/new-cdnjs | ajax/libs/mocha/1.12.0/mocha.js | JavaScript | mit | 131 |
var trackByIndexModel = new Vue({
el: "#app",
data: {
items: [{
_uid: '88f869d',
message: 'foo'
}, {
_uid: '7496c10',
message: 'bar'
}]
}
})
| igeligel/vuejs-guide | list-rendering/array-change-detection/track-by-index.js | JavaScript | mit | 225 |
var TaskQueue = require('../lib/taskQueue');
exports.testAsyncTasks = function(test) {
var taskCount = 5;
var queue = new TaskQueue();
test.expect(1);
count = 0;
for (i = 0; i < taskCount; i++) {
queue.addTask(function(queue) {
setTimeout(function() {
queue.next();
count++;
if (count === taskCount) {
test.ok(true, "ran all tasks");
test.done();
}
}, 500);
});
}
};
exports.testSyncTasks = function(test) {
var taskCount = 5;
var queue = new TaskQueue();
test.expect(1);
count = 0;
for (i = 0; i < taskCount; i++) {
queue.addTask(function(queue) {
count++;
queue.next();
});
}
test.ok(count === taskCount, "ran all tasks");
test.done();
};
| bkcpuclub/msgbox | test/taskQueue._test.js | JavaScript | mit | 997 |
/* eslint-disable no-console */
/* eslint-disable comma-dangle */
/* eslint-disable function-paren-newline */
import browserSync from 'browser-sync'
import compression from 'compression'
import chalk from 'chalk'
const env = process.env.NODE_ENV
const bs = browserSync.create()
bs.init({
server: {
baseDir: ['build'],
middleware: [
compression(),
],
},
port: 4000,
ui: {
port: 4001,
},
open: false,
reloadOnRestart: true,
single: true,
})
bs.emitter.on('init', () => {
console.log(chalk.green(
`[Browsersync] Browsersync server is running.
[Browsersync] NODE_ENV is set to ${chalk.white.bold(env)}.
[Browsersync] Access URLs are listed below.
`
))
})
| stsiarzhanau/webpack-react-redux-starter | tools/prodServer.js | JavaScript | mit | 712 |
function GetKeyValueRow(table, data, field, better_name) {
if (data.hasOwnProperty(field)) {
AddRow(table, better_name, data[field])
}
}
function AddRow(table, key, value) {
row = $("<tr>");
col1 = $("<td>");
col1.text(key);
col2 = $("<td>");
col2.text(value)
row.append(col1);
row.append(col2);
table.append(row);
}
function processResultController($scope) {
result = $scope.result;
var table = angular.element('table')
GetKeyValueRow(table, result, 'serial-number', 'Serial Number');
case_header = result['case-file-header'];
GetKeyValueRow(table, case_header, 'mark-identification', 'Word Mark');
GetKeyValueRow(table, case_header, 'domestic-representative-name', 'Attorney of Record');
statements = result['case-file-statements']
console.log(statements);
text = ''
if (statements.hasOwnProperty('case-file-statement')) {
statement = statements['case-file-statement'];
console.log(statement)
for (var i = 0; i < statement.length; i++) {
text += statement[i]['text'];
text +='\n'
}
}
if (text != '') {
AddRow(table, "Trademark Text", text)
}
text = ''
if (result.hasOwnProperty('correspondent')) {
address = result['correspondent'];
text = address['address-1'] + '\t' + address['address-2']
+ address['address-3'] + '\t' + address['address-4']
}
AddRow(table, "Correspondent", text)
}
| xuy/tms | frontend/js/display.js | JavaScript | mit | 1,454 |
// check content scripts
chrome.runtime.sendMessage({
action: window.isContentScriptLoaded ? 'onContentReady' : 'injectContentScript'
});
| bubkoo/crx-element-capture | src/js/isLoaded.js | JavaScript | mit | 142 |
"use strict";
angular.module("mixtapes", ["angularSoundManager"]); | oolawo09/booth-to-block | app/mixtapes/mixtapes.module.js | JavaScript | mit | 68 |
'use strict';
/* App Module */
angular.module('pizzaShop', ['pizzaFilters', 'pizzaServices']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/pizzas', {templateUrl: 'partials/pizza-list.html', controller: PizzaListCtrl}).
when('/pizza/:pizzaId', {templateUrl: 'partials/pizza-detail.html', controller: PizzaDetailCtrl}).
when('/order', {templateUrl: 'partials/order.html', controller: OrderCtrl}).
otherwise({redirectTo: '/pizzas'});
}]);
| SergKam/pizzajs | js/app.js | JavaScript | mit | 500 |
'use strict';
/**
* Module dependencies.
*/
var vehicles = require('../controllers/vehicles.server.controller');
module.exports = function(app) {
// Articles collection routes
app.route('/api/vehicles')//.all(vehicletypePolicy.isAllowed)
.get(vehicles.list)
.post(vehicles.create);
// Single article routes
app.route('/api/vehicles/:vehicleId')//.all(vehicletypePolicy.isAllowed)
.get(vehicles.read)
.put(vehicles.update)
.delete(vehicles.delete);
// Finish by binding the article middleware
app.param('vehicleId', vehicles.vehicleById);
}; | GregoryCollett/dispatcha-controller | modules/vehicles/server/routes/vehicles.server.routes.js | JavaScript | mit | 562 |
const renderError = function(error, response) {
response.send(`ERROR: ${error.message}`)
}
module.exports = renderError;
| yaseenagag/pizza-restaurant | src/server/utils.js | JavaScript | mit | 124 |
var Similar = require('../src/similar');
describe("Foreach with one entry", () => {
var similar = new Similar(),
entry = { key: 'stringkey', val: 'stringval' };
similar.list.push(entry);
similar.size = 1;
it("iterates keys", () => {
similar.forEach((val, key) => {
expect(key).toEqual(entry.key);
});
});
it("iterates vals", () => {
similar.forEach((val, key) => {
expect(val).toEqual(entry.val);
});
});
});
describe("Foreach with NaN entries", () => {
var similar = new Similar(),
entries = [
{ key: NaN, val: 'stringval' },
{ key: undefined, val: { b: 2 } },
{ key: NaN, val: null },
{ key: [NaN, 6, '%', { l: 'x'}], val: ['_', 4, { a: 1 }] }
],
i = 0;
entries.forEach(entry => similar.list.push(entry));
similar.size = entries.length;
it("iterates keys", () => {
i = 0;
similar.forEach((val, key) => {
expect(key).toEqual(entries[i].key);
i++;
});
});
it("iterates vals", () => {
i = 0;
similar.forEach((val, key) => {
expect(val).toEqual(entries[i].val);
i++;
});
});
});
describe("Foreach with multiple complex entries", () => {
var similar = new Similar(),
entries = [
{ key: 'stringkey', val: 'stringval' },
{ key: { a: 1 }, val: { b: 2 } },
{ key: undefined, val: null },
{ key: ['a', 6, '%', { l: 'x'}], val: ['_', 4, { a: 1 }] }
],
i = 0;
entries.forEach(entry => similar.list.push(entry));
similar.size = entries.length;
it("iterates keys", () => {
i = 0;
similar.forEach((val, key) => {
expect(key).toEqual(entries[i].key);
i++;
});
});
it("iterates vals", () => {
i = 0;
similar.forEach((val, key) => {
expect(val).toEqual(entries[i].val);
i++;
});
});
}); | thinkloop/map-or-similar | tests/foreach.js | JavaScript | mit | 1,703 |
import { connect } from 'react-redux';
import getGenerationDetails from '../selectors/getGenerationDetails';
import getFoci from '../selectors/getFoci';
import { getAttributes } from '../selectors/simple';
import {
setRank,
setFocus,
purchaseOrUnpurchaseDot
} from '../actions/characterCreationActions';
import Attributes from '../components/Attributes';
const mapStateToProps = state => {
const attributeBonus = getGenerationDetails(state).attributeBonus;
const foci = getFoci(state);
return {
attributes: getAttributes(state),
attributeBonus,
foci
};
};
const mapDispatchToProps = {
setRank,
setFocus,
purchaseOrUnpurchaseDot
};
export default connect(mapStateToProps, mapDispatchToProps)(Attributes);
| TrueWill/embracer | src/containers/AttributesContainer.js | JavaScript | mit | 740 |
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['89',"Tlece.Common.Helpers Namespace","topic_00000000000000CE.html"],['110',"StringExtension Class","topic_00000000000000DE.html"],['111',"Methods","topic_00000000000000DE_methods--.html"]]; | asiboro/asiboro.github.io | vsdoc/toc--/topic_00000000000000DE_methods--.html.js | JavaScript | mit | 294 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("specialchar","sv",{euro:"Eurotecken",lsquo:"Enkelt vänster citattecken",rsquo:"Enkelt höger citattecken",ldquo:"Dubbelt vänster citattecken",rdquo:"Dubbelt höger citattecken",ndash:"Snedstreck",mdash:"Långt tankstreck",iexcl:"Inverterad utropstecken",cent:"Centtecken",pound:"Pundtecken",curren:"Valutatecken",yen:"Yentecken",brvbar:"Brutet lodrätt streck",sect:"Paragraftecken",uml:"Diaeresis",copy:"Upphovsrättstecken",ordf:"Feminit ordningstalsindikator",laquo:"Vänsterställt dubbelt vinkelcitationstecken",
not:"Icke-tecken",reg:"Registrerad",macr:"Macron",deg:"Grader",sup2:"Upphöjt två",sup3:"Upphöjt tre",acute:"Akut accent",micro:"Mikrotecken",para:"Alinea",middot:"Centrerad prick",cedil:"Cedilj",sup1:"Upphöjt en",ordm:"Maskulina ordningsändelsen",raquo:"Högerställt dubbelt vinkelcitationstecken",frac14:"Bråktal - en kvart",frac12:"Bråktal - en halv",frac34:"Bråktal - tre fjärdedelar",iquest:"Inverterat frågetecken",Agrave:"Stort A med grav accent",Aacute:"Stort A med akutaccent",Acirc:"Stort A med circumflex",
Atilde:"Stort A med tilde",Auml:"Stort A med diaresis",Aring:"Stort A med ring ovan",AElig:"Stort Æ",Ccedil:"Stort C med cedilj",Egrave:"Stort E med grav accent",Eacute:"Stort E med aktuaccent",Ecirc:"Stort E med circumflex",Euml:"Stort E med diaeresis",Igrave:"Stort I med grav accent",Iacute:"Stort I med akutaccent",Icirc:"Stort I med circumflex",Iuml:"Stort I med diaeresis",ETH:"Stort Eth",Ntilde:"Stort N med tilde",Ograve:"Stort O med grav accent",Oacute:"Stort O med aktuaccent",Ocirc:"Stort O med circumflex",
Otilde:"Stort O med tilde",Ouml:"Stort O med diaeresis",times:"Multiplicera",Oslash:"Stor Ø",Ugrave:"Stort U med grav accent",Uacute:"Stort U med akutaccent",Ucirc:"Stort U med circumflex",Uuml:"Stort U med diaeresis",Yacute:"Stort Y med akutaccent",THORN:"Stort Thorn",szlig:"Litet dubbel-s/Eszett",agrave:"Litet a med grav accent",aacute:"Litet a med akutaccent",acirc:"Litet a med circumflex",atilde:"Litet a med tilde",auml:"Litet a med diaeresis",aring:"Litet a med ring ovan",aelig:"Bokstaven æ",
ccedil:"Litet c med cedilj",egrave:"Litet e med grav accent",eacute:"Litet e med akutaccent",ecirc:"Litet e med circumflex",euml:"Litet e med diaeresis",igrave:"Litet i med grav accent",iacute:"Litet i med akutaccent",icirc:"LItet i med circumflex",iuml:"Litet i med didaeresis",eth:"Litet eth",ntilde:"Litet n med tilde",ograve:"LItet o med grav accent",oacute:"LItet o med akutaccent",ocirc:"Litet o med circumflex",otilde:"LItet o med tilde",ouml:"Litet o med diaeresis",divide:"Division",oslash:"ø",
ugrave:"Litet u med grav accent",uacute:"Litet u med akutaccent",ucirc:"LItet u med circumflex",uuml:"Litet u med diaeresis",yacute:"Litet y med akutaccent",thorn:"Litet thorn",yuml:"Litet y med diaeresis",OElig:"Stor ligatur av OE",oelig:"Liten ligatur av oe",372:"Stort W med circumflex",374:"Stort Y med circumflex",373:"Litet w med circumflex",375:"Litet y med circumflex",sbquo:"Enkelt lågt 9-citationstecken",8219:"Enkelt högt bakvänt 9-citationstecken",bdquo:"Dubbelt lågt 9-citationstecken",hellip:"Horisontellt uteslutningstecken",
trade:"Varumärke",9658:"Svart högervänd pekare",bull:"Listpunkt",rarr:"Högerpil",rArr:"Dubbel högerpil",hArr:"Dubbel vänsterpil",diams:"Svart ruter",asymp:"Ungefär lika med"}); | maukoese/jabali | app/assets/js/ckeditor/plugins/specialchar/dialogs/lang/sv.js | JavaScript | mit | 3,481 |
export default {
'description-caption': 'Описание',
'description-placeholder': 'Описание интерфейса',
'packet-caption': 'Пакет',
'packet-placeholder': 'Наименование пакета',
'namespace-postfix-caption': 'Постфикс пространства имен',
'namespace-postfix-placeholder': 'Наименование постфикса',
'bs-caption': 'Бизнес-сервер',
'bs-events-caption': 'События бизнес-сервера',
};
| Flexberry/ember-flexberry-designer | addon/locales/ru/components/fd-interface-editing-panel.js | JavaScript | mit | 515 |
export default function medianOfTwoArray(arr1, arr2) {
const arr = arr1.concat(arr2).sort((prev, next) => {
return prev - next
})
const half = arr.length / 2
return parseInt(half) === half ? (arr[half - 1] + arr[half]) / 2 : arr[Math.floor(half)]
}
const arr11 = [1, 2]
const arr12 = [3, 4]
const arr1 = medianOfTwoArray(arr11, arr12)
console.log(arr1) | nnecec/laboratory | LeetCode/4.Median of Two Sorted Arrays✅/index.0.js | JavaScript | mit | 361 |
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom'
class ResultPage extends React.Component {
// mixins: [
// Router.Navigation
// ]
goHome() {
// this.transitionTo('home');
}
render() {
return (
< div className = 'result-page' >
result page
< /div >
);
}
}
export default ResultPage;
| jimmykobe1171/chinese-food-detector-frontend | www/src/js/pages/result.js | JavaScript | mit | 422 |
/* global exports, it, describe */
// module Test.Spec.Mocha
if (typeof describe !== 'function' || typeof it !== 'function') {
throw new Error('Mocha globals seem to be unavailable!');
}
exports.itAsync = function (only) {
"use strict";
return function (name) {
return function (run) {
return function () {
var f = only ? it.only : it;
f(name, function (done) {
return run(function () {
done();
return function () {};
})(function (err) {
done(err);
return function () {};
})();
});
};
};
};
};
exports.itPending = function (name) {
"use strict";
return function () {
it(name);
};
};
exports.describe = function (only) {
"use strict";
return function (name) {
return function (nested) {
return function () {
var f = only ? describe.only : describe;
f(name, function () {
nested();
});
};
};
};
};
| owickstrom/purescript-spec-reporter-mocha | src/Test/Spec/Mocha.js | JavaScript | mit | 1,201 |
/**
* _scripts
* @author Steven Krebs
* @description gulp subtask for script bundling
* @copyright 2016, Steven Krebs
* @license MIT
*/
// Gulp Dependencies
var gulp = require('gulp'),
rename = require('gulp-rename'),
config = require('../config'),
gulpif = require('gulp-if'),
gutil = require('gulp-util'),
// Browser sync
browserSync = require('browser-sync'),
reload = browserSync.reload,
// Script Dependencies
browserify = require('browserify'),
bulkify = require('bulkify'),
watchify = require('watchify'),
tsify = require('tsify'),
uglify = require('gulp-uglify'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
//Source mapping Dependencies
sourcemaps = require('gulp-sourcemaps');
gulp.task('_scripts', bundler);
//Set if dev or deploy
var b = browserify(config.compiler.scripts.browserify);
if (environment.dev) {
b.plugin(watchify, config.compiler.scripts.watchify);
b.on('update', function(ids){
gutil.log('[' + gutil.colors.blue('Watchify') + '] ' + "File(s) changed: " + gutil.colors.cyan(ids));
bundler()
});
b.on('log', function(msg) {
gutil.log('[' + gutil.colors.blue('Watchify') + '] ' + "Finished: " + gutil.colors.magenta(msg));
});
}
b.plugin(tsify, config.compiler.scripts.tsify);
//The actual building pipe
function bundler() {
return b.transform(bulkify)
.bundle()
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source(config.names.temp))
.pipe(buffer())
.pipe(gulpif(environment.dev, sourcemaps.init(config.compiler.sourcemaps)))
.pipe(gulpif(!environment.dev, uglify()))
.on('error', gutil.log.bind(gutil, 'Uglify Error'))
.pipe(rename(config.names.rename))
.pipe(gulpif(environment.dev, sourcemaps.write()))
.pipe(gulp.dest(config.paths.scripts.dest))
.pipe(reload(config.compiler.scripts.browserSync));
}
| StevenKrebs/division-zero | gulp/tasks/_scripts.js | JavaScript | mit | 2,090 |
Brahma.applications.fabric('module',['events','tie'], function() {});
/* Функция создает простой модуль */
Brahma.module = function(extend,args) {
return Brahma.applications.create('module',extend||{},args||[]);
}; | morulus/brahma | .dvlp/scripts/brahma/methods/module.js | JavaScript | mit | 246 |
const assert = require('assert');
const generateClasses = require('./generate-classes');
const classes = {
someClass: {
name: 'someClass',
shortname: 'someClass',
classitems: [],
description: '<h1>Some HTML</h1>',
file: 'some/file/path.js',
extends: 'Ember.Component'
},
anotherClass: {
name: 'anotherClass',
shortname: 'anotherClass',
classitems: [],
description: '<p>Some HTML</p>',
file: 'another/file/path.js',
extends: 'Ember.Component'
},
'lonely.Class': {
name: 'lonely.Class',
shortname: 'lonely.Class',
classitems: [],
description: '<p>Some HTML</p>',
file: 'another/lonely/path.js',
extends: 'Ember.Component'
}
};
const classItems = [
{
file: 'some/file/path.js',
line: 15,
description: 'some `code`',
itemtype: 'method',
name: 'itemC',
type: '{Object}',
class: 'someClass'
},
{
file: 'some/file/path.js',
line: 15,
description: 'some `code`',
itemtype: 'property',
name: 'itemB',
type: '{Object}',
class: 'someClass'
},
{
file: 'some/file/path.js',
line: 15,
description: 'This itemB should be used b/c its declared last',
itemtype: 'property',
name: 'itemB',
type: '{Object}',
class: 'someClass'
},
{
file: 'some/file/path.js',
line: 15,
description: 'Should end in the beginning',
itemtype: 'property',
name: 'itemA',
type: '{Object}',
class: 'someClass'
},
{
file: 'some/file/path.js',
line: 15,
description: 'some `code`',
itemtype: 'event',
name: 'itemC',
type: '{Object}',
class: 'anotherClass'
}
];
describe('generate-classes', function() {
it('returns empty arrays if there is no data', () => {
const actual = generateClasses({}, []);
assert.ok(Array.isArray(actual.classesMeta), 'returns empty array even if there is no data');
assert.ok(Array.isArray(actual.classesDatas), 'returns empty array even if there is no data');
});
it('returns meta data for classes', () => {
const testClasses = JSON.parse(JSON.stringify(classes));
const testClassItems = JSON.parse(JSON.stringify(classItems));
const expected = [
{ name: 'anotherClass', type: 'classes' },
{ name: 'lonely.Class', type: 'classes' },
{ name: 'someClass', type: 'classes' }
];
const actual = generateClasses(testClasses, testClassItems).classesMeta;
assert.deepEqual(actual, expected, 'appropriate meta for modules is returned as modulesMeta');
});
it('it adds all class items to their parent class', () => {
const testClasses = JSON.parse(JSON.stringify(classes));
const testClassItems = JSON.parse(JSON.stringify(classItems));
const actual = generateClasses(testClasses, testClassItems);
const someClass = actual.classesDatas.filter(klass => klass.name === 'someClass')[0];
const anotherClass = actual.classesDatas.filter(klass => klass.name === 'anotherClass')[0];
const lonelyClass = actual.classesDatas.filter(klass => klass.name === 'lonely.Class')[0];
assert.ok(Array.isArray(actual.classesMeta), 'returns array of class meta');
assert.ok(Array.isArray(actual.classesDatas), 'returns array of class objects');
assert.ok(someClass, 'returns class someClass in results');
assert.ok(anotherClass, 'returns class anotherClass in results');
assert.ok(lonelyClass, 'returns class lonely.Class in results');
assert.equal(someClass.classitems.length, 3, 'someClass should have only 3 classes after deduping');
assert.equal(anotherClass.classitems.length, 1, 'all classitems for anotherClass are attached');
assert.equal(lonelyClass.classitems.length, 0, 'lonelyClass has no class items');
assert.ok(Array.isArray(someClass.method), 'method array is added to classes');
assert.ok(Array.isArray(someClass.property), 'property array is added to classes');
assert.ok(Array.isArray(someClass.event), 'event array is added to classes');
assert.equal(someClass.method.length, 1, 'method class item was attached to correct class');
assert.equal(someClass.property.length, 2, 'property class item was attached to correct class');
assert.equal(someClass.event.length, 0, 'no event class items returns empty array for class');
assert.equal(someClass.property[0].name, 'itemA', 'class items are sorted alphabetically');
assert.equal(someClass.property[1].description,
'<p>This itemB should be used b/c its declared last</p>\n',
'duplicate itemB should pick up last declared item');
assert.equal(anotherClass.method.length, 0, 'no method class items returns empty array for class');
assert.equal(anotherClass.property.length, 0, 'no property class items returns empty array for class');
assert.equal(anotherClass.event.length, 1, 'events class item was attached to correct class');
});
});
| healthsparq/ember-fountainhead | lib/data-types/generate-classes.spec.js | JavaScript | mit | 4,894 |
import React, { Component, PropTypes } from 'react';
import { Modal, Button } from 'react-bootstrap';
export default class ModalClass extends Component {
static propTypes = {
title: PropTypes.string.isRequired,
content: PropTypes.string.isRequired,
showModal: PropTypes.bool,
}
constructor(props) {
this.props = props;
}
render() {
return (
<div className="static-modal">
<Modal.Dialog show={this.props.showModal} >
<Modal.Header>
<Modal.Title>{this.props.title}</Modal.Title>
</Modal.Header>
<Modal.Body>
{this.props.content}
</Modal.Body>
<Modal.Footer>
<Button>Close</Button>
<Button bsStyle="primary">Save changes</Button>
</Modal.Footer>
</Modal.Dialog>
</div>
);
}
}
| epicallan/akilihub | src/components/Modal/Modal.js | JavaScript | mit | 821 |
/*
UIMenu is a wrapper around the standard init/update/draw functionality of the Dialog and CustomMenu components.
Project: Support Framework (https://github.com/nhmkdev/support-framework)
Author: Tim Stair
*/
ig.module(
'support.uimenu'
)
.requires(
'impact.game',
'impact.font',
'support.util',
'support.save',
'support.window'
)
.defines(function(){
var Support = ig.global.support;
var Save = Support.save;
var Window = Support.window;
var Util = Support.util;
ig.global.support.UIMenu = ig.Class.extend
({
font:null,
menuChoices:null,
menuClass:null,
menuData:null,
menuObject:null,
menuText:'',
selectChar:'>',
selectedIndex:0,
selectedIcon:null,
selectedIconSettings:null,
settings:{},
windows:[],
windowsExtra:[],
init:function(object, data)
{
this.menuObject = object;
this.menuData = data;
if(!Util.defined(this.menuData['s']))
{
this.logErr("UIMenu must have settings entry!");
//TODO: throwing exception or returning null with constructor
}
this.selectChar = this.getSetting('sc', '>');
var fontPath = this.getSetting('f', null);
if(fontPath != null)
{
this.font = Util.loadFont(fontPath);
}
else
{
this.logErr("UIMenu must have a font defined!");
//TODO: throwing exception or returning null with constructor
}
this.settings.x = this.getSetting('x', 0);
this.settings.y = this.getSetting('y', 0);
this.settings.width = this.getSetting('w', 0);
var optionSettings = this.getSetting('o', {});
this.settings.o = {};
this.settings.o.x = Util.getProperty(optionSettings['x'], 0);
this.settings.o.y = Util.getProperty(optionSettings['y'], 0);
this.settings.o.width = Util.getProperty(optionSettings['w'], 0);
this.settings.o.yOffset = Util.getProperty(optionSettings['yo'], 0);
// this is an offset away from the selector (char or icon)
this.settings.o.xOffset = Util.getProperty(optionSettings['xo'], 0);
this.menuClass = this.getSetting('c', null);
if(this.menuClass != null)
{
var dialogClass = Util.getNestedProperty(ig.global, this.menuClass, null);
if(null == dialogClass)
{
this.logErr('Dialog class was unable to be evaluated');
this.menuClass = null;
}
else
{
// set the actual class, not the string
this.menuClass = dialogClass;
}
}
var selectedIcon = this.getSetting('si', null);
if(selectedIcon != null)
{
this.selectedIcon = Util.loadImage(selectedIcon);
var iconSettings = this.getSetting('sia', {});
this.selectedIconSettings = {};
this.selectedIconSettings.sx = Util.getProperty(iconSettings['sx'], 0);
this.selectedIconSettings.sy = Util.getProperty(iconSettings['sy'], 0);
this.selectedIconSettings.w = Util.getProperty(iconSettings['w'], this.selectedIcon.width);
this.selectedIconSettings.h = Util.getProperty(iconSettings['h'], this.selectedIcon.height);
this.selectedIconSettings.yOffset = Util.getProperty(iconSettings['yo'], 0);
}
this.settings.o.selectWidth = (this.selectedIcon == null ?
this.font.widthMap[this.selectChar.charCodeAt(0) - this.font.firstChar] :
this.selectedIcon.width) + this.settings.o.xOffset;
// load dialog windows
// 'win' can include base windows
Window.loadWindows(this.getSetting('win', null), this.windows);
// 'winex' can include base windows but is also an extension
Window.loadWindows(this.getSetting('winex', null), this.windows);
},
/*
Gets a setting from the dialog data 's' property (defaulting to the base)
@param (string) setting - The setting to get
@param (object) defaultValue - The default value if nothing is found
@return {object} The resulting value
*/
getSetting:function(setting, defaultValue)
{
return Util.getOverrideProperty(setting, this.menuData.s, this.menuData.s.base, defaultValue);
},
/*
Updates the layout/text/options based on the current state
*/
updateLayout:function(rawText, arrayChoices)
{
var heightData = {};
if(this.menuClass != null && Util.defined(this.menuClass['getKeyString']))
{
rawText = Util.localizeString(rawText, this.menuClass);
}
this.menuText = Util.splitStringToWidth(rawText, this.settings.width, this.font, heightData);
// TODO: potential for overlap if the state text is too long, height of rectangle is meaningless
this.menuChoices = [];
if(Util.defined(arrayChoices))
{
var choiceY = this.settings.o.y;
var optionMaxWidth = this.settings.o.width - this.settings.o.selectWidth;
for( var idx = 0, len = arrayChoices.length; idx < len; idx++)
{
var choice = arrayChoices[idx];
if(Util.defined(choice['r']))
{
if(!Save.processReqsObject(choice.r))
{
continue;
}
}
var choiceData = {};
rawText = choice.t;
if(this.menuClass != null)
{
rawText = Util.localizeString(rawText, this.menuClass);
}
choiceData.text = Util.splitStringToWidth(rawText, optionMaxWidth, this.font, heightData);
choiceData.x = this.settings.o.x + this.settings.o.selectWidth;
choiceData.y = choiceY;
choiceData.optionData = choice;
this.menuChoices.push(choiceData);
choiceY += heightData.height + this.settings.o.yOffset;
}
// check the valid choices for the first that is marked as default
for(var idx = 0, len = this.menuChoices.length; idx < len; idx++)
{
if(Util.getProperty(this.menuChoices['d']), false)
{
this.selectedIndex = idx;
break;
}
}
if(this.selectedIndex >= this.menuChoices.length || this.selectedIndex < 0)
{
this.selectedIndex = 0;
}
}
},
itemClicked:function(itemClicked){},
backClicked:function(){},
/*
Update processor (usually called in the game mode blocking all other activity)
@return (bool) true if still operating in the dialog, false otherwise
*/
update:function()
{
if(this.menuData == null)
{
return false;
}
if(ig.input.pressed ('primary'))
{
this.itemClicked.apply(
this.menuObject,
this.menuChoices.length > 0 ? [this.menuChoices[this.selectedIndex].optionData] : null);
}
else if(ig.input.pressed('secondary') && this.settings.allowBack)
{
this.backClicked.apply(this.menuObject);
}
else if (ig.input.pressed('down'))
{
this.selectedIndex++;
if (this.selectedIndex > this.menuChoices.length - 1)
{
this.selectedIndex = 0;
}
}
else if (ig.input.pressed('up'))
{
this.selectedIndex--;
if (0 > this.selectedIndex)
{
this.selectedIndex = this.menuChoices.length - 1;
}
}
return true;
},
/*
Draw processor for the dialog (usually called in the game mode)
@return {bool} true if drawing the dialog, false otherwise
*/
draw:function()
{
if(this.menuData == null)
{
return false;
}
// render windows
Window.drawWindows(this.windows);
Window.drawWindows(this.windowsExtra);
// render text
this.font.draw(this.menuText, this.settings.x, this.settings.y, ig.Font.ALIGN.LEFT);
// render dialog text items (and selector)
for( var idx = 0, len = this.menuChoices.length; idx < len; idx++)
{
var stateChoice = this.menuChoices[idx];
// draw the indicator that this item is selected
if (this.selectedIndex == idx)
{
if (this.selectedIcon == null)
{
this.font.draw(this.selectChar, this.settings.o.x, stateChoice.y, ig.Font.ALIGN.RIGHT);
}
else
{
this.selectedIcon.draw(this.settings.o.x, stateChoice.y + this.selectedIconSettings.yOffset,
this.selectedIconSettings.sx,
this.selectedIconSettings.sy,
this.selectedIconSettings.w,
this.selectedIconSettings.h);
}
}
// draw the text
this.font.draw(stateChoice.text, stateChoice.x, stateChoice.y, ig.Font.ALIGN.LEFT);
}
return true;
}
})
}); | nhmkdev/support-framework | lib/support/uimenu.js | JavaScript | mit | 9,430 |
import { createStore, applyMiddleware, compose } from 'redux';
import { createLogger } from 'redux-logger';
import persistState from 'redux-localstorage';
import thunk from 'redux-thunk';
import { apiMiddleware } from './middleware';
import { validateToken } from './actionCreators/auth';
import reducers from './reducers';
const middlewares = [
apiMiddleware,
thunk
];
if (process.env.NODE_ENV !== 'production') {
middlewares.push(createLogger());
}
const enhancer = compose(
applyMiddleware(
...middlewares
),
persistState('auth', {
key: 'rad.io-state-auth'
})
);
export const store = createStore(
reducers,
enhancer
);
// We instantly validate the token.
store.dispatch(validateToken()); | arnoschutijzer/rad.io | frontend/src/state/index.js | JavaScript | mit | 721 |
var SailsWebApi = require('../../../components/utils/SailsWebApi'),
AppDispatcher = require('../../../components/utils/AppDispatcher'),
ErrorMessageConstants = require('../../../components/constants/ErrorMessageConstants'),
UserConstants = require('../../../components/constants/UserConstants');
function getCreateUserErrorMessage(error) {
if (error.error.invalidAttributes['"loginName"']) {
return "Login name is already in use.";
}
if (error.error.invalidAttributes['email']) {
return "Email is already in use.";
}
}
module.exports = {
setSessionUser: function(user) {
console.log("Testing set session user",user)
if (typeof (Storage) !== 'undefined') {
localStorage.setItem('token', user.token)
}
if(user.id == -1){
localStorage.setItem('token', "")
}
AppDispatcher.dispatch({
type: UserConstants.SET_SESSION_USER,
user: user
})
},
getAllUsers: function() {
console.log("Testing get all users")
SailsWebApi.getAllUsers(function(error, users) {
AppDispatcher.dispatch({
type: UserConstants.GET_ALL_USERS,
users: users
})
})
},
setEditTarget: function(user) {
AppDispatcher.dispatch({
type: UserConstants.SET_EDIT_TARGET,
user: user
})
},
createUser: function(user) {
SailsWebApi.createUser(user, function(error, user) {
if (error) {
AppDispatcher.dispatch({
type: ErrorMessageConstants.ERROR_MESSAGE,
event: "Create User Error",
error: error,
message: getCreateUserErrorMessage(error)
})
}
else {
AppDispatcher.dispatch({
type: UserConstants.CREATE_USER,
user: user
})
}
})
},
updateUser: function(user) {
SailsWebApi.updateUser(user, function(error, user) {
AppDispatcher.dispatch({
type: UserConstants.UPDATE_USER,
user: user
})
})
},
deleteUser: function(user) {
SailsWebApi.deleteUser(user, function(error, user) {
AppDispatcher.dispatch({
type: UserConstants.DELETE_USER,
user: user
})
})
},
setUserGroup: function(group) {
AppDispatcher.dispatch({
type: UserConstants.SET_USER_GROUP,
group: group
})
}
};
| availabs/auth_container | src/routes/AuthContainer/modules/UserActions.js | JavaScript | mit | 2,679 |
import React from 'react'
import {Link} from 'react-router'
import RoundButton from './round-button'
import Icon from './icon'
/* Links to the help page specified by link_to. */
class HelpButton extends React.Component {
render() {
return (
<Link to={this.props.link_to}><RoundButton><Icon name='ionicon-help' type='inline'/></RoundButton></Link>
)
}
}
export default HelpButton
| Aokibi/Regents-Navigation | source/components/help-button.js | JavaScript | mit | 390 |
/* global describe, it */
import {expect} from 'chai'
import {generateToken} from './token'
import {shareOperation} from '../../src/operations/share'
import Promise from 'bluebird'
import {StaRHsAPIClient} from '../../src/apiclient'
import {URIValue} from 'rheactor-value-objects'
const mountURL = new URIValue('https://api.example.com')
describe('/share', () => {
it('should share a staRH', done => {
const mockClient = new StaRHsAPIClient('myapikey', 'apiuser', 'apipass')
mockClient.getStaRHsStatus = sessionToken => {
expect(sessionToken).to.equal('some-session-token')
return Promise.resolve({
'CycleStaRHsToShare': 10,
'YouHaveShared': 1,
'YouHaveReceived': 2,
'YouHaveLeft': 8,
'TotalShared': 19,
'TotalReceived': 11
})
}
mockClient.shareStaRH = (sessionToken, to, amount, message) => {
expect(sessionToken).to.equal('some-session-token')
expect(to).to.equal('some-user-id')
expect(message).to.equal('a staRH for you')
expect(amount).to.equal(2)
done()
}
const share = shareOperation(mountURL, mockClient)
generateToken()
.then(token => share.post({
to: `${mountURL}/profile/some-user-id`,
message: 'a staRH for you',
amount: 2
}, [], token))
})
})
| ResourcefulHumans/starhs-api-proxy-aws-lambda | test/operations/share.js | JavaScript | mit | 1,322 |
var _ = require('lodash')
, dbc = require('dbc.js')
, Cocktail = require('cocktail')
;
function Objectify() {
}
Cocktail.mix(Objectify, {
'@exports': module
});
Objectify.build = function (schema, defaults) {
var self = this;
if (_.isObject(schema)) {
dbc([typeof schema === 'object'], 'Schema type is required');
createObjectOfType(schema.type);
} else if (_.isString(schema)) {
var schemaFromPath = require(schema);
if (schemaFromPath == null || schemaFromPath.length === 0) {
throw new Error('Schema path is wrong');
}
} else {
throw new Error('Schema must be a string or an object');
}
};
function createObjectOfType(type) {
type = type.toLowerCase() || 'object';
if (type === 'object')
return {};
else if (type === 'boolean')
return false;
else if (type === 'string')
return ''
else if (type === 'number') {
return 0;
} else if (type === 'array') {
return []
} else if (type === 'regex') {
return /\*/;
} else if (type === 'function') {
return function () {
};
} else if (type === 'undefined') {
return undefined;
} else if (type === 'null') {
return null;
}
}
module.exports = Objectify; | TylerGarlick/objectify | index.js | JavaScript | mit | 1,215 |
'use strict';
import { cloneDeep, update } from 'lodash';
import { stripHTML } from '../server/lib/sanitize-html';
module.exports = {
up: async queryInterface => {
const [collectives] = await queryInterface.sequelize.query(`
SELECT id, "settings" FROM "Collectives" c
WHERE "settings" -> 'paymentMethods' -> 'manual' -> 'instructions' IS NOT NULL
AND ("settings" -> 'paymentMethods' -> 'manual' -> 'instructions')::varchar LIKE '%<%'
`);
for (const collective of collectives) {
const newSettings = cloneDeep(collective.settings);
update(newSettings, 'paymentMethods.manual.instructions', stripHTML);
await queryInterface.sequelize.query(`UPDATE "Collectives" SET settings = :settings WHERE id = :id`, {
replacements: { settings: JSON.stringify(newSettings), id: collective.id },
});
}
},
down: async () => {
// No rollback
},
};
| OpenCollective/opencollective-api | migrations/20210421090229-remove-markup-in-manual-payment-instructions.js | JavaScript | mit | 913 |
//model
var state = {
dispatch: function(action, args) {
state[action].apply(state, args || [])
requestAnimationFrame(function() {
localStorage["todos-mithril"] = JSON.stringify(state.todos)
})
},
todos: JSON.parse(localStorage["todos-mithril"] || "[]"),
editing: null,
filter: "",
remaining: 0,
todosByStatus: [],
createTodo: function(title) {
state.todos.push({title: title.trim(), completed: false})
},
setStatuses: function(completed) {
for (var i = 0; i < state.todos.length; i++) state.todos[i].completed = completed
},
setStatus: function(todo, completed) {
todo.completed = completed
},
destroy: function(todo) {
var index = state.todos.indexOf(todo)
if (index > -1) state.todos.splice(index, 1)
},
clear: function() {
for (var i = 0; i < state.todos.length; i++) {
if (state.todos[i].completed) state.destroy(state.todos[i--])
}
},
edit: function(todo) {
state.editing = todo
},
update: function(title) {
if (state.editing != null) {
state.editing.title = title.trim()
if (state.editing.title === "") state.destroy(state.editing)
state.editing = null
}
},
reset: function() {
state.editing = null
},
computed: function(vnode) {
state.showing = vnode.attrs.status || ""
state.remaining = state.todos.filter(function(todo) {return !todo.completed}).length
state.todosByStatus = state.todos.filter(function(todo) {
switch (state.showing) {
case "": return true
case "active": return !todo.completed
case "completed": return todo.completed
}
})
}
}
//view
var Todos = {
add: function(e) {
if (e.keyCode === 13) {
state.dispatch("createTodo", [e.target.value])
e.target.value = ""
}
},
toggleAll: function() {
state.dispatch("setStatuses", [document.getElementById("toggle-all").checked])
},
toggle: function(todo) {
state.dispatch("setStatus", [todo, !todo.completed])
},
focus: function(vnode, todo) {
if (todo === state.editing && vnode.dom !== document.activeElement) {
vnode.dom.value = todo.title
vnode.dom.focus()
vnode.dom.selectionStart = vnode.dom.selectionEnd = todo.title.length
}
},
save: function(e) {
if (e.keyCode === 13 || e.type === "blur") state.dispatch("update", [e.target.value])
else if (e.keyCode === 27) state.dispatch("reset")
},
oninit: state.computed,
onbeforeupdate: state.computed,
view: function(vnode) {
var ui = vnode.state
return [
m("header.header", [
m("h1", "todos"),
m("input#new-todo[placeholder='What needs to be done?'][autofocus]", {onkeypress: ui.add}),
]),
m("section#main", {style: {display: state.todos.length > 0 ? "" : "none"}}, [
m("input#toggle-all[type='checkbox']", {checked: state.remaining === 0, onclick: ui.toggleAll}),
m("label[for='toggle-all']", {onclick: ui.toggleAll}, "Mark all as complete"),
m("ul#todo-list", [
state.todosByStatus.map(function(todo) {
return m("li", {class: (todo.completed ? "completed" : "") + " " + (todo === state.editing ? "editing" : "")}, [
m(".view", [
m("input.toggle[type='checkbox']", {checked: todo.completed, onclick: function() {ui.toggle(todo)}}),
m("label", {ondblclick: function() {state.dispatch("edit", [todo])}}, todo.title),
m("button.destroy", {onclick: function() {state.dispatch("destroy", [todo])}}),
]),
m("input.edit", {onupdate: function(vnode) {ui.focus(vnode, todo)}, onkeyup: ui.save, onblur: ui.save})
])
}),
]),
]),
state.todos.length ? m("footer#footer", [
m("span#todo-count", [
m("strong", state.remaining),
state.remaining === 1 ? " item left" : " items left",
]),
m("ul#filters", [
m("li", m("a[href='/']", {oncreate: m.route.link, class: state.showing === "" ? "selected" : ""}, "All")),
m("li", m("a[href='/active']", {oncreate: m.route.link, class: state.showing === "active" ? "selected" : ""}, "Active")),
m("li", m("a[href='/completed']", {oncreate: m.route.link, class: state.showing === "completed" ? "selected" : ""}, "Completed")),
]),
m("button#clear-completed", {onclick: function() {state.dispatch("clear")}}, "Clear completed"),
]) : null,
]
}
}
m.route(document.getElementById("todoapp"), "/", {
"/": Todos,
"/:status": Todos,
})
| barneycarroll/mithril.js | examples/todomvc/todomvc.js | JavaScript | mit | 4,275 |
/******** Project - Final *********************************
Authors: Eric Wooley, Tandra Felly, Lauryn Loudermilk
Description: Javascript automata engine.
**********************************************************/
function calculate_distance(point1, point2){
var xs = 0;
var ys = 0;
xs = point2.x - point1.x;
xs = xs * xs;
ys = point2.y - point1.y;
ys = ys * ys;
return Math.sqrt( xs + ys );
};
function closest_object(loc, objects){
if(objects.length < 1) return false;
var ret;
var nearest;
$.each(objects, function(index, val){
if(!nearest || !ret){
nearest = calculate_distance(loc, val.geo.getPosition());
ret = val;
}
var challenger = calculate_distance(loc, val.geo.getPosition());
if(challenger < nearest){
ret = val;
nearest = challenger;
}
});
return ret;
};
function points_angle(P1, P2){
var deltaY = P2.y - P1.y;
var deltaX = P2.x - P1.x;
return Math.atan2(deltaY, deltaX) * 180 / Math.PI
}
function prompt(options){
options = options || {};
if(!options.modal) options.modal = "#transitionOptions";
$("#prompt_input").val(options.defaultText || '');
$("#prompt_input").attr("placeholder", options.placeholder || '');
$( options.modal ).dialog({
autoOpen: false,
width: 400,
title: options.title || "Prompt",
buttons: [
{
text: "Ok",
click: function() {
var prompt = $(options.modal).find("#prompt_input");
if(options.onOk) options.onOk(prompt.val());
$( this ).dialog( "close" );
}
},
{
text: "Cancel",
click: function() {
if(options.onCancel) options.onCancel();
$( this ).dialog( "close" );
}
}
]
});
$(options.modal ).dialog( "open" );
};
function moveStartingMarker(state){
startingState = state;
var newLoc = state.geo.getPosition();
var halfMarkerWidth = state.geo.getRadius() / 2;
startingMarker.setPosition(newLoc.x - halfMarkerWidth - state.geo.getRadius()/2, newLoc.y);
state.stateShapes.add(startingMarker);
dfa_layer.draw();
};
function setDraggable(draggable){
$.each(states, function(index, s){
s.setDraggable(draggable);
});
}
function objectCount(obj){
var c= 0;
for(var p in obj)
if(obj.hasOwnProperty(p))
++c;
return c;
}
function firstInObject(obj){
for(var p in obj)
return obj[p]
}
//there is no right click event, so we have to override the context menu
//to perform functions on right click
window.oncontextmenu = function ()
{
//showCustomMenu(); // show your context menu
return false; // cancel default menu
}
| ericwooley/html5-automaton-gui | lib/functions.js | JavaScript | mit | 2,889 |
//! moment.js locale configuration
//! locale : Kyrgyz [ky]
//! author : Chyngyz Arystan uulu : https://github.com/chyngyz
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.Px.moment)
}(this, (function (moment) { 'use strict';
var suffixes = {
0: '-чү',
1: '-чи',
2: '-чи',
3: '-чү',
4: '-чү',
5: '-чи',
6: '-чы',
7: '-чи',
8: '-чи',
9: '-чу',
10: '-чу',
20: '-чы',
30: '-чу',
40: '-чы',
50: '-чү',
60: '-чы',
70: '-чи',
80: '-чи',
90: '-чу',
100: '-чү'
};
var ky = moment.defineLocale('ky', {
months : 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'),
monthsShort : 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'),
weekdays : 'Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби'.split('_'),
weekdaysShort : 'Жек_Дүй_Шей_Шар_Бей_Жум_Ише'.split('_'),
weekdaysMin : 'Жк_Дй_Шй_Шр_Бй_Жм_Иш'.split('_'),
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD.MM.YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd, D MMMM YYYY HH:mm'
},
calendar : {
sameDay : '[Бүгүн саат] LT',
nextDay : '[Эртең саат] LT',
nextWeek : 'dddd [саат] LT',
lastDay : '[Кече саат] LT',
lastWeek : '[Өткен аптанын] dddd [күнү] [саат] LT',
sameElse : 'L'
},
relativeTime : {
future : '%s ичинде',
past : '%s мурун',
s : 'бирнече секунд',
m : 'бир мүнөт',
mm : '%d мүнөт',
h : 'бир саат',
hh : '%d саат',
d : 'бир күн',
dd : '%d күн',
M : 'бир ай',
MM : '%d ай',
y : 'бир жыл',
yy : '%d жыл'
},
dayOfMonthOrdinalParse: /\d{1,2}-(чи|чы|чү|чу)/,
ordinal : function (number) {
var a = number % 10,
b = number >= 100 ? 100 : null;
return number + (suffixes[number] || suffixes[a] || suffixes[b]);
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 7 // The week that contains Jan 1st is the first week of the year.
}
});
return ky;
})));
| cdgallahue/atomic-turbine | web/bower_components/px-moment-imports/momentLocale/ky.js | JavaScript | mit | 2,783 |
'use strict';
angular.module('security.retryQueue', [])
// This is a generic retry queue for security failures. Each item is expected to expose two functions: retry and cancel.
.factory('securityRetryQueue', ['$q', '$log', function($q, $log){
var retryQueue = [];
var service = {
// The security service puts its own handler in here!
onItemAddedCallbacks: [],
hasMore: function(){
return retryQueue.length > 0;
},
push: function(retryItem){
retryQueue.push(retryItem);
$log.log('onItemAddedCallbacks', service.onItemAddedCallbacks);
//Call all the onItemAdded callbacks
angular.forEach(service.onItemAddedCallbacks, function(cb){
try{
cb(retryItem);
} catch(e){
$log.error('securityRetryQueue.push(retryItem): callback threw an error' + e);
}
});
},
pushRetryFn: function(reason, retryFn){
//The reason parameter is optional
if(arguments.length === 1){
retryFn = reason;
reason = undefined;
}
//The deferred object that will be resolved or rejected by calling retry or cancel
var deferred = $q.defer();
var retryItem = {
reason: reason,
retry: function(){
//Wrap the result of the retryFn into a promise if it not already
$q.when(retryFn()).then(function(value){
//If it was successful then resolve our deferred object
deferred.resolve(value);
}, function(value){
//Otherwise, reject it
deferred.reject(value);
});
},
cancel: function(){
//Give up on retrying and reject our deferred object
deferred.reject();
}
};
service.push(retryItem);
return deferred.promise;
},
retryReason: function(){
return service.hasMore() && retryQueue[0].reason;
},
cancelAll: function(){
while(service.hasMore()){
retryQueue.shift().cancel();
}
},
retryAll: function(){
while(service.hasMore()){
retryQueue.shift().retry();
}
}
};
return service;
}]); | CommonsCloud/ngCommonsCloud | app/js/commonscloud/security/retryQueue.js | JavaScript | mit | 1,941 |
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
name: String,
password: String,
email: { type: 'string', unique: true }
});
userSchema.path('email').index({ unique: true });
userSchema.pre("save", function (next) {
var self = this;
mongoose.models["User"].findOne({ email: self.email }, function (err, user) {
if (err) {
next(err);
} else if (user) {
self.invalidate("email", "email must be unique");
next(new Error("email must be unique"));
} else {
next();
}
});
});
userSchema.methods.register = function (callback) {
var self = this;
this.save(function (err) {
if (err) {
callback(err);
} else {
callback(undefined, self);
}
});
};
userSchema.methods.login = function (callback) {
var self = this;
mongoose.models["User"].findOne({ email: self.email }, function (err, user) {
if (err) {
callback(err);
} else if (!user) {
self.invalidate("email", "user doesn't exist");
callback(new Error("user doesn't exist"));
} else if (user.password != self.password) {
self.invalidate("password", "wrong password");
callback(new Error("wrong password"));
} else {
callback(undefined, user);
}
});
};
exports.User = mongoose.model('User', userSchema); | drvic10k/movie-poll | models/user.js | JavaScript | mit | 1,463 |
import PropTypes from 'prop-types';
const routerContextTypes = {
router: PropTypes.shape({
history: PropTypes.shape({
push: PropTypes.func.isRequired,
replace: PropTypes.func.isRequired,
createHref: PropTypes.func.isRequired,
}).isRequired,
}).isRequired,
};
export default routerContextTypes;
| lighter-cd/ezui_react_one | src/lib/utils/routerContextType.js | JavaScript | mit | 326 |
const Discord = require("discord.js");
const config = require('./config');
const crowfallBot = new Discord.Client();
const fs = require("fs");
const moment = require('moment');
const log = (msg) => {
console.log(`[${moment().format("YYYY-MM-DD HH:mm:ss")}] ${msg}`);
};
const pool = require('./lib/db');
function populationCapture() {
return function() {
let serverName = "Crowfall Discord";
let theServer = crowfallBot.guilds.find("name", serverName);
if (!theServer) return log(`Unable to find ${serverName}!`);
let totalUsers = 0;
let activeUsers = 0;
let idleUsers = 0;
let offlineUsers = 0;
theServer.fetchMembers()
.then(() => {
theServer.members.forEach(user => {
if (!user.presence)
offlineUsers += 1;
if (user.presence.status == 'online')
activeUsers += 1;
if (user.presence.status == 'dnd')
activeUsers += 1;
if (user.presence.status == 'idle')
idleUsers += 1;
if (user.presence.status == 'offline')
offlineUsers += 1;
totalUsers += 1;
})
})
.then(() => {
pool.query('INSERT INTO data_storage.discord_population (pop_active, pop_idle, pop_offline, pop_total) VALUES ($1, $2, $3, $4)', [activeUsers, idleUsers, offlineUsers, totalUsers])
.then(function(res) {
log(`Active: ${activeUsers} Idle: ${idleUsers} Offline: ${offlineUsers} Total ${totalUsers}`);
})
.catch(function(err) {
log(`error running query: ${err}`);
})
})
}
}
crowfallBot.on("ready", () => {
log("Beginning Crowfall Discord Population Capture...")
setInterval(populationCapture(), 900000)
});
crowfallBot.login(config.botToken);
crowfallBot.on("error", (err) => {
log(err);
});
crowfallBot.on("warn", (warn) => {
log(warn)
});
crowfallBot.on("disconnect", (disconnect) => {
log(disconnect);
process.exit();
});
crowfallBot.on("reconnecting", (restart) => {
log(restart);
process.exit();
});
process.on('unhandledRejection', (error) => {
log(`Unhandled error caught: ${error}`);
});
| TheObsidian/crowfallBot | scanner-discord.js | JavaScript | mit | 2,155 |
(function() {
'use strict';
angular.module("app").config(['$stateProvider', '$urlRouterProvider', 'dataServiceProvider', configureRoutes]);
function configureRoutes($stateProvider, $urlRouterProvider, dataServiceProvider) {
$urlRouterProvider.otherwise('/summary');
$stateProvider
.state('summary', {
url: '/summary',
templateUrl: 'App/Summary/summary.html',
controller: 'summary',
controllerAs: 'vm',
resolve: {
summaryData: function () {
return dataServiceProvider.$get().getData("summary").then(function (response) {
return response.data;
});
}
}
})
.state('associations', {
url: '/associations',
templateUrl: 'App/Associations/viewall.html',
controller: 'viewall',
controllerAs: 'vm',
resolve: {
associations: function() {
return dataServiceProvider.$get().getData("allassc").then(function (response) {
return response.data;
});
}
}
})
.state('associations.add', {
url: '/add',
templateUrl: 'App/Associations/edit.html',
controller: 'edit',
controllerAs: 'vm',
resolve: {
isNew: function() {
return true;
}
}
})
.state('associations.edit', {
url: '/edit/{id}',
templateUrl: 'App/Associations/edit.html',
controller: 'edit',
controllerAs: 'vm',
resolve: {
isNew: function() {
return false;
}
}
})
.state('association', {
url: '/association/{id}',
templateUrl: 'App/Association/view.html',
controller: 'view',
controllerAs: 'vm',
resolve: {
association: function ($stateParams) {
return dataServiceProvider.$get().getData("assoc|" + $stateParams.id).then(function(response) {
return response.data;
});
}
}
})
.state('association.payments', {
url: '/payments',
templateUrl: 'App/Association/payments.html',
controller: 'payments',
controllerAs: 'vm',
resolve: {
association: function ($stateParams) {
return dataServiceProvider.$get().getData("assoc|" + $stateParams.id).then(function (response) {
return response.data;
});
}
}
})
.state('association.addpayment', {
url: '/addpayment',
templateUrl: 'App/Association/addpayment.html',
controller: 'addpayment',
controllerAs: 'vm',
resolve: {
association: function ($stateParams) {
return dataServiceProvider.$get().getData("assoc|" + $stateParams.id).then(function (response) {
return response.data;
});
}
}
})
.state('association.subscription', {
url: '/subscription',
templateUrl: 'App/Association/subscription.html',
controller: 'subscription',
controllerAs: 'vm',
resolve: {
association: function ($stateParams) {
return dataServiceProvider.$get().getData("assoc|" + $stateParams.id).then(function (response) {
return response.data;
});
}
}
})
.state('association.subscribe', {
url: '/subscribe',
templateUrl: 'App/Association/subscribe.html',
controller: 'subscribe',
controllerAs: 'vm',
resolve: {
association: function ($stateParams) {
return dataServiceProvider.$get().getData("assoc|" + $stateParams.id).then(function (response) {
return response.data;
});
}
}
})
.state('demos', {
url: '/demos',
templateUrl: 'App/Demos/demos.html',
controller: 'demos',
controllerAs: 'vm',
resolve: {
demos: function() {
return dataServiceProvider.$get().getData("demos" ).then(function (response) {
return response.data;
});
}
}
})
.state('demos.view', {
url: '/view/{id}',
templateUrl: 'App/Demos/demo.html',
controller: 'demo',
controllerAs: 'vm',
resolve: {
demo: function ($stateParams) {
return dataServiceProvider.$get().getData("demo|" + $stateParams.id).then(function (response) {
return response.data;
});
},
viewOnly: function() {
return true;
}
}
})
.state('demos.edit', {
url: '/edit/{id}',
templateUrl: 'App/Demos/demo.html',
controller: 'demo',
controllerAs: 'vm',
resolve: {
demo: function ($stateParams) {
return dataServiceProvider.$get().getData("demo|" + $stateParams.id).then(function (response) {
return response.data;
});
},
viewOnly: function() {
return false;
}
}
})
}
})(); | isboat/ibunionportal | src/PortalBackend/Backend.Web/App/routeHelper.js | JavaScript | mit | 6,638 |
import React, { PropTypes, Component } from 'react';
import { StyleSheet, Text } from 'react-native';
import { Container, Header, Title, Content, Footer, FooterTab, Button, Left, Right, Body, Icon } from 'native-base';
export default class Home extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Container>
<Header >
<Left>
<Button transparent>
<Icon name='menu' />
</Button>
</Left>
<Body>
<Title>WindSurf Community</Title>
</Body>
<Right />
</Header>
<Content>
</Content>
<Footer>
<FooterTab>
<Button>
<Icon name='home' />
</Button>
<Button onPress={this.props.goReport}>
<Icon name='person' />
</Button>
<Button onPress={this.props.goStatistics}>
<Icon name='pulse' />
</Button>
<Button onPress={this.props.goSettings}>
<Icon name='settings' />
</Button>
</FooterTab>
</Footer>
</Container>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
Home.propTypes = {
goReport: PropTypes.func.isRequired,
goStatistics: PropTypes.func.isRequired,
goSettings: PropTypes.func.isRequired,
}
| gziny/windsurf-community-mobile | components/home/home.js | JavaScript | mit | 1,749 |
/*
AngularJS v1.3.16
(c) 2010-2014 Google, Inc. http://angularjs.org
License: MIT
*/
!function(p,g,n){"use strict";g.module("ngCookies",["ng"]).factory("$cookies",["$rootScope","$browser",function(e,b){var h,c={},f={},k=!1,l=g.copy,m=g.isUndefined;return b.addPollFn(function(){var a=b.cookies();h!=a&&(h=a,l(a,f),l(a,c),k&&e.$apply())})(),k=!0,e.$watch(function(){var a,d,e;for(a in f)m(c[a])&&(b.cookies(a,n),delete f[a]);for(a in c)d=c[a],g.isString(d)||(d=""+d,c[a]=d),d!==f[a]&&(b.cookies(a,d),f[a]=d,e=!0);if(e)for(a in d=b.cookies(),c)c[a]!==d[a]&&(m(d[a])?(delete c[a],delete f[a]):c[a]=f[a]=d[a])}),c}]).factory("$cookieStore",["$cookies",function(e){return{get:function(b){return(b=e[b])?g.fromJson(b):b},put:function(b,c){e[b]=g.toJson(c)},remove:function(b){delete e[b]}}}])}(window,window.angular); | guandai/DataPanels | app-dist/bower_components/angular-cookies/angular-cookies.min.js | JavaScript | mit | 815 |
'use strict';
var benchmark = require('benchmark');
var EventEmitter1 = require('events').EventEmitter
, EventEmitter3 = require('eventemitter3')
, FE = require('fastemitter')
, Master = require('../../');
var MAX_LISTENERS = Math.pow(2, 32) - 1;
function handle() {
if (arguments.length > 100) console.log('damn');
}
var ee1 = new EventEmitter1()
, ee3 = new EventEmitter3()
, master = new Master()
, fe = new FE();
ee1.setMaxListeners(MAX_LISTENERS);
fe.setMaxListeners(MAX_LISTENERS);
for (var i = 0; i < 25; i++) {
ee1.on('event', handle);
ee3.on('event', handle);
master.on('event', handle);
fe.on('event', handle);
}
//
// eventemitter2 doesn't correctly handle listeners as they can be removed by
// doing `ee2.listeners('event').length = 0;`. Same counts for Drip.
//
// event-emitter and contra/emitter do not implement `listeners`.
//
(
new benchmark.Suite()
).add('EventEmitter1', function () {
ee1.listeners('event');
}).add('[email protected]', function() {
ee3.listeners('event');
}).add('EventEmitter3(master)', function() {
master.listeners('event');
}).add('fastemitter', function() {
fe.listeners('event');
}).on('cycle', function cycle(e) {
console.log(e.target.toString());
}).on('complete', function completed() {
console.log('Fastest is %s', this.filter('fastest').map('name'));
}).run({ async: true });
| primus/eventemitter3 | benchmarks/run/listeners.js | JavaScript | mit | 1,373 |
'use strict';
var MersenneTwister = require('mersenne-twister');
var generator = new MersenneTwister();
var chancer = module.exports = {
seed: seed,
random: random,
float: float,
int: int,
coinToss: coinToss,
fromArray: fromArray,
shuffleArray: shuffleArray,
fillArray: fillArray,
uuid: uuid
};
// Specify a seed in order to get a repeatable random sequence
function seed (num) {
if (typeof num === 'number' && (num % 1) === 0) {
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
generator.init_seed(num);
return true;
}
else {
return undefined;
}
}
// Returns a floating-point number between 0 and 1
function random () {
return generator.random();
}
// Returns a floating-point number between <min> (inclusive) and <max> (exclusive)
function float (min, max) {
if (typeof min === 'number' && typeof max === 'number') {
return generator.random() * (max - min) + min;
}
else {
return undefined;
}
}
// Returns an integer between <min> (inclusive) and <max> (inclusive)
function int (min, max) {
if (typeof min === 'number' && typeof max === 'number') {
return Math.floor(generator.random() * (max - min + 1)) + min;
}
else {
return undefined;
}
}
// Returns a 0 or 1 to represent a coin toss
// Optionally associate any other values for the coin sides (true/false, yes/no, heads/tails, etc)
function coinToss (heads, tails) {
var first = (typeof heads !== 'undefined') ? heads : 0;
var second = (typeof tails !== 'undefined') ? tails : 1;
return (Math.floor(generator.random() * 2) === 0) ? first : second;
}
// Returns a random item from an array
function fromArray (obj) {
if (typeof obj !== 'undefined' && obj && obj.constructor === Array) {
return obj[Math.floor(generator.random() * obj.length)];
}
else {
return undefined;
}
}
// Returns an array shuffled into a random order
function shuffleArray (obj) {
if (typeof obj !== 'undefined' && obj && obj.constructor === Array) {
return shuffle(obj);
}
else {
return undefined;
}
}
function shuffle (arr) {
for (var i = arr.length - 1; i >= 0; i--) {
var j = chancer.int(0, i);
/* istanbul ignore else */
if (j !== i) {
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
return arr;
}
// Returns an array of integers between <min> (inclusive) and <max> (inclusive)
// If no <total> specified return all possible values between <min> and <max>
function fillArray (min, max, total) {
if (typeof min === 'number' && typeof max === 'number') {
var num = (total) ? total : (max - min) + 1;
var arr;
/* istanbul ignore else */
if (typeof num === 'number' && (((max - min) + 1) >= num)) {
arr = generateArray(min, max, num);
}
return arr;
}
else {
return undefined;
}
}
function generateArray (min, max, total) {
var arr = [];
while (arr.length < total) {
var randomNumber = chancer.int(min, max);
var found = false;
for (var i = 0; i < arr.length; i++) {
/* istanbul ignore else */
if (arr[i] === randomNumber) {
found = true;
break;
}
}
/* istanbul ignore else */
if (!found) {
arr[arr.length] = randomNumber;
}
}
return arr;
}
// Returns a random value as a universally unique identifier (UUID) version 4 (RFC4122)
// xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
// where x is any hexadecimal digit and y is one of 8, 9, A, or B
// e.g., efe1f2aa-1e99-40f2-83fa-8519acd8c34c
function uuid () {
var template = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
return template.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0;
var v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
| howlingmad/chancer | lib/chancer.js | JavaScript | mit | 4,039 |
export { default } from 'em-tgraph/utils/data-processor';
| sreenaths/em-tgraph | app/utils/data-processor.js | JavaScript | mit | 58 |
import Joi from 'joi';
import { postHandlerFactory, getHandlerFactory, dependsOnBoolean, dataTransformer} from './common';
import previouslyRegisteredStep from './previously-registered';
const schema = Joi.object().keys({
'registered-address-correct': Joi.boolean().required()
.meta({
componentType: 'radio-horizontal',
children: [
{ label: 'Yes', value: 'true' },
{ label: 'No', value: 'false' },
],
variant: 'radio',
})
.options({
language: {
any: { required: 'Please answer this question' },
},
}),
'submit': Joi.any().optional().strip()
});
const title = 'Are you registered at {{ data.previouslyRegistered.gpName | default(data.previouslyRegistered.manualGPName) }} with this address?';
const key = 'registedAddress';
const slug = 'registered-address';
const beforeTemplate = '_includes/current-address.njk';
const template = 'register-form/registered-address.njk';
const handlers = {
GET: (prevSteps) => getHandlerFactory(
key, title, schema, prevSteps, null, beforeTemplate, '', template
),
POST: (prevSteps, nextSteps) => postHandlerFactory(
key, title, schema, prevSteps, nextSteps, {beforeTemplate, template, dataTransformer}
),
};
const checkApplies = dependsOnBoolean(previouslyRegisteredStep, 'previously-registered');
/**
* @type Step
*/
export default {
key,
slug,
title,
schema,
handlers,
checkApplies,
};
| nhsuk/register-with-a-gp-beta-web | src/server/plugins/register-form/steps/registered-address.js | JavaScript | mit | 1,443 |
Package.describe({
summary: "Reload the page while preserving application state.",
internal: true
});
Package.on_use(function (api) {
api.use(['underscore', 'logging', 'json'], 'client');
api.export('Reload', 'client');
api.add_files('reload.js', 'client');
});
| awwx/meteor-offline-worker | packages/reload/package.js | JavaScript | mit | 273 |
/**
* @class Oskari.mapframework.bundle.parcel.service.ParcelWfst
*
*
* Transforms OpenLayers geometry to WFS Transactions.
* Also, provides functions to load feature data from the server.
*
* Notice, uses instance configuration information to get the query URL and WFST transaction URL,
* and feature type strings for protocol feature types.
*
* Notice, if queryUrl and transaction Url differ, WFST uses INSERT, otherwise UPDATE.
* Also, FID is parced to be only a number for WFST action.
*/
//TODO: refactor with Oskari.mapframework.bundle.parcel.service.PreParcelWFSTStore
Oskari.clazz.define('Oskari.mapframework.bundle.parcel.service.ParcelWfst',
/**
* @method create called automatically on construction
* @static
* @param {Oskari.mapframework.bundle.parcel.DrawingToolInstance} instance
*/
function (instance) {
var srsName = instance.getSandbox().getMap().getSrsName();
this.instance = instance;
this.protocols = {};
this.protocols.parcel = new OpenLayers.Protocol.WFS({
version: '1.1.0',
srsName: srsName,
featureType: instance.conf.parcelFeatureType,
featureNS: 'http://xml.nls.fi/ktjkiiwfs/2010/02',
featurePrefix: 'ktjkiiwfs',
readOptions: {
meThis: this
},
parseResponse: function (request, options) {
return options.meThis._parseResponse(request, options);
},
url: instance.conf.queryUrl
});
this.protocols.registerUnit = new OpenLayers.Protocol.WFS({
version: '1.1.0',
srsName: srsName,
featureType: instance.conf.registerUnitFeatureType,
featureNS: 'http://xml.nls.fi/ktjkiiwfs/2010/02',
featurePrefix: 'ktjkiiwfs',
url: instance.conf.queryUrl
});
var urlCommit = instance.conf.transactionUrl || instance.conf.queryUrl;
this.protocols.parcelCommit = new OpenLayers.Protocol.WFS({
version: '1.1.0',
srsName: srsName,
featureType: this.instance.conf.parcelFeatureType,
featureNS: 'http://xml.nls.fi/ktjkiiwfs/2010/02',
featurePrefix: 'ktjkiiwfs',
url: urlCommit
});
this.protocols.registerUnitCommit = new OpenLayers.Protocol.WFS({
version: '1.1.0',
srsName: srsName,
featureType: this.instance.conf.registerUnitFeatureType,
featureNS: 'http://xml.nls.fi/ktjkiiwfs/2010/02',
featurePrefix: 'ktjkiiwfs',
url: urlCommit
});
this.response = null;
}, {
/**
* @method loadParcel
* Loads feature from the server asynchronously and gets the feature via callback.
* @param {String} fid FID for the feature that should be loaded from the server.
* @param {Function} cb Callback function. Requires the downloaded feature as a parameter or undefined if error occurred.
*/
loadParcel: function (fid, cb) {
this._downloadFeature(fid, this.protocols.parcel, cb);
},
/**
* @method loadRegisterUnit
* Loads feature from the server asynchronously and gets the feature via callback.
* @param {String} fid FID for the feature that should be loaded from the server.
* @param {Function} cb Callback function. Requires the downloaded feature as a parameter or undefined if error occurred.
*/
loadRegisterUnit: function (fid, cb) {
this._downloadFeature(fid, this.protocols.registerUnit, cb);
},
/**
* @method saveParcel
* Saves feature to the server asynchronously and gives the success information via callback.
* @param {OpenLayers.Feature.Vector} feature The feature whose data will be saved to the server by using WFST.
* @param {String} placeName Name of the place.
* @param {String} placeDescription Description of the place.
* @param {Fuction} cb Requires information about the success as boolean parameter.
*/
saveParcel: function (feature, placeName, placeDescription, cb) {
this._commitFeature(feature, placeName, placeDescription, this.protocols.parcelCommit, cb);
},
/**
* @method saveRegisterUnit
* Saves feature to the server asynchronously and gives the success information via callback.
* @param {OpenLayers.Feature.Vector} feature The feature whose data will be saved to the server by using WFST.
* @param {String} placeName Name of the place.
* @param {String} placeDescription Description of the place.
* @param {Fuction} cb Requires information about the success as boolean parameter.
*/
saveRegisterUnit: function (feature, placeName, placeDescription, cb) {
// no use ? this._commitFeature(feature, placeName, placeDescription, this.protocols['registerUnitCommit'], cb);
},
/**
* @method _downloadFeature
* @private
* Loads feature from the server asynchronously and gets the feature via callback.
* @param {String} fid FID for the feature that should be loaded from the server.
* @param {Function} cb Callback function. Requires the downloaded feature as a parameter or undefined if error occurred.
*/
_downloadFeature: function (fid, protocol, cb) {
var me = this,
lit,
i,
j;
// IE11 workaround: http://osgeo-org.1560.x6.nabble.com/WFS-and-IE-11-td5090636.html
var _class = OpenLayers.Format.XML;
var originalWriteFunction = _class.prototype.write;
var patchedWriteFunction = function()
{
var child = originalWriteFunction.apply( this, arguments );
// NOTE: Remove the rogue namespaces as one block of text.
// The second fragment "NS1:" is too small on its own and could
// cause valid text (in, say, ogc:Literal elements) to be erroneously removed.
child = child.split('xmlns:NS1="" NS1:').join('');
return child;
};
_class.prototype.write = patchedWriteFunction;
// Handle two fid formats: with "0" or "-" symbols
if (fid.indexOf("-") === -1) {
lit = fid;
} else {
lit = "";
var fields = fid.split("-");
// Not valid?
if (fields.length !== 4) return;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3 - fields[i].length; j++) {
lit = lit.concat("0");
}
for (j = 0; j < fields[i].length; j++) {
lit = lit.concat(fields[i].charAt(j));
}
}
for (i = 2; i < 4; i++) {
for (j = 0; j < 4 - fields[i].length; j++) {
lit = lit.concat("0");
}
for (j = 0; j < fields[i].length; j++) {
lit = lit.concat(fields[i].charAt(j));
}
}
}
var filter = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: 'ktjkiiwfs:kiinteistotunnus',
value: lit
});
var loc = this.instance.getLocalization('notification').placeLoading,
dialog = Oskari.clazz.create('Oskari.userinterface.component.Popup'),
controlButtons,
cancelBtn;
controlButtons = [];
cancelBtn = Oskari.clazz.create('Oskari.userinterface.component.buttons.CancelButton');
cancelBtn.setHandler(function () {
if (me.response) {
protocol.abort(me.response);
me.response = null;
}
dialog.close();
});
cancelBtn.addClass('primary');
controlButtons.push(cancelBtn);
dialog.show(loc.title, loc.message, controlButtons);
this.response = protocol.read({
filter: filter,
callback: function (response) {
dialog.close();
if (response && response.features && response.features.polFeatures && response.features.polFeatures.length > 0) {
cb(response.features);
} else {
var locError = me.instance.getLocalization('notification').error;
me.instance.showMessage(locError.title, locError.loadPlace);
cb();
}
}
});
},
/**
* @method _commitFeature
* Saves feature to the server asynchronously and gives the success information via callback.
* @param {OpenLayers.Feature.Vector} feature The feature whose data will be saved to the server by using WFST.
* @param {String} placeName Name of the place.
* @param {String} placeDescription Description of the place.
* @param {OpenLayers.Protocol.WFS} protocol The protocol that is used for the WFST action.
* @param {Fuction} cb Requires information about the success as boolean parameter.
*/
_commitFeature: function (feature, placeName, placeDescription, protocol, cb) {
var me = this;
// Set the place and description for the feature if they are given.
// If they are not given, then do not set them.
if (feature.attributes) {
if (placeName) {
// Here we suppose that server uses "nimi" property for the place name.
feature.attributes.nimi = placeName;
}
if (placeDescription || typeof placeDescription === "string") {
// Set the place description also if an empty string is given.
// Here we suppose that server uses "kuvaus" property for the place description.
feature.attributes.kuvaus = placeDescription;
}
}
// Insert feature to the server if transaction URL differs from the query URL that has given the feature.
// Otherwise, update data if the query server is same as the transaction server.
var featureState = feature.state;
if (this.instance.conf.transactionUrl && this.instance.conf.queryUrl != this.instance.conf.transactionUrl) {
feature.toState(OpenLayers.State.INSERT);
} else {
// toState may handle some workflow stuff and may not work here
feature.toState(OpenLayers.State.UPDATE);
// just to be sure
feature.state = OpenLayers.State.UPDATE;
}
// Before commit, change the fid to be number.
// Query server may give a prefix in fid but it is not wanted in commit.
feature.fid = me._parseFidNumber(feature.fid);
// Show dialog to inform about the asynchronous operation.
var dialogAdding = Oskari.clazz.create('Oskari.userinterface.component.Popup'),
loc = this.instance.getLocalization('notification').placeAdding;
dialogAdding.show(loc.title, loc.message);
// Commit feature to the server.
protocol.commit([feature], {
callback: function (response) {
dialogAdding.close();
// Change feature state to its original value after operation
// because state was set above for the commit.
feature.state = featureState;
var success = response && !response.error;
if (!success) {
var locError = me.instance.getLocalization('notification').error;
me.instance.showMessage(locError.title, locError.savePlace);
}
// Callback requires information about the success.
cb(success);
}
});
},
/**
* @method _parseFidNumber
* @private
* Removes the possible string prefix from the given fid.
* @param {String} fid
* @return {String} Parsed fid. Notice, this will return only positive numbers. "-" is also parsed away.
*/
_parseFidNumber: function (fid) {
var newFid = fid;
if (newFid && (typeof newFid) === "string" && newFid.length > 0 && !isNaN(newFid.substr(length - 1))) {
// Get the number from the end of the string.
// Possible string prefix is removed.
newFid = parseInt(newFid.match(/(\d+)$/)[0], 10);
}
return newFid;
},
/**
* Custom parser for Parcel WFS request
*
* @param request OpenLayers.Protocool.WFS parseResponse param
* @param options OpenLayers.Protocool.WFS parseResponse param
* @returns {{}} Parcel polygons and polygon boundary points
* @private
*/
_parseResponse: function (request, options) {
var me = this,
featureSet = {},
pointFeatures = [],
formatgml = new OpenLayers.Format.GML(),
format = new OpenLayers.Format.XML(),
pf;
// Point features
var document = format.read(request.responseText).documentElement;
if (document) {
var featureNodes = document.getElementsByTagName("ktjkiiwfs:rajamerkinTietoja");
if (featureNodes.length === 0) featureNodes = document.getElementsByTagName("rajamerkinTietoja"); // crome
for (var i = 0; i < featureNodes.length; i++) {
pf = formatgml.parseFeature(featureNodes[i]);
if (pf) {
pointFeatures.push(pf);
}
}
}
// Polygon features
var gmlOptionsm = {
featureType: me.instance.conf.parcelFeatureType,
featurePrefix: "ktjkiiwfs",
featureNS: "http://xml.nls.fi/ktjkiiwfs/2010/02"
};
var gmlOptionsInm = OpenLayers.Util.extend(
OpenLayers.Util.extend({}, gmlOptionsm)
);
var formatm = new OpenLayers.Format.GML.v3(gmlOptionsInm),
polFeatures = formatm.read(request.responseText);
featureSet.polFeatures = polFeatures;
featureSet.pointFeatures = pointFeatures;
return featureSet;
}
});
| uhef/Oskari-Routing-frontend | bundles/framework/bundle/parcel/service/ParcelWfst.js | JavaScript | mit | 15,087 |
$(window).scroll(function () {
if ($(this).scrollTop() >= 50) { // If page is scrolled more than 50px
$('#return-to-top').fadeIn(100); // Fade in the arrow
} else {
$('#return-to-top').fadeOut(100); // Else fade out the arrow
}
});
$('#return-to-top').click(function () { // When arrow is clicked
$('body,html').animate({
scrollTop: 0 // Scroll to top of body
}, 500);
});
| East-Assembly/godledmusic | js/scroll.js | JavaScript | mit | 417 |
// Require mongoose
var mongoose = require("mongoose");
// Create Schema class
var Schema = mongoose.Schema;
// Create article schema
var ArticleSchema = new Schema({
// title is a required string
title: {
type: String,
required: true
},
// url is a required string
url: {
type: String,
unique: true,
required: true
},
date: {
type: Date
},
// This saves an array of note's ObjectId, ref refers to the Note model
note: [{
type: Schema.Types.ObjectId,
ref: "Note"
}]
});
// Create the Article model with the ArticleSchema
var Article = mongoose.model("Article", ArticleSchema,"Article");
// Export the model
module.exports = Article;
| KevinAngeles/nytreact | models/Article.js | JavaScript | mit | 716 |
define(['views/menu/Menu', 'views/deck-info/DeckInfoDialog',
'views/select-item/SelectItemDialog', 'views/create-item/CreateItemDialog',
'views/create-backup/CreateBackupDialog', 'views/restore-backup/RestoreBackupDialog',
'views/review-mode/ReviewModeDialog',
'views/loading-cards/LoadingCards1Dialog', 'views/loading-cards/LoadingCards2Dialog',
'views/card-view/CardView', 'views/decks-list/DecksView',
'views/select-file/SelectFileDialog'],
function(Menu, DeckInfoDialog, SelectItemDialog, CreateItemDialog,
CreateBackupDialog, RestoreBackupDialog, ReviewModeDialog,
LoadingCards1Dialog, LoadingCards2Dialog,
CardView, DecksView, SelectFileDialog){
return {
menu : {
view : Menu
},
'deck-info' : {
view : DeckInfoDialog
},
'select-lang' : {
view : SelectItemDialog,
options : {
title : 'Select lang'
}
},
'create-deck' : {
view : CreateItemDialog,
options : {
title : 'Create Deck'
}
},
'select-decks' : {
view : SelectItemDialog,
options : {
title : 'Select Decks'
}
},
'create-backup' : {
view : CreateBackupDialog
},
'restore-backup' : {
view : RestoreBackupDialog
},
'review-mode' : {
view : ReviewModeDialog
},
'select-target-deck' : {
view : SelectItemDialog,
options : {
title : 'Select target Deck for cards'
}
},
'load-cards-1' : {
view : LoadingCards1Dialog
},
'load-cards-2' : {
view : LoadingCards2Dialog
},
'decks-list' : {
view : DecksView
},
'card-view' : {
view : CardView
},
'select-file' : {
view : SelectFileDialog
}
};
}); | iuriikyian/lang-flashcards | src/js/app/ViewsConfig.js | JavaScript | mit | 1,604 |
import ReactDOM from 'react-dom';
import React from 'react';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { syncHistory, routeReducer } from 'react-router-redux';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { fetchUser } from './actions/userProfileActions';
import adminReducers from './reducers/admin';
import modalReducer from './reducers/modals';
import AdminComponent from './components/admin/AdminComponent';
import AdminHomeComponent from './components/admin/AdminHomeComponent';
const appReducer = combineReducers(Object.assign({}, adminReducers, {
routing: routeReducer
}));
const reduxRouterMiddleware = syncHistory(browserHistory);
const createStoreWithMiddleware = applyMiddleware(reduxRouterMiddleware, thunk)(createStore);
const store = createStoreWithMiddleware(appReducer);
const getRoutes = (store) => {
const hasLoggedInUser = (nextState, replaceState, callback) => {
const state = store.getState();
if (!state.userProfileReducer.user) {
store.dispatch(fetchUser()).then(
({ type, payload }) => {
callback();
},
(err) => { window.location = '/login' }
);
}
};
return (
<Route path='admin' component={AdminComponent} onEnter={hasLoggedInUser}>
<IndexRoute component={AdminHomeComponent} />
</Route>
);
};
(function() {
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
{ getRoutes(store) }
</Router>
</Provider>, document.getElementById('app-container'));
}());
| jrm2k6/i-heart-reading | resources/assets/js/i-heart-reading-admin.js | JavaScript | mit | 1,677 |
GLOW.ThreeJS = (function() {
"use strict"; "use restrict";
// methods
// init - set up uniform to handle THREE math
return {
init: function() {
if( THREE === undefined ) {
GLOW.error( "GLOW.ThreeJS.init: THREE is not loaded. Quitting." );
return;
}
GLOW.Uniform.prototype.getNativeValue = function() {
if( !this.data.GLOW ) {
if( this.data instanceof THREE.Vector2 ) {
this.data.GLOW = new Float32Array( 2 );
this.getNativeValue = function() {
this.data.GLOW[ 0 ] = this.data.x;
this.data.GLOW[ 1 ] = this.data.y;
return this.data.GLOW;
};
} else if( this.data instanceof THREE.Vector3 ) {
this.data.GLOW = new Float32Array( 3 );
this.getNativeValue = function() {
this.data.GLOW[ 0 ] = this.data.x;
this.data.GLOW[ 1 ] = this.data.y;
this.data.GLOW[ 2 ] = this.data.z;
return this.data.GLOW;
};
} else if( this.data instanceof THREE.Vector4 ) {
this.data.GLOW = new Float32Array( 4 );
this.getNativeValue = function() {
this.data.GLOW[ 0 ] = this.data.x;
this.data.GLOW[ 1 ] = this.data.y;
this.data.GLOW[ 2 ] = this.data.z;
this.data.GLOW[ 3 ] = this.data.w;
return this.data.GLOW;
};
} else if( this.data instanceof THREE.Color ) {
this.data.GLOW = new Float32Array( 3 );
this.getNativeValue = function() {
this.data.GLOW[ 0 ] = this.data.r;
this.data.GLOW[ 1 ] = this.data.g;
this.data.GLOW[ 2 ] = this.data.b;
return this.data.GLOW;
};
} else if( this.data instanceof THREE.Matrix3 ) {
this.data.GLOW = new Float32Array( 9 );
this.getNativeValue = function() {
this.data.GLOW[ 0 ] = this.data.n11;
this.data.GLOW[ 1 ] = this.data.n21;
this.data.GLOW[ 2 ] = this.data.n31;
this.data.GLOW[ 3 ] = this.data.n12;
this.data.GLOW[ 4 ] = this.data.n22;
this.data.GLOW[ 5 ] = this.data.n32;
this.data.GLOW[ 6 ] = this.data.n13;
this.data.GLOW[ 7 ] = this.data.n23;
this.data.GLOW[ 8 ] = this.data.n33;
return this.data.GLOW;
};
} else if( this.data instanceof THREE.Matrix4 ) {
this.data.GLOW = new Float32Array( 16 );
this.getNativeValue = function() {
this.data.flattenToArray( this.data.GLOW );
return this.data.GLOW;
};
}
return this.getNativeValue();
}
};
},
// parse geometry
parseGeometry: function( geometry ) {
if( geometry.GLOW ) return geometry.GLOW;
var elements = [];
var vertices = [];
var normals = [];
var uvs = [];
var colors = [];
var edges = [];
var e, el = geometry.faces.length, ei = 0;
var i, il, iLetters = [ "a", "b", "c", "d" ];
var element, vertex, uv, color, normal;
for( e = 0; e < el; e++ ) {
// elements
element = geometry.faces[ e ];
if( element instanceof THREE.Face3 ) {
elements.push( ei++ );
elements.push( ei++ );
elements.push( ei++ );
il = 3;
} else {
elements.push( ei + 0 );
elements.push( ei + 1 );
elements.push( ei + 2 );
elements.push( ei + 0 );
elements.push( ei + 2 );
elements.push( ei + 3 );
ei += 4;
il = 4;
}
// vertices
for( i = 0; i < il; i++ ) {
vertex = geometry.vertices[ element[ iLetters[ i ]]].position;
vertices.push( vertex.x );
vertices.push( vertex.y );
vertices.push( vertex.z );
}
// colors
if( element.vertexColors && element.vertexColors.length ) {
for( i = 0; i < il; i++ ) {
color = element.vertexColors[ i ];
colors.push( color.r );
colors.push( color.g );
colors.push( color.b );
}
} else if( element.color ) {
color = element.color;
for( i = 0; i < il; i++ ) {
color = element.vertexColors[ i ];
colors.push( color.r );
colors.push( color.g );
colors.push( color.b );
}
}
// normals
if( element.vertexNormals && element.vertexNormals.length ) {
for( i = 0; i < il; i++ ) {
normal = element.vertexNormal[ i ];
normals.push( normal.x );
normals.push( normal.y );
normals.push( normal.z );
}
} else if( element.normal ) {
normal = element.normal;
for( i = 0; i < il; i++ ) {
normals.push( normal.x );
normals.push( normal.y );
normals.push( normal.z );
}
}
}
geometry.GLOW = {
elements: new Float32Array( elements ),
vertices: new Float32Array( vertices ),
colors: new Float32Array( colors ),
normals: new Float32Array( normals )
};
return geometry.GLOW;
}
};
})();
GLOW.ThreeJS.Mesh = (function() {
if( THREE ) {
"use strict"; "use restrict";
// constructor
function mesh( geometry, parameters ) {
THREE.Object3D.call( this );
// parse geometry
this.geometry = geometry;
GLOW.ThreeJS.parseGeometry( this.geometry );
if( parameters ) {
parameters.elements = this.geometry.GLOW.elements;
for( var d in parameters.data ) {
if( parameters.data[ d ] === "vertices" ) {
parameters.data[ d ] = this.geometry.GLOW.vertices;
} else if( parameters.data[ d ] === "colors" ) {
parameters.data[ d ] = this.geometry.GLOW.colors;
} else if( parameters.data[ d ] === "normals" ) {
parameters.data[ d ] = this.geometry.GLOW.normals;
} else if( parameters.data[ d ] === "matrix" ) {
parameters.data[ d ] = this.matrix;
} else if( parameters.data[ d ] === "matrixWorld" ) {
parameters.data[ d ] = this.matrixWorld;
} else if( parameters.data[ d ] === "matrixRotationWorld" ) {
parameters.data[ d ] = this.matrixRotationWorld;
} else if( parameters.data[ d ] === "position" ) {
parameters.data[ d ] = this.position;
} else if( parameters.data[ d ] === "rotation" ) {
parameters.data[ d ] = this.rotation;
} else if( parameters.data[ d ] === "scale" ) {
parameters.data[ d ] = this.scale;
}
}
this.shader = new GLOW.Shader( parameters );
}
}
// inherit
mesh.prototype = new THREE.Object3D();
mesh.prototype.constructor = mesh;
// methods
mesh.prototype.draw = function() {
this.shader.draw();
};
mesh.prototype.clone = function( except ) {
// create material-less mesh
var clone = new GLOW.ThreeJS.Mesh( this.geometry );
// match exceptions
for( var e in except ) {
if( except[ e ] === "matrix" ) {
except[ e ] = clone.matrix;
} else if( except[ e ] === "matrixWorld" ) {
except[ e ] = clone.matrixWorld;
} else if( except[ e ] === "matrixRotationWorld" ) {
except[ e ] = clone.matrixRotationWorld;
} else if( except[ e ] === "position" ) {
except[ e ] = clone.position;
} else if( except[ e ] === "rotation" ) {
except[ e ] = clone.rotation;
} else if( except[ e ] === "scale" ) {
except[ e ] = clone.scale;
}
}
// create shader
clone.shader = this.shader.clone( except );
// create and return
return clone;
};
return mesh;
}
return function() { GLOW.error( "GLOW.ThreeJS.Mesh.construct: THREE not loaded"); };
})();
| empaempa/GLOW | src/extras/compatibility/Three.js | JavaScript | mit | 10,254 |
import { expect, should } from 'chai';
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { reduxReqMiddleware } from '../src/middleware';
const lastAction = (state = { action: true }, action) => (
Object.assign({}, state, { action: action.type })
);
const rootReducer = combineReducers({
lastAction
});
describe('middleware', () => {
it('Should dispatch a request and return a success action', (done) => {
const middleware = applyMiddleware(
reduxReqMiddleware({
request: '_REQUEST',
success: '_SUCCESS',
error: '_ERROR'
}));
const store = createStore(rootReducer, {}, middleware);
const result = store.dispatch({
type: 'DATA_REQUEST',
request: new Promise((resolve) => resolve({ id: 22 }))
});
const expectedResult = {
type: 'DATA_SUCCESS',
payload: { id: 22 }
};
expect(store.getState().lastAction.action).to.equal('DATA_REQUEST');
result
.then(action => {
expect(action).to.deep.equal(expectedResult);
done();
});
});
it('Should dispatch a request and return a error action', (done) => {
const middleware = applyMiddleware(
reduxReqMiddleware({
request: '_REQUEST',
success: '_SUCCESS',
error: '_ERROR'
}));
const store = createStore(rootReducer, {}, middleware);
const result = store.dispatch({
type: 'DATA_REQUEST',
request: new Promise((resolve, reject) => reject({ err: true }))
});
const expectedResult = {
type: 'DATA_ERROR',
payload: { err: true }
};
expect(store.getState().lastAction.action).to.equal('DATA_REQUEST');
result.then(action => {
expect(action).to.deep.equal(expectedResult);
done();
});
});
it('Should dispatch a request and return a success action without config', (done) => {
const middleware = applyMiddleware(reduxReqMiddleware());
const store = createStore(rootReducer, {}, middleware);
const result = store.dispatch({
type: 'DATA',
request: new Promise((resolve) => resolve({ id: 22 }))
});
const expectedResult = {
type: 'DATA_SUCCESS',
payload: { id: 22 }
};
expect(store.getState().lastAction.action).to.equal('DATA');
result.then(action => {
expect(action).to.deep.equal(expectedResult);
done();
});
});
it('Should return an error action without config', (done) => {
const middleware = applyMiddleware(reduxReqMiddleware());
const store = createStore(rootReducer, {}, middleware);
const result = store.dispatch({
type: 'DATA',
request: new Promise((resolve, reject) => reject({ err: true }))
});
const expectedResult = {
type: 'DATA_ERROR',
payload: { err: true }
};
expect(store.getState().lastAction.action).to.equal('DATA');
result.then(action => {
expect(action.type).to.equal('DATA_ERROR');
done();
});
});
it('Should merge partial config', (done) => {
const middleware = applyMiddleware(reduxReqMiddleware({ success: '_OK' }));
const store = createStore(rootReducer, {}, middleware);
const result = store.dispatch({
type: 'LECHES',
request: new Promise((resolve) => resolve({ id: 44 }))
});
const expectedResult = {
type: 'LECHES_OK',
payload: { id: 44 }
};
expect(store.getState().lastAction.action).to.equal('LECHES');
result.then(action => {
expect(action).to.deep.equal(expectedResult);
done();
});
});
it('Should thrown an exception if request is not a promise', (done) => {
const middleware = applyMiddleware(
reduxReqMiddleware({
request: '_REQUEST',
success: '_SUCCESS',
error: '_ERROR'
}));
const store = createStore(() => ({}), middleware);
try {
store.dispatch({
type: 'DATA_REQUEST',
request: 22
});
} catch (err) {
// fixme
expect(true).to.equal(true);
done();
}
});
}); | pmagaz/redux-req-middleware | spec/middleware.spec.js | JavaScript | mit | 4,118 |
// https://www.npmjs.org/package/react-interpolate-component
// TODO: Drop this in favor of es6 string interpolation
import React from 'react';
import ValidComponentChildren from './utils/ValidComponentChildren';
const REGEXP = /\%\((.+?)\)s/;
const Interpolate = React.createClass({
displayName: 'Interpolate',
propTypes: {
format: React.PropTypes.string
},
getDefaultProps() {
return { component: 'span' };
},
render() {
let format = (ValidComponentChildren.hasValidComponent(this.props.children) ||
(typeof this.props.children === 'string')) ?
this.props.children : this.props.format;
let parent = this.props.component;
let unsafe = this.props.unsafe === true;
let props = Object.assign({}, this.props);
delete props.children;
delete props.format;
delete props.component;
delete props.unsafe;
if (unsafe) {
let content = format.split(REGEXP).reduce(function(memo, match, index) {
let html;
if (index % 2 === 0) {
html = match;
} else {
html = props[match];
delete props[match];
}
if (React.isValidElement(html)) {
throw new Error('cannot interpolate a React component into unsafe text');
}
memo += html;
return memo;
}, '');
props.dangerouslySetInnerHTML = { __html: content };
return React.createElement(parent, props);
} else {
let kids = format.split(REGEXP).reduce(function(memo, match, index) {
let child;
if (index % 2 === 0) {
if (match.length === 0) {
return memo;
}
child = match;
} else {
child = props[match];
delete props[match];
}
memo.push(child);
return memo;
}, []);
return React.createElement(parent, props, kids);
}
}
});
export default Interpolate;
| RichardLitt/react-bootstrap | src/Interpolate.js | JavaScript | mit | 1,929 |
import React from 'react';
import { Link } from 'react-router';
export default function MainMenu(props) {
return (
<ul>
<li><Link to="/races">New Game</Link></li>
<li><a>Load Game</a></li>
</ul>
)
}
| VitorHP/TI3 | src/js/components/main_menu.js | JavaScript | mit | 224 |
const express = require('express');
const router = express.Router();
router.use(function(req, res, next) {
console.log(Date.now());
next();
});
router.get('/', function(req, res) {
res.end('books');
});
router.get('/list', function(req, res) {
res.end('books-list');
});
module.exports = router;
| wangding/nodejs-demo | 20-express/05-router-module/router/books.js | JavaScript | mit | 308 |
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('form-controls/base-input', 'Integration | Component | {{form-controls/base-input}}', {
integration: true
});
test('It renders an input', function(assert) {
this.render(hbs`{{form-controls/base-input}}`);
assert.equal(this.$('input').length, 1, 'Input is rendered');
});
test(`it's possible to bind 'autocomplete'`, function(assert) {
this.render(hbs`{{form-controls/base-input autocomplete="on"}}`);
assert.equal(this.$('input').attr('autocomplete'), 'on', 'attribute autocomplete is set');
});
test(`it's possible to bind 'accesskey'`, function(assert) {
this.render(hbs`{{form-controls/base-input accesskey="x"}}`);
assert.equal(this.$('input').attr('accesskey'), 'x', 'attribute accesskey is set');
});
test(`It's possible to bind 'autofocus'`, function(assert) {
this.render(hbs`{{form-controls/base-input autofocus=true}}`);
assert.equal(this.$('input').attr('autofocus'), 'autofocus', 'Attribute autofocus is set');
});
test(`it's possible to bind 'dir'`, function(assert) {
this.render(hbs`{{form-controls/base-input dir="rtl"}}`);
assert.equal(this.$('input').attr('dir'), 'rtl', 'attribute dir is set');
});
test(`It's possible to bind 'disabled'`, function(assert) {
this.render(hbs`{{form-controls/base-input disabled=true}}`);
assert.equal(this.$('input').attr('disabled'), 'disabled', 'Attribute disabled is set');
});
test(`It's possible to bind 'form'`, function(assert) {
this.render(hbs`{{form-controls/base-input form='form_one'}}`);
assert.equal(this.$('input').attr('form'), 'form_one', 'Attribute form is set');
});
test(`it's possible to bind 'hidden'`, function(assert) {
this.render(hbs`{{form-controls/base-input hidden="hidden"}}`);
assert.equal(this.$('input').attr('hidden'), 'hidden', 'attribute hidden is set');
});
test(`it's possible to bind 'lang'`, function(assert) {
this.render(hbs`{{form-controls/base-input lang="en-US"}}`);
assert.equal(this.$('input').attr('lang'), 'en-US', 'attribute lang is set');
});
test(`It's possible to bind 'name'`, function(assert) {
this.render(hbs`{{form-controls/base-input name='username'}}`);
assert.equal(this.$('input').attr('name'), 'username', 'Attribute name is set');
});
test(`It's possible to bind 'readonly'`, function(assert) {
this.render(hbs`{{form-controls/base-input readonly=true}}`);
assert.equal(this.$('input').attr('readonly'), 'readonly', 'attribute readonly is set');
});
test(`It's possible to bind 'required'`, function(assert) {
this.render(hbs`{{form-controls/base-input required=true}}`);
assert.equal(this.$('input').attr('required'), 'required', 'attribute required is set');
});
test('Required also sets aria-required', function(assert) {
this.render(hbs`{{form-controls/base-input required=true}}`);
assert.equal(this.$('input').attr('aria-required'), 'true', 'attribute aria-required is set');
});
test('If not required, set aria-require=false', function(assert) {
this.render(hbs`{{form-controls/base-input}}`);
assert.equal(this.$('input').attr('aria-required'), 'false', 'attribute aria-required is set');
});
test('Invalid=true sets araia-invalid="true"', function(assert) {
this.render(hbs`{{form-controls/base-input invalid=true}}`);
assert.equal(this.$('input').attr('aria-invalid'), 'true', 'attribute aria-invalid is set');
});
test('It is possible to set describedBy', function(assert) {
this.render(hbs`{{form-controls/base-input describedBy="element-one"}}`);
assert.equal(this.$('input').attr('aria-describedby'), 'element-one', 'attribute aria-describedby is set');
});
test(`It's possible to bind 'tabindex'`, function(assert) {
this.render(hbs`{{form-controls/base-input tabindex=4}}`);
assert.equal(this.$('input').attr('tabindex'), 4, 'attribute tabindex is set');
});
test(`it's possible to bind 'title'`, function(assert) {
this.render(hbs`{{form-controls/base-input title="A Title"}}`);
assert.equal(this.$('input').attr('title'), 'A Title', 'attribute title is set');
});
test(`it's possible to bind 'type'`, function(assert) {
this.render(hbs`{{form-controls/base-input type="date"}}`);
assert.equal(this.$('input').attr('type'), 'date', 'attribute type is set');
});
test(`it's possible to bind 'value'`, function(assert) {
this.render(hbs`{{form-controls/base-input value="test"}}`);
assert.equal(this.$('input').val(), 'test', 'attribute value is set');
});
| nucleartide/ember-form-for | tests/integration/components/form-controls/base-input-test.js | JavaScript | mit | 4,512 |
/**
* kue hook
*/
module.exports = function (sails) {
/**
* Module dependencies.
*/
var kue = require('kue');
/**
* Expose hook definition
*/
return {
// Run when sails loads-- be sure and call `next()`.
initialize: function (next) {
sails.after('hook:orm:loaded', function () {
sails.log.info("Starting kue")
var kue_engine = sails.config.kue;
//register kue.
sails.log.info("Registering jobs")
var jobs = require('include-all')({
dirname : sails.config.appPath +'/jobs',
filter : /(.+)\.js$/,
excludeDirs : /^\.(git|svn)$/,
optional : true
});
sails.log.info("HUMPBACK.JOBS.DIR:" + sails.config.appPath + "/jobs");
_.forEach(jobs, function(job, name){
sails.log.info("Registering kue handler: "+name)
kue_engine.process(name, job);
})
process.once('SIGTERM', function (sig) {
kue_engine.shutdown(function (err) {
console.log('Kue is shut down.', err || '');
process.exit(0);
}, 5000);
});
});
return next();
}
};
}; | CaliStyle/humpback | api/hooks/kue/index.js | JavaScript | mit | 1,214 |
/*
secretcodes.js v1.0
Adds secret codes, like videogame cheat codes (e.g. Konami code), to the web browser.
You supply the codes to be performed and a callback function for each code when they are input.
AUTHOR: Adam Wicks
LICENCE: MIT
DEPENDENCIES: none!
LINK: https://github.com/procky/secretcodes
WARNING: This is NOT a secure way of adding a password and is purely for fun. This source code and your chosen "secret codes" are publicly viewable.
*/
var SCJS = {};
SCJS.Manager = (function() {
"use strict";
// If you wish to expand the dictionary you can find the number relating to the key here: https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
// Some keys cross browser vary. Keys that modify like shift+a are not supported currently. Here might help: http://unixpapa.com/js/key.html
var keyValueDictionary = {
8: "backspace",
9: "tab",
12: "num",
13: "enter",
16: "shift",
17: "ctrl",
18: "alt",
19: "pause",
20: "caps",
27: "escape",
32: "space",
33: "pageup",
34: "pagedown",
35: "end",
36: "home",
37: "left",
38: "up",
39: "right",
40: "down",
44: "print",
45: "insert",
46: "delete",
48: "0",
49: "1",
50: "2",
51: "3",
52: "4",
53: "5",
54: "6",
55: "7",
56: "8",
57: "9",
65: "a",
66: "b",
67: "c",
68: "d",
69: "e",
70: "f",
71: "g",
72: "h",
73: "i",
74: "j",
75: "k",
76: "l",
77: "m",
78: "n",
79: "o",
80: "p",
81: "q",
82: "r",
83: "s",
84: "t",
85: "u",
86: "v",
87: "w",
88: "x",
89: "y",
90: "z",
96: "num_0",
97: "num_1",
98: "num_2",
99: "num_3",
100: "num_4",
101: "num_5",
102: "num_6",
103: "num_7",
104: "num_8",
105: "num_9",
106: "num_multiply",
107: "num_add",
108: "num_enter",
109: "num_subtract",
110: "num_decimal",
111: "num_divide",
112: "f1",
113: "f2",
114: "f3",
115: "f4",
116: "f5",
117: "f6",
118: "f7",
119: "f8",
120: "f9",
121: "f10",
122: "f11",
123: "f12",
124: "print",
144: "num",
145: "scroll",
186: ";",
187: "=",
188: ",",
189: "-",
190: ".",
191: "/",
192: "`",
219: "[",
220: "\\",
221: "]",
222: "\'"
};
var secretCodeGuess = [];
var secretCodeGuessMaxLength = 0;
var secretCode = [];
var keyDownGuess = function(event) {
var charCode = (event.which) ? event.which : event.keyCode;
var guessKey = (keyValueDictionary[charCode]) ? keyValueDictionary[charCode] : 'unidentified';
var i = 0;
var secretCodeGuessStr = '';
var matchFoundIndexPosition = '';
secretCodeGuess.push(guessKey);
// Have any codes been input?
secretCodeGuessStr = secretCodeGuess.join(' ');
for(i = 0; i < secretCode.length; i++) {
matchFoundIndexPosition = secretCodeGuessStr.length - secretCode[i].code.length;
if(secretCodeGuessStr.lastIndexOf(secretCode[i].code) === matchFoundIndexPosition && matchFoundIndexPosition >= 0) {
secretCode[i].callback();
}
}
// Keep the guess array as small as possible
if(secretCodeGuess.length >= secretCodeGuessMaxLength) {
secretCodeGuess.splice(0, 1);
}
};
var domReady = function(ready) {
if(/in/.test(document.readyState)) {
return setTimeout(function() { return domReady(ready); }, 9);
}
return ready();
};
var init = function() {
var el = document;
if(el.addEventListener) {
el.addEventListener('keydown', keyDownGuess, false);
} else if(el.attachEvent) {
el.attachEvent('onkeydown', keyDownGuess);
}
};
domReady(init);
return {
addSecretCode: function(codeToSet, callbackWhenPasswordInputted) {
var codeArr = {code: codeToSet, callback: callbackWhenPasswordInputted};
secretCode.push(codeArr);
secretCodeGuessMaxLength = secretCode.reduce(function(a, b) { return a.code.split(' ').length > b.code.split(' ').length ? a : b; }).code.split(' ').length;
},
getCurrentGuess: function() {
return secretCodeGuess.join(' ');
}
};
})(); | procky/secretcodes | secretcodes.js | JavaScript | mit | 3,929 |
import { name } from 'package.json'
export default {
name,
debug: false,
keys: ['123-change-me'],
methodOverride: {
getter: '_method',
methods: ['POST']
},
etag: {
weak: false
},
compress: {
filter: undefined,
threshold: 1024
},
bodyparser: {
enableTypes: ['json', 'form'],
encode: 'utf-8',
formLimit: '56kb',
jsonLimit: '1mb',
textLimit: '1mb',
strict: true,
detectJSON: undefined,
extendTypes: {},
onError: undefined
}
}
| azide0x37/wifey | app/config/app.js | JavaScript | mit | 502 |
(function () {
'use strict';
angular
.module('publicspaces')
.run(menuConfig);
menuConfig.$inject = ['Menus'];
function menuConfig(Menus) {
// Set top bar menu items
Menus.addMenuItem('topbar', {
title: 'Publicspaces',
state: 'publicspaces',
type: 'dropdown',
roles: ['*']
});
// Add the dropdown list item
Menus.addSubMenuItem('topbar', 'publicspaces', {
title: 'List Publicspaces',
state: 'publicspaces.list'
});
// Add the dropdown create item
Menus.addSubMenuItem('topbar', 'publicspaces', {
title: 'Create Publicspace',
state: 'publicspaces.create',
roles: ['user']
});
}
})();
| mpatc/meanSpace | modules/publicspaces/client/config/publicspaces.client.config.js | JavaScript | mit | 696 |
// Layout
import markdown from 'markdown-in-js'
import withDoc, { components } from '../../../lib/with-doc'
// Author
import { todd } from '../../../lib/data/team'
export default withDoc({
title: 'License',
date: '18 Sept 2017',
authors: [todd]
})(markdown(components)`
[MIT License](https://opensource.org/licenses/MIT)
Copyright (c) 2017 Todd Austin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
`)
| cnvs/docs | pages/docs/essentials/license.js | JavaScript | mit | 1,390 |
'use strict'
import NSObject from '../ObjectiveC/NSObject'
import SKColor from '../SpriteKit/SKColor'
/**
* dummy class for NSKeyedArchiver/Unarchiver
* @access public
* @extends {NSObject}
*/
export default class NSColor extends NSObject {
/**
* @access public
* @param {NSCoder} coder -
* @returns {_Buffer} -
*/
static initWithCoder(coder) {
return SKColor.initWithCoder(coder)
}
}
| magicien/JSceneKit | src/js/AppKit/NSColor.js | JavaScript | mit | 415 |
"use strict";
const debug = require('debug')('bot-express:skill');
const zip_code = require("../sample_service/zip-code");
const mecab = require("mecabaas-client");
const support = require("../sample_service/support");
module.exports = class SkillJuminhyo {
constructor(){
this.required_parameter = {
type: {
message_to_confirm: {
type: "template",
altText: "住民票ですね。今回必要なのは世帯全員分ですか?あるいはご本人だけ?",
template: {
type: "buttons",
text: "住民票ですね。今回必要なのは世帯全員分ですか?あるいはご本人だけ?",
actions: [
{type:"message", label:"世帯全員分", text:"世帯全員分"},
{type:"message", label:"本人だけ", text:"本人だけ"}
]
}
},
parser: async (value, bot, event, context) => {
if (["世帯全員分", "本人だけ"].includes(value)){
return value;
}
throw new Error();
},
reaction: async (error, value, bot, event, context) => {
if (error){
return;
}
bot.queue({text: `${value}ですね。OKです。`});
}
},
name: {
message_to_confirm: {
type: "text",
text: "次にご本人のことを少々。お名前教えてもらえますか?"
},
parser: async (value, bot, event, context) => {
return mecab.parse(value).then(
(response) => {
let name = {};
for (let elem of response){
if (elem[3] == "人名" && elem[4] == "姓"){
name.lastname = elem[0];
} else if (elem[3] == "人名" && elem[4] == "名"){
name.firstname = elem[0];
}
}
return name;
},
(response) => {
throw new Error();
}
);
},
reaction: async (error, value, bot, event, context) => {
if (error) return;
if (value && value.lastname && value.firstname){
// We got Lastname & Firstname so going to check with user if this is correct.
bot.collect({
is_name_correct: {
message_to_confirm: {
type: "template",
altText: `一応ご確認を。${value.lastname} ${value.firstname}さんでよかったでしょうか?`,
template: {
type: "confirm",
text: `一応ご確認を。${value.lastname} ${value.firstname}さんでよかったでしょうか?`,
actions: [
{type: "message", label: "はい", text: "はい"},
{type: "message", label: "いいえ", text: "いいえ"}
]
}
},
parser: (value, bot, event, context) => {
const acceptable_values = ["はい", "いいえ"];
if (acceptable_values.indexOf(value) >= 0){
return value;
}
throw new Error();
},
reaction: (error, value, bot, event, context) => {
if (error) return;
if (value == "はい"){
bot.queue({
text: "ハイカラなお名前じゃないですか〜。いいですね。"
});
} else {
bot.queue({
text: "大変失礼しました。ご面倒ですが姓と名を順に教えていただきたく。"
});
bot.collect("lastname");
}
}
}
});
} else {
// We got limited information about Name so going to ask for the user.
bot.queue({text: `すいません、私不勉強なものでどれが姓でどれが名かわかりませんでした。ご面倒ですがそれぞれ順に教えていただきたく。`});
bot.collect("lastname");
}
}
},
zip_code: {
message_to_confirm: {
type: "text",
text: "郵便番号を教えていただけますか?"
},
parser: async (value, bot, event, context) => {
return zip_code.search(value).then(
(response) => {
// In case we could not find the address.
if (response == null){
return {
zip_code: value,
resolved_address: null
};
}
// In case we could find the address.
let address = response.address1 + response.address2 + response.address3;
return {
zip_code: value,
resolved_address: address
};
},
(response) => {
throw new Error();
}
);
},
reaction: async (error, value, bot, event, context) => {
if (error){
if (error.message == "zip code format is incorrect."){
// Provide zip code is incorrect.
bot.change_message_to_confirm("zip_code", {
type: "text",
text: "なんだか郵便番号が正しくないような気がします。もう一度教えていただいてもいいですか?"
});
return;
} else {
// While provided zip code is correct, zip code search is not working.
bot.queue({
type: "text",
text: "すみません、郵便番号検索が不調のようで該当する住所を探せませんでした。"
});
bot.collect("address");
return;
}
}
if (!value.resolved_address){
// While provided zip code seems correct, we could not find the address.
bot.queue({
type: "text",
text: "すみません、郵便番号に該当する住所が見つかりませんでした。"
});
bot.collect("address");
return;
}
// It seems we could find the corresponding address.
// Set resolved address as city.
context.confirmed.city = context.confirmed.zip_code.resolved_address;
bot.collect({
is_city_correct: {
message_to_confirm: {
type: "template",
altText: `住所は「${context.confirmed.zip_code.resolved_address}」で間違いないですか?(はい・いいえ)`,
template: {
type: "confirm",
text: `住所は「${context.confirmed.zip_code.resolved_address}」で間違いないですか?`,
actions: [
{type:"message", label:"はい", text:"はい"},
{type:"message", label:"いいえ", text:"いいえ"}
]
}
},
parser: (value, bot, event, context) => {
const acceptable_values = ["はい", "いいえ"];
if (acceptable_values.indexOf(value) >= 0){
return value;
}
throw new Error();
},
reaction: (error, value, bot, event, context) => {
if (error) return;
if (value == "はい"){
// Going to collect remaining street address.
bot.collect("street");
} else if (value == "いいえ"){
bot.collect({
zip_code: {
message_to_confirm: {
type: "text",
text: "なんと。もう一度郵便番号うかがってもいいですか?"
}
}
});
}
}
}
});
}
},
social_id: {
message_to_confirm: {
type: "text",
text: "最後に身分証をカメラで撮って送ってもらえますか?"
}
}
}
this.optional_parameter = {
lastname: {
message_to_confirm: {
type: "text",
text: "氏名(姓)を教えてもらえますか?"
},
reaction: async (error, value, bot, event, context) => {
if (error) return;
bot.collect("firstname");
}
},
firstname: {
message_to_confirm: {
type: "text",
text: "氏名(名)を教えてもらえますか?"
},
reaction: async (error, value, bot, event, context) => {
if (error) return;
bot.queue({text: `${context.confirmed.lastname} ${value}さん、なかなかナウい名前ですね。`});
}
},
street: {
message_to_confirm: {
type: "text",
text: "OK. では残りの番地を教えていただけますか?"
}
},
address: {
message_to_confirm: {
type: "text",
text: "ご住所を教えていただけますか?"
}
}
}
this.clear_context_on_finish = true;
}
async finish(bot, event, context){
let address = context.confirmed.address || context.confirmed.city + context.confirmed.street;
let name;
if (context.confirmed.is_name_correct == "はい"){
name = context.confirmed.name.lastname + " " + context.confirmed.name.firstname;
} else {
name = context.confirmed.lastname + " " + context.confirmed.firstname;
}
let messages = {
type: "text",
text: `${name}さん、完璧です。${address}が身分証のご住所と一致しているか担当者がチェックし、問題なければご住所に住民票をお届けしますね。手数料は代引きで300円です。`
};
await bot.reply(messages);
}
};
| nkjm/bot-express | sample_skill/juminhyo.js | JavaScript | mit | 13,363 |
/*
1600 - 2399 年の秋分を正しく計算できるかテスト
正確な日付は以下のアドレスから得た
https://ja.wikipedia.org/wiki/%E7%A7%8B%E5%88%86
*/
const data = [
// from to +0 +1 +2 +3 (at the boundary)
[1600, 1635, 23, 23, 23, 23],
[1636, 1667, 22, 23, 23, 23],
[1668, 1695, 22, 22, 23, 23],
[1696, 1699, 22, 22, 22, 23, 1698, 22],
[1700, 1727, 23, 23, 23, 24],
[1728, 1763, 23, 23, 23, 23, 1760, 22],
[1764, 1791, 22, 23, 23, 23],
[1792, 1799, 22, 22, 23, 23, 1793, 22],
[1800, 1823, 23, 23, 24, 24, 1822, 23],
[1824, 1851, 23, 23, 23, 24],
[1852, 1887, 23, 23, 23, 23, 1855, 23],
[1888, 1899, 22, 23, 23, 23, 1888, 22],
[1900, 1919, 23, 24, 24, 24, 1917, 23],
[1920, 1947, 23, 23, 24, 24],
[1948, 1979, 23, 23, 23, 24],
[1980, 2011, 23, 23, 23, 23],
[2012, 2043, 22, 23, 23, 23],
[2044, 2075, 22, 22, 23, 23, 2074, 22],
[2076, 2099, 22, 22, 22, 23],
[2100, 2103, 23, 23, 23, 24],
[2104, 2139, 23, 23, 23, 23],
[2140, 2167, 22, 23, 23, 23],
[2168, 2199, 22, 22, 23, 23, 2198, 22],
[2200, 2227, 23, 23, 23, 24],
[2228, 2263, 23, 23, 23, 23, 2260, 22],
[2264, 2291, 22, 23, 23, 23],
[2292, 2299, 22, 22, 23, 23],
[2300, 2323, 23, 23, 24, 24, 2322, 23],
[2324, 2351, 23, 23, 23, 24],
[2352, 2383, 23, 23, 23, 23],
[2384, 2399, 22, 23, 23, 23],
];
const assert = require('assert');
const Holidays = require('../lib/japanese-holidays.min.js');
const shubun = Holidays.__forTest.shubunWithTime;
data.forEach(function(entry){
// from to
for (var y = entry[0]; y <= entry[1]; y += 4){
for (var i = 0; i < 4; i++){
var s = shubun(y+i);
if (Holidays.getJDate(s) !== entry[2+i])
console.log(y+i, entry[2+i], Holidays.getJDate(s),
Holidays.getJHours(s), Holidays.getJMinutes(s));
assert( Holidays.getJDate(s) === entry[2+i],
"Shubun on " + (y+i) + " should be " + entry[2+i] +
" but was " + Holidays.getJDate(s));
}
}
});
| osamutake/japanese-holidays-js | test/shubun.js | JavaScript | mit | 2,063 |
// @flow
import invert from '../invert'
describe('invert', () => {
it('should invert a reduced hex color', () => {
expect(invert('#448')).toEqual('#bb7')
})
it('should invert a hex color', () => {
expect(invert('#CCCD64')).toEqual('#33329b')
})
it('should invert an 8-digit hex color', () => {
expect(invert('#6564CDB3')).toEqual('rgba(154,155,50,0.7)')
})
it('should invert an 4-digit hex color', () => {
expect(invert('#0f08')).toEqual('rgba(255,0,255,0.53)')
})
it('should invert a color with opacity', () => {
expect(invert('rgba(101,100,205,0.7)')).toEqual('rgba(154,155,50,0.7)')
})
it('should return transparent when passed transparent', () => {
expect(invert('transparent')).toEqual('transparent')
})
})
| styled-components/polished | src/color/test/invert.test.js | JavaScript | mit | 766 |
'use strict';
app.controller('NavController', function($scope, $location, Auth, toaster) {
$scope.currentUser = Auth.user;
$scope.signedIn = Auth.signedIn;
$scope.logout = function() {
Auth.logout();
toaster.pop('succes', "Logged out successfully");
//console.log("Logged out!");
$location.path('/');
};
}); | dreamtocode/Task-Rabbit | scripts/controllers/nav.js | JavaScript | mit | 324 |
JARS.internal('Handlers/BundleCoremodule', function(getInternal) {
'use strict';
var RequestHandler = getInternal('Handlers/Request'),
MSG_STRINGS = ['core module'];
/**
* @memberof JARS~internals.Handlers
*
* @param {JARS~internals.Subjects.Bundle} bundle
*
* @return {JARS~internals.Handlers.Request}
*/
function BundleCoremodule(bundle) {
return new RequestHandler(bundle, [bundle.module.name], MSG_STRINGS, function() {
bundle.processor.register();
});
}
return BundleCoremodule;
});
| HROH/JAR | src/internals/Handlers/BundleCoremodule.js | JavaScript | mit | 581 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.