text
stringlengths 2
6.14k
|
|---|
'use strict';
exports.__esModule = true;
var _slice = Array.prototype.slice;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _Container2 = require('./Container');
var _Container3 = _interopRequireDefault(_Container2);
var ContainerComponent = (function (_Container) {
_inherits(ContainerComponent, _Container);
function ContainerComponent() {
_classCallCheck(this, ContainerComponent);
_Container.apply(this, arguments);
}
ContainerComponent.prototype.componentDidMount = function componentDidMount() {
var _Container$prototype$componentDidMount;
(_Container$prototype$componentDidMount = _Container.prototype.componentDidMount).call.apply(_Container$prototype$componentDidMount, [this].concat(_slice.call(arguments)));
this.context.container.add(this.node);
};
return ContainerComponent;
})(_Container3['default']);
ContainerComponent.contextTypes = {
container: _react2['default'].PropTypes.object.isRequired
};
exports['default'] = ContainerComponent;
module.exports = exports['default'];
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var index = require('./routes/index');
//var users = require('./routes/users');
var pub_scr = require('./routes/dop.pubscr.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'dop_dcdp2')));
app.use(express.static(path.join(__dirname, 'template')));
app.use(express.static(path.join(__dirname, 'uploads')));
//app.use('/', index);
app.use('/pub_scr', pub_scr);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
|
var width = document.body.clientWidth;
var height = document.body.clientHeight;
var canvas = document.getElementById('theCanvas');
var interaction_canvas = document.getElementById('interactionCanvas');
var param_names = {
realMin: "Minimum X",
realMax: "Maximum X",
imagMin: "Minimum Y",
imagMax: "Maximum Y",
maxIter: "Maximal Iterations",
minResolution: "Minimal Resolution",
CR: "C (Real part)",
CI: "C (Imaginary part)",
newtonThresh: "Threshold",
newtonContrast: "Constrast"
}
/* Scaling */
var real_scale = d3.scale.linear()
.range([0, width])
.domain([-1.7,1.7]);
var imag_scale = d3.scale.linear()
.range([0, height])
.domain([-1,1]);
d3.selectAll("canvas")
.attr("width", width)
.attr("height", height);
var ctx = canvas.getContext('2d');
jul = fractal(width,height)
.context(ctx)
.minResolution(21);
/* Colors */
var bw = d3.scale.sqrt()
.domain([0, jul.__.maxIter])
.range(["white", "black"])
.interpolate(d3.interpolateLab);
var mixed = d3.scale.linear()
.domain([0, 12, 30, 50, 100, 180, 260, 380, 600, 800, 1200, 1600, 3200])
.range(["moccasin", "#999", "steelblue", "yellow", "brown", "#222", "pink", "purple", "#027", "#260", "orange", "yellow", "blue"])
.interpolate(d3.interpolateHcl);
var greenBlack = d3.scale.sqrt()
.domain([0, jul.__.maxIter])
.range(["black", "green"])
.interpolate(d3.interpolateLab);
var deep = d3.scale.linear()
.domain(d3.range(0,jul.__.maxIter,20))
.range(d3.range(0,100).map(function(i) { return d3.hcl(190+120*i, 40+35*Math.round(Math.cos(i/5)), 18+6*(i%10)).toString(); }))
.interpolate(d3.interpolateLab);
var zoom = d3.behavior.zoom()
.x(real_scale)
.y(imag_scale)
.on("zoom", onzoom)
function onzoom() {
d3.select("#input-realMin").attr("value", real_scale.domain()[0]);
d3.select("#input-imagMin").attr("value", imag_scale.domain()[0]);
d3.select("#input-realMax").attr("value", real_scale.domain()[1]);
d3.select("#input-imagMax").attr("value", imag_scale.domain()[1]);
jul.zoom(real_scale.domain(), imag_scale.domain());
};
function resetZoom() {
real_scale.domain([-1.7,1.7]);
imag_scale.domain([-1,1]);
zoom.scale(1)
.translate([0,0])
.x(real_scale)
.y(imag_scale);
onzoom();
}
function changeMethod(method){
real_scale.domain([-1.7,1.7]);
imag_scale.domain([-1,1]);
zoom.scale(1)
.translate([0,0])
.x(real_scale)
.y(imag_scale);
d3.select("#input-realMin").attr("value", real_scale.domain()[0]);
d3.select("#input-imagMin").attr("value", imag_scale.domain()[0]);
d3.select("#input-realMax").attr("value", real_scale.domain()[1]);
d3.select("#input-imagMax").attr("value", imag_scale.domain()[1]);
jul.changeMethod(method, real_scale.domain(), imag_scale.domain());
updateKeys(method);
activate(method)
}
function activate(method){
d3.selectAll(".subchoice").classed("active", false)
d3.selectAll(".choice").classed("active", false)
d3.select("#"+method.id).classed("active", true)
}
function updateMethods() {
d3.select("#methods").html("")
d3.keys(jul._menuItems).
forEach(function(menuItem) {
var menu = jul._menuItems[menuItem]
d3.select("#methods")
.append("span")
.attr("id", menu.main.id)
.attr("class", "choice")
.html(menu.name+"<br/>")
.on("click", function(){changeMethod(menu.main)})
menu.others.forEach(function(item){
d3.select("#methods")
.append("span")
.attr("id", item.id)
.attr("class", "subchoice")
.html(item.name+"<br/>")
.on("click", function(){changeMethod(item)})
})
});
}
function changeColor(color){
jul.changeColor(color)
d3.select("#mixed").classed("active", color==mixed);
d3.select("#deep").classed("active", color==deep);
d3.select("#bw").classed("active", color==bw);
d3.select("#greenBlack").classed("active", color==greenBlack);
}
// bind inputs to julia parameters
function updateKeys(method) {
d3.select("#tools").html('')
d3.keys(jul.__).filter(
function(key){
var specificFilterJ = (method.id == 'j' || method.id=='j3') | ((key != "CR") & (key != "CI"));
var specificFilterN = method.id== 'n' | ((key != "newtonThresh") & (key != "newtonContrast"));
var generalFilter = (key!= "method");
return specificFilterJ & specificFilterN & generalFilter;
}).
forEach(function(key) {
d3.select("#tools")
.append("div")
.html(param_names[key] + "<br/>")
.append("input")
.attr({
id: "input-" + key,
type: "text",
value: jul[key]()
})
.on("keyup", function() {
jul[key](this.value);
});
});
}
jul.color = deep;
updateKeys(jul.__.method);
updateMethods()
activate(jul.__.method)
jul.go();
d3.select(interaction_canvas)
.call(zoom);
window.onresize = function() {
width = document.body.clientWidth;
height = document.body.clientHeight;
real_scale.range([0, width]);
imag_scale.range([0, height]);
jul.x_extent(width)
.y_extent(height);
d3.selectAll("canvas")
.attr("width", width)
.attr("height", height);
resetZoom()
}
|
import DynamicLayer from 'esri/layers/ArcGISDynamicMapServiceLayer';
import TiledLayer from 'esri/layers/ArcGISTiledMapServiceLayer';
import ImageLayer from 'esri/layers/ArcGISImageServiceLayer';
import ImageParameters from 'esri/layers/ImageParameters';
import WebTiledLayer from 'esri/layers/WebTiledLayer';
import GraphicsLayer from 'esri/layers/GraphicsLayer';
import FeatureLayer from 'esri/layers/FeatureLayer';
import SimpleRenderer from 'esri/renderers/SimpleRenderer';
import Symbols from 'helpers/Symbols';
import KEYS from 'js/constants';
import {errors} from 'js/config';
/**
* Map Function that gets called for each entry in the provided layers config and returns an array of ArcGIS Layers
* @param {object} layer - Layer Config object, see the layersConfig object in js/map/config.js for example
* @return {Layer} esriLayer - Some sort of esri layer, current types are:
* - ArcGISDynamicMapServiceLayer
* - ArcGISTiledMapServiceLayer
* - ArcGISImageServiceLayer
* - FeatureLayer
*/
export default (layer) => {
if ((!layer.url && layer.type !== 'graphic') || !layer.type) { throw new Error(errors.missingLayerConfig); }
let esriLayer, options = {}, imageParameters;
switch (layer.type) {
case 'tiled':
options.id = layer.id;
options.visible = layer.visible || false;
esriLayer = new TiledLayer(layer.url, options);
break;
case 'webtiled':
options.id = layer.id;
options.visible = layer.visible || false;
esriLayer = new WebTiledLayer(layer.url, options);
break;
case 'image':
options.id = layer.id;
options.visible = layer.visible || false;
options.opacity = layer.opacity || 1;
esriLayer = new ImageLayer(layer.url, options);
break;
case 'dynamic':
// Create some image parameters
imageParameters = new ImageParameters();
imageParameters.layerOption = ImageParameters.LAYER_OPTION_SHOW;
imageParameters.layerIds = layer.layerIds;
imageParameters.format = 'png32';
// Populate the options and then add the layer
options.id = layer.id;
options.visible = layer.visible || false;
options.opacity = layer.opacity || 1.0;
options.imageParameters = imageParameters;
if (layer.defaultDefinitionExpression) {
var layerDefs = [];
layer.layerIds.forEach(val => {
// ['ACQ_DATE', 1]
// "ACQ_DATE > date'" + new window.Kalendae.moment().subtract(1, 'd').format('YYYY-MM-DD') + "'",
const date = new Date();
date.setDate(date.getDate() - layer.defaultDefinitionExpression[1]);
const dateString = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
layerDefs[val] = layer.defaultDefinitionExpression[0] + ' > date \'' + dateString + '\'';
// layerDefs[val] = layer.defaultDefinitionExpression;
});
imageParameters.layerDefinitions = layerDefs;
}
esriLayer = new DynamicLayer(layer.url, options);
break;
case 'feature':
options.id = layer.id;
options.visible = layer.visible || false;
options.outFields = layer.outFields || ['*'];
esriLayer = new FeatureLayer(layer.url, options);
if (layer.id === KEYS.smallGrants) {
const pointSymbol = Symbols.getGrantsPointSymbol();
const renderer = new SimpleRenderer(pointSymbol);
esriLayer.renderer = renderer;
}
break;
case 'graphic':
options.id = layer.id;
options.visible = layer.visible || false;
esriLayer = new GraphicsLayer(options);
break;
default:
throw new Error(errors.incorrectLayerConfig(layer.type));
}
return esriLayer;
};
|
const path = require('path');
module.exports = (config, env) => {
const moduleResolve = config.resolve.modules;
moduleResolve.push(path.resolve('./src'));
return config;
}
|
var _debug = true;
var ajaxCalls = new Array();
var resultDisplayed = false;
$( document ).ready(function() {
$("#searchField").first().focus();
});
$('#advanced_link').click(function() {
$('#advanced_link').addClass("hide");
$('#row_advanced_search').removeClass("hide");
});
$('#combo_structure').change(function() {
$('#combo_sous_structure').html('<option value="">Chargement...</option>');
$.ajax({
url: 'sous-structure.php',
data: {struct: $('#combo_structure').val()}
})
.done(function (data) {
debug("done sous-structure with data: " + data);
var html = '<option value="">Sous-Structure</option>';
data.forEach(function(elt) {
html += '<option value="'+ elt.structure.structId +'">'+ elt.structureLibelle +'</option>';
});
$('#combo_sous_structure').html(html);
})
.fail(function () {
debug("error");
})
.always(function () {
debug("complete");
});
search();
});
$('#combo_sous_structure').change(function() {
search();
});
$('#searchField').on('input', function (e) {
cancelAjaxCalls();
search();
});
function search() {
text = $('#searchField').val();
if (text.length > 2 || $('#combo_structure').val() != '') {
$("#row_result").html('');
$("#row_result").addClass("loading");
var ajaxCall = $.ajax({
url: 'result.php',
data: {
name: text,
struct: $('#combo_structure').val(),
sstruct: $('#combo_sous_structure').val()
}
})
.done(function (data) {
debug("done for: " + text);
$("#row_result").removeClass("loading");
$('#row_result').html(data);
})
.fail(function () {
debug("error");
})
.always(function () {
debug("complete");
ajaxCalls.slice(ajaxCalls.indexOf(ajaxCall));
});
ajaxCalls.push(ajaxCall);
displayResult();
}else {
$("#row_result").html('');
$("#row_result").removeClass('loading');
}
}
function displayResult() {
if (!resultDisplayed)
{
$('#search').removeClass("vertical-center");
$('#search').addClass("top-search");
$('#column_logo').removeClass("small-12");
$('#column_logo').addClass("small-5");
$('#column_logo').addClass("medium-3");
$('#column_logo').addClass("large-2");
$('#column_search').removeClass("small-12");
$('#column_search').addClass("small-7");
$('#column_search').addClass("medium-9");
$('#column_search').addClass("large-10");
$('#column_logo').html('<a href="' + SITE_URL + '">' + $('#column_logo').html() + '</a>');
resultDisplayed = true;
}
}
function cancelAjaxCalls() {
debug("Cancelling all ajax calls...");
debug(ajaxCalls);
ajaxCalls.forEach(function (a) {
a.abort();
ajaxCalls.slice(ajaxCalls.indexOf(a),1);
});
}
function debug(msg) {
if (_debug) {
console.log(msg);
}
}
|
// api used to check the status of the service and database
module.exports = (db) => {
var express = require('express');
var router = express.Router();
router.use('/status', function(req, res, next) {
console.log('status router.use');
next();
});
router.route('/status')
.get(function(req, res) {
console.log('GET /status');
res.sendStatus(200);
})
.post(function(req, res) {
console.log('POST /status');
console.log('body: %j', req.body);
res.sendStatus(200);
});
router.route('/status/db')
.get(function(req, res) {
console.log('GET /status/db');
db.query('SELECT 1', function(err, rows) {
//db.ping(function(err) {
if(err) {
res.status(err.status || 500);
res.json({message: err.message, error: err });
}
else
res.sendStatus(200);
});
});
return router;
};
|
'use strict';
// 培训信息子集
exports = module.exports = function(mongo, mongoose) {
var trainInfoSubset = new mongoose.Schema({
startDate: { type: Date }, // 培训起始时间
content: { type: String }, // 培训内容
lessonHour: { type: Number }, // 课时
notes: { type: String }, // 备注
endDate: { type: Date }, // 培训结束时间
lecturer: { type: String }, // 主讲师
address: { type: String }, // 培训地址
employee: { type: mongoose.Schema.Types.ObjectId, ref: "Employee" }, // 员工ID
_remove: { type: Boolean }
});
trainInfoSubset.index({ employee: 1 });
trainInfoSubset.index({ _remove: 1 });
mongo.model('TrainInfoSubset', trainInfoSubset);
};
|
'use strict';
const CONSTANTS = require('./../constants');
const resetRoles = (data, message) => {
let reply = 'You have no roles to reset ' + message.author.toString();
if (message.member.roles.cache) {
var found = false;
//reset user roles
message.member.roles.cache.forEach( (role) => {
if (CONSTANTS.PROTECTED_ROLES.indexOf(role.name) == -1) {
if(!found) reply = message.author.toString() + ', I am removing the following roles:';
found = true;
reply += ' ' + role.name;
message.member.roles.remove(role).catch(console.error);
}
});
found = false;
// reset channel overwritten permissions
Object.keys(data.channelsByName).forEach((channelName) => {
let channel = data.channelsByName[channelName];
if(channel.name.indexOf('-') > -1) {
let foundOverwrite = channel.permissionOverwrites.get(message.author.id);
if(foundOverwrite) {
if(!found) reply += '\n' + message.author.toString() + ', I am unhiding these neighborhood channels: ';
found = true; // do not repeat found message
reply += `#${channel.name}`;
foundOverwrite.delete();
}
}
});
}
message.channel.send(reply);
return reply;
};
module.exports = (data) => ( (message) => {
return resetRoles(data, message);
});
|
// http://bonesmoses.org/2016/07/15/pg-phriday-a-postgres-persepctive-on-mongodb/
use db
var timing = new Array()
var currentDate = new Date();
currentDate.setHours(0,0,0,0)
var batch = new Array()
var start = new Date()
for (var i = 1; i <= 1000000; i++) {
batch[i] = {
_id: i,
location: i % 1000,
reading: i % 100,
readingDate: new Date(currentDate - i * 10000)
}
}
db.sensorLog.insert(batch)
// We start at 1 to match the ID of the MySQL query performance data
timing[1] = (new Date() - start) / 1000
// 13.638
start = new Date()
db.sensorLog.ensureIndex( { readingDate: 1 } )
timing[2] = (new Date() - start) / 1000
// 3.013
var currentDate = new Date()
currentDate.setHours(0,0,0,0)
start = new Date()
db.sensorLog.update({
readingDate: {
$gte: new Date(currentDate.getTime() - 8*86400000),
$lt: new Date(currentDate.getTime() - 7*86400000)
}
},
{ $inc: { reading: 1 } },
{ multi: true }
)
timing[3] = (new Date() - start) / 1000
//WriteResult({ "nMatched" : 8640, "nUpserted" : 0, "nModified" : 8640 })
// 77
start = new Date()
db.sensorLog.remove({
readingDate: {
$gte: new Date(currentDate.getTime() - 9*86400000),
$lt: new Date(currentDate.getTime() - 8*86400000)
}
}
)
timing[4] = (new Date() - start) / 1000
// WriteResult({ "nRemoved" : 8640 })
// 154
start = new Date()
db.sensorLog.count()
timing[5] = (new Date() - start) / 1000
// 4
start = new Date()
db.sensorLog.find({
readingDate: {
$lt: new Date(currentDate.getTime() - 14*86400000)
}
}
).sort({readingDate: 1}).skip(20).limit(5)
timing[6] = (new Date() - start) / 1000
// 14
timing.shift(); // Remove the 0th position
//
var output = {};
var v = 1;
timing.forEach(function(e) { this.output[this.v++] = e;});
// Produce the series (data frame)
q = { "mongo" : output }
db.dropDatabase()
|
import config from '../../config.json';
import gulp from 'gulp';
import yargs from 'yargs'
import browserSync from 'browser-sync';
const argv = yargs.argv
const browserSyncTask = () => {
var browserSyncWatch = [
config.dist.markup + '**/*.{html,php,twig,rss}',
config.dist.images.base + '**/*.{jpg,jpeg,webp,gif,png,svg,ico}',
config.dist.css + '**/*.css',
];
// Build a condition when Proxy is active
var bsProxy, bsServer;
const url = argv.url || config.browsersync.proxy;
// Condition for Proxy
if( config.browsersync.proxy ) {
bsProxy = url;
bsServer = false;
} else {
bsProxy = false;
bsServer = { baseDir : config.dist.browserSyncDir};
}
var browserSyncConfig = {
proxy: bsProxy,
ghostMode: {
clicks: true,
forms: true,
links: true,
scroll: true
},
logLevel: 'info', // info, debug, warn, silent
watchTask: true,
open: config.browsersync.openbrowser, // false if you don't want to automatically open the browser
server: bsServer,
stream: true,
notify: {
styles: [
'padding: 10px 20px;',
'font-family: arial;',
'line-height: 1',
'position: fixed;',
'font-size: 10px;',
'font-weight: bold',
'z-index: 9999;',
'top: inherit',
'border-radius: 0',
'right: 0;',
'bottom: 0;',
'color: #fff;',
'background-color: rgba(0,0,0, .5)',
'text-transform: uppercase'
]
}
}
browserSync.init(browserSyncWatch, browserSyncConfig);
}
gulp.task('browser-sync', browserSyncTask);
module.exports = { browserSyncTask }
|
import 'styles/styles.css'
import React from 'react'
import { Field } from 'redux-form'
import RenderValidationField from 'components/survey/RenderValidationField'
import { required } from 'redux-form-validators'
const TextQuestion = ({
fields,
input: { name, value },
meta: { error, submitFailed, invalid, touched },
index,
isShowcase,
isEdit,
onEdit,
type
}) => {
if (isEdit) {
return (
<div className='question-body'>
<Field name={`${name}.question`}
type='text'
className='form-control'
placeholder='Question'
component={RenderValidationField}
validate={required()}
span
/>
<div className='d-flex justify-content-end'>
<button type='button'
className='btn btn-success'
onClick={() => onEdit(true)}
disabled={invalid}
>
Save
</button>
<button type='button'
className='btn btn-danger'
onClick={() => onEdit(false)}
>
Cancel
</button>
</div>
</div>
)
}
return (
<div className='question-body'>
<Field name={`${name}.answer`}
className='form-control'
placeholder='Answer'
component={RenderValidationField}
textarea
rows='3'
validate={isShowcase && fields.get(index).isRequired ? required() : null}
/>
</div>
)
}
export default TextQuestion
|
var assert = require('assert');
var noDef = ' is not defined';
module.exports = {
str: function () {
assert(this.editor.gruntfile.toString, 'gruntfile.toString' + noDef);
return this.editor.gruntfile.toString();
},
read: function (file) {
return require('fs').readFileSync(file, 'utf-8').trim();
},
insertConfig: function (name, body) {
assert(this.editor.insertConfig, 'insertConfig' + noDef);
return this.editor.insertConfig.bind(this.editor, name, body);
},
insertVariable: function (name, value) {
assert(this.editor.insertVariable, 'insertVariable' + noDef);
return this.editor.insertVariable.bind(this.editor, name, value);
},
prependJavaScript: function (code) {
assert(this.editor.prependJavaScript, 'prependJavaScript' + noDef);
return this.editor.prependJavaScript.bind(this.editor, code);
},
appendJavaScript: function (code) {
assert(this.editor.appendJavaScript, 'appendJavaScript' + noDef);
return this.editor.appendJavaScript.bind(this.editor, code);
},
load: function (plugin) {
assert(this.editor.loadNpmTasks, 'loadNpmTasks' + noDef);
return this.editor.loadNpmTasks.bind(this.editor, plugin);
},
registerTask: function (group, desc, tasks, multi) {
assert(this.editor.registerTask, 'registerTask' + noDef);
return this.editor.registerTask.bind(this.editor, group, desc, tasks, multi);
}
};
|
/**
* Created by truls on 29.06.17.
*/
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const socialSchema = new Schema({
facebook: { type: 'String', required: false },
twitter: { type: 'String', required: false },
youtube: { type: 'String', required: false },
provider: { type: 'String', required: true },
});
export default mongoose.model('Social', socialSchema);
|
/* jshint esversion:6, node: true */
/*
* Loblaws Messenger - recipe.js
*
* Recipe search handler.
*/
const request = require('request'),
net_handler = require('../net_handler.js');
function requestRecipe(sender, query) {
console.log("[INFO] " + sender + ": Requested search for recipe with query: \'" + query + "\'");
// Produces URL to make search request with Loblaws
let url = 'https://community-food2fork.p.mashape.com/search?key=9a266ac158d1966f7a00f043259f2c5e&q=';
url = url.concat(query.trim());
// Array to be sent with request
let options = {
url: url,
headers: {
'X-Mashape-Key': 'RNsZ2tiy2pmshxmPkPRrn6viHrUwp1UZ22BjsnbuPVLyEnTS57',
'Accept': 'application/json'
}
};
// Send the search request
request(options, function callback(error, response, body) {
if (!error && response.statusCode == 200) {
let results = JSON.parse(body);
//console.log(body);
console.log("[INFO] " + "Received response from product query with: " + results.count + " results");
if (results.count !== 0) {
sendRecipeResults(sender, results.recipes);
} else {
sendTextMessage(sender, "There are no results for that search.");
}
}
});
delete net_handler.userStates.sender;
}
/*
* Process the returned recipe response, then sends it to the user.
* Makes a carouel displaying tile, description, and image.
* sender (String): The user to be sent to
* recipes (JSON Object): The response of recipes
*/
function sendRecipeResults(sender, recipes) {
let messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": loadRecipeElements(recipes) // Load the products into an object that messenger api can handle
}
}
};
if (net_handler.sendFBRequest(sender, messageData)) {
console.log("[INFO] " + sender + ": Sent recipe results");
}
}
/*
* Load recipes into an array that can be handled by messenger API.
* Makes carousel as long as the number of responses.
*/
function loadRecipeElements(recipes) {
let elements = []; // Create blank array
let length = recipes.length > 10 ? 10 : recipes.length;
for (let i = 0; i < length; i++) {
let element = {
"title": recipes[i].title, // Sets title
"subtitle": recipes[i].publisher, // Sets description
"image_url": recipes[i].image_url, // Sets image
"buttons": [
{
"type": "postback",
"title": "Let's make this!",
"payload": "recipeSelected - " + recipes[i].recipe_id
},{
"type": "web_url",
"title": "More Info",
"url": recipes[i].source_url
}
]
};
elements.push(element); // Add the element to the array
}
return elements;
}
/* Sends a text messsage to the user. */
function sendTextMessage(sender, text) {
let messageData = { text: text };
if (net_handler.sendFBRequest(sender, messageData)) {
console.log("[INFO] " + sender + ": Sent message: \'" + text + "\'");
}
}
module.exports = {
requestRecipe: requestRecipe
};
|
(function() {
'use strict';
angular.module('app.tasks', [
'app.core',
'app.widgets'
]);
})();
|
var alt = angular.module('alt', ['ngResource', 'ngRoute', 'wu.masonry']);
alt
.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', { templateUrl: '/pages/index' })
.when('/brand/chapter/products/all', { templateUrl: '/pages/brand-products-all', controller: 'brandCtrl' })
.when('/brand/chapter/products/featured', { templateUrl: '/pages/brand-products-featured' })
.when('/brand/chapter/trace', { templateUrl: '/pages/brand-products-all' })
.when('/brand/chapter/:chapter', { templateUrl: '/pages/brand-chapter' })
.when('/product', { templateUrl: '/pages/product', controller: 'productCtrl' })
.when('/products', { templateUrl: '/pages/products', controller: 'productCtrl' })
.when('/account-mylove', { templateUrl: '/pages/account-mylove', controller: 'productCtrl' })
.when('/search', { templateUrl: '/pages/search', controller: 'searchCtrl' })
.when('/signin', { templateUrl: '/pages/signin' });
});
|
this["JST"] = this["JST"] || {};
this["JST"]["test/fixtures/it's-a-bad-filename.hbs"] = Handlebars.template({"compiler":[8,">= 4.3.0"],"main":function(container,depth0,helpers,partials,data) {
return "Why would you name your file like this?";
},"useData":true});
|
var should = require('should')
var Browser = require('zombie')
var Driver = require('zombify')
describe("Viewing a hotel room", function() {
var driver = new Driver('../Hotelier')
, client = null
before(function(done) {
driver.start(done)
})
after(function(done) {
driver.stop(done)
})
describe('With a single hotel room', function() {
before(function(done) {
driver.invoke('InMemoryHotel.AddHotelRoom', {
id: '200',
number: '101',
capacity: 3
}, done)
})
describe("Viewing the room's page", function(done) {
before(function(done) {
client = new Browser()
client.visit(driver.baseHref + '/Room/Index/200', handleVisit(client, done))
})
it('Should have the hotel room number as the header', function() {
client.querySelector('h1').textContent
.should.equal('101')
})
it('Should state the room\'s capacity', function() {
client.querySelector('.capacity').textContent
.should.equal('3')
})
})
})
})
function handleVisit(client, cb) {
return function() {
if(client.statusCode !== 200) {
var message = client.querySelector('h1').textContent
var stacktrace = client.querySelector('tbody pre').textContent
console.error(message, stacktrace)
}
cb()
}
}
|
Excel.run(function (ctx) {
var chart = ctx.workbook.worksheets.getActiveWorksheet().charts.getItemAt(0);
chart.dataLabels.showSeriesName = true;
return ctx.sync();
}).catch(function (error) {
console.log(error);
});
|
//------------------------------------------------------------------
//
// Creates an explosion effect that emits all particles at creation time.
// The spec is defined as:
// {
// center: { x: , y: },
// howMany: // How many particles to emit
// }
//
//------------------------------------------------------------------
Demo.components.ParticleSystem.createEffectExplosion = function(spec) {
'use strict';
let effect = { };
effect.update = function() {
for (let particle = 0; particle < spec.howMany; particle += 1) {
//
// Create a new fire particle
let sizeStart = Random.nextGaussian(0.015, 0.005);
let sizeEnd = sizeStart * 0.2;
Demo.components.ParticleSystem.createParticle({
image: Demo.assets['fire'],
alphaStart: 1.0,
alphaEnd: 0.2,
center: { x: spec.center.x, y: spec.center.y },
sizeStart: sizeStart,
sizeEnd: sizeEnd,
direction: Random.nextCircleVector(1.0),
speed: Random.nextGaussian(0.0003, 0.0001),
rateRotation: (2 * Math.PI) / 1000, // Radians per millisecond
lifetime: Random.nextGaussian(1500, 250)
});
}
return false; // One time emit!
};
return Demo.components.ParticleSystem.addEffect(effect);
};
|
class Test {
constructor() {
}
pai() {
let list = [1, 2, 3, 4];
list.forEach(d => {
//console.log(d)
});
}
getMin() {
let getMinIdx = function (list) {
let min = Math.min(...list);
return list.indexOf(min);
};
let list = [1, 4, 6];
let sum = list.reduce((a, b) => a + b);
let list2 = [[1, 2, 3], [4, 5], [2, 4, 6]];
let tList = list2.flat();
}
}
let test = new Test();
test.getMin();
|
'use strict';
angular.module('ccFilters', []).filter('noTransparent', function() {
return function(colors) {
var output = [];
angular.forEach (colors, function(color) {
if (color.color != 'transparent') {
output.push(color);
}
})
return output;
};
});
|
/**
* Created by vmalla on 11/20/2014.
*/
var GhostServer = require('./index');
|
openRequest.onupgradeneeded = function(e){
database = e.target.result;
createObjectStore(database,"profile",false);
var ms= createObjectStore(database,"messages",false);
ms.createIndex("between",'f');
ms.createIndex("profile",'m.p.u');
createObjectStore(database,"application",true);
};
openRequest.onsuccess = function(e){
database = e.target.result;
checkSession();
};
openRequest.onerror = function(e){
console.log(e);
};
function getStore(objectStore,permission){
var tran = database.transaction([objectStore],permission);
var store = tran.objectStore(objectStore);
return store;
};
function addToStore(item,key,store){
var storeObject = getStore(store,"readwrite");
if(key){
storeObject.put(item,key);
}
if(!key){
storeObject.put(item);
}
return storeObject;
};
function createObjectStore(database,name,key){
if(database.objectStoreNames.contains(name))return null;
if(key){
return database.createObjectStore(name);
}
if(!key){
return database.createObjectStore(name,{autoIncrement:true});
}
return null;
};
|
import React, { Component } from 'react'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Header from '../Shared/Header'
import Body from './Body'
import Footer from './Footer'
import injectTapEventPlugin from 'react-tap-event-plugin';
const TheContainer = React.createClass({
render: function () {
return (
<div>
</div>
)
}
});
class MainPage extends Component {
render(){
return(
<MuiThemeProvider>
<div>
<Header />
<Body className="generic-center borderless"/>
<Footer />
</div>
</MuiThemeProvider>
)
}
}
export default MainPage
|
(function() {
'use strict';
document.addEventListener('DOMContentLoaded', function() {
var includes = document.querySelectorAll('.includes-link');
for(var i = 0; i < includes.length; i++) {
includes[i].addEventListener('click', function(e) {
e.preventDefault();
var example_box = this.parentElement.parentElement;
example_box.classList.toggle('hide-includes');
})
}
})
})();
|
import Blockly from 'node-blockly/browser';
Blockly.JavaScript['stop_motor'] = function (block) {
var motor = Blockly.JavaScript.valueToCode(block, 'MOTOR', Blockly.JavaScript.ORDER_ATOMIC);
let actualMotor = eval(motor);
return(`bot.motors.${actualMotor.motor}.stop();\n`)
};
|
'use strict';
angular.module('projects', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('projects', {
url: '/projects',
controller: 'ProjectsCtrl'
})
.state('projects.project', {
url: '/:project',
controller: 'ProjectsCtrl'
});
}])
.controller('ProjectsCtrl', ['$scope', function($scope) {
var self = this;
var project1 = {
name: 'The Insomniac',
placecard: 'cube-18.jpg',
date: (new Date(2015, 5)).getTime(),
sref: 'The-Insomniac',
content: ''
};
var project4 = {
name: 'TileTraveler',
placecard: 'composition-01.jpg',
date: (new Date(2013, 11)).getTime();
sref: 'TileTraveler',
content: ''
};
var project2 = {
name: 'GIS Lookup System',
placecard: 'photoshoot-09.jpg',
date: (new Date(2015, 5)).getTime(),
sref: 'GIS',
content: ''
};
var project3 = {
name: 'Protein Cavity Finder',
placecard: 'cube-13.jpg',
date: (new Date(2015, 4)).getTime(),
sref: 'Protein-Cavity-Finder',
content: ''
};
self.activeProject = '';
self.projectItems = [project1, project2, project3, project4];
self.projectFormData = [];
self.newProject = {name: '', placecard: '', month: 1 + (new Date()).getMonth(), year: 1970 + (new Date()).getYear(), sref: '', content: ''};
for (var i = 0; i < self.projectItems.length; i++)
{
var projectItem = projectItems[i];
self.projectFormData["_"+projectItem.sref] = {};
self.projectFormData["_"+projectItem.sref].name = projectItem.name;
self.projectFormData["_"+projectItem.sref].placecard = projectItem.placecard;
self.projectFormData["_"+projectItem.sref].date = projectItem.date;
self.projectFormData["_"+projectItem.sref].sref = projectItem.sref;
self.projectFormData["_"+projectItem.sref].content = projectItem.content;
}
$scope.$watch('$stateParams.project', function(val) {
if (val != null)
{
var newProject = self.getFromSref(val);
self.activeProject = newProject;
}
});
self.getFromSref = function (sref) {
var theProject self.projectItems.filter(function(obj)
{
return obj.sref === sref;
})
return ((theProject[0] === null || theProject[0] === undefined) ? null : theProject[0]);
};
self.resetProjectForm = function(sref) {
var modelProject = self.getFromSref(name);
self.projectFormData["_" + sref].name = modelProject.name;
self.projectFormData["_" + sref].placecard = modelProject.placecard;
self.projectFormData["_" + sref].date = modelProject.date;
self.projectFormData["_" + sref].sref = modelProject.sref;
self.projectFormData["_" + sref].content = modelProject.content;
}
self.updateProject = function(sref)
{
var projectFields = self.projectFormData["_"+sref];
var updatedProject = {name: projectFields.name, placecard: projectFields.placecard, date: projectFields.date, sref: projectFields.sref, content: projectFields.content};
console.log("Updated: \n", updatedProject);
}
self.deleteProject = function(date)
{
var delProject = self.getFromSref(name);
if($window.confirm("Delete project '" + delProject.title + "'?"))
{
console.log("Deleted: \n", delProject);
}
}
self.submitProject = function() {
var projectFields = self.projectFormData["_"+sref];
var newProject = {name: projectFields.name, placecard: projectFields.placecard, date: projectFields.date, sref: projectFields.sref, content: projectFields.content};
console.log("Submitting: ", newProject);
}
}])
|
function toggleSide(node) {
$('.sidebar').toggleClass('hidden');
$('.page-main').toggleClass('hidden');
}
$(document).ready(function(){
$('.sidebar').css('height',document.body.offsetHeight+"px");
$('.sidebar .scrollpane>ul.nav').slimScroll({
height: '100%'
});
if(!window.module)return;
var active = $('.sidebar .doc-link[module="'+module+'"][name="'+name+'"]');
active.addClass('active');
//scroll to
$('.sidebar .scrollpane ul[name="scrolllist"]').slimScroll({
scrollTo:active.offset().top - 200/*paddingTop*/ +'px'
});
});
function openWindow(path){
var code = EDITOR.getValue();
localStorage.setItem("code",code);
window.open('window.html',module+"-"+name,'width=800,height=600');
}
function runjs(){
var code = EDITOR.getValue();
localStorage.setItem("code",code);
//stop all games
soya2d.games.forEach(function(game){
game.destroy();
});
new Function(code)();
}
|
function readURL(input,x) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.img').eq(x).attr('src', e.target.result);
try {
resizeImg();
} catch(e) {
}
};
reader.readAsDataURL(input.files[0]);
}
}
|
require('chai').use(require('chai-as-promised'))
if (global.__env__) {
process.env.CHROMANODE_URL = global.__env__.CHROMANODE_URL
}
let errors = require('../src').errors
process.on('unhandledRejection', (err) => {
let msg = (err && err.stack || err).toString()
if (err instanceof errors.Network.Chromanode.Fail ||
err instanceof errors.Network.SubscribeError) {
console.error(msg.split('\n')[0])
return
}
console.log(msg)
})
describe('blockchainjs', () => {
// network
require('./network/network')
require('./network/chromanode')
// storage
require('./storage/interface')
require('./storage/indexeddb')
require('./storage/localstorage')
require('./storage/memory')
require('./storage/sqlite')
require('./storage/websql')
// blockchain
require('./blockchain/blockchain')
require('./blockchain/naive')
require('./blockchain/verified')
})
|
import state from './basket.state'
import actions from './basket.actions'
import mutations from './basket.mutations'
export default {
state,
actions,
mutations
}
|
function compose() {
const argz = arguments;
return x => [...argz].reduceRight((acc, curr) => curr(acc), x);
}
const addClass = name => el => {
el.classList.add(name);
}
const S = f => g => x => {
const fx = f(x);
const gx = g(x);
const result = fx(gx);
return result;
}
const K = x => y => {
return x;
}
const addClassOK = name => S(K)(addClass(name));
// x => K(x)(addClass(name)(x));
const getElement = document.getElementById.bind(document);
const mess = compose (addClassOK('red'), addClassOK('large'), getElement);
const mess2 = el => addClassOK('red')(addClassOK('large')(getElement(el)));
const newMess = el => PIPPO().GetElement(el).AddClassOK('large').AddClassOK('red');
function PIPPO() {
let _target;
const result = {
target: () => _target,
GetElement: id => { _target = getElement(id); return result; },
AddClassOK: name => { addClassOK(name)(result.target()); return result; },
};
return result;
}
|
import { map } from '@ember/object/computed';
import { isEmpty } from '@ember/utils';
import { observer, get, defineProperty } from '@ember/object';
import Helper from '@ember/component/helper';
export default Helper.extend({
compute([func, array]) {
this.set('func', func);
this.set('array', array);
return this.get('content');
},
changed: observer('content', function() {
this.recompute();
}),
funcDidChange: observer('func', function() {
let func = get(this, 'func');
if ( isEmpty(func) ) {
defineProperty(this, 'content', []);
return;
}
defineProperty(this, 'content', map('array', func));
}),
});
|
// chrome.tabs
// -----------------
// ref:
// - http://chrome.liuyixi.com/tabs.html
(function (root, factory) {
'use strict';
if ('function' === typeof define && define.amd) {
define([], factory);
} else {
root.tabs = factory();
}
}(window, function () {
'use strict';
var tabs = {
/* *
* 获取一个标签页对象
*
* @method get
* @param {Number} tabId 标签页 Id
* @returns {Object} 标签页对象
* */
get: function (tabId) {
return new Promise(function (resolve) {
chrome.tabs.get(tabId, function (tab) {
resolve(tab);
});
});
},
/* *
* 获取该方法被调用时所在的标签页对象,在 background 和 popup 中时返回 undefined
*
* @method getCurrent
* @returns {Object} 标签页对象
* */
getCurrent: function () {
return new Promise(function (resolve) {
chrome.tabs.getCurrent(function (tab) {
resolve(tab);
});
});
},
query: function (queryInfo) {
return new Promise(function (resolve, reject) {
chrome.tabs.query(queryInfo, function (tabs) {
var error = chrome.extension.lastError;
error ? reject(error) : resolve(tabs);
});
});
},
getSelected: function () {
return this.query({active: true});
},
getAllInWindow: function (windowId) {
return this.query({windowId: windowId});
},
/* *
* 向内容页或注入到页面的 iframe 发送消息
*
* @method sendMessage
* @param {String} tabId 标签 id
* @param {Any} message 消息内容
* @returns {Promise}
* */
sendMessage: function (tabId, message, options) {
return new Promise(function (resolve, reject) {
function cb(response) {
var error = chrome.extension.lastError;
error ? reject(error) : resolve(response);
}
options
? chrome.tabs.sendMessage(tabId, message, options, cb)
: chrome.tabs.sendMessage(tabId, message, cb);
});
}
};
return Object.freeze(tabs);
}));
|
$(document).ready(function(){
var modulante = document.getElementById("modulante");
var ctxM= modulante.getContext("2d");
var inicio2 = 0;
var inc2 = 0;
function set(){
ampMod= $("#ampMod").val();
freqMod = $("#myselect").val();
velAngular2 = 2*Math.PI/freqMod;
a = 0;
b = 125;
}
function loop(){
ctxM.fillStyle = "black";
ctxM.fill();
ctxM.fillRect(0,0,700,400);
ctxM.strokeStyle = "#33ff77";
ctxM.lineWidth = 1;
ampMod = $("#ampMod").val();
inicio2 = inc2;
for(var count = 0; count < 700; count++){
ctxM.beginPath();
ctxM.moveTo(a,b);
a++;
b = -ampMod*Math.sin(inicio2) + 125;
inicio2 += velAngular2;
ctxM.lineTo(a,b);
ctxM.stroke();
}
inc2 += velAngular2/2;
ctxM.strokeStyle = "#3333ff";
ctxM.lineWidth = 1;
//eixo X
ctxM.moveTo(0,125);
ctxM.lineTo(493,125);
ctxM.stroke();
//eixo Y
ctxM.moveTo(50,0);
ctxM.lineTo(50,250);
ctxM.stroke();
}
$("#click").click(function(){
setInterval(function(){
set();
loop();
},7);
});
});
|
module.exports.log = function (msg) {
console.log(msg);
};
|
'use strict';
angular.module('com.module.sectors',[]);
|
const typeResult = async (opt = {}, tape, context, appContext) => {
let cheerio = appContext.require('cheerio');
let get = appContext.get;
let _console = null;
let timeout = false;
/**/
let htmlRes = null;
let htmlLastRes = null;
let doc = null;
let expectedHtml = null;
let counter = 0;
let nodeConsole = null;
let end = false;
let intervalRerender = null;
if (appContext.isDev && appContext.isWin && process.stdout && process.stderr) {
nodeConsole = nodeConsole || require('console');
_console = new nodeConsole.Console(process.stdout, process.stderr);
} else {
_console = appContext.logger;
}
const removeListener = () => {
context.renderEvent.removeListener('RENDER', onRender);
};
const removeInterval = () => {
if (intervalRerender) {
clearInterval(intervalRerender);
intervalRerender = null;
}
};
const _end = async () => {
timeout = true;
removeInterval();
removeListener();
await context.timeout(100);
if (!opt.avoidGoBack) await context.goBack();
await tape.end();
_console = null;
nodeConsole = null;
get = null;
cheerio = null;
return true;
};
if (opt == {} || !tape || !context || !appContext) {
tape.ok(false, 'insufficient args');
return await _end();
}
const _onRender = async event => {
if (!timeout) {
const result = context.getLastviewEvent();
if (!result) {
await tape.ok(false, 'No result');
return await _end();
}
doc = result._document;
if (!doc) {
await tape.ok(false, 'No document');
return await _end();
}
if (cheerio && opt.elHtml) {
try {
htmlRes = cheerio
.load(doc)(opt.elHtml || 'div')
.eq(0)
.html();
if (htmlRes && htmlRes.length) htmlLastRes = htmlRes;
} catch (e) {
await tape.ok(false, ['error', e]);
if (!appContext.isDev) appContext.logger.warn(e, counter, opt.elHtml, doc);
return await _end();
}
}
if (opt.expectedHtml) {
expectedHtml = opt.expectedHtml;
if (opt.whitOutSpaces) {
if (htmlRes) htmlRes = htmlRes.replace(/\s/g, '');
if (expectedHtml) expectedHtml = expectedHtml.replace(/\s/g, '');
}
if (opt.toLowerCase) {
if (htmlRes) htmlRes = htmlRes.toLowerCase();
if (expectedHtml) expectedHtml = expectedHtml.toLowerCase();
}
if (opt.verbose && opt.expectedHtml && _console.log) _console.log(htmlRes, counter, expectedHtml);
if (!end && opt.expectedHtml && (htmlRes || '').indexOf(expectedHtml) !== -1) {
end = true;
tape.plan(1);
await tape.ok(true, 'expectedHtml ok');
return await _end();
}
}
counter++;
}
};
const onRender = opt.onRender ? async $event => await opt.onRender($event, _end, { log: _console.log }) : _onRender;
context.renderEvent.on('RENDER', onRender);
if (opt.typeKeySequence) {
if (!opt.avoidGoBack) await context.goBack();
await context.keySequence(context.keyString2array(opt.typeKeySequence));
} else if (opt.setPath) {
if (!opt.avoidGoBack) await context.goBack();
appContext.setPath(opt.setPath);
}
if (opt.timeToForceReRender) {
await context.timeout(opt.timeToForceReRender);
context.renderEvent.emit('MAIN_FORCE_UPDATE');
}
if (opt.intervalTToForceReRender && !intervalRerender) {
intervalRerender = setInterval(() => {
if (!timeout) context.renderEvent.emit('MAIN_FORCE_UPDATE');
}, opt.intervalTToForceReRender);
}
await context.timeout(opt.timeout || 5000);
if (!timeout) {
context.renderEvent.emit('MAIN_FORCE_UPDATE');
tape.comment('mhhh... long wait try re-render');
await context.timeout(1000);
}
if (!timeout) {
//FAIL
tape.ok(false, [
'timeout / not found ',
' / res: ',
htmlLastRes,
' / exp: ',
expectedHtml,
opt.verbose || true ? '/ doc: ' : '',
opt.verbose || true ? doc : '',
'/ counter: ',
counter,
]);
return await _end();
}
return true;
};
module.exports = {
typeResult,
};
/* EXAMPLE */
/*
'use strict';
const getTapeTests = appContext => {
const { typeResult } = appContext.require('@uitests/_aux_tests_short_tapes.js');
return [
{
name: 'TEST JSX',
options: {},
callBack: async (tape, context) => {
return await typeResult(
{
typeKeySequence: 'T,T,B,0,0,1,J,S,X',
expectedHtml: 'test TTB001JSX ok!',
elHtml: '#ruleViewerWrapp',
timeout: 10000,
whitOutSpaces: true,
},
tape,
context,
appContext
);
},
},
];
};
module.exports = appContext => [...getTapeTests(appContext)];
*/
|
/**
* Module dependencies.
*/
var request = require('request');
var mongoose = require('mongoose');
var Query = mongoose.model('Query');
var Photo = mongoose.model('Photo');
var https = require('https');
var API_KEY = require('config').flickr_api_key;
/**
* Searching images in Flickr API
* @param {String} searchText searching text
* @param {Number} page page
* @param {Number} perPage items per page
* @param {Date} maxDate max date of upload images
* @return {Promise} Promise
*/
var searchAPI = function (searchText, page, perPage, maxDate) {
var apiKey = API_KEY;
var promise = new Promise((resolve, reject) => {
var url = `\/services\/rest\/?method=flickr.photos.search&text=${searchText}&page=${page}&per_page=${perPage}&max_upload_date=${maxDate}&api_key=${apiKey}&format=json&nojsoncallback=1`; // the rest of the url with parameters if needed
var options = {
method: 'GET',
url: 'https://api.flickr.com' + url,
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
var callback = function(error, response, body) {
var data;
if (error) {
console.log('error', error);
reject(error)
res.send(500, 'something went wrong');
}
try {
data = JSON.parse(body);
data.photos.photo.map(function (obj) {
obj.flickrId = obj.id;
delete obj.id;
return obj;
});
} catch(e) {
console.log('malformed request', body);
reject(e)
return res.status(400).send('malformed request: ' + body);
}
resolve(data);
}
request(options, callback);
});
return promise;
};
/**
* Searching images in Flickr API and store
* returned value in database for a future
* cache purpose
* @param {String} searchText searching text
* @param {Number} page page
* @param {Number} perPage items per page
* @param {Date} maxDate max date of upload images
* @return {Promise} Promise
*/
var storeSearchQuery = function(searchText, page, perPage, maxDate) {
var photosJSON;
var refs = [];
var promise = new Promise((resolve, reject) => {
//Get query from API
searchAPI(searchText, page, perPage, maxDate)
.then((photosRes) => {
photosJSON = photosRes;
return Photo.findOrCreate(photosRes.photos.photo);
})
.then(function saveQuery(foundedOrCreated) {
//Collecting ID's of images
if (foundedOrCreated) {
foundedOrCreated.forEach((photo) => {
if (photo && photo._id) {
refs.push(photo._id);
}
});
}
var query = new Query({
searchText: searchText,
page: photosJSON.photos.page,
pages: photosJSON.photos.pages,
perpage: photosJSON.photos.perpage,
total: photosJSON.photos.total,
maxDate: maxDate,
photo: refs // Adding images to query
});
return query.save();
})
.then(function getSavedQuery(query) {
console.log('jestem tutaj!!');
return Query.findOne(query._id).populate('photo').exec();
})
.then(function returnValues(photos) {
resolve({
photos: photos,
stat: 'ok'
});
})
.catch(reject);
});
return promise;
};
/**
* Searching using database if query was previously cached
* if not we are going to use Flickr API and store values
* in database for a future
* @param {String} searchText searching text
* @param {Number} page page
* @param {Number} perPage items per page
* @param {Date} maxDate max date of upload images
* @return {Promise} Promise
*/
var search = function (searchText, page, perPage, maxDate) {
var promise = new Promise((resolve, reject) => {
// Check if we already have saved query
Query.findOne({
searchText: searchText,
page: page,
perpage: perPage,
maxDate: maxDate
})
.populate('photo')
.exec()
.then(function doWeHaveQueryInDB(query) {
if (query) {
console.log('HIT! to database!');
resolve({
photos: query,
stat: 'ok'
});
} else {
console.log('Getting images from Flickr');
storeSearchQuery(searchText, page, perPage, maxDate)
.then(resolve, reject)
}
}, reject)
});
return promise;
};
/**
* Expose
*/
exports.search = search;
exports.searchAPI = searchAPI;
|
'use strict';
var _ = require( './utils' );
var Object3D = require( './object3d' );
var Vector3 = require( './math/vector3' );
var Matrix4 = require( './math/matrix4' );
var DEG_TO_RAD = Math.PI / 180;
// Temp Matrix4.
var mt = new Matrix4();
function Camera( fov, aspect, near, far ) {
Object3D.call( this );
this.fov = fov || 60;
this.aspect = aspect || 1;
this.near = near || 0.1;
this.far = far || 1000;
this.matrixWorldInverse = new Matrix4();
this.projectionMatrix = new Matrix4();
this.updateProjectionMatrix();
}
_.extends( Camera, Object3D );
Camera.prototype.lookAt = function( vector ) {
mt.lookAt( this.position, vector, Vector3.Y );
this.quaternion.setFromRotationMatrix( mt );
};
Camera.prototype.updateProjectionMatrix = function() {
var near = this.near,
far = this.far;
var top = near * Math.tan( this.fov * 0.5 * DEG_TO_RAD ),
bottom = -top,
left = bottom * this.aspect,
right = top * this.aspect;
var x = 2 * near / ( right - left ),
y = 2 * near / ( top - bottom );
var a = ( right + left ) / ( right - left ),
b = ( top + bottom ) / ( top - bottom ),
c = -( far + near ) / ( far - near ),
d = -2 * far * near / ( far - near );
var m = this.projectionMatrix.elements;
m[ 0 ] = x;
m[ 1 ] = 0;
m[ 2 ] = 0;
m[ 3 ] = 0;
m[ 4 ] = 0;
m[ 5 ] = y;
m[ 6 ] = 0;
m[ 7 ] = 0;
m[ 8 ] = a;
m[ 9 ] = b;
m[ 10 ] = c;
m[ 11 ] = -1;
m[ 12 ] = 0;
m[ 13 ] = 0;
m[ 14 ] = d;
m[ 15 ] = 0;
return this;
};
module.exports = Camera;
|
const name = {0:'Ace', 1:'2', 2:'3', 3:'4', 4:'5', 5:'6', 6:'7', 7:'8', 8:'9', 9:'10', 10:'Jack', 11:'Queen', 12:'King'};
const points = {0:1, 1:2, 2:3, 3:4, 4:5, 5:6, 6:7, 7:8, 8:9, 9:10, 10:10, 11:10, 12:10};
const suits = {0:'Spade', 1:'Heart', 2:'Club', 3:'Diamond'};
export {name, points, suits};
export function splicer(remainingCards) {
let card = remainingCards.splice(parseInt(Math.random() * remainingCards.length, 10), 1)[0]
return {card, remainingCards};
}
|
(function(){
angular
.module('<%= appname %>')
.run(runner);
function runner($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
}
})();
|
var inherit = require('./inherit'),
Sprite = require('../display/Sprite'),
Tilemap = require('../tilemap/Tilemap'),
Rectangle = require('../geom/Rectangle'),
BitmapText = require('../text/BitmapText');
/**
* The object factory makes it simple to create and add objects to a parent. One is added
* to a State's world and camera by default, but they can be used for any parent but they
* can only belong to a single state.
*
* @class ObjectFactory
* @extends Object
* @constructor
* @param state {State} The game state this factory belongs to
* @param parent {Container} The container to act as the parent for created objects
*/
var ObjectFactory = function(state, parent) {
this.state = state;
this.game = state.game;
this.parent = parent;
};
inherit(ObjectFactory, Object, {
/**
* Adds a generic object to the world or camera
*
* @method obj
* @param object {mixed} Any game object you want to add to the parent
* @return {mixed} Returns the added object
*/
obj: function(obj) {
return this.parent.addChild(obj);
},
/**
* Creates a new sprite and adds it to the game world
*
* @method sprite
* @param texture {String|Texture} The texture for the sprite, or the key for one in the cache
* @param [frame=null] {String|Number} A specific frame of a sprite sheet to use, either the index or string key
* depending on the type of the sheet when loaded.
* @param [physics=true] {Boolean} Should this sprite be added to the physics simulation?
* @return {Sprite} The sprite added
*/
sprite: function(tx, frame, physics) {
var spr,
game = this.game;
if(typeof tx === 'string') {
if(frame || frame === 0)
tx = game.cache.getTextures(tx)[frame];
else
tx = game.cache.getTexture(tx);
}
if(!tx) {
tx = game.cache.getTexture('__default');
}
spr = new Sprite(tx);
//if undefined, then default to true
if(physics || physics === undefined) {
spr.enablePhysics(this.state.physics);
//this.state.physics.addSprite(spr);
}
return this.parent.addChild(spr);
},
/**
* Creates a new AudioPlayer to play the sound passed in
*
* @method audio
* @param key {String} The unique cache key for the preloaded audio
* @param [settings] {Object} All the settings for the audio player (see AudioManager.add for all settings)
* @return {AudioPlayer} The player added
*/
audio: function(key, settings) {
return this.state.audio.add(key, settings);
},
/**
* Creates a new tilemap to add to the world
*
* @method tilemap
* @param key {String} The unique cache key for the preloaded tilemap data
* @param [constrain=true] {Boolean} Should the camera be constrained to this tilemap's size?
* @return {Tilemap} The tilemap added
*/
tilemap: function(key, constrain) {
var obj = this.game.cache.getTilemap(key) || {},
tilemap = new Tilemap(this.state, obj.data, obj.textures);
if(constrain) {
this.state.camera.constrain(new Rectangle(0, 0, tilemap.realSize.x, tilemap.realSize.y));
}
//force render of tilemap
tilemap.render(
-this.state.world.position.x,
-this.state.world.position.x,
this.game.width,
this.game.height
);
tilemap._cachekey = key;
return this.parent.addChild(tilemap);
},
/**
* Creates a new instance of BitmapText
*
* @method bitmaptext
* @param text {String} The text for the BitmapText to display
* @param font {String} The key for the bitmap font loaded into the cache
* @param interactive {Boolean} Can the item be interacted with by mouse (clicked, dragged, etc)
* @return {BitmapText} The bitmap text object added
*/
bitmaptext: function(text, font, style) {
if(typeof font === 'string')
font = this.game.cache.getBitmapFont(font);
return this.parent.addChild(new BitmapText(text, font, style));
}
});
module.exports = ObjectFactory;
|
"use strict";
var expect = require('expect.js');
var List = require('../lib/list.js');
var Pair = require('../lib/pair.js');
var Data = require('../lib/data.js');
var PP = require('../lib/pprinter.js');
var Parser = require('../lib/parser.js');
var Dentaku = require('../lib/dentaku.normal.js');
describe('dentaku.normal', () => {
it("evaluate", (next) => {
expect(
Dentaku.evaluate("123")
).to.eql(
123
);
expect(
Dentaku.evaluate("1 + 2")
).to.eql(
3
);
expect(
Dentaku.evaluate("2 - 1")
).to.eql(
1
);
expect(
Dentaku.evaluate("1.2 * 2")
).to.eql(
2.4
);
expect(
Dentaku.evaluate("3.9 / 3")
).to.eql(
1.3
);
next();
});
// describe('parser', () => {
// it("expr", (next) => {
// expect(
// PP.print(Parser.parse(Dentaku.expr())(List.fromString("123")))
// // PP.print(Parser.parse(Dentaku.expr())(List.fromString("123")))
// ).to.eql(
// '[(123,[]),nil]'
// );
// next();
// });
// it("factor", (next) => {
// expect(
// PP.print(Parser.parse(Dentaku.factor())(List.fromString("123")))
// ).to.eql(
// '[(123,[]),nil]'
// );
// next();
// });
// it("term", (next) => {
// expect(
// PP.print(Parser.parse(Dentaku.term())(List.fromString("1 * 2")))
// ).to.eql(
// '[(2,[]),nil]'
// );
// next();
// });
// });
});
|
import './APICode';
import './devtools';
import './goToURL';
import './uninstall';
import './updateAvailable';
import './appDetails';
import './lyrics';
import './openPort';
import './onlineStatus';
// Anything that requires the DOM needs to go here as of Electron 0.36.6
document.addEventListener('DOMContentLoaded', () => {
require('./webviewLoader');
require('./control-bar');
});
|
// Initializes the `deals` service on path `/deals`
const createService = require('feathers-mongoose');
const createModel = require('../../models/deals.model');
const hooks = require('./deals.hooks');
const filters = require('./deals.filters');
module.exports = function() {
const app = this;
const Model = createModel(app);
const options = {
name: 'deals',
Model,
};
// Initialize our service with any options it requires
app.use('/deals', createService(options));
// Get our initialized service so that we can register hooks and filters
const service = app.service('deals');
service.hooks(hooks);
if (service.filter) {
service.filter(filters);
}
};
|
require("ember-bootstrap/mixins/focus_support");
var Bootstrap = window.Bootstrap,
get = Ember.get;
Bootstrap.Forms.Select = Bootstrap.Forms.Field.extend({
optionLabelPath: 'content',
optionValuePath: 'content',
inputField: Ember.Select.extend(Bootstrap.FocusSupport, {
contentBinding: 'parentView.content',
optionLabelPathBinding: 'parentView.optionLabelPath',
optionValuePathBinding: 'parentView.optionValuePath',
valueBinding: 'parentView.value',
selectionBinding: 'parentView.selection',
promptBinding: 'parentView.prompt',
multipleBinding: 'parentView.multiple',
autofocusBinding: 'parentView.autofocus',
disabledBinding: 'parentView.disabled',
classNameBindings: ['parentView.inputClassNames'],
name: Ember.computed(function() {
return this.get('parentView.name') || this.get('parentView.label');
}).property('parentView.name', 'parentView.label'),
_IE10AndLaterHack: function () { //doesn't fill in the selected value when content is loaded after the selection
if (('documentMode' in document && 'atob' in window)) {//IE10+
this.rerender();
}
}.observes('content.[]')
})
});
|
import createServer from 'rally-point-server'
const secret = process.env.SB_RALLY_POINT_SECRET
const port = Number(process.env.SB_RALLY_POINT_LOCAL_PORT ?? 14098)
const server = createServer('::', port, secret)
server.bind().then(() => {
console.log('rally-point server running on port ' + port)
})
|
// alternative tips
texts_join_button1_tip = "Sende Dein Foto in nur 3 Klicks";
texts_join_button2_tip = "Wähle einen Bild auf Deinem Rechner";
// error messages
texts_error_server = "Entschuldigung, aber etwas stimmt mit Deinem Server nicht. Kannst Du nochmal versuchen?";
texts_error_imagetype = "Wähle eine JPG, GIF, BMP oder PND Datei aus";
texts_error_field = "Bitte dieses Feld ausfüllen";
texts_error_imagesize = "Wähle eine Datei, die weniger als 6 MB hat";
|
var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var postSchema=Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true
},
slug: {
type: String,
required: true,
unique: true
},
created_at: {
type: Date,
default: Date.now
}
});
module.exports=mongoose.model('Post',postSchema);
|
import React, { Component } from "react";
export default class AdminContainer extends Component {
render() {
return (
<div>
<h1>Admin Page.</h1>
</div>
);
}
}
|
import { LitElement, html, css } from '../../web_modules/lit-element.js';
import '../components/Link.js';
import '../components/Carousel.js';
import '../components/Social.js';
import '../components/Quote.js';
class About extends LitElement {
static get styles () {
return css`
img {
border-radius: 50%;
width: 72px;
height: 72px;
float: left;
margin-right: 5px;
}
`;
}
render () {
return html`
<div>
<img role="presentation" src="images/me-blur.jpg">
<div>
My name is <span title="Ruh-juht Sai-guhl"><strong>Rajat Sehgal</strong></span>, I am
a <strong>Software Engineering Manager</strong>, located in the <r-link text="Greater Boston"></r-link> area.
I have been working at <r-link text="MathWorks"></r-link> for more than 9 years now.
<br>
Before that I was at <r-link text="University of Florida"></r-link>, where I completed
my <strong>Masters</strong> in <strong>Computer Science</strong> while also working as a
Software Developer at the <r-link text="Florida Museum of Natural History"></r-link>. I was born and
brought up in <r-link text="New Delhi"></r-link>, India where I also earned
my <strong>Bachelors</strong> in <strong>Computer Science</strong>.
<br>
When I am not at work and my wife is fast asleep, I enjoy working on some
side <r-link text="projects"></r-link>.
</div>
<r-social></r-social>
<r-carousel>
<r-quote text="Rajat’s deep and growing knowledge of web UI technologies, coupled with his strong design skills make him a powerhouse developer. He is always working to further his knowledge and technique in these areas. As a result he is widely respected and consulted." author="Peter Muellers"></r-quote>
<r-quote text="Rajat is a hardworking and detail driven individual who likes to deliver very modular and highly extensible code. He's Efficient in analyzing issues and deriving action items. He continually seeks solutions, not blame." author="Saoli Mitra"></r-quote>
<r-quote text="Rajat is meticulous when it comes to starting a new piece of work. He evaluates and understands the problem statement with respect to use cases, before thinking about the design and implementation details." author="Deepak Anand"></r-quote>
<r-quote text="I find Rajat to be very easy to work with, very responsive and willing when it comes to answering questions." author="Melissa DeVeau"></r-quote>
<r-quote text="Rajat possesses excellent communication skills and has been very helpful in sharing his knowledge." author="Koundinya Surepeddi"></r-quote>
<r-quote text="Rajat has a good command over the language and was able to point out a lot of good practices for writing clean code." author="Keerthi Gurijala"></r-quote>
</r-carousel>
</div>
`;
}
}
customElements.define('r-about', About);
|
import * as M from "@effectful/core";
function a() {
var a = M.context();
a.$run = a_1;
a.$cont = 4;
return M.scope();
}
function b() {
var b = M.context();
b.$run = b_1;
b.$err = b_err;
b.$cont = 4;
return M.scope();
}
function c() {
var c = M.context();
c.$run = c_1;
c.$err = c_err;
c.$fin = c_fin;
c.$cont = 4;
return M.scope();
}
function d() {
var d = M.context();
d.$run = d_1;
d.$err = d_err;
d.$fin = d_fin;
d.$cont = 4;
return M.scope();
}
async function af1() {
if (await a) await b;
return await c;
}
function b2() {
var b2 = M.context();
b2.$run = b2_1;
b2.$err = b2_err;
b2.$cont = 4;
return M.scope();
}
async function af2() {
if (await a) await b;
return await c;
}
function a_1(a, p) {
switch (a.$cont) {
case 4:
a.$cont = 5;
return M.yldStar(M.yld(1));
case 5:
a.$cont = 6;
return M.yldStar(M.yld(2));
case 6:
return M.pure();
case 0:
return M.pure(p);
case 2:
return M.$redir(p);
default:
throw new Error("invalid state");
}
}
function b_err(s) {
switch (s) {
case 5:
return 8;
default:
return 1;
}
}
function b_1(b, p) {
var e;
switch (b.$cont) {
case 4:
b.$cont = 5;
return M.yldStar(M.yld(1));
case 5:
b.$cont = 7;
return M.yldStar(M.yld(2));
case 6:
e = b._ex;
b.$cont = 7;
b._ex = null;
return M.yldStar(M.yld(e));
case 7:
return M.pure();
case 0:
return M.pure(p);
case 8:
b.$cont = 6;
b._ex = p;
return M.jump();
case 2:
return M.$redir(p);
default:
throw new Error("invalid state");
}
}
function c_err(s) {
switch (s) {
case 5:
return 11;
case 6:
return 13;
default:
return 1;
}
}
function c_fin(s) {
switch (s) {
case 5:
case 6:
return 12;
default:
return 0;
}
}
function c_1(c, p) {
var e;
switch (c.$cont) {
case 4:
c.$cont = 5;
return M.yldStar(M.yld(1));
case 5:
c.$cont = 7;
c._fc = 8;
return M.yldStar(M.yld(2));
case 6:
e = c._ex;
c.$cont = 7;
c._fc = 8, c._ex = null;
return M.yldStar(M.yld(e));
case 7:
c.$cont = c._fc;
e = c._fc, c._fc = null;
return M.yldStar(M.yld("F"));
case 8:
return M.pure();
case 0:
return M.pure(p);
case 9:
c.$cont = 0;
e = c._r, c._r = null;
return M.jump(e);
case 10:
return M.raise(c._err1);
case 11:
c.$cont = 6;
c._ex = p;
return M.jump();
case 12:
c.$cont = 7;
c._fc = 9, c._r = p;
return M.jump();
case 13:
c.$cont = 7;
c._fc = 10, c._err1 = p;
return M.jump();
case 2:
return M.$redir(p);
default:
throw new Error("invalid state");
}
}
function d_err(s) {
switch (s) {
case 5:
case 6:
return 11;
default:
return 1;
}
}
function d_fin(s) {
switch (s) {
case 5:
case 6:
return 12;
default:
return 0;
}
}
function d_1(d, p) {
var a;
switch (d.$cont) {
case 4:
d._loop = M.iterator(s);
d.$cont = 5;
return M.jump();
case 5:
if (!(d._loop = d._loop.step()).done) {
d._i = d._loop.value;
d.$cont = 6;
return M.yldStar(M.yldStar([d._i]));
} else {
d.$cont = 7;
d._fc = 8, d._i = null;
return M.jump();
}
case 6:
d.$cont = 5;
return M.yldStar(M.yld(d._i));
case 7:
if (d._loop.exit) {
d._loop.exit();
}
d.$cont = d._fc;
a = d._fc, d._loop = null, d._fc = null;
return M.jump();
case 8:
return M.pure();
case 0:
return M.pure(p);
case 9:
d.$cont = 0;
a = d._r, d._r = null;
return M.jump(a);
case 10:
return M.raise(d._err1);
case 11:
d.$cont = 7;
d._fc = 10, d._err1 = p;
return M.jump();
case 12:
d.$cont = 7;
d._fc = 9, d._r = p;
return M.jump();
case 2:
return M.$redir(p);
default:
throw new Error("invalid state");
}
}
function b2_err(s) {
switch (s) {
case 5:
return 8;
default:
return 1;
}
}
function b2_1(b2, p) {
var e;
switch (b2.$cont) {
case 4:
b2.$cont = 5;
return M.yldStar(M.yld(1));
case 5:
b2.$cont = 7;
return M.yldStar(M.yld(2));
case 6:
e = b2._ex;
b2.$cont = 7;
b2._ex = null;
return M.yldStar(M.yld(e));
case 7:
return M.pure();
case 0:
return M.pure(p);
case 8:
b2.$cont = 6;
b2._ex = p;
return M.jump();
case 2:
return M.$redir(p);
default:
throw new Error("invalid state");
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import formControlState from '../FormControl/formControlState';
import withFormControlContext from '../FormControl/withFormControlContext';
import withStyles from '../styles/withStyles';
import FormLabel from '../FormLabel';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
display: 'block',
transformOrigin: 'top left',
},
/* Styles applied to the root element if `focused={true}`. */
focused: {},
/* Styles applied to the root element if `disabled={true}`. */
disabled: {},
/* Styles applied to the root element if `error={true}`. */
error: {},
/* Styles applied to the root element if `required={true}`. */
required: {},
/* Styles applied to the asterisk element. */
asterisk: {},
/* Styles applied to the root element if the component is a descendant of `FormControl`. */
formControl: {
position: 'absolute',
left: 0,
top: 0,
// slight alteration to spec spacing to match visual spec result
transform: 'translate(0, 24px) scale(1)',
},
/* Styles applied to the root element if `margin="dense"`. */
marginDense: {
// Compensation for the `Input.inputDense` style.
transform: 'translate(0, 21px) scale(1)',
},
/* Styles applied to the `input` element if `shrink={true}`. */
shrink: {
transform: 'translate(0, 1.5px) scale(0.75)',
transformOrigin: 'top left',
},
/* Styles applied to the `input` element if `disableAnimation={false}`. */
animated: {
transition: theme.transitions.create(['color', 'transform'], {
duration: theme.transitions.duration.shorter,
easing: theme.transitions.easing.easeOut,
}),
},
/* Styles applied to the root element if `variant="filled"`. */
filled: {
// Chrome's autofill feature gives the input field a yellow background.
// Since the input field is behind the label in the HTML tree,
// the input field is drawn last and hides the label with an opaque background color.
// zIndex: 1 will raise the label above opaque background-colors of input.
zIndex: 1,
pointerEvents: 'none',
transform: 'translate(12px, 20px) scale(1)',
'&$marginDense': {
transform: 'translate(12px, 17px) scale(1)',
},
'&$shrink': {
transform: 'translate(12px, 10px) scale(0.75)',
'&$marginDense': {
transform: 'translate(12px, 7px) scale(0.75)',
},
},
},
/* Styles applied to the root element if `variant="outlined"`. */
outlined: {
// see comment above on filled.zIndex
zIndex: 1,
pointerEvents: 'none',
transform: 'translate(14px, 20px) scale(1)',
'&$marginDense': {
transform: 'translate(14px, 17px) scale(1)',
},
'&$shrink': {
transform: 'translate(14px, -6px) scale(0.75)',
},
},
});
const InputLabel = React.forwardRef(function InputLabel(props, ref) {
const {
classes,
className,
disableAnimation = false,
margin,
muiFormControl,
shrink: shrinkProp,
variant,
...other
} = props;
let shrink = shrinkProp;
if (typeof shrink === 'undefined' && muiFormControl) {
shrink = muiFormControl.filled || muiFormControl.focused || muiFormControl.adornedStart;
}
const fcs = formControlState({
props,
muiFormControl,
states: ['margin', 'variant'],
});
return (
<FormLabel
data-shrink={shrink}
className={clsx(
classes.root,
{
[classes.formControl]: muiFormControl,
[classes.animated]: !disableAnimation,
[classes.shrink]: shrink,
[classes.marginDense]: fcs.margin === 'dense',
[classes.filled]: fcs.variant === 'filled',
[classes.outlined]: fcs.variant === 'outlined',
},
className,
)}
classes={{
focused: classes.focused,
disabled: classes.disabled,
error: classes.error,
required: classes.required,
asterisk: classes.asterisk,
}}
ref={ref}
{...other}
/>
);
});
InputLabel.propTypes = {
/**
* The contents of the `InputLabel`.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, the transition animation is disabled.
*/
disableAnimation: PropTypes.bool,
/**
* If `true`, apply disabled class.
*/
disabled: PropTypes.bool,
/**
* If `true`, the label will be displayed in an error state.
*/
error: PropTypes.bool,
/**
* If `true`, the input of this label is focused.
*/
focused: PropTypes.bool,
/**
* If `dense`, will adjust vertical spacing. This is normally obtained via context from
* FormControl.
*/
margin: PropTypes.oneOf(['dense']),
/**
* @ignore
*/
muiFormControl: PropTypes.object,
/**
* if `true`, the label will indicate that the input is required.
*/
required: PropTypes.bool,
/**
* If `true`, the label is shrunk.
*/
shrink: PropTypes.bool,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['standard', 'outlined', 'filled']),
};
export default withStyles(styles, { name: 'MuiInputLabel' })(withFormControlContext(InputLabel));
|
define([
'jquery',
"../utils/constants",
'../core/SPServices.utils',
//---------------------------
// We don't need local variables for these dependencies
// because they are added to the jQuery namespace.
'../core/SPServices.core'
], function (
$,
constants,
utils
) {
"use strict";
// Function which provides a link on a Lookup column for the user to follow
// which allows them to add a new value to the Lookup list.
// Based on http://blog.mastykarz.nl/extending-lookup-fields-add-new-item-option/
// by Waldek Mastykarz
$.fn.SPServices.SPLookupAddNew = function (options) {
var opt = $.extend({}, {
lookupColumn: "", // The display name of the Lookup column
promptText: "Add new {0}", // Text to use as prompt + column name
newWindow: false, // If true, the link will open in a new window *without* passing the Source.
ContentTypeID: "", // [Optional] Pass the ContentTypeID if you'd like to specify it
completefunc: null, // Function to call on completion of rendering the change.
debug: false // If true, show error messages;if false, run silent
}, options);
var thisFunction = "SPServices.SPLookupAddNew";
// Find the lookup column's select (dropdown)
var lookupSelect = $().SPServices.SPDropdownCtl({
displayName: opt.lookupColumn
});
if (lookupSelect.Obj.html() === null && opt.debug) {
utils.errBox(thisFunction, "lookupColumn: " + opt.lookupColumn, constants.TXTColumnNotFound);
return;
}
var newUrl = "";
var lookupListUrl = "";
var lookupColumnStaticName = "";
// Use GetList for the current list to determine the details for the Lookup column
$().SPServices({
operation: "GetList",
async: false,
cacheXML: true,
listName: $().SPServices.SPListNameFromUrl(),
completefunc: function (xData) {
$(xData.responseXML).find("Field[DisplayName='" + opt.lookupColumn + "']").each(function () {
lookupColumnStaticName = $(this).attr("StaticName");
// Use GetList for the Lookup column's list to determine the list's URL
$().SPServices({
operation: "GetList",
async: false,
cacheXML: true,
listName: $(this).attr("List"),
completefunc: function (xData) {
$(xData.responseXML).find("List").each(function () {
lookupListUrl = $(this).attr("WebFullUrl");
// Need to handle when list is in the root site
lookupListUrl = lookupListUrl !== constants.SLASH ? lookupListUrl + constants.SLASH : lookupListUrl;
});
}
});
// Get the NewItem form for the Lookup column's list
newUrl = utils.getListFormUrl($(this).attr("List"), "NewForm");
// Stop looking;we're done
return false;
});
}
});
if (lookupListUrl.length === 0 && opt.debug) {
utils.errBox(thisFunction, "lookupColumn: " + opt.lookupColumn, "This column does not appear to be a lookup column");
return;
}
if (newUrl.length > 0) {
// Build the link to the Lookup column's list enclosed in a div with the id="SPLookupAddNew_" + lookupColumnStaticName
var newHref = lookupListUrl + newUrl;
// If requested, open the link in a new window and if requested, pass the ContentTypeID
newHref += opt.newWindow ?
((opt.ContentTypeID.length > 0) ? "?ContentTypeID=" + opt.ContentTypeID : "") + "' target='_blank'" :
"?" + ((opt.ContentTypeID.length > 0) ? "ContentTypeID=" + opt.ContentTypeID + "&" : "") + "Source=" + utils.escapeUrl(location.href) + "'";
var newLink = "<div id='SPLookupAddNew_" + lookupColumnStaticName + "'>" + "<a href='" + newHref + ">" + opt.promptText.replace(/\{0\}/g, opt.lookupColumn) + "</a></div>";
// Append the link to the Lookup columns's formbody table cell
$(lookupSelect.Obj).parents("td.ms-formbody").append(newLink);
} else if (opt.debug) {
utils.errBox(thisFunction, "lookupColumn: " + opt.lookupColumn, "NewForm cannot be found");
return;
}
// If present, call completefunc when all else is done
if (opt.completefunc !== null) {
opt.completefunc();
}
}; // End $.fn.SPServices.SPLookupAddNew
return $;
});
|
const fs = require('fs');
/**
* Thanks to @williammustaffa for this compiler.
* Original src: https://github.com/williammustaffa/jGame.js/blob/master/compile.js
*
*/
// Project src
const srcDir = './app/assets/javascript'
const entryPoint = `${srcDir}/main.js`;
// regex to serach @include('file'); declarations
const searchRegex = /include\((\'|\")[^\)]*(\'|\")\)/;
function jsCompiler() {
// Parse entry point
let content = parseInclude(entryPoint);
// write the parsed/replaced content into a single file
fs.writeFileSync('./app/assets/javascript/bundle/mobifycloud.js', content);
console.log('JS assets compiled into -> app/assets/javascript/mobifycloud.js');
}
/**
* Replaces all @include('file') declarations with file content
*
* @param {String} file src
* @returns {String} File content with 'includes' content
*/
function parseInclude(src) {
let content = fs.readFileSync(src, 'utf8');
// verify all include declarations and replace with file content
while((searchResult = searchRegex.exec(content))) {
content = content.replace(';', '');
let includeDeclaration = searchResult[0];
// get included file path
let includePath = getPath(includeDeclaration);
// parse include declaration content
let includeContent = parseInclude(includePath);
// replace include with file content
content = content.replace(includeDeclaration, includeContent);
}
return content;
}
/**
* Retrive the include declaration file path
*
* @param {String} include declaration like @include('test.js')
* @returns {String} path
*/
function getPath(include) {
return `${srcDir}/${include.replace(/include\((\'|\")|(\'|\")\)/g, '')}`;
}
function insertFileInfo(src, content) {
let prefix = `/* >> ${src} START */`,
sufix = `/* << ${src} END */`;
return prefix + '\n' + content + '\n' + sufix;
}
module.exports = jsCompiler;
|
import React from "react";
import Tile from "./tile";
export default class Index extends React.Component {
render() {
const data = this.props.data,
tileNodes = data.map( (data) => {
return (
<Tile
show={this.props.show}
data={data}
/>
);
});
return (
<div className="container">
<main className="tile-container">
{tileNodes}
</main>
</div>
);
}
}
|
var test = require('tap').test
var Depsify = require('../')
var sink = require('sink-transform')
var splicer = require('labeled-stream-splicer')
test('pack', function(t) {
t.plan(1)
var stream = splicer.obj(Depsify.prototype.pack())
stream.write({ id: 'a', file: 'a', source: 'a{}', deps: { b: 'b', c: 'c' } })
stream.write({ id: 'b', file: 'b', source: 'b{}', deps: { c: 'c' } })
stream.end({ id: 'c', file: 'c', source: 'c{}', deps: {} })
stream.pipe(sink.str(function (body, done) {
t.equal(body, 'c{}b{}a{}')
done()
}))
})
|
#!/usr/bin/env node
'use strict';
const path = require('path');
const assert = require('assert');
const utils = require('../utils.js');
const fetch = require('pkg-fetch');
assert(!module.parent);
assert(__dirname === process.cwd());
const host = 'node' + process.version.match(/^v(\d+)/)[1];
const target = process.argv[2] || host;
let right;
fetch.need({
nodeRange: target,
platform: fetch.system.hostPlatform,
arch: fetch.system.hostArch
}).then(function (needed) {
right = utils.spawn.sync(
'./' + path.basename(needed),
[ '--expose-gc',
'-e', 'if (global.gc) console.log("ok");' ],
{ cwd: path.dirname(needed),
env: { PKG_EXECPATH: 'PKG_INVOKE_NODEJS' } }
);
assert.equal(right, 'ok\n');
}).catch(function (error) {
console.error(`> ${error.message}`);
process.exit(2);
});
|
const express = require('express');
const app = express();
const port = 5000;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Import Routes directory
require('./routes')(app);
app.get('/', (req, res) => {
res.send('PORT 5000');
});
app.listen(port, (err) => {
if (err) { console.log(err); };
console.log('Listening on port ' + port);
});
|
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
let _HeadlineView;
const _ = require('underscore');
const Backbone = require('backbone');
const _s = require('underscore.string');
export const HeadlineView = (_HeadlineView = class HeadlineView extends Backbone.View {
initialize({ collection, params, facets, stuckFacet, stuckParam }) {
this.collection = collection;
this.params = params;
this.facets = facets;
this.stuckFacet = stuckFacet;
this.stuckParam = stuckParam;
this.listenTo(this.collection, "initial:fetch", this.setHeadline, this);
if (this.stuckParam === 'fair_id') { this.stuckFacet = null; }
for (let facet of Array.from(this.facets)) {
this.listenTo(this.params, `change:${facet}`, this.setHeadline, this);
}
return this.counts = _.clone(this.collection.counts);
}
setHeadline() {
if (this.anyFacetsSelected() || this.stuckFacet) {
return this.$el.text(this.paramsToHeading()).show();
} else {
return this.$el.text("").hide();
}
}
facetName(facet){
return __guard__(__guard__(this.counts != null ? this.counts[facet] : undefined, x1 => x1[this.params.get(facet)]), x => x.name);
}
anyFacetsSelected() {
return _.any(this.facets, facet => this.params.has(facet));
}
humanizeMedium() {
// replace the 'slash' in 'film-slash-video'
return _s.humanize(this.params.get('medium')).replace('slash', '/');
}
displayMedium() {
if (this.stuckFacet) {
if (this.params.has('medium')) {
return this.humanizeMedium();
} else {
return this.stuckFacet.get('name');
}
} else {
return this.humanizeMedium() || 'Artworks';
}
}
paramsToHeading() {
if (this.anyFacetsSelected() || this.stuckFacet) {
return _.compact([
this.facetName('dimension_range'),
(this.displayMedium()),
this.facetName('price_range')
]).join(' ');
}
}
});
function __guard__(value, transform) {
return (typeof value !== 'undefined' && value !== null) ? transform(value) : undefined;
}
|
var $mod$364 = core.VW.Ecma2015.Utils.module(require('../moment'));
exports.default = $mod$364.default.defineLocale('cy', {
months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split('_'),
monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split('_'),
weekdays: 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split('_'),
weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'),
weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'),
weekdaysParseExact: true,
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: '[Heddiw am] LT',
nextDay: '[Yfory am] LT',
nextWeek: 'dddd [am] LT',
lastDay: '[Ddoe am] LT',
lastWeek: 'dddd [diwethaf am] LT',
sameElse: 'L'
},
relativeTime: {
future: 'mewn %s',
past: '%s yn ôl',
s: 'ychydig eiliadau',
m: 'munud',
mm: '%d munud',
h: 'awr',
hh: '%d awr',
d: 'diwrnod',
dd: '%d diwrnod',
M: 'mis',
MM: '%d mis',
y: 'blwyddyn',
yy: '%d flynedd'
},
ordinalParse: /\d{1,2}(fed|ain|af|il|ydd|ed|eg)/,
ordinal: function (number) {
var b = number, output = '', lookup = [
'',
'af',
'il',
'ydd',
'ydd',
'ed',
'ed',
'ed',
'fed',
'fed',
'fed',
'eg',
'fed',
'eg',
'eg',
'fed',
'eg',
'eg',
'fed',
'eg',
'fed'
];
if (b > 20) {
if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) {
output = 'fed';
} else {
output = 'ain';
}
} else if (b > 0) {
output = lookup[b];
}
return number + output;
},
week: {
dow: 1,
doy: 4
}
});
|
$('.returnTopAction').live('click', function() {
$('html, body').animate({scrollTop: '0'}, 700);
});
$('.link').live('tap', function(event) {
url = $(this).attr("rel");
loadURL(url);
});
function loadURL(url){
navigator.app.loadUrl(url, { openExternal:true });
return false;
}
|
'use strict';
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
legacyDecorators: true,
},
},
plugins: ['ember'],
extends: ['plugin:prettier/recommended', 'eslint:recommended', 'plugin:ember/recommended'],
env: {
browser: true,
},
rules: {},
overrides: [
// node files
{
files: [
'.eslintrc.js',
'.template-lintrc.js',
'ember-cli-build.js',
'testem.js',
'blueprints/*/index.js',
'config/**/*.js',
'lib/*/index.js',
'server/**/*.js',
],
parserOptions: {
sourceType: 'script',
},
env: {
browser: false,
node: true,
},
plugins: ['node'],
extends: ['plugin:node/recommended'],
rules: {
// this can be removed once the following is fixed
// https://github.com/mysticatea/eslint-plugin-node/issues/77
'node/no-unpublished-require': 'off',
},
},
],
};
|
'use strict';
// PeopleWorks
module.exports = function (sequelize, DataTypes) {
let PeopleWorks = sequelize.define('people_works', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
rol: DataTypes.INTEGER
});
PeopleWorks.associate = function (models) {
PeopleWorks.belongsTo(models.Works);
PeopleWorks.belongsTo(models.People);
};
return PeopleWorks;
};
|
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('formInv', { title: 'Express' });
});
module.exports = router;
|
require("babel-register");
var unexpected = require('unexpected');
unexpected.use(require('unexpected-sinon'));
unexpected.use(require('unexpected-set'));
var Bluebird = require('bluebird');
require('sinon-as-promised')(Bluebird);
var Sequelize = require('sequelize');
unexpected.addType({
name: 'Sequelize.Instance',
identify: /^[45]/.test(Sequelize.version) ?
function (value) {
return value && value instanceof Sequelize.Model && 'isNewRecord' in value;
} :
function (value) {
return value && value instanceof Sequelize.Instance;
},
inspect: function (value, depth, output, inspect) {
const name = value.name || value.$modelOptions.name || value._modelOptions.name; // v3 vs v4
output
.text(name.singular).text('(')
.append(inspect(value.get(), depth))
.text(')');
},
equal: function (a, b) {
const aModel = a.Model || a.constructor; // v3 vs v4
const bModel = b.Model || b.constructor;
const pk = aModel.primaryKeyAttribute;
return aModel.name === bModel.name && a.get(pk) === b.get(pk);
}
});
unexpected.addType({
name: 'Sequelize.Association',
identify: function (value) {
return value && value instanceof Sequelize.Association;
},
inspect: function (value, depth, output) {
output
.text(value.associationType).text(': ')
.text(value.source.name).text(' -> ').text(value.target.name)
.text('(').text(value.as).text(')');
},
equal: function (a, b, equal) {
return a.associationType === b.associationType && equal(a.source, b.source) && equal(a.target, b.target) && a.as === b.as;
}
});
unexpected.addAssertion('<function> [not] to be shimmed', function (expect, subject) {
return expect(subject, '[not] to have property', '__wrapped');
});
|
import route from 'routes/EightBall';
describe('(Route) EightBall', () => {
let _component;
beforeEach(() => {
_component = route.component;
});
it('should return a route', () => {
expect(typeof route).to.equal('object');
expect(route.path).to.equal('magic-eight-ball');
});
it('should define a component', () => {
expect(typeof _component).to.equal('function');
});
});
|
'use strict';
var utils = require('../integration-utils.js');
var setup = utils.setup;
var algoliasearchHelper = require('../../');
var random = require('lodash/random');
test('[INT][FILTERS] Should retrieve different values for multi facetted records', function(done) {
var indexName = '_circle-algoliasearch-helper-js-' +
(process.env.CIRCLE_BUILD_NUM || 'DEV') +
'helper_refinements' + random(0, 5000);
setup(indexName, function(client, index) {
return index.addObjects([
{facet: ['f1', 'f2']},
{facet: ['f1', 'f3']},
{facet: ['f2', 'f3']}
])
.then(function() {
return index.setSettings({
attributesToIndex: ['facet'],
attributesForFaceting: ['facet']
});
})
.then(function(content) {
return index.waitTask(content.taskID);
}).then(function() {
return client;
});
}).then(function(client) {
var helper = algoliasearchHelper(client, indexName, {
facets: ['facet']
});
var calls = 0;
helper.on('error', function(event) {
done.fail(event.error);
});
helper.on('result', function(event) {
calls++;
var results = event.results;
if (calls === 1) {
expect(results.hits.length).toBe(2);
expect(results.facets[0].data).toEqual({
f1: 2,
f2: 1,
f3: 1
});
helper.addRefine('facet', 'f2').search();
}
if (calls === 2) {
expect(results.hits.length).toBe(1);
expect(results.facets[0].data).toEqual({
f1: 1,
f2: 1
});
helper.toggleRefine('facet', 'f3').search();
}
if (calls === 3) {
expect(results.hits.length).toBe(0);
expect(results.facets[0]).toBe(undefined);
helper.removeRefine('facet', 'f2').search();
}
if (calls === 4) {
expect(results.hits.length).toBe(1);
expect(results.facets[0].data).toEqual({
f1: 1,
f3: 1
});
client.deleteIndex(indexName);
if (!process.browser) {
client.destroy();
}
done();
}
});
helper.addRefine('facet', 'f1').search();
});
});
|
'use strict';
angular.module('mean.goals').config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/goals');
//================================================
// Check if the user is connected
//================================================
var checkLoggedin = function($q, $timeout, $http, $location) {
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0')
$timeout(deferred.resolve, 0);
// Not Authenticated
else {
$timeout(function() {
deferred.reject();
}, 0);
$location.url('/login');
}
});
return deferred.promise;
};
//================================================
// Check if the user is not conntect
//================================================
var checkLoggedOut = function($q, $timeout, $http, $location) {
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0') {
$timeout(function() {
deferred.reject();
}, 0);
$location.url('/login');
}
// Not Authenticated
else {
$timeout(deferred.resolve, 0);
}
});
return deferred.promise;
};
//================================================
$stateProvider
.state('goals', {
url: '/goals',
templateUrl: 'public/goals/views/goals.html',
controller: 'GoalsCtrl',
data: {goals: 'all'}
})
.state('my goals', {
url: '/goals/my',
templateUrl: 'public/goals/views/goals.html',
controller: 'GoalsCtrl',
data: {goals: 'my'}
})
.state('my goals.new', {
url: '/new',
templateUrl: 'public/goals/views/new_goal.html',
controller: 'NewGoalCtrl',
resolve: {
loggedin: checkLoggedin
}
})
.state('goals.new', {
url: '/new',
templateUrl: 'public/goals/views/new_goal.html',
controller: 'NewGoalCtrl',
resolve: {
loggedin: checkLoggedin
}
})
.state('my goals.detail', {
url: '/:id',
templateUrl: 'public/goals/views/goal.html',
controller: 'GoalCtrl'
})
.state('goals.detail', {
url: '/:id',
templateUrl: 'public/goals/views/goal.html',
controller: 'GoalCtrl'
});
}]);
|
$(document).ready(function () {
$('#id_1-alternative-1').focus();
$('form').submit(function() {
removeEmptyAlts();
});
});
function removeAlt(altIndex) {
if ($('.cloned').length > 2) {
doRemoveAlt(altIndex);
} else {
showMessageInDialogBox('More than two alternatives should exist to perform delete.');
}
}
function doRemoveAlt(altIndex) {
// how many cloned input fields there are currently
var num = $('.cloned').length;
// the numeric ID after the textbox is deleted
var newNum = new Number(num - 1);
var delElement = $(this).find('#input' + altIndex);
// delete element
$('#input' + altIndex).remove();
// update count of alternatives
$('#num-alternatives').val(newNum);
var i = new Number(altIndex + 1);
var j = 0;
for (i; i <= num; i++) {
j = i - 1;
$('#input' + i).attr('id', 'input' + j);
$('#id_1-alternative-' + i).attr('name', '1-alternative-' + j);
$('#id_1-alternative-' + i).attr('tabindex', j);
$('#id_1-alternative-' + i).attr('id', 'id_1-alternative-' + j);
$('#btn-del-' + i).attr('onclick', 'removeAlt(' + j + ')');
$('#btn-del-' + i).attr('id', 'btn-del-' + j);
}
//update tabindexes
$('#btn-add').attr('tabindex', newNum);
$('#btn-submit').attr('tabindex', newNum + 1);
$('#btn-prev-step').attr('tabindex', newNum + 2);
}
function removeEmptyAlts() {
$('.cloned input:text[value=""]').each(function() {
var index = parseInt($(this).attr('id').substring("id_1-alternative-".length));
doRemoveAlt(index);
});
}
$(document).on('focus', '.cloned input[type=text]', function() {
var numEmpty = $('.cloned input:text[value=""]').length;
var numEmptyRequired = 2;
if ($(this).val()) {
numEmptyRequired--;
}
if(numEmpty < numEmptyRequired) {
// how many cloned input fields there are currently
var num = $('.cloned').length;
// the numeric ID of the new input field being added
var newNum = new Number(num + 1);
// update count of alternatives
$('#num-alternatives').val(newNum);
// create the new element
var divId = 'input'+newNum;
var inputName = '1-alternative-' + newNum;
var inputId = 'id_1-alternative-' + newNum;
//create the new button
var buttonId = 'btn-del-' + newNum;
var removefun = 'removeAlt('+newNum+')';
var newElem = '<div id="' + divId + '" class="cloned"><input type="text" name="' + inputName + '" id="' + inputId + '" tabindex="' + newNum + '" size="30" /> <input type="button" id="' + buttonId + '" value="X" onclick="' + removefun + '" /></div>';
// insert the new element after the last input field
$('#input' + num).after(newElem);
// focus on the new element
// update the tab indexes of the rest elements
$('#btn-add').attr('tabindex', newNum + 1);
$('#btn-submit').attr('tabindex', newNum + 2);
$('#btn-prev-step').attr('tabindex', newNum + 3);
}
});
|
/*jslint node:true */
'use strict';
module.exports.map = function () {
/* global exp, emit */
var doc = this;
function access(obj, prop) {
var segs = prop.split('.');
while (segs.length) {
var k = segs.shift();
if (obj[k]) {
obj = obj[k];
}
else {
obj = undefined;
}
}
return obj;
}
var values, fields = exp;
if (fields.length === 1) {
values = access(doc, fields[0]);
if (values !== undefined) {
if (!Array.isArray(values)) {
values = [values];
}
values = values.sort().map(function(value) {
var o = {};
o[fields[0]] = value;
return o;
});
}
}
else if (fields.length > 1) {
values = fields
.map(function(field) {
var fieldValues = {};
fieldValues[field] = access(doc, field);
return fieldValues;
})
.reduce(function(previous, current) {
var field = Object.keys(current)[0];
if (Array.isArray(current[field])) {
current[field].sort().forEach(function (value) {
var o = {};
o[field] = value;
previous.push(o);
});
}
else {
var o = {};
o[field] = current[field];
previous.push(o);
}
return previous;
}, []);
}
// var seen = {};
values
// .filter(function(item) {
// return seen.hasOwnProperty(item) ? false : (seen[item] = true);
// })
.forEach(function(v, i) {
values.slice(i + 1).forEach(function(w) {
emit(JSON.stringify([v,w]), 1);
});
});
};
module.exports.reduce = function (key, values) {
return Array.sum(values);
};
|
var structtesting_1_1internal_1_1_matcher_tuple_3_01_1_1testing_1_1tuple_3_01_a1_01_4_01_4 =
[
[ "type", "structtesting_1_1internal_1_1_matcher_tuple_3_01_1_1testing_1_1tuple_3_01_a1_01_4_01_4.html#a8463ac100366f7e8b6ad1035e42ec4b0", null ]
];
|
import React from 'react';
import PropTypes from 'prop-types';
const keyCodeEnter = 13;
export default class MenuItem extends React.Component {
constructor(...args) {
super(...args);
this.onKeyDown = this.onKeyDown.bind(this);
}
// Prevent focusing on mousedown
onMouseDown(event) {
event.preventDefault();
}
onKeyDown(e) {
if (e.keyCode === keyCodeEnter) {
this.props.onClick(e);
}
}
render() {
const { children, ...restProps } = this.props;
return (
<div
role="menuitem"
tabIndex="0"
onKeyDown={this.onKeyDown}
onMouseDown={this.onMouseDown}
{...restProps}
>
{children}
</div>
);
}
}
MenuItem.propTypes = {
children: PropTypes.node.isRequired,
onClick: PropTypes.func.isRequired,
};
|
'use strict';
let gulp = require('gulp');
let runSequence = require('run-sequence');
gulp.task('build-ts', function(cb) {
return runSequence('ts-lint', 'ts', cb);
});
|
/**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'sourcedialog', {
// lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
lang: 'es', // %REMOVE_LINE_CORE%
icons: 'sourcedialog,sourcedialog-rtl', // %REMOVE_LINE_CORE%
hidpi: true, // %REMOVE_LINE_CORE%
init: function( editor ) {
// Register the "source" command, which simply opens the "source" dialog.
editor.addCommand( 'sourcedialog', new CKEDITOR.dialogCommand( 'sourcedialog' ) );
// Register the "source" dialog.
CKEDITOR.dialog.add( 'sourcedialog', this.path + 'dialogs/sourcedialog.js' );
// If the toolbar is available, create the "Source" button.
if ( editor.ui.addButton ) {
editor.ui.addButton( 'Sourcedialog', {
label: editor.lang.sourcedialog.toolbar,
command: 'sourcedialog',
toolbar: 'mode,10'
});
}
}
});
|
(function(){ 'use strict';
'use strict';
angular.module('gc.statusCodeService', [
]).factory('StatusCodeService', [
function StatusCodeServiceFactory() {
var statuses = {
'1': 'info',
'2': 'success',
'3': 'redirect',
'4': 'client-error',
'5': 'server-error'
};
var EMPTY = '';
function matchStatus(code, status) {
var matcher = new RegExp('^' + code + '\\d{2}$');
return status.match(matcher);
}
function safeString(maybeString) {
if (maybeString == null) return '';
return (maybeString).toString();
}
var service = {
isError: function isError(statusCode) {
statusCode = safeString(statusCode);
return !!statusCode.match(/^[4-5]\d{2}$/);
},
isSuccess: function isSuccess(statusCode) {
return !service.isError(statusCode);
},
getLabel: function getLabel(statusCode) {
statusCode = safeString(statusCode);
var prefix = statusCode.substring(0, 1);
if ((prefix in statuses) && matchStatus(prefix, statusCode)) {
return statuses[prefix];
} else {
return EMPTY;
}
}
};
return service;
}
]);
})();
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ArrowKeyStepper = require('./ArrowKeyStepper');
Object.defineProperty(exports, 'ArrowKeyStepper', {
enumerable: true,
get: function get() {
return _ArrowKeyStepper.ArrowKeyStepper;
}
});
var _AutoSizer = require('./AutoSizer');
Object.defineProperty(exports, 'AutoSizer', {
enumerable: true,
get: function get() {
return _AutoSizer.AutoSizer;
}
});
var _CellMeasurer = require('./CellMeasurer');
Object.defineProperty(exports, 'CellMeasurer', {
enumerable: true,
get: function get() {
return _CellMeasurer.CellMeasurer;
}
});
Object.defineProperty(exports, 'defaultCellMeasurerCellSizeCache', {
enumerable: true,
get: function get() {
return _CellMeasurer.defaultCellSizeCache;
}
});
Object.defineProperty(exports, 'uniformSizeCellMeasurerCellSizeCache', {
enumerable: true,
get: function get() {
return _CellMeasurer.defaultCellSizeCache;
}
});
var _Collection = require('./Collection');
Object.defineProperty(exports, 'Collection', {
enumerable: true,
get: function get() {
return _Collection.Collection;
}
});
var _ColumnSizer = require('./ColumnSizer');
Object.defineProperty(exports, 'ColumnSizer', {
enumerable: true,
get: function get() {
return _ColumnSizer.ColumnSizer;
}
});
var _FlexTable = require('./FlexTable');
Object.defineProperty(exports, 'defaultFlexTableCellDataGetter', {
enumerable: true,
get: function get() {
return _FlexTable.defaultCellDataGetter;
}
});
Object.defineProperty(exports, 'defaultFlexTableCellRenderer', {
enumerable: true,
get: function get() {
return _FlexTable.defaultCellRenderer;
}
});
Object.defineProperty(exports, 'defaultFlexTableHeaderRenderer', {
enumerable: true,
get: function get() {
return _FlexTable.defaultHeaderRenderer;
}
});
Object.defineProperty(exports, 'defaultFlexTableRowRenderer', {
enumerable: true,
get: function get() {
return _FlexTable.defaultRowRenderer;
}
});
Object.defineProperty(exports, 'FlexTable', {
enumerable: true,
get: function get() {
return _FlexTable.FlexTable;
}
});
Object.defineProperty(exports, 'FlexColumn', {
enumerable: true,
get: function get() {
return _FlexTable.FlexColumn;
}
});
Object.defineProperty(exports, 'SortDirection', {
enumerable: true,
get: function get() {
return _FlexTable.SortDirection;
}
});
Object.defineProperty(exports, 'SortIndicator', {
enumerable: true,
get: function get() {
return _FlexTable.SortIndicator;
}
});
var _Grid = require('./Grid');
Object.defineProperty(exports, 'defaultCellRangeRenderer', {
enumerable: true,
get: function get() {
return _Grid.defaultCellRangeRenderer;
}
});
Object.defineProperty(exports, 'Grid', {
enumerable: true,
get: function get() {
return _Grid.Grid;
}
});
var _InfiniteLoader = require('./InfiniteLoader');
Object.defineProperty(exports, 'InfiniteLoader', {
enumerable: true,
get: function get() {
return _InfiniteLoader.InfiniteLoader;
}
});
var _ScrollSync = require('./ScrollSync');
Object.defineProperty(exports, 'ScrollSync', {
enumerable: true,
get: function get() {
return _ScrollSync.ScrollSync;
}
});
var _VirtualScroll = require('./VirtualScroll');
Object.defineProperty(exports, 'VirtualScroll', {
enumerable: true,
get: function get() {
return _VirtualScroll.VirtualScroll;
}
});
var _WindowScroller = require('./WindowScroller');
Object.defineProperty(exports, 'WindowScroller', {
enumerable: true,
get: function get() {
return _WindowScroller.WindowScroller;
}
});
|
"use strict";
/**
* Ajax error handler
*/
$.ajaxSetup({
error: function (xhr) {
humane.info("We're so sorry, something is wrong on our end.");
}
});
|
import { E2EGlobal } from './helpers/E2EGlobal';
import { E2EApp } from './helpers/E2EApp';
import { E2EMeetingSeries } from './helpers/E2EMeetingSeries';
import { E2EMinutes } from './helpers/E2EMinutes';
import { E2ETopics } from './helpers/E2ETopics';
import { formatDateISO8601 } from '../../imports/helpers/date';
describe('MeetingSeries Items list', function () {
const aProjectName = "MeetingSeries Topic List";
let aMeetingCounter = 0;
let aMeetingNameBase = "Meeting Name #";
let aMeetingName;
before("reload page and reset app", function () {
E2EApp.resetMyApp(true);
E2EApp.launchApp();
});
beforeEach("goto start page and make sure test user is logged in", function () {
E2EApp.gotoStartPage();
expect(E2EApp.isLoggedIn()).to.be.true;
aMeetingCounter++;
aMeetingName = aMeetingNameBase + aMeetingCounter;
E2EMeetingSeries.createMeetingSeries(aProjectName, aMeetingName);
E2EMinutes.addMinutesToMeetingSeries(aProjectName, aMeetingName);
});
it("displays all info- and action-items of all topics", function () {
E2ETopics.addTopicToMinutes('some topic');
E2ETopics.addInfoItemToTopic({subject: 'some information'}, 1);
E2ETopics.addInfoItemToTopic({subject: 'some action item', itemType: "actionItem"}, 1);
E2ETopics.addTopicToMinutes('some other topic');
E2ETopics.addInfoItemToTopic({subject: 'some information of another topic'}, 1);
E2ETopics.addInfoItemToTopic({subject: 'some action item of another topic', itemType: "actionItem"}, 1);
E2EMinutes.finalizeCurrentMinutes();
E2EMinutes.gotoParentMeetingSeries();
E2EMeetingSeries.gotoTabItems();
expect(E2ETopics.getAllItemsFromItemList().length, "List should have 4 items").to.equal(4);
expect(E2ETopics.getNthItemFromItemList(0).value, "First item should have correct subject").to.have.string("some action item of another topic");
expect(E2ETopics.getNthItemFromItemList(1).value, "First item should have correct subject").to.have.string("some information of another topic");
expect(E2ETopics.getNthItemFromItemList(2).value, "First item should have correct subject").to.have.string("some action item");
expect(E2ETopics.getNthItemFromItemList(3).value, "First item should have correct subject").to.have.string("some information");
});
it('can expand an info item to display its details on the item list', function () {
E2ETopics.addTopicToMinutes('some topic');
E2ETopics.addInfoItemToTopic({subject: 'some information'}, 1);
E2ETopics.addDetailsToActionItem(1, 1, "Amazing details for this information item");
E2EMinutes.finalizeCurrentMinutes();
E2EMinutes.gotoParentMeetingSeries();
E2EMeetingSeries.gotoTabItems();
E2ETopics.expandDetailsForNthInfoItem(1);
expect(E2ETopics.getNthItemFromItemList(0).value)
.to.have.string(formatDateISO8601(new Date()) + ' New' + '\nAmazing details for this information item');
});
});
|
// @flow
"use strict";
/**
* @author dusiyu
* @date 4/17/17.
*/
import type {PluginInvocation} from './plugin';
import type {Node} from './schema';
export type PrimitiveType =
| string
| number
| boolean
| null
export type Document =
| {[string]: Document}
| Array<Document>
| PrimitiveType
export type ResolverInfo = {
node: Node,
options: Object,
args: Object
}
export type ResolverResult =
| Document
| Promise<Document>
| PluginInvocation
export type Resolver = (parentValue: {[string]: Document}, info: ResolverInfo) => ResolverResult;
export type Loader<Id, Value> = (ids: Array<Id>) => Promise<{[Id]: Value}>
|
/*
* This file is part of the Mosaic Platform.
*
* (c) Rommel M. Zamora <rommel.zamora@groupm.com>
* (c) Andrew Aculana <andrew.aculana@movent.com>
*
* Copyright (c) 2017. For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*/
function BrueryAjaxBlock(options) {
this.settings = options.settings;
this.init();
}
BrueryAjaxBlock.prototype = {
init: function() {
if(jQuery('.'+this.settings.id).length > 0) {
this.execute(this);
}
},
execute: function(obj) {
jQuery.ajax({
url: obj.settings.ajax.url,
type: obj.settings.ajax.type,
success: function(json) {
if(json.status === "OK") {
var elm = jQuery(obj.settings.ajax.target);
elm.children().remove();
// fix issue with html comment ...
elm.html(jQuery(json.content.replace(/<!--[\s\S]*?-->/g, "")).html());
} else {
// jQuery('#'+obj.settings.ajax.target).parent().effect("highlight", {'color' : '#C43C35'}, 2000);
}
}
});
}
}
|
var should = require('should');
var annotationModule = require('../index.js');
var mockPath = './fixtures/emptyMock.js';
describe('empty module', function() {
describe('asynchronous', function() {
var err;
var result;
before(function(done){
annotationModule(mockPath, function(e, a){
err = e;
result = a;
done();
});
});
it('should have gone well', function(){
should.ifError(err);
});
it('should have the module name', function(){
result.module.name.should.be.equal('emptyMock');
});
it('module annotations should be empty', function(){
result.module.annotations.should.be.empty;
});
it('ref should be the empty module', function(){
result.module.ref.should.be.equal(require(mockPath));
});
it('functions should be empty', function(){
result.functions.should.be.empty;
});
});
describe('synchronous', function() {
var err;
var result;
before(function(){
try {
result = annotationModule.sync(mockPath);
} catch (e) {
err = e;
}
});
it('should have gone well', function(){
should.ifError(err);
});
it('should have the module name', function(){
result.module.name.should.be.equal('emptyMock');
});
it('module annotations should be empty', function(){
result.module.annotations.should.be.empty;
});
it('ref should be the empty module', function(){
result.module.ref.should.be.equal(require(mockPath));
});
it('functions should be empty', function(){
result.functions.should.be.empty;
});
});
});
|
module.exports = class ViewController {
constructor() {
this.views = {};
}
callViewMethod(type, methodName, data) {
let v = this.getViews(type);
if(!v) {
setTimeout(() => {
this.callViewMethod(type, methodName, data);
}, 750);
}
for(let i in v) {
v[i][methodName](data);
}
}
registerView(type, instance) {
if(!this.views[type]) {
this.views[type] = [];
}
this.views[type].push(instance);
}
getViews(type) {
return this.views[type];
}
}
|
/*jslint nomen:true*/
/*global define*/
define([
'underscore',
'backbone',
'backgrid',
'./header-cell/header-cell'
], function (_, Backbone, Backgrid, HeaderCell) {
"use strict";
var Header;
/**
* Datagrid header widget
*
* @export orodatagrid/js/datagrid/header
* @class orodatagrid.datagrid.Header
* @extends Backgrid.Header
*/
Header = Backgrid.Header.extend({
/** @property */
tagName: "thead",
/** @property */
row: Backgrid.HeaderRow,
/** @property */
headerCell: HeaderCell,
/**
* @inheritDoc
*/
initialize: function (options) {
if (!options.collection) {
throw new TypeError("'collection' is required");
}
if (!options.columns) {
throw new TypeError("'columns' is required");
}
this.columns = options.columns;
if (!(this.columns instanceof Backbone.Collection)) {
this.columns = new Backgrid.Columns(this.columns);
}
this.row = new this.row({
columns: this.columns,
collection: this.collection,
headerCell: this.headerCell
});
this.subviews = [this.row];
},
/**
* @inheritDoc
*/
dispose: function () {
if (this.disposed) {
return;
}
_.each(this.row.cells, function (cell) {
cell.dispose();
});
delete this.row.cells;
delete this.row;
delete this.columns;
Header.__super__.dispose.apply(this, arguments);
}
});
return Header;
});
|
(function (w,i,d,g,e,t,s) {w[d] = w[d]||[];t= i.createElement(g);
t.async=1;t.src=e;s=i.getElementsByTagName(g)[0];s.parentNode.insertBefore(t, s);
})(window, document, '_gscq','script','//widgets.getsitecontrol.com/50978/script.js');
|
var exports = module.exports = {}
, nlp = require("nlp_compromise")
, speak = require("speakeasy-nlp")
, modules = [
require('./modules/weather'),
require('./modules/heather')
]
exports.initiate = function() {
console.log('[I] There\'s ' + modules.length + ' modules loaded.');
}
exports.sendCommand = function(command,callback) {
analyseSentence(command);
for(var k in modules) {
modules[k].initiate(command,function(output){
return callback(output);
});
}
}
/** PRIVATE FUNCTIONS **/
function analyseSentence(sentence) {
/**##########################
| VARIABLES
##########################**/
var sentence_type = null;
var sentence_nlp = nlp.sentence(sentence);
/**##########################
| PROCEDURES
##########################**/
sentence_type = get_sentence_type(sentence); // Checking the type of the sentence 👀
sentence_geo = get_places(sentence); // Checking if the sentence contains a location 📌
}
function get_sentence_type(sentence) {
var result = nlp.sentence(sentence.order).sentence_type(); // Initiate the standard NLP analyzer 👍
var sentence_classified = speak.classify(expand_sentence(sentence.order)); // Classify through speak NLP
var interrogative_keywords = ["what","where","why"]; // Identifying the interrogative keywords
if(interrogative_keywords.indexOf(sentence_classified.action) >= 0) $result = "interrogative"; // Quick check
return result; // Return the sentence type
}
function get_places(sentence) {
var places = nlp.place(sentence);
var geo = (places.city == null && places.region == null && places.country == null) ? false : true;
return geo;
}
function expand_sentence(sentence) {
analysedSentence = nlp.sentence(sentence)
analysedSentence.contractions.expand();
analysedSentence = analysedSentence.text();
return analysedSentence;
}
|
import { EventEmitter } from 'events';
class TabManager extends EventEmitter {
constructor() {
super();
// default tab is home
this.tabName = 'home';
this.tabOptions = undefined;
}
setTab(tabName, tabOptions) {
if (tabName === this.tabName && tabOptions === this.tabOptions) {
return;
}
else {
this.tabName = tabName;
this.tabOptions = tabOptions;
this.emit('changed', tabName, tabOptions);
}
}
}
module.exports = new TabManager();
|
/* ==========================================================================
Styleguide -- Version: 0.4.1 - Updated: 2/22/2014
========================================================================== */
// Create Hex color code from color return
function hexc(colorval) {
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
delete(parts[0]);
for (var i = 1; i <= 3; ++i) {
parts[i] = parseInt(parts[i]).toString(16);
if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
color = '#' + parts.join('');
}
// Get color value of swatch and print to div
var color = '';
$('.swatch').each(function() {
var classList = $(this).children('.swatch-color').attr('class').split(' ');
for(i=0; i <= classList.length-1; i++){
if(classList[i].match(/color-/g)){
$(this).children('.swatch-info').prepend('<p>$' + classList[i] + '</p>');
break;
}
}
var x = $(this).children('.swatch-color').css('backgroundColor');
hexc(x);
$(this).children('.swatch-info').append('<p>' + color + '</p>');
$(this).children('.swatch-info').append('<p>' + x + '</p>');
});
(function($) {
$.fn.vs = function() {
// View source buttons
$('.vs').click(function(){
$(this).parent().next().find('.prettyprint').toggle();
$(this).not('.disabled').toggleClass('js-active');
return false;
});
}
}(jQuery));
$('.vs').vs();
// Get font-family property and return
$('.fonts').each(function(){
var fonts = $(this).css('font-family');
$(this).prepend(fonts);
});
|
var StatusBarView, View;
var __hasProp = {}.hasOwnProperty;
var __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
View = require('atom').View;
module.exports = StatusBarView = (function(_super) {
__extends(StatusBarView, _super);
function StatusBarView() {
return StatusBarView.__super__.constructor.apply(this, arguments);
}
StatusBarView.content = function() {
return this.div({
"class": 'inline-block'
}, (function(_this) {
return function() {
return _this.div({
outlet: "statusText"
});
};
})(this));
};
StatusBarView.prototype.updateText = function(text) {
return this.statusText.html(text);
};
StatusBarView.prototype.initialize = function(statusBar) {
this.statusBar = statusBar;
return null;
};
StatusBarView.prototype.attach = function() {
return this.statusBar.appendLeft(this);
};
StatusBarView.prototype.destroy = function() {
return this.remove();
};
return StatusBarView;
})(View);
|
import fs from './fs';
export default fs;
|
/*global console, alert, prompt*/
/*
Author: Yahia Hegazy
Created: 2016-05-12
Updated: 2016-05-19
Final: 2016-05-19
Project: PlayPen Information
The purpose of this project started out as a simple need to test my javascript skills.
*/
//Gloabal Variables
var setStatus = document.getElementById('status'),
getStatus = localStorage.getItem('status');
function sysinfo() {
'use strict';
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
//Declaring variables, grouped by similiarites
var sysDate = new Date(),
language = "Current language: " + navigator.language,
online = "Browser connectivity: " + navigator.onLine,
cookies = "Cookies enabled: " + navigator.cookieEnabled,
js = "JavaScript enabled: true",
monitorResolution = "Monitor resolution: " + window.screen.width + ' x ' + window.screen.height,
browserDimension = "Browser dimension: " + window.innerWidth + ' x ' + window.innerHeight,
localLocation = "Location: ",
localCoordinates = "Coordinates: ",
message = document.getElementById("sysinfo"),
pc = new window.RTCPeerConnection({iceServers: []}),
noop = function () {};
//Looks up IP address
pc.createDataChannel(""); //create a bogus data channel
pc.createOffer(pc.setLocalDescription.bind(pc), noop); // create offer and set local description
pc.onicecandidate = function (ice) { //listen for candidate events
var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
if (!ice || !ice.candidate || !ice.candidate.candidate) {
return;
}
myIP = 'Your IP: ' + myIP;
pc.onicecandidate = noop;
//Output message
message.innerHTML = sysDate + '<br>' + myIP + '<br>' + online + '<br>' + cookies + '<br>' + js + '<br>' + language + '<br>' + monitorResolution + '<br>' + browserDimension;
};
}
setStatus.onclick = function () {
'use strict';
if (document.getElementById('status').checked === true) {
localStorage.setItem('status', "true");
} else {
localStorage.setItem('status', "false");
}
};
if (getStatus === "true") {
sysinfo();
}
function load() {
'use strict';
var checked = JSON.parse(localStorage.getItem('status'));
document.getElementById('status').checked = checked;
}
function reset() {
'use strict';
location.reload();
localStorage.clear();
}
|
// @flow
function setStatus(name: string, value: string) : Action {
return {
type: 'SET_STATUS',
name,
value
};
}
module.exports = {
setStatus
}
|
define(['model/entity', 'transition', 'lib/pixi', 'enums', 'model/charactermovement'], function (Entity, Transition, PIXI, Enums, CharacterMovement) {
class Character extends Entity {
constructor(CharIndex, gridX, gridY, Heading, Name, clan, Body, Head, Weapon, Shield, Helmet, FX, FXLoops, NickColor) {
super(gridX, gridY);
var self = this;
if (!Name) // es un bicho o npc
{
this.moveSpeed = 200;
}// bicho (duracion de movimiento en ms, animaciones de mov se setean automaticamnete a esta vel (abajo) )
else {
this.moveSpeed = 210;
} // PJ TODO: setear bien estos valores, fijarse que en lo posible no haya resetmovements (esto pasa si la animacion es mas lenta que el llamado a cambiar de pos)
this.id = CharIndex;
this._heading = Heading;
this.sprite = null;
this.spriteNombre = null;
this.texto = null;
this.movement = new CharacterMovement(this);
this._nombre = Name;
this._clan = clan;
this._body = Body;
this._head = Head;
this._weapon = Weapon;
this._shield = Shield;
this._helmet = Helmet;
this._fx = FX;
this._fxLoops = FXLoops;
this._nickColor = NickColor;
}
setSpeed(speed){
this.moveSpeed = speed;
this.sprite.setSpeed(speed);
}
update(delta){
this.movement.update(delta);
//this.sprite.update(delta);
//if (this.spriteNombre){
// this.spriteNombre.update(delta);
//}
if (this.texto){
this.texto.update(delta);
}
}
mover(dir, movimientoCallback, finMovimientoCallback) {
this._animarMovimiento();
let finCb = () => {
this._finAnimarMovimiento();
if (finMovimientoCallback) {
finMovimientoCallback();
}
};
return this.movement.mover(dir, movimientoCallback, finCb);
}
estaMoviendose(){
return this.movement.estaMoviendose();
}
resetMovement() {
return this.movement.resetMovement();
}
_animarMovimiento() {
if (this.sprite) {
this.sprite.loop(true);
this.sprite.play();
}
}
_finAnimarMovimiento() {
if (this.sprite) {
this.sprite.loop(false);
}
}
get muerto(){
return (this.head === Enums.Muerto.cabezaCasper) || (this.body === Enums.Muerto.cuerpoFragataFantasmal);
}
get heading(){
return this._heading;
}
set heading(heading){
if (this._heading !== heading){
this._heading = heading;
this.emit('headingChanged');
}
}
get body(){
return this._body;
}
set body(body){
if (this._body !== body){
this._body = body;
this.emit('bodyChanged');
}
}
get head(){
return this._head;
}
set head(head){
if (this._head !== head){
this._head = head;
this.emit('headChanged');
}
}
get weapon(){
return this._weapon;
}
set weapon(weapon){
if (this._weapon !== weapon){
this._weapon = weapon;
this.emit('weaponChanged');
}
}
get shield(){
return this._shield;
}
set shield(shield){
if (this._shield !== shield){
this._shield = shield;
this.emit('shieldChanged');
}
}
get helmet(){
return this._helmet;
}
set helmet(helmet){
if (this._helmet !== helmet){
this._helmet = helmet;
this.emit('helmetChanged');
}
}
get fx(){
return this._fx;
}
set fx(fx){
if (this._fx !== fx){
this._fx = fx;
this.emit('fxChanged');
}
}
get fxLoops(){
return this._fxLoops;
}
set fxLoops(fxLoops){
if (this._fxLoops !== fxLoops){
this._fxLoops = fxLoops;
this.emit('fxLoopsChanged');
}
}
get nombre(){
return this._nombre;
}
get clan(){
return this._clan;
}
get nickColor(){
return this._nickColor;
}
setName(nombre,clan,color) {
if (this._nombre !== nombre || this._clan !== clan || this._nickColor !== color) {
this._nombre = nombre;
this._clan = clan;
this._nickColor = color;
this.emit('nameChanged');
}
}
}
return Character;
});
|
/**
* @fileoverview Tests for google-camelcase rule.
* @author Gregg Tavares (but it's just a modified version of camelcase by Nicholas C. Zakas)
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var linter = require("eslint").linter;
var ESLintTester = require("eslint-tester");
var eslintTester = new ESLintTester(linter);
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
eslintTester.addRuleTest("lib/rules/google-camelcase", {
valid: [
"firstName = \"Nicholas\"",
"FIRST_NAME = \"Nicholas\"",
"__myPrivateVariable = \"Patrick\"",
"myPrivateVariable_ = \"Patrick\"",
"function doSomething(){}",
"do_something()",
"foo.do_something()",
"var foo = bar.baz_boom;",
"var foo = bar.baz_boom.something;",
"foo.boom_pow.qux = bar.baz_boom.something;",
"if (bar.baz_boom) {}",
"var obj = { key: foo.bar_baz };",
"var arr = [foo.bar_baz];",
"[foo.bar_baz]",
"var arr = [foo.bar_baz.qux];",
"[foo.bar_baz.nesting]",
"if (foo.bar_baz === boom.bam_pow) { [foo.baz_boom] }",
"var a = opt_test;",
"var args = var_args;"
],
invalid: [
{
code: "first_name = \"Nicholas\"",
errors: [
{
message: "Identifier 'first_name' is not in camel case.",
type: "Identifier"
}
]
},
{
code: "__private_first_name = \"Patrick\"",
errors: [
{
message: "Identifier '__private_first_name' is not in camel case.",
type: "Identifier"
}
]
},
{
code: "function foo_bar(){}",
errors: [
{
message: "Identifier 'foo_bar' is not in camel case.",
type: "Identifier"
}
]
},
{
code: "obj.foo_bar = function(){};",
errors: [
{
message: "Identifier 'foo_bar' is not in camel case.",
type: "Identifier"
}
]
},
{
code: "bar_baz.foo = function(){};",
errors: [
{
message: "Identifier 'bar_baz' is not in camel case.",
type: "Identifier"
}
]
},
{
code: "[foo_bar.baz]",
errors: [
{
message: "Identifier 'foo_bar' is not in camel case.",
type: "Identifier"
}
]
},
{
code: "if (foo.bar_baz === boom.bam_pow) { [foo_bar.baz] }",
errors: [
{
message: "Identifier 'foo_bar' is not in camel case.",
type: "Identifier"
}
]
},
{
code: "foo.bar_baz = boom.bam_pow",
errors: [
{
message: "Identifier 'bar_baz' is not in camel case.",
type: "Identifier"
}
]
},
{
code: "var foo = { bar_baz: boom.bam_pow }",
errors: [
{
message: "Identifier 'bar_baz' is not in camel case.",
type: "Identifier"
}
]
},
{
code: "foo.qux.boom_pow = { bar: boom.bam_pow }",
errors: [
{
message: "Identifier 'boom_pow' is not in camel case.",
type: "Identifier"
}
]
}
]
});
|
(function (global, undefined) {
var instruments = (function () {
var _simpleCashflowList = {
cashflows: function () {
return [ { amount: 5, paymentDate: new Date(2012, 01, 01) },
{ amount: 105, paymentDate: new Date(2012, 07, 07) }
];
}
};
return {
simpleCashflowList: _simpleCashflowList
};
} ());
global.instruments = instruments;
} (this));
|
define(['jquery', '//cdn.jsdelivr.net/web-animations/1.0.6/web-animations.min.js'], function($) {
'use strict';
return function(args, ctx) {
var i = $.inArray('--waitForEnd', args), waitForEnd = false, dir, duration = 900, keyframes;
if (i !== -1 && i + 1 < args.length) {
waitForEnd = true;
}
i = $.inArray('--direction', args);
if (i !== -1 && i + 1 < args.length) {
dir = args[i + 1];
}
i = $.inArray('--duration', args);
if (i !== -1 && i + 1 < args.length) {
duration = args[i + 1];
}
var op = args[1];
var elem = document.querySelector(args[args.length - 1]);
if (op === 'in') {
elem.style.opacity = 0;
elem.style.display = 'block';
elem.style.visibility = 'visible';
if (dir === 'down-left') {
keyframes = [
{transform: 'rotate3d(0, 0, 1, -45deg)', opacity: '0', transformOrigin: 'left bottom', offset: 0},
{transform: 'none', opacity: '1', transformOrigin: 'left bottom', offset: 1}
];
} else if (dir === 'down-right') {
keyframes = [
{transform: 'rotate3d(0, 0, 1, 45deg)', opacity: '0', transformOrigin: 'right bottom', offset: 0},
{transform: 'none', opacity: '1', transformOrigin: 'right bottom', offset: 1}
];
} else if (dir === 'up-left') {
keyframes = [
{transform: 'rotate3d(0, 0, 1, 45deg)', opacity: '0', transformOrigin: 'left bottom', offset: 0},
{transform: 'none', opacity: '1', transformOrigin: 'left bottom', offset: 1}
];
} else if (dir === 'up-right') {
keyframes = [
{transform: 'rotate3d(0, 0, 1, -45deg)', opacity: '0', transformOrigin: 'right bottom', offset: 0},
{transform: 'none', opacity: '1', transformOrigin: 'right bottom', offset: 1}
];
} else {
keyframes = [
{transform: 'rotate3d(0, 0, 1, -200deg)', opacity: '0', transformOrigin: 'center', offset: 0},
{transform: 'none', opacity: '1', transformOrigin: 'center', offset: 1}
];
}
var player = elem.animate(keyframes, {duration: duration, iterations: 1});
player.onfinish = function() {
elem.style.opacity = 1;
if (waitForEnd) {
ctx.done();
}
}
} else if (op === 'out') {
if (dir === 'down-left') {
keyframes = [
{transform: 'none', opacity: '1', transformOrigin: 'left bottom', offset: 0},
{transform: 'rotate3d(0, 0, 1, 45deg)', opacity: '0', transformOrigin: 'left bottom', offset: 1}
];
} else if (dir === 'down-right') {
keyframes = [
{transform: 'none', opacity: '1', transformOrigin: 'right bottom', offset: 0},
{transform: 'rotate3d(0, 0, 1, -45deg)', opacity: '0', transformOrigin: 'right bottom', offset: 1}
];
} else if (dir === 'up-left') {
keyframes = [
{transform: 'none', opacity: '1', transformOrigin: 'left bottom', offset: 0},
{transform: 'rotate3d(0, 0, 1, -45deg)', opacity: '0', transformOrigin: 'left bottom', offset: 1}
];
} else if (dir === 'up-right') {
keyframes = [
{transform: 'none', opacity: '1', transformOrigin: 'right bottom', offset: 0},
{transform: 'rotate3d(0, 0, 1, 45deg)', opacity: '0', transformOrigin: 'right bottom', offset: 1}
];
} else {
keyframes = [
{transform: 'none', opacity: '1', transformOrigin: 'center', offset: 0},
{transform: 'rotate3d(0, 0, 1, 200deg)', opacity: '0', transformOrigin: 'center', offset: 1}
];
}
var player = elem.animate(keyframes, {duration: duration, iterations: 1});
player.onfinish = function() {
elem.style.display = 'none';
if (waitForEnd) {
ctx.done();
}
}
} else {
return ctx.done;
}
if (!waitForEnd) {
return ctx.done;
}
};
});
|
/// <reference path="../../jquery-1.8.3.intellisense.js" />
/// <reference path="../../miniui/miniui.js" />
/// <reference path="../../jquery-bbq/jquery.ba-bbq.js" />
(function (window) {
$().ready(function () {
$("#selectSkin").change(function () {
onSkinChange($(this).val());
});
var skin = getCookie("miniuiSkin");
if (skin) {
onSkinChange(skin);
$("#selectSkin").val(skin);
}
else {
onSkinChange($("#selectSkin").val());
}
});
})(window);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.