commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
6f7826bda2a1fe290893995e3da5dc5fa4582d7d
|
Fix tests
|
packages/server/lib/game-managers/pending-game-manager.js
|
packages/server/lib/game-managers/pending-game-manager.js
|
"use strict";
const _ = require("lodash"),
SwappableProxy = require("swappable-proxy"),
GameFactory = require("dc-game-factory"),
PendingGameStatus = GameFactory.PendingGameStatus,
dcConstants = require("dc-constants"),
MessageType = dcConstants.MessageType,
ResponseCode = dcConstants.ResponseCode,
Symbols = dcConstants.Symbols,
PlayerTurnBeginState = require("dc-game-states").PlayerTurnBeginState,
GameManager = require("./game-manager"),
InProgressGameManager = require("./in-progress-game-manager"),
config = require("config").get("dc-server");
function PendingGameManager() {
GameManager.call(this);
let supr = _.clone(this);
let self = this;
let proxy = new SwappableProxy(this);
let factory = new GameFactory(config.deckConfig),
owner;
// callback is used to send messages to
// the players in the game
function addPlayer(userId, callbacks) {
let player = factory.addPlayer();
if(!player) return null;
self._callbacks.set(player, callbacks);
// If the game didn't have an owner, it does now
// This should only happen when the game is first created
// and the initial player is added
if(!owner)
owner = player;
self._users[userId] = { id: userId, player };
return player;
}
this.addPlayer = addPlayer;
function removePlayer(player) {
factory.removePlayer(player);
self._callbacks.remove(player);
let user = _.find(self._users, {
player: { id: player.id }
});
delete self._users[user.id];
if(owner === player) {
owner = factory.players[0];
}
}
this.removePlayer = removePlayer;
function isEmpty() {
return factory.players.length === 0;
}
this.isEmpty = isEmpty;
function startGame(player, ack) {
// Only the owner can start the game
if(player !== owner) {
ack({ result: ResponseCode.StartError });
return;
}
let preset;
preset = {
state: {
class: PlayerTurnBeginState,
args: [ Symbols.player1 ]
},
players: [{
money: 17000,
dcCards: [ "list3", ..._.fill(new Array(4), Symbols.random) ],
cars: [ 24 , ..._.fill(new Array(3), Symbols.random) ],
insurances: [ "fire" ]
}, {
money: 17000,
dcCards: _.fill(new Array(5), Symbols.random),
cars: _.fill(new Array(4), Symbols.random),
insurances: [ Symbols.random ]
}]
};
// If we're able to start the game, then delegate to a
// new game manager which will actually start the game
// and manage the gameplay.
let factoryStatus = factory.status();
let newGameManager;
if(factoryStatus === PendingGameStatus.ReadyToStart) {
newGameManager = new InProgressGameManager(self, factory, preset);
proxy.swap(newGameManager);
}
// Either way, send an appropriate acknowledgement
ack({ result: factoryStatusToResponseCode(factoryStatus) });
self._callbacks.toOthers(player, "action", {
cmd: MessageType.GameStarted
});
}
this.startGame = startGame;
function performCommand(player, msg, ack) {
if(msg.cmd === MessageType.StartGame) {
startGame(player, ack);
} else {
supr.performCommand(player, msg, ack);
}
}
this.performCommand = performCommand;
function factoryStatusToResponseCode(factoryStatus) {
switch(factoryStatus) {
case PendingGameStatus.ReadyToStart:
return ResponseCode.StartOk;
case PendingGameStatus.NotEnoughPlayers:
return ResponseCode.StartNotEnoughPlayers;
}
return null;
}
Object.defineProperties(this, {
id: {
enumerable: true,
get: factory.hashCode
}
});
return proxy.instance;
}
PendingGameManager.prototype = Object.create(GameManager);
module.exports = PendingGameManager;
|
JavaScript
| 0.000003 |
@@ -2069,16 +2069,19 @@
set;%0A
+ //
preset
@@ -2083,24 +2083,27 @@
eset = %7B%0A
+ //
state: %7B%0A
@@ -2101,24 +2101,27 @@
state: %7B%0A
+ //
class:
@@ -2141,24 +2141,27 @@
inState,%0A
+ //
args: %5B
@@ -2178,24 +2178,27 @@
layer1 %5D%0A
+ //
%7D,%0A
@@ -2190,24 +2190,27 @@
// %7D,%0A
+ //
players:
@@ -2211,24 +2211,27 @@
yers: %5B%7B%0A
+ //
money:
@@ -2232,32 +2232,35 @@
oney: 17000,%0A
+ //
dcCards: %5B
@@ -2311,28 +2311,31 @@
dom) %5D,%0A
+//
+
cars: %5B 24 ,
@@ -2377,24 +2377,27 @@
ndom) %5D,%0A
+ //
insuran
@@ -2411,24 +2411,27 @@
%22fire%22 %5D%0A
+ //
%7D, %7B%0A
@@ -2425,24 +2425,27 @@
/ %7D, %7B%0A
+ //
money:
@@ -2450,24 +2450,27 @@
: 17000,%0A
+ //
dcCards
@@ -2508,24 +2508,27 @@
random),%0A
+ //
cars: _
@@ -2563,24 +2563,27 @@
random),%0A
+ //
insuran
@@ -2609,16 +2609,19 @@
om %5D%0A
+ //
%7D%5D%0A
@@ -2621,16 +2621,19 @@
%7D%5D%0A
+ //
%7D;%0A%0A
|
e127bf831089b87f62fcfb73d9a657f90817b26f
|
Print cwd on failure
|
lib/utils/error-handler.js
|
lib/utils/error-handler.js
|
module.exports = errorHandler
var cbCalled = false
, log = require("./log")
, npm = require("../../npm")
, rm = require("./rm-rf")
, constants = require("constants")
, itWorked = false
, path = require("path")
process.on("exit", function (code) {
if (code) itWorked = false
if (itWorked) log("ok")
else {
if (!cbCalled) {
log.error("cb() never called!\n ")
}
log.error([""
,"Additional logging details can be found in:"
," " + path.resolve("npm-debug.log")
].join("\n"))
log.win("not ok")
}
itWorked = false // ready for next exit
})
function errorHandler (er) {
if (cbCalled) throw new Error("Callback called more than once.")
cbCalled = true
if (!er) return exit(0)
if (!(er instanceof Error)) {
log.error(er)
return exit(1)
}
if (!er.errno) {
var m = er.message.match(/^(?:Error: )?(E[A-Z]+)/)
if (m) {
m = m[1]
if (!constants[m] && !npm[m]) constants[m] = {}
er.errno = npm[m] || constants[m]
}
}
switch (er.errno) {
case constants.ECONNREFUSED:
log.error(er)
log.error(["If you are using Cygwin, please set up your /etc/resolv.conf"
,"See step 4 in this wiki page:"
," http://github.com/ry/node/wiki/Building-node.js-on-Cygwin-%28Windows%29"
,"If you are not using Cygwin, please report this"
,"at <http://github.com/isaacs/npm/issues>"
,"or email it to <[email protected]>"
].join("\n"))
break
case constants.EACCES:
case constants.EPERM:
log.error(er)
log.error(["",
"Please use 'sudo' or log in as root to run this command."
,""
," sudo npm "
+npm.config.get("argv").original.map(JSON.stringify).join(" ")
,""
,"or set the 'unsafe-perm' config var to true."
,""
," npm config set unsafe-perm true"
].join("\n"))
break
case npm.ELIFECYCLE:
log.error(er.message)
log.error(["","Failed at the "+er.pkgid+" "+er.stage+" script."
,"This is most likely a problem with the "+er.pkgname+" package,"
,"not with npm itself."
,"Tell the author that this fails on your system:"
," "+er.script
,"You can get their info via:"
," npm owner ls "+er.pkgname
,"There is likely additional logging output above."
].join("\n"))
break
case npm.EJSONPARSE:
log.error(er.message)
log.error("File: "+er.file)
log.error(["Failed to parse package.json data."
,"package.json must be actual JSON, not just JavaScript."
,"","This is not a bug in npm."
,"Tell the package author to fix their package.json file."
].join("\n"), "JSON.parse")
break
case npm.E404:
log.error(["'"+er.pkgid+"' is not in the npm registry."
,"You should bug the author to publish it."
,"Note that you can also install from a tarball or folder."
].join("\n"), "404")
break
case npm.EPUBLISHCONFLICT:
log.error(["Cannot publish over existing version."
,"Bump the 'version' field, set the --force flag, or"
," npm unpublish '"+er.pkgid+"'"
,"and try again"
].join("\n"), "publish fail" )
break
case npm.EISGIT:
log.error([er.message
," "+er.path
,"Refusing to remove it. Update manually,"
,"or move it out of the way first."
].join("\n"), "git" )
break
case npm.ECYCLE:
log.error([er.message
,"While installing: "+er.pkgid
,"Found a pathological dependency case that npm cannot solve."
,"Please report this to the package author."
].join("\n"))
break
case npm.EENGINE:
log.error([er.message
,"Not compatible with your version of node/npm: "+er.pkgid
,"Required: "+JSON.stringify(er.required)
,"Actual: "
+JSON.stringify({npm:npm.version
,node:npm.config.get("node-version")})
].join("\n"))
break
case constants.EEXIST:
log.error([er.message
,"File exists: "+er.path
,"Move it away, and try again."].join("\n"))
break
default:
log.error(er)
log.error(["Report this *entire* log at:"
," <http://github.com/isaacs/npm/issues>"
,"or email it to:"
," <[email protected]>"
].join("\n"))
break
}
var os = require("os")
log.error("")
log.error(os.type() + " " + os.release(), "System")
log.error(process.argv
.map(JSON.stringify).join(" "), "command")
exit(typeof er.errno === "number" ? er.errno : 1)
}
function exit (code) {
var doExit = npm.config.get("_exit")
log.verbose([code, doExit], "exit")
if (code) writeLogFile(reallyExit)
else {
rm("npm-debug.log", function () { rm(npm.tmp, reallyExit) })
}
function reallyExit() {
itWorked = !code
if (doExit) process.exit(code || 0)
else process.emit("exit", code || 0)
}
}
function writeLogFile (cb) {
var fs = require("./graceful-fs")
, fstr = fs.createWriteStream("npm-debug.log")
, sys = require("util")
log.history.forEach(function (m) {
var lvl = log.LEVEL[m.level]
, pref = m.pref ? " " + m.pref : ""
, b = lvl + pref + " "
, msg = typeof m.msg === "string" ? m.msg
: msg instanceof Error ? msg.stack || msg.message
: sys.inspect(m.msg, 0, 4)
fstr.write(new Buffer(b
+(msg.split(/\n+/).join("\n"+b))
+ "\n"))
})
fstr.end()
fstr.on("close", cb)
}
|
JavaScript
| 0.000076 |
@@ -4915,16 +4915,50 @@
mmand%22)%0A
+ log.error(process.cwd(), %22cwd%22)%0A
exit(t
|
fc618417b9ba43b75e24953c730139ffad9a658c
|
update state
|
lib/views/StatusBarTile.js
|
lib/views/StatusBarTile.js
|
'use babel';
/** @jsx etch.dom */
/* @flow*/
import etch from 'etch';
import { Emitter, CompositeDisposable } from 'atom';
import type { TesterState } from '../types';
export default class ConsoleOutputView {
properties: {
state: {results: TesterState};
onclick: Function;
}
refs: any;
element: any;
panel: any;
emitter: Emitter;
disposables: CompositeDisposable;
constructor(properties :Object) {
this.properties = properties;
this.emitter = new Emitter();
this.disposables = new CompositeDisposable();
console.log('properties', properties);
etch.initialize(this);
this.disposables.add(atom.tooltips.add(this.refs.failed, { title: 'Failed Tests' }));
this.disposables.add(atom.tooltips.add(this.refs.skipped, { title: 'Skipped Tests' }));
this.disposables.add(atom.tooltips.add(this.refs.passed, { title: 'Passed Tests' }));
this.disposables.add(atom.tooltips.add(this.refs.beaker, { title: 'Click to toggle Tester' }));
}
render() {
let messages = this.properties.state.results.messages;
if (!messages || messages.constructor !== Array) {
messages = [];
}
const failedTests = messages.filter(result => result.state === 'failed').length;
const skippedTests = messages.filter(result => result.state === 'skipped').length;
const passedTests = messages.filter(result => result.state === 'passed').length;
return (
<div class='status-bar-tester inline-block' onclick={this.properties.onclick} style='display:inline-block;font-size: 0.9em;'>
<a ref='beaker' class='icon icon-beaker'></a>
<a ref='failed' class={failedTests > 0 ?
'tester-bottom-status tester-status-failed highlight-error' :
'tester-bottom-status tester-status-failed highlight'}>
{failedTests}
</a>
<a ref='skipped' class={skippedTests > 0 ?
'tester-bottom-status tester-status-skipped highlight-warning' :
'tester-bottom-status tester-status-skipped highlight'}>
{skippedTests}
</a>
<a ref='passed' class={passedTests > 0 ?
'tester-bottom-status tester-status-passed highlight-success' :
'tester-bottom-status tester-status-passed highlight'}>
{passedTests}
</a>
<span ref='tiny' class={this.properties.state.results.counter > 0 ?
'tester-tiny loading loading-spinner-tiny inline-block' :
'tester-tiny loading loading-spinner-tiny inline-block idle'}/>
</div>
);
}
update(newState :TesterState) {
console.log('newState', newState);
if (this.properties.state !== newState) {
return etch.update(this);
}
return Promise.resolve();
}
async destroy() {
await etch.destroy(this);
this.disposables.dispose();
}
getElement() {
return this.element;
}
}
|
JavaScript
| 0.000001 |
@@ -2537,16 +2537,26 @@
ewState
+:%7Bresults
:TesterS
@@ -2555,24 +2555,25 @@
:TesterState
+%7D
) %7B%0A cons
@@ -2645,24 +2645,64 @@
newState) %7B%0A
+ this.properties.state = newState;%0A
return
|
1e8cd2b873bed97b24d81b0e23d02aa0222ecf83
|
Read aeternum output to find out the pid
|
lib/solenoid.js
|
lib/solenoid.js
|
var fs = require('fs'),
os = require('os'),
path = require('path'),
spawn = require('child_process').spawn,
mkdirp = require('mkdirp'),
async = require('async'),
pkgcloud = require('pkgcloud'),
semver = require('semver'),
useradd = require('useradd');
function noop() {}
//
// Starts an application.
//
exports.start = function (options, callback) {
async.parallel([
async.apply(fetch, options),
async.apply(createUser, options)
], function (err) {
if (err) {
return callback(err);
}
async.series([
async.apply(unpack, options),
async.apply(readPackageJSON, options),
async.apply(findEngine, options),
async.apply(startApp, options)
], callback);
});
};
exports.stop = function (options, callback) {
fs.readFile(options.pidFile, 'utf8', function (err, content) {
if (err) {
return callback(err);
}
try {
process.kill(parseInt(content, 10));
}
catch (ex) {
return callback(ex);
}
});
};
var fetch = exports.fetch = function fetch(options, callback) {
var client = pkgcloud.storage.createClient(options.storage),
tries = 0,
maxTries = 5,
packedSnapshotPath = path.join(os.tmpDir(), 'snapshot.tgz');
options.packedSnapshotPath = packedSnapshotPath;
function doFetch(callback) {
++tries;
var stream = client.download({
container: options.storage.container,
remote: [ options.app.user, options.app.name, options.app.version ].join('-') + '.tgz'
});
stream.pipe(fs.createWriteStream(packedSnapshotPath))
stream.on('error', function (err) {
console.error('Error while fetching snapshot: ' + err.message);
return tries === maxTries
? callback(err)
: doFetch(callback);
});
stream.on('end', function () {
console.log('Application snapshot fetched.');
callback();
});
}
console.log('Fetching application snapshot...');
doFetch(callback);
};
//
// Create a dedicated user account.
//
var createUser = exports.createUser = function createUser(options, callback) {
console.log('Creating user...');
useradd({
login: 'nodejitsu-' + options.app.user,
shell: false,
home: false
}, callback);
};
var unpack = exports.unpack = function unpack(options, callback) {
var snapshotPath = path.join(os.tmpDir(), 'snapshot'),
child;
console.log('Unpacking snapshot...');
options.snapshotPath = snapshotPath;
options.packagePath = path.join(snapshotPath, 'package');
mkdirp(snapshotPath, function (err) {
if (err) {
return callback(err);
}
child = spawn('tar', ['-xf', options.packedSnapshotPath], {
cwd: snapshotPath
});
child.on('exit', function (code, signal) {
fs.unlink(options.packedSnapshotPath, noop);
if (code !== 0) {
return callback(
new Error('`tar` exited with ' + (code
? 'code ' + code.toString()
: 'signal ' + signal.toString()
))
);
}
return callback();
});
});
};
var readPackageJSON = exports.readPackageJSON = function readPackageJSON(options, callback) {
console.log('Reading `package.json`...');
fs.readFile(path.join(options.packagePath, 'package.json'), function (err, data) {
if (err) {
return callback(new Error('Error while reading `package.json`: ' + err.message));
}
try {
data = JSON.parse(data);
}
catch (ex) {
return callback(new Error('Error while parsing `package.json`: ' + err.message));
}
options['package.json'] = data;
callback();
});
};
var findEngine = exports.findEngine = function findEngine(options, callback) {
// TODO: support engines other than node
var package = options['package.json'],
match,
node;
if (!package.engines || !package.engines.node) {
return callback(new Error('node.js version is required'));
}
node = package.engines.node;
if (!semver.validRange(node)) {
return callback(new Error(node + ' is not a valid SemVer version'));
}
fs.readdir(options.engines.node.path, function (err, files) {
if (err) {
err.message = 'Cannot read engines directory: ' + err.message;
return callback(err);
}
match = semver.maxSatisfying(files, node);
if (!match) {
err = new Error('No satisfying engine version found.\n' +
'Available versions are: ' + files.join(','));
return callback(err);
}
options.enginePath = path.join(options.engines.node.path, match, 'bin', 'node');
callback();
});
};
var startApp = exports.startApp = function startApp(options, callback) {
var args = [],
pid = '',
child;
console.log('Starting application...');
args = ['start', '-o', 'estragon.log', '-p', options.pidFile, '--', 'estragon'];
options.instruments.forEach(function (instrument) {
args.push('-h', instrument.host + ':' + (instrument.port || 8556).toString());
});
args.push('--app-user', options.app.user);
args.push('--app-name', options.app.name);
args.push('--', options.enginePath, options['package.json'].scripts.start.split(' ')[1]);
child = spawn('aeternum', args, {
cwd: path.join(options.snapshotPath, 'package')
});
child.on('error', callback);
child.on('exit', function () {
callback();
});
};
|
JavaScript
| 0 |
@@ -4820,31 +4820,8 @@
og',
- '-p', options.pidFile,
'--
@@ -5271,47 +5271,170 @@
ild.
-on('error', callback);%0A child
+stdout.on('readable', function () %7B%0A var chunk = child.stdout.read();%0A if (chunk) %7B%0A pid += chunk.toString('utf8');%0A %7D%0A %7D);%0A%0A child.stdout
.on('e
-xit
+nd
', f
@@ -5445,24 +5445,142 @@
ion () %7B%0A
+ pid = parseInt(pid, 10).toString();%0A console.log('%60aeternum%60 pid: ' + pid);%0A fs.writeFile(options.pidFile, pid,
callback();
@@ -5568,29 +5568,28 @@
e, pid, callback
-(
);%0A %7D);
%0A%7D;%0A
@@ -5568,28 +5568,60 @@
e, pid, callback);%0A %7D);
+%0A%0A child.on('error', callback);
%0A%7D;%0A
|
c3a0cf01c376c9449c77a7aceca3f1a140d4b942
|
Fix typo
|
src/initialState.js
|
src/initialState.js
|
import basicArithmetic from 'keyboardLayouts/basicArithmetic'
export default {
keys: basicArithmetic,
settings: {
authorName: 'Panagiotis Panagi',
authorUrl: 'https://github.com/panayi',
repoUrl: 'https://github.com/panayi/calculator',
tweetText: '3R Calculator build with React, Redux and Ramda',
tweetVia: 'ppanagi'
},
themes: [
{ name: 'dark', active: true },
{ name: 'light', active: false }
]
}
|
JavaScript
| 0.999999 |
@@ -280,17 +280,17 @@
tor buil
-d
+t
with Re
|
1c8e1302993d5049cabc3579b96bef98afc89d42
|
add support for enums
|
src/instantiator.js
|
src/instantiator.js
|
'use strict';
// The JSON Object that defines the default values of certain types.
var typesInstantiator = {
'string': '',
'number': 0,
'integer': 0,
'null': null,
'boolean': false, // Always stay positive?
'object': { }
};
/**
* Checks whether a variable is a primitive.
* @param obj - an object.
* @returns {boolean}
*/
function isPrimitive(obj) {
var type = obj.type;
return typesInstantiator[type] !== undefined;
}
/**
* Checks whether a property is on required array.
* @param property - the property to check.
* @param requiredArray - the required array
* @returns {boolean}
*/
function isPropertyRequired(property, requiredArray) {
var found = false;
requiredArray = requiredArray || [];
requiredArray.forEach(function(requiredProperty) {
if (requiredProperty === property) {
found = true;
}
});
return found;
}
function shouldVisit(property, obj, options) {
return (!options.requiredPropertiesOnly) || (options.requiredPropertiesOnly && isPropertyRequired(property, obj.required));
}
/**
* Instantiate a primitive.
* @param val - The object that represents the primitive.
* @returns {*}
*/
function instantiatePrimitive(val) {
var type = val.type;
// Support for default values in the JSON Schema.
if (val.default) {
return val.default;
}
return typesInstantiator[type];
}
/**
* The main function.
* Calls sub-objects recursively, depth first, using the sub-function 'visit'.
* @param schema - The schema to instantiate.
* @returns {*}
*/
function instantiate(schema, options) {
options = options || {};
/**
* Visits each sub-object using recursion.
* If it reaches a primitive, instantiate it.
* @param obj - The object that represents the schema.
* @param name - The name of the current object.
* @param data - The instance data that represents the current object.
*/
function visit(obj, name, data) {
if (!obj) {
return;
}
var i;
var type = obj.type;
// We want non-primitives objects (primitive === object w/o properties).
if (type === 'object' && obj.properties) {
data[name] = data[name] || { };
// Visit each property.
for (var property in obj.properties) {
if (obj.properties.hasOwnProperty(property)) {
if (shouldVisit(property, obj, options)) {
visit(obj.properties[property], property, data[name]);
}
}
}
} else if (obj.allOf) {
for (i = 0; i < obj.allOf.length; i++) {
visit(obj.allOf[i], name, data);
}
} else if (type === 'array') {
data[name] = [];
var len = 1;
if (obj.minItems || obj.minItems === 0) {
len = obj.minItems;
}
// Instantiate 'len' items.
for (i = 0; i < len; i++) {
visit(obj.items, i, data[name]);
}
} else if (isPrimitive(obj)) {
data[name] = instantiatePrimitive(obj);
}
}
var data = {};
visit(schema, 'kek', data);
return data['kek'];
}
// If we're using Node.js, export the module.
if (typeof module !== 'undefined') {
module.exports = {
instantiate: instantiate
};
}
|
JavaScript
| 0 |
@@ -1357,24 +1357,515 @@
r%5Btype%5D;%0A%7D%0A%0A
+/**%0A * Checks whether a variable is an enum.%0A * @param obj - an object.%0A * @returns %7Bboolean%7D%0A */%0Afunction isEnum(obj) %7B%0A return Object.prototype.toString.call(obj.enum) === '%5Bobject Array%5D'%0A%7D%0A%0A/**%0A * Instantiate an enum.%0A * @param val - The object that represents the primitive.%0A * @returns %7B*%7D%0A */%0Afunction instantiateEnum(val) %7B%0A // Support for default values in the JSON Schema.%0A if (val.default) return val.default;%0A if (!val.enum.length) return undefined;%0A return val.enum%5B0%5D;%0A%7D%0A%0A
/**%0A * The m
@@ -2897,19 +2897,16 @@
%5Bname%5D);
-
%0A
@@ -3327,24 +3327,94 @@
%5D);%0A %7D%0A
+ %7D else if (isEnum(obj)) %7B%0A data%5Bname%5D = instantiateEnum(obj);
%0A %7D else
|
c223c29d9937f7a882ebd112ada65b8625037390
|
fix unsynched source script
|
inotify-rsync.js
|
inotify-rsync.js
|
#!/usr/bin/env node
/*
* inotify-rsync
*
* Copyright (c) 2017 Rurik Bogdanov <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
var DEBUG=false;
var csv_parse=require('csv-parser');
var child_process=require('child_process');
var watchdir=process.argv[2];
var rsync_destination=process.argv[3];
var inotifywait_options=process.argv.slice(4)||[];
var path=require('path');
var fs=require('fs');
if (!rsync_destination) {
console.log('usage: inotify-sync <dirname> <rsync_destination> <inotifywait_options>');
process.exit(1);
}
process.cwd(watchdir);
var inotifywait_args=[
'-m',
'--csv'
].concat(inotifywait_options);
inotifywait_args.push('.');
var inotifywait=child_process.spawn('inotifywait',inotifywait_args,{
cwd: watchdir,
stdio: ['pipe','pipe',process.stderr]
});
var parser=csv_parse({
delimiter: ',',
columns: ['dirname','eventname','filename']
});
inotifywait.stdout.pipe(parser).on('data',function(row){
var colname=['dirname','eventname','filename'];
var i=0;
var event={};
for (var col in row) {
event[colname[i++]]=row[col];
}
if (i<3) return;
var pathname=path.join(watchdir,event.dirname,event.filename);
fs.stat(pathname,function(err,stats){
if (err) {
console.log(err)
} else if (stats.isFile()) {
if (DEBUG) {
console.error(event);
}
switch(event.eventname){
case 'CLOSE_WRITE,CLOSE':
case 'MOVED_TO':
rsync(pathname,event.dirname);
break;
}
}
})
});
function rsync(pathname,destdir){
var cmd=[
'rsync -zav',
pathname,
path.join(rsync_destination,destdir)
];
cmd.push('>&2');
try {
console.error(cmd.join(' '));
var stdout=child_process.execSync(cmd.join(' '),{
cwd: watchdir
});
} catch(e){
console.log(e.message);
notify('Copy failed: '+path.basename(pathname));
return;
}
notify('Copy done: '+path.basename(pathname));
}
function notify(message){
try {
child_process.execSync("notify-send '"+message.replace(/'/,"\'")+"'");
} catch(e) {
console.log(e);
}
try {
child_process.execSync("espeak '"+message.replace(/'/,"\'")+"'");
} catch(e) {
console.log(e);
}
}
|
JavaScript
| 0.000002 |
@@ -784,25 +784,8 @@
*/%0A
-var DEBUG=false;%0A
var
@@ -1294,17 +1294,16 @@
('.');%0A%0A
-%0A
var inot
@@ -1472,14 +1472,14 @@
,%0A
-column
+header
s: %5B
@@ -1573,172 +1573,170 @@
ion(
-row)%7B%0A var colname=%5B'dirname','eventname','filename'%5D;%0A var i=0;%0A var event=%7B%7D;%0A for (var col in row) %7B%0A event%5Bcolname%5Bi++%5D%5D=row%5Bcol%5D;%0A %7D%0A if (i%3C3)
+event)%7B%0A if (event.eventname!='CLOSE_WRITE,CLOSE'%0A && event.eventname!='MOVED_TO'%0A ) %7B%0A return;%0A %7D%0A%0A if (!event.dirname %7C%7C !event.filename) %7B%0A
return;
%0A%0A
@@ -1731,16 +1731,20 @@
return;
+%0A %7D
%0A%0A var
@@ -1917,58 +1917,8 @@
) %7B%0A
- if (DEBUG) %7B%0A%09%09%09%09console.error(event);%0A%09%09%09%7D%0A
@@ -2546,16 +2546,40 @@
ssage)%7B%0A
+ console.log(message);%0A
try %7B%0A
|
90f6292cb05ad6f727da9ed90fd4bdf0f9b69933
|
work on AboutArrays.js
|
koans/AboutArrays.js
|
koans/AboutArrays.js
|
describe("About Arrays", function() {
//We shall contemplate truth by testing reality, via spec expectations.
it("should create arrays", function() {
var emptyArray = [];
expect(typeof(emptyArray)).toBe('object'); //A mistake? - http://javascript.crockford.com/remedial.html
expect(emptyArray.length).toBe(0);
var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
expect(multiTypeArray[0]).toBe(0);
expect(multiTypeArray[2]).toBe("two");
expect(multiTypeArray[3]()).toBe(3);
expect(multiTypeArray[4].value1).toBe(4);
expect(multiTypeArray[4]["value2"]).toBe(5);
expect(multiTypeArray[5][0]).toBe(6);
});
it("should understand array literals", function () {
var array = [];
expect(array).toEqual([]);
array[0] = 1;
expect(array).toEqual([1]);
array[1] = 2;
expect(array).toEqual([1, FILL_ME_IN]);
array.push(3);
expect(array).toEqual(FILL_ME_IN);
});
it("should understand array length", function () {
var fourNumberArray = [1, 2, 3, 4];
expect(fourNumberArray.length).toBe(FILL_ME_IN);
fourNumberArray.push(5, 6);
expect(fourNumberArray.length).toBe(FILL_ME_IN);
var tenEmptyElementArray = new Array(10);
expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);
tenEmptyElementArray.length = 5;
expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);
});
it("should slice arrays", function () {
var array = ["peanut", "butter", "and", "jelly"];
expect(array.slice(0, 1)).toEqual(FILL_ME_IN);
expect(array.slice(0, 2)).toEqual(FILL_ME_IN);
expect(array.slice(2, 2)).toEqual(FILL_ME_IN);
expect(array.slice(2, 20)).toEqual(FILL_ME_IN);
expect(array.slice(3, 0)).toEqual(FILL_ME_IN);
expect(array.slice(3, 100)).toEqual(FILL_ME_IN);
expect(array.slice(5, 1)).toEqual(FILL_ME_IN);
});
it("should know array references", function () {
var array = [ "zero", "one", "two", "three", "four", "five" ];
function passedByReference(refArray) {
refArray[1] = "changed in function";
}
passedByReference(array);
expect(array[1]).toBe(FILL_ME_IN);
var assignedArray = array;
assignedArray[5] = "changed in assignedArray";
expect(array[5]).toBe(FILL_ME_IN);
var copyOfArray = array.slice();
copyOfArray[3] = "changed in copyOfArray";
expect(array[3]).toBe(FILL_ME_IN);
});
it("should push and pop", function () {
var array = [1, 2];
array.push(3);
expect(array).toEqual(FILL_ME_IN);
var poppedValue = array.pop();
expect(poppedValue).toBe(FILL_ME_IN);
expect(array).toEqual(FILL_ME_IN);
});
it("should know about shifting arrays", function () {
var array = [1, 2];
array.unshift(3);
expect(array).toEqual(FILL_ME_IN);
var shiftedValue = array.shift();
expect(shiftedValue).toEqual(FILL_ME_IN);
expect(array).toEqual(FILL_ME_IN);
});
});
|
JavaScript
| 0 |
@@ -893,26 +893,17 @@
ual(%5B1,
-FILL_ME_IN
+2
%5D);%0A%0A
@@ -940,34 +940,33 @@
ay).toEqual(
-FILL_ME_IN
+%5B1, 2, 3%5D
);%0A %7D);%0A%0A
@@ -1093,34 +1093,25 @@
ength).toBe(
-FILL_ME_IN
+4
);%0A fourN
@@ -1169,34 +1169,25 @@
ength).toBe(
-FILL_ME_IN
+6
);%0A%0A var
@@ -1265,34 +1265,26 @@
ength).toBe(
-FILL_ME_IN
+10
);%0A%0A tenE
@@ -1353,34 +1353,25 @@
ength).toBe(
-FILL_ME_IN
+5
);%0A %7D);%0A%0A
@@ -1499,34 +1499,36 @@
1)).toEqual(
-FILL_ME_IN
+%5B 'peanut' %5D
);%0A expec
@@ -1552,34 +1552,46 @@
2)).toEqual(
-FILL_ME_IN
+%5B 'peanut', 'butter' %5D
);%0A expec
@@ -1615,34 +1615,26 @@
2)).toEqual(
-FILL_ME_IN
+%5B%5D
);%0A expec
@@ -1659,34 +1659,39 @@
0)).toEqual(
-FILL_ME_IN
+%5B'and','jelly'%5D
);%0A expec
@@ -1715,34 +1715,26 @@
0)).toEqual(
-FILL_ME_IN
+%5B%5D
);%0A expec
@@ -1760,34 +1760,33 @@
0)).toEqual(
-FILL_ME_IN
+%5B'jelly'%5D
);%0A expec
@@ -1810,34 +1810,26 @@
1)).toEqual(
-FILL_ME_IN
+%5B%5D
);%0A %7D);%0A%0A
|
5ff8deb1837a161dfbcdd4b4db5adf3e98bfdb4c
|
Simplify rearg function definitions.
|
lathe/js/rearg.js
|
lathe/js/rearg.js
|
/*
global
THREE
sizeBox
widthBox
heightBox
depthBox
getBoxVertex
setBoxVertices
setXBoxVertices
setYBoxVertices
setZBoxVertices
copyBoxVertices
centroidBox
alignBox
relativeAlignBox
lerpBoxVertices
relativeLerpBoxVertices
applyBoxVertexColors
applyBoxFaceVertexColors
defaultVertexColors
translateBoxVertices
scaleBoxVertices
translateXBoxVertices
translateYBoxVertices
translateZBoxVertices
scaleXBoxVertices
scaleYBoxVertices
scaleZBoxVertices
*/
/* exported geometryArguments */
const geometryArguments = (() => {
'use strict';
function reargMethod( method ) {
return ( ...args ) => {
return geometry => {
geometry[ method ]( ...args );
return geometry;
};
};
}
const geometryMethods = [
'rotateX',
'rotateY',
'rotateZ',
'translate',
'scale',
];
const shorthandGeometryMethods = [ 'rx', 'ry', 'rz', 't', 's' ];
const reargGeometryMethods = geometryMethods.map( reargMethod );
function reargAxisMethod( method, identity = new THREE.Vector3() ) {
const vector = new THREE.Vector3();
return axis => {
return ( value = identity.getComponent( axis ) ) => {
return geometry => {
vector
.copy( identity )
.setComponent( axis, value );
geometry[ method ]( ...vector.toArray() );
return geometry;
};
};
};
}
const geometryAxisMethods = [
'translateX',
'translateY',
'translateZ',
'scaleX',
'scaleY',
'scaleZ',
];
const shorthandGeometryAxisMethods = [ 'tx', 'ty', 'tz', 'sx', 'sy', 'sz' ];
const translateGeometryAxis = reargAxisMethod( 'translate' );
const scaleGeometryAxis = reargAxisMethod( 'scale', new THREE.Vector3( 1, 1, 1 ) );
const reargGeometryAxisMethods = [
translateGeometryAxis( 0 ),
translateGeometryAxis( 1 ),
translateGeometryAxis( 2 ),
scaleGeometryAxis( 0 ),
scaleGeometryAxis( 1 ),
scaleGeometryAxis( 2 ),
];
function rearg( fn ) {
return ( ...args ) => geometry => fn( geometry, ...args );
}
const reargGetVertex = rearg( getBoxVertex );
const reargSet = rearg( setBoxVertices );
const reargSetX = rearg( setXBoxVertices );
const reargSetY = rearg( setYBoxVertices );
const reargSetZ = rearg( setZBoxVertices );
const reargCopy = rearg( copyBoxVertices );
const reargCentroid = rearg( centroidBox );
const reargAlign = rearg( alignBox );
const reargColors = rearg( applyBoxVertexColors );
const reargFaceColors = rearg( applyBoxFaceVertexColors );
const reargDefaultColors = rearg( defaultVertexColors );
const reargTranslateVertices = rearg( translateBoxVertices );
const reargScaleVertices = rearg( scaleBoxVertices );
const reargLerp = rearg( lerpBoxVertices );
const reargTranslateXVertices = rearg( translateXBoxVertices );
const reargTranslateYVertices = rearg( translateYBoxVertices );
const reargTranslateZVertices = rearg( translateZBoxVertices );
const reargScaleXVertices = rearg( scaleXBoxVertices );
const reargScaleYVertices = rearg( scaleYBoxVertices );
const reargScaleZVertices = rearg( scaleZBoxVertices );
function reargRelativeAlign( alignmentA ) {
return ( geometryB, alignmentB ) => {
return rearg( relativeAlignBox )( alignmentA, geometryB, alignmentB );
};
}
function reargRelativeLerp( verticesA, t ) {
return ( geometryB, verticesB ) => {
return rearg( relativeLerpBoxVertices )( verticesA, geometryB, verticesB, t );
};
}
return {
keys: [
'THREE',
'size',
'width',
'height',
'depth',
'vertex',
'set',
'setX',
'setY',
'setZ',
'copy',
'centroid',
'align',
'relativeAlign',
'lerp',
'relativeLerp',
'color',
'faceColor',
'defaultColor',
'$translate',
'$t',
'$scale',
'$s',
'$translateX',
'$tx',
'$translateY',
'$ty',
'$translateZ',
'$tz',
'$scaleX',
'$sx',
'$scaleY',
'$sy',
'$scaleZ',
'$sz',
]
.concat( geometryMethods )
.concat( shorthandGeometryMethods )
.concat( geometryAxisMethods )
.concat( shorthandGeometryAxisMethods ),
values: [
THREE,
sizeBox,
widthBox,
heightBox,
depthBox,
reargGetVertex,
reargSet,
reargSetX,
reargSetY,
reargSetZ,
reargCopy,
reargCentroid,
reargAlign,
reargRelativeAlign,
reargLerp,
reargRelativeLerp,
reargColors,
reargFaceColors,
reargDefaultColors,
reargTranslateVertices,
reargTranslateVertices,
reargScaleVertices,
reargScaleVertices,
reargTranslateXVertices,
reargTranslateXVertices,
reargTranslateYVertices,
reargTranslateYVertices,
reargTranslateZVertices,
reargTranslateZVertices,
reargScaleXVertices,
reargScaleXVertices,
reargScaleYVertices,
reargScaleYVertices,
reargScaleZVertices,
reargScaleZVertices,
]
.concat( reargGeometryMethods )
.concat( reargGeometryMethods )
.concat( reargGeometryAxisMethods )
.concat( reargGeometryAxisMethods ),
};
})();
|
JavaScript
| 0 |
@@ -4077,33 +4077,21 @@
z',%0A
-%5D%0A .concat(
+ ...
geometry
@@ -4093,34 +4093,33 @@
metryMethods
- )
+,
%0A .
concat( shor
@@ -4102,32 +4102,26 @@
ods,%0A .
-concat(
+..
shorthandGeo
@@ -4128,34 +4128,33 @@
metryMethods
- )
+,
%0A .
concat( geom
@@ -4141,24 +4141,18 @@
%0A .
-concat(
+..
geometry
@@ -4158,34 +4158,33 @@
yAxisMethods
- )
+,
%0A .
concat( shor
@@ -4171,24 +4171,18 @@
%0A .
-concat(
+..
shorthan
@@ -4197,26 +4197,31 @@
yAxisMethods
- )
+,%0A %5D
,%0A values
@@ -5050,25 +5050,13 @@
-%5D%0A .concat(
+ ...
rear
@@ -5067,34 +5067,33 @@
metryMethods
- )
+,
%0A .
concat( rear
@@ -5076,32 +5076,26 @@
ods,%0A .
-concat(
+..
reargGeometr
@@ -5098,34 +5098,33 @@
metryMethods
- )
+,
%0A .
concat( rear
@@ -5107,32 +5107,26 @@
ods,%0A .
-concat(
+..
reargGeometr
@@ -5141,18 +5141,17 @@
hods
- )
+,
%0A .
conc
@@ -5150,16 +5150,10 @@
.
-concat(
+..
rear
@@ -5172,18 +5172,23 @@
sMethods
- )
+,%0A %5D
,%0A %7D;%0A%7D
|
3ab4eaeef85abb2ad2458489a08f59e06876474d
|
Update deploy commit message
|
build/gh-pages.js
|
build/gh-pages.js
|
module.exports = function (grunt) {
return {
main: {
options: {
add : (grunt.option('cleanup') ? false : true),
base : 'dist',
branch : 'gh-pages',
message: global.release_target ? 'Release to ' + global.release_target : 'Auto-generated commit',
},
src: global.branch ? [global.branch_prefix + global.branch + '/**'] : ['**', '!' + (global.branch_prefix || 'br_') + '*/**']
},
trigger_tests: {
options: {
add : true,
base : 'dist',
branch : 'master',
repo : '[email protected]:binary-com/robot-framework.git',
message: 'Trigger tests',
},
src: grunt.option('staging') ? 'version' : '',
},
}
};
|
JavaScript
| 0 |
@@ -311,31 +311,50 @@
t :
-'Auto-generated commit'
+%60Deploy to $%7Bglobal.branch %7C%7C 'gh-pages'%7D%60
,%0A
|
52b68fa9b83f9a4022402e0f8190aaa75b694c6e
|
Update build/make/amd.js
|
build/make/amd.js
|
build/make/amd.js
|
steal('can/construct/proxy', 'can/construct/super', 'can/control', 'can/control/plugin',
'can/control/view', 'can/view/modifiers', 'can/model', 'can/view/ejs',
'can/observe/attributes', 'can/observe/delegate', 'can/observe/setter',
'can/observe/validations', 'can/route', 'can/view/modifiers', 'can/observe/backup',
'can/util/mootools', 'can/util/dojo', 'can/util/yui', 'can/util/zepto', 'can/util/jquery',
function(can) {
return can;
});
|
JavaScript
| 0 |
@@ -153,16 +153,36 @@
ew/ejs',
+ 'can/view/mustache'
%0A%09'can/o
@@ -332,16 +332,37 @@
ackup',%0A
+%09'can/util/fixture',%0A
%09'can/ut
|
9bc6041852edacb2eb85bf31b5aa5a2e0a67dc28
|
Replace promise with async await and handle error cases
|
server/trello-microservice/src/utils/passportMiddleweare.js
|
server/trello-microservice/src/utils/passportMiddleweare.js
|
import fetch from 'node-fetch';
import { userModel } from '../models/index';
export const authenticatedWithToken = (req, res, next) => {
let csrf;
let jwt;
if (req && req.cookies && req.headers){
csrf = req.headers.csrf;
jwt = req.cookies.jwt;
const opts = {
headers: {
csrf,
jwt
}
};
fetch('http://localhost:3002/signcheck', opts)
.then(res => {
if (res.status === 401) {
return null;
}
return res.json();
})
.then(user => {
if (!user) {
return next();
} else {
return userModel.findOne({name: user.name})
.then(user => {
req.user = user;
return next();
});
}
})
}
};
|
JavaScript
| 0 |
@@ -109,16 +109,22 @@
hToken =
+ async
(req, r
@@ -144,39 +144,30 @@
%7B%0A
-let csrf;%0A let jwt;%0A%0A if (req
+if (req && req.cookies
&&
@@ -169,32 +169,36 @@
s && req.cookies
+.jwt
&& req.headers)
@@ -200,15 +200,40 @@
ders
-)
+ && req.headers.csrf)
%7B%0A
+let
csrf
@@ -257,16 +257,20 @@
rf;%0A
+let
jwt = re
@@ -367,16 +367,32 @@
%7D;%0A%0A
+let res = await
fetch('h
@@ -433,34 +433,11 @@
pts)
-%0A .then(res =%3E %7B%0A
+;%0A%0A
@@ -460,36 +460,32 @@
== 401) %7B%0A
-
return null;%0A
@@ -489,110 +489,73 @@
-
-
%7D%0A%0A
- return res.json();%0A %7D)%0A .then(user =%3E %7B%0A if (!user) %7B%0A return
+let resJson = await res.json();%0A%0A if (!resJson) %7B%0A
nex
@@ -555,28 +555,24 @@
next();%0A
-
%7D else %7B
@@ -582,88 +582,108 @@
- return userModel.findOne(%7Bname: user.name%7D)%0A .then(user =%3E %7B%0A
+try %7B%0A let user = await userModel.findOne(%7Bname: resJson.name%7D).exec();%0A%0A if (user) %7B%0A
@@ -711,24 +711,36 @@
;%0A
+ next();%0A
%0A
@@ -735,70 +735,157 @@
+%7D
%0A
- return next();
+%7D catch (error) %7B%0A console.log(error)
%0A
+%7D%0A
%7D
-);
%0A
- %7D%0A %7D)
+%7D else %7B%0A req.err = 'Either the cookie or the token is missing';%0A%0A next();
%0A %7D
|
b2bc33ba9860260a578a2e64dbc90c3fb8cf9951
|
Add required studentId to RecordService JS spec
|
spec/javascripts/student_profile/record_service_spec.js
|
spec/javascripts/student_profile/record_service_spec.js
|
//= require ./fixtures
describe('RecordService', function() {
var dom = window.shared.ReactHelpers.dom;
var createEl = window.shared.ReactHelpers.createEl;
var merge = window.shared.ReactHelpers.merge;
var RecordService = window.shared.RecordService;
var SpecSugar = window.shared.SpecSugar;
var Fixtures = window.shared.Fixtures;
var helpers = {
renderInto: function(el, props) {
var mergedProps = merge(props || {}, {
studentFirstName: 'Tamyra',
serviceTypesIndex: Fixtures.studentProfile.serviceTypesIndex,
educatorsIndex: Fixtures.studentProfile.educatorsIndex,
nowMoment: Fixtures.nowMoment,
currentEducator: Fixtures.currentEducator,
onSave: jasmine.createSpy('onSave'),
onCancel: jasmine.createSpy('onCancel'),
requestState: null
});
return ReactDOM.render(createEl(RecordService, mergedProps), el);
},
serviceTypes: function(el) {
return $(el).find('.btn.service-type').toArray().map(function(el) {
return $.trim(el.innerText);
});
},
findSaveButton: function(el) {
return $(el).find('.btn.save');
}
};
SpecSugar.withTestEl('integration tests', function() {
it('renders dialog for recording services', function() {
var el = this.testEl;
helpers.renderInto(el);
expect(el).toContainText('Which service?');
expect(helpers.serviceTypes(el)).toEqual([
'Counseling, in-house',
'Counseling, outside',
'Reading intervention',
'Math intervention',
'Attendance Officer',
'Attendance Contract',
'Behavior Contract'
]);
expect(el).toContainText('Who is working with Tamyra?');
// TODO (as): test staff dropdown autocomplete async
expect(el).toContainText('When did they start?');
expect($(el).find('.Datepicker .datepicker.hasDatepicker').length).toEqual(1);
expect(helpers.findSaveButton(el).length).toEqual(1);
expect(helpers.findSaveButton(el).attr('disabled')).toEqual('disabled');
expect($(el).find('.btn.cancel').length).toEqual(1);
});
});
});
|
JavaScript
| 0 |
@@ -820,16 +820,38 @@
te: null
+,%0A studentId: 1
%0A %7D
|
2485f5bdbdb275ea5b8af8aa85b6ed8e4583cb6f
|
move init to post-script
|
CurrentActions/metadata/aura/MInsightList/MInsightListController.js
|
CurrentActions/metadata/aura/MInsightList/MInsightListController.js
|
({
doInit : function(component, event, helper) {
// try {
//Fetch the insight list from the Apex controller
helper.getInsightList(component, helper);
//helper.registerServiceWorker();
helper.sampleControllerAction(component);
//Set up the callback
var name_action = component.get("c.getUserName");
name_action.setCallback(this, function(actionResult) {
var result = actionResult.getReturnValue();
component.set("v.name", result);
});
$A.enqueueAction(name_action);
var total_action = component.get("c.maxCount");
total_action.setCallback(this, function(actionResult) {
var result = actionResult.getReturnValue();
component.set("v.totalCount", result);
});
$A.enqueueAction(total_action);
// } catch (err) {
// console.log('MIinsight List Init Error');
// console.log(err.stack);
// }
},
postScript: function(component, event, helper) {
//$('<meta>', {name: 'viewport',content: 'user-scalable=no'}).appendTo('head');
},
nav : function(component, event, helper) {
var filterH = component.get("v.filterH");
var filterV = component.get("v.filterV");
var swiperV = component.get("v.swiperV");
var swiperH = component.get("v.swiperH");
var topH = component.get("v.topH");
if (event.getParam("filterOne")) {
filterH.slideTo(0,0);
filterV.slideTo(1,200);
}
if (event.getParam("filterHead")) {
topH.slideTo(1, 0);
swiperV.slideTo(0,0);
swiperH.slideTo(0,0);
filterH.slideTo(0,0);
filterV.slideTo(0,0);
}
},
assocSearch : function(component, event, helper) {
if (event.hasOwnProperty("sourceIndex")) {
return;
}
var source = event.getParam("source");
var field = event.getParam("field");
var self = this;
var action = component.get("c.getInsightsForSourceAndField");
action.setParams({
"source": source, "field": field
});
action.setCallback(self, function(actionResult) {
var filtered = actionResult.getReturnValue();
//debugger;
console.log('just loaded in some filtered insights:'+filtered.length);
component.set("v.filtered", filtered);
});
$A.enqueueAction(action);
},
filteredInsightsChanged : function(component, event, helper) {
var filterH = component.get("v.filterH");
filterH.slideTo(0);
_.defer(function () {
$A.getCallback(function() {
filterH.update();
});
});
},
showPopup : function(component, event, helper) {
//called on clicking your button
//run your form render code after that, run the following lines
helper.showPopupHelper(component, helper, 'modaldialog', 'slds-fade-in-');
helper.showPopupHelper(component, helper, 'backdrop','slds-backdrop--');
},
hidePopup : function(component, event, helper) {
helper.hidePopupHelper(component, helper, 'modaldialog', 'slds-fade-in-');
helper.hidePopupHelper(component, helper, 'backdrop', 'slds-backdrop--');
},
showModalForInsight : function(component, event, helper) {
var insight = event.getParam("insight");
helper.showPopupHelper(component, helper, 'modaldialog', 'slds-fade-in-', insight);
helper.showPopupHelper(component, helper, 'backdrop','slds-backdrop--');
}
})
|
JavaScript
| 0 |
@@ -40,24 +40,82 @@
helper) %7B%0A%0A
+%0A%0A%09%7D,%0A%0A%09postScript: function(component, event, helper) %7B%0A%0A
%09%09// try %7B%0A%0A
@@ -899,147 +899,8 @@
%7D,%0A%0A
-%09postScript: function(component, event, helper) %7B%0A%0A%09%09//$('%3Cmeta%3E', %7Bname: 'viewport',content: 'user-scalable=no'%7D).appendTo('head');%0A%0A%09%7D,%0A%0A
%09nav
|
d85ab87ceaee2c38ae2e8c1245fe699bca6181be
|
Add support for conditional template blocks
|
lib/template.js
|
lib/template.js
|
var fs = require("fs");
var templates = {};
function make_safe(text) {
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\'/g, "'").replace(/\"/g, """);
}
function flatten_object(object) {
var output,
prop,
subobject,
subprop,
i;
if(typeof(object) === "string" || typeof(object) === "number") {
return object;
} else if(Array.isArray(object)) {
output = {};
for(i=0; i<object.length; i++) {
output[i] = object[i];
}
return flatten_object(output);
} else if(object && typeof(object) === "object") {
output = {};
for(prop in object) {
subobject = flatten_object(object[prop]);
if(typeof(subobject) === "object") {
for(subprop in subobject) {
output[prop + "." + subprop] = subobject[subprop];
}
} else {
output[prop] = object[prop];
}
}
return output;
}
return "" + object;
}
exports.render = function(template, content, escape_html) {
var prop, c;
content = flatten_object(content);
for(prop in content) {
c = "" + content[prop];
if(escape_html) {
c = make_safe(c);
}
template = template.replace(new RegExp("\\{\\{\\s*" + prop + "\\s*\\}\\}", "ig"), c);
}
return template;
};
exports.render_file = function(template_path, content, escape_html) {
var template;
if(!templates[template_path]) {
templates[template_path] = fs.readFileSync(template_path, "utf8");
}
template = templates[template_path];
return exports.render(template, content, escape_html);
};
|
JavaScript
| 0 |
@@ -1086,16 +1086,482 @@
ect;%0A%7D%0A%0A
+var ifPattern = /%5C%7B%25%5Cs*if%5Cs+(%5CS+?)%5Cs*%25%5C%7D((?:%5B%5Cs%5CS%5D(?!%5C%7B%25))*%5B%5Cs%5CS%5D)%5C%7B%25%5Cs*endif%5Cs*%25%7D/i;%0Avar ifNotPattern = /%5C%7B%25%5Cs*if%5Cs+not%5Cs+(.+?)%5Cs*%25%5C%7D((?:%5B%5Cs%5CS%5D(?!%5C%7B%25))*%5B%5Cs%5CS%5D)%5C%7B%25%5Cs*endif%5Cs*%25%7D/i;%0A%0Afunction contains(content, prop) %7B%0A if(content.hasOwnProperty(prop)) %7B%0A return true;%0A %7D else %7B%0A for(var p in content) %7B%0A if(new RegExp(%22%5E%22 + prop + %22%5B%5C.$%5D%22, %22i%22).test(p)) %7B%0A return true;%0A %7D%0A %7D%0A %7D%0A%0A return false;%0A%7D%0A%0A
exports.
@@ -1627,16 +1627,25 @@
prop, c
+, matches
;%0A%0A c
@@ -1797,32 +1797,32 @@
e(c);%0A %7D%0A
-
template
@@ -1898,32 +1898,605 @@
g%22), c);%0A %7D%0A%0A
+ while(ifPattern.test(template)) %7B%0A matches = ifPattern.exec(template);%0A%0A if(contains(content, matches%5B1%5D)) %7B%0A template = template.replace(matches%5B0%5D, matches%5B2%5D);%0A %7D else %7B%0A template = template.replace(matches%5B0%5D, %22%22);%0A %7D%0A %7D%0A%0A while(ifNotPattern.test(template)) %7B%0A matches = ifNotPattern.exec(template);%0A%0A if(!contains(content, matches%5B1%5D)) %7B%0A template = template.replace(matches%5B0%5D, matches%5B2%5D);%0A %7D else %7B%0A template = template.replace(matches%5B0%5D, %22%22);%0A %7D%0A %7D%0A%0A
return templ
|
fb3d2c2d0700551572d3b671632e73ef3347cfe4
|
Make CHTML-preview previews inherit the surrounding color
|
unpacked/extensions/CHTML-preview.js
|
unpacked/extensions/CHTML-preview.js
|
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*************************************************************
*
* MathJax/extensions/CHTML-preview.js
*
* Implements a fast preview using the Common-HTML output jax
* and then a slower update to the more accurate HTML-CSS output
* (or whatever the user has selected).
*
* ---------------------------------------------------------------------
*
* Copyright (c) 2014 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function (HUB,HTML) {
var CHTMLpreview = MathJax.Extension["CHTML-preview"] = {
version: "1.0",
//
// Configuration for the chinking of the main output
// after the previews have been created
//
config: HUB.CombineConfig("CHTML-preview",{
EqnChunk: 5, EqnChunkFactor: 1, EqnChunkDelay: 150
}),
//
// Ajust the chunking of the output jax
//
Config: function () {
HUB.Config({
"HTML-CSS": this.config,
"SVG": this.config
});
},
//
// Insert a preview span, if there isn't one already,
// and call the CommonHTML output jax to create the preview
//
Preview: function (data) {
var preview = data.script.previousSibling;
if (!preview || preview.className !== MathJax.Hub.config.preRemoveClass) {
preview = HTML.Element("span",{className:MathJax.Hub.config.preRemoveClass});
data.script.parentNode.insertBefore(preview,data.script);
}
preview.innerHTML = "";
return this.postFilter(preview,data);
return data;
},
postFilter: function (preview,data) {
try {
data.math.root.toCommonHTML(preview);
} catch (err) {
if (!err.restart) {throw err} // an actual error
return MathJax.Callback.After(["postFilter",this,preview,data],err.restart);
}
},
//
// Hook into the inut jax postFilter to create the previews as
// the input jax are processed.
//
Register: function (name) {
HUB.Register.StartupHook(name+" Jax Require",function () {
var jax = MathJax.InputJax[name];
var delay = HUB.config.delayJaxRegistration;
HUB.config.delayJaxRegistration = true;
HUB.Register.StartupHook(name+" Jax Ready",function () {HUB.config.delayJaxRegistration = delay});
jax.require.push(
"[MathJax]/jax/output/CommonHTML/config.js",
"[MathJax]/jax/output/CommonHTML/jax.js"
);
jax.postfilterHooks.Add(["Preview",MathJax.Extension["CHTML-preview"]],50);
});
}
}
//
// Hook into each input jax
//
CHTMLpreview.Register("TeX");
CHTMLpreview.Register("MathML");
CHTMLpreview.Register("AsciiMath");
HUB.Register.StartupHook("End Config",["Config",CHTMLpreview]);
})(MathJax.Hub,MathJax.HTML);
MathJax.Ajax.loadComplete("[MathJax]/extensions/CHTML-preview.js");
|
JavaScript
| 0.000009 |
@@ -1364,16 +1364,25 @@
%7B%0A
+Chunks: %7B
EqnChunk
@@ -1423,16 +1423,40 @@
lay: 150
+%7D,%0A color:%22inherit%22
%0A %7D),
@@ -1592,16 +1592,23 @@
s.config
+.Chunks
,%0A
@@ -1613,13 +1613,11 @@
-%22
SVG
-%22
: th
@@ -1625,23 +1625,106 @@
s.config
-%0A
+.Chunks,%0A %7D);%0A MathJax.Ajax.Styles(%7B%22.MathJax_Preview%22:%7Bcolor:this.config.color%7D
%7D);%0A
|
7936e25d221b7b0c999547de67705d70b832ce56
|
Fix for ENYO-2385
|
source/ui/Repeater.js
|
source/ui/Repeater.js
|
/**
_enyo.Repeater_ is a simple control for making lists of items.
The components of a repeater are copied for each item created, and are
wrapped in a control that keeps the state of the item index.
Example:
{kind: "Repeater", count: 2, onSetupItem: "setImageSource", components: [
{kind: "Image"}
]}
setImageSource: function(inSender, inEvent) {
var index = inEvent.index;
var item = inEvent.item;
item.$.image.setSrc(this.imageSources[index]);
return true;
}
Be sure to return _true_ from your _onSetupItem_ handler to avoid having
other event handlers further up the tree try to modify your item control.
For more information, see the documentation on
[Lists](https://github.com/enyojs/enyo/wiki/Lists) in the Enyo Developer
Guide.
*/
enyo.kind({
name: "enyo.Repeater",
published: {
//* Number of items
count: 0
},
events: {
/**
Fires when each item is created.
_inEvent.index_ contains the item's index.
_inEvent.item_ contains the item control, for decoration.
*/
onSetupItem: ""
},
create: function() {
this.inherited(arguments);
this.countChanged();
},
//* @protected
initComponents: function() {
this.itemComponents = this.components || this.kindComponents;
this.components = this.kindComponents = null;
this.inherited(arguments);
},
countChanged: function() {
this.build();
},
itemAtIndex: function(inIndex) {
return this.controlAtIndex(inIndex);
},
//* @public
/** Renders the collection of items. This will delete any existing items and
recreate the repeater if called after the repeater has been rendered.
This is called automatically if _setCount_ is called, even if the count
remains the same.
*/
build: function() {
this.destroyClientControls();
for (var i=0, c; i<this.count; i++) {
c = this.createComponent({kind: "enyo.OwnerProxy", index: i});
// do this as a second step so 'c' is the owner of the created components
c.createComponents(this.itemComponents);
// invoke user's setup code
this.doSetupItem({index: i, item: c});
}
this.render();
},
/**
Renders a specific item in the collection. This does not destroy the
item, but just calls the _onSetupItem_ event handler again for it, so
any state stored in the item is preserved.
*/
renderRow: function(inIndex) {
var c = this.itemAtIndex(inIndex);
this.doSetupItem({index: inIndex, item: c});
}
});
// Sometimes client controls are intermediated with null-controls.
// These overrides reroute events from such controls to the nominal delegate,
// as would happen in the absence of intermediation.
enyo.kind({
name: "enyo.OwnerProxy",
tag: null,
decorateEvent: function(inEventName, inEvent, inSender) {
if (inEvent) {
inEvent.index = this.index;
// update delegate during bubbling to account for proxy
// by moving the delegate up to the repeater level
if (inEvent.delegate && inEvent.delegate.owner === this) {
inEvent.delegate = this.owner;
}
}
this.inherited(arguments);
},
delegateEvent: function(inDelegate, inName, inEventName, inEvent, inSender) {
if (inDelegate == this) {
inDelegate = this.owner.owner;
}
return this.inherited(arguments, [inDelegate, inName, inEventName, inEvent, inSender]);
}
});
|
JavaScript
| 0 |
@@ -2704,25 +2704,28 @@
nSender) %7B%0A%09
-%09
+
if (inEvent)
@@ -2719,24 +2719,49 @@
if (inEvent
+ && !(%22index%22 in inEvent)
) %7B%0A%09%09%09inEve
@@ -2785,17 +2785,35 @@
ndex;%0A%09%09
-%09
+%7D%0A %0A
// updat
@@ -2860,19 +2860,24 @@
r proxy%0A
-%09%09%09
+
// by mo
@@ -2923,15 +2923,31 @@
vel%0A
-%09%09%09if (
+ if (inEvent &&
inEv
@@ -3000,17 +3000,16 @@
s) %7B%0A%09%09%09
-%09
inEvent.
@@ -3032,22 +3032,20 @@
owner;%0A%09
-%09%09%7D%0A%09%09
+
%7D%0A%09%09this
@@ -3304,17 +3304,16 @@
Sender%5D);%0A%09%7D%0A%7D);
-%0A
|
3d8a938c30be69bf557f84e484b17e35506c85c8
|
work on button
|
ui/widgets/button.js
|
ui/widgets/button.js
|
goog.provide('recoil.ui.widgets.ButtonWidget');
goog.require('recoil.ui.WidgetScope');
/**
* @constructor
* @param {recoil.ui.WidgetScope} scope
* @param {Element} container the container that the tree will go into
*/
recoil.ui.widgets.ButtonWidget = function (scope, container) {
};
recoil.ui.widgets.ButtonWidget.prototype.attach = function(value) {
this.config_.attach(recoil.frp.struct.get('config', value, goog.ui.tree.TreeControl.defaultConfig));
this.state_.attach(recoil.frp.struct.get('callback', value));
this.state_.attach(recoil.frp.struct.get(enabled));
};
|
JavaScript
| 0.000001 |
@@ -284,13 +284,383 @@
) %7B%0A
+ this.container_ = container;%0A /**%0A * @private%0A * @type goog.ui.Button%0A * %0A */%0A this.button_ = null;%0A /**%0A * @private%0A * @type recoil.structs.Tree%0A */%0A this.config_ = new recoil.ui.WidgetHelper(scope, container, this, this.updateConfig_);%0A this.state_ = new recoil.ui.WidgetHelper(scope, container, this, this.updateState_);
%0A
-
%7D;%0A%0A
@@ -728,16 +728,79 @@
lue) %7B%0A%0A
+ this.callback_ = recoil.frp.struct.get('callback', value);%0A
this
@@ -923,107 +923,1065 @@
ach(
-recoil.frp.struct.get('callback', value));%0A this.state_.attach(recoil.frp.struct.get(enabled));%0A
+this.callback_,%0A recoil.frp.struct.get('text', value), %0A recoil.frp.struct.get('tooltip', value, %22%22),%0A recoil.frp.struct.get('enabled', value, true));%0A%0A%7D;%0A%0Arecoil.ui.widgets.ButtonWidget.updateConfig_ = function(helper, configB) %7B%0A var me = this;%0A var good = helper.isGood();%0A%0A if (good) %7B%0A if (me.button_ !== null) %7B%0A goog.dom.removeChildren(this.container_);%0A %7D%0A var config = configB.get();%0A this.button_ = new goog.button.Button(config.content, config.renderer, config.domHelper);%0A this.button_.render(me.container_); %0A goog.events.listen(this.button_, goog.ui.Component.EventType.ACTION,%0A function(e) %7B%0A me.set(e);%0A %7D); %0A // and created a new one%0A me.state_.forceUpdate();%0A %7D%0A%7D;%0A%0A%0Arecoil.ui.widgets.ButtonWidget.updateState_ = function(helper, callbackB, textB, tooltipB, enabledB) %7B%0A if (this.button_) %7B%0A this.button_.setEnabled(helper.isGood())%0A %7D
%0A%7D;%0A
|
6484a22689930301c7a3ed5437409836ad05d9aa
|
fix duplicate gradient used on Convo tab
|
source/views/views.js
|
source/views/views.js
|
// @flow
import * as c from './components/colors'
export type ViewType =
| {
type: 'view',
view: string,
title: string,
icon: string,
foreground: 'light' | 'dark',
tint: string,
gradient?: [string, string],
}
| {
type: 'url',
view: string,
url: string,
title: string,
icon: string,
foreground: 'light' | 'dark',
tint: string,
gradient?: [string, string],
}
export const allViews: ViewType[] = [
{
type: 'view',
view: 'MenusView',
title: 'Menus',
icon: 'bowl',
foreground: 'light',
tint: c.emerald,
gradient: c.grassToLime,
},
{
type: 'view',
view: 'SISView',
title: 'OneCard',
icon: 'credit-card',
foreground: 'light',
tint: c.goldenrod,
gradient: c.yellowToGoldDark,
},
{
type: 'view',
view: 'BuildingHoursView',
title: 'Building Hours',
icon: 'clock',
foreground: 'light',
tint: c.wave,
gradient: c.lightBlueToBlueDark,
},
{
type: 'view',
view: 'CalendarView',
title: 'Calendar',
icon: 'calendar',
foreground: 'light',
tint: c.coolPurple,
gradient: c.magentaToPurple,
},
{
type: 'url',
url: 'https://apps.carleton.edu/campus/directory/',
view: 'DirectoryView',
title: 'Stalkernet',
icon: 'v-card',
foreground: 'light',
tint: c.indianRed,
gradient: c.redToPurple,
},
{
type: 'view',
view: 'StreamingView',
title: 'Streaming Media',
icon: 'video',
foreground: 'light',
tint: c.denim,
gradient: c.lightBlueToBlueLight,
},
{
type: 'view',
view: 'NewsView',
title: 'News',
icon: 'news',
foreground: 'light',
tint: c.eggplant,
gradient: c.purpleToIndigo,
},
{
type: 'url',
url: 'https://apps.carleton.edu/map/',
view: 'MapView',
title: 'Campus Map',
icon: 'map',
foreground: 'light',
tint: c.coffee,
gradient: c.navyToNavy,
},
{
type: 'view',
view: 'ContactsView',
title: 'Important Contacts',
icon: 'phone',
foreground: 'light',
tint: c.crimson,
gradient: c.orangeToRed,
},
{
type: 'view',
view: 'TransportationView',
title: 'Transportation',
icon: 'address',
foreground: 'light',
tint: c.cardTable,
gradient: c.grayToDarkGray,
},
{
type: 'url',
url: 'https://wiki.carleton.edu',
view: 'CarlpediaView',
title: 'Carlpedia',
icon: 'open-book',
foreground: 'light',
tint: c.olive,
gradient: c.pinkToHotpink,
},
{
type: 'url',
url: 'https://apps.carleton.edu/student/orgs/',
view: 'StudentOrgsView',
title: 'Student Orgs',
icon: 'globe',
foreground: 'light',
tint: c.periwinkle,
gradient: c.tealToSeafoam,
},
{
type: 'view',
view: 'ConvocationsView',
title: 'Convo',
icon: 'globe',
foreground: 'light',
tint: c.periwinkle,
gradient: c.lightBlueToBlueDark,
},
{
type: 'url',
url: 'https://moodle.carleton.edu/',
view: 'MoodleView',
title: 'Moodle',
icon: 'graduation-cap',
foreground: 'light',
tint: c.cantaloupe,
gradient: c.yellowToGoldLight,
},
{
type: 'view',
view: 'HelpView',
title: 'Report A Problem',
icon: 'help',
foreground: 'light',
tint: c.lavender,
gradient: c.seafoamToGrass,
},
]
export const allViewNames = allViews.map(v => v.view)
|
JavaScript
| 0 |
@@ -2690,35 +2690,36 @@
ient: c.
-lightBlue
+carlsBlueLight
ToBlue
-Dark
,%0A%09%7D,%0A%09%7B
|
48fd5507c9c5724b2de43619f363ab70bcf5c06c
|
Fix JSON parser on advanced build. Fixes #64
|
lime/src/helper/parser/json.js
|
lime/src/helper/parser/json.js
|
goog.provide('lime.parser.JSON');
goog.require('goog.math.Rect');
goog.require('goog.math.Vec2');
goog.require('goog.math.Size');
(function(){
lime.parser.JSON = function(data){
var dict = {};
var root = data['frames'];
for(var i in root){
var frame = root[i];
var w = frame['frame']['w'], h= frame['frame']['h'];
if(frame['rotated']){
h=frame['frame']['w'];
w=frame['frame']['h'];
}
dict[i] = [new goog.math.Rect(frame['frame']['x'],frame['frame']['y'],w,h),
new goog.math.Vec2(frame['spriteSourceSize']['x'],frame['spriteSourceSize']['y']),
new goog.math.Size(frame['sourceSize']['w'],frame['sourceSize']['h']),frame['rotated']
];
}
return dict;
};
})();
|
JavaScript
| 0 |
@@ -129,23 +129,8 @@
);%0A%0A
-(function()%7B%0A%0A%0A
lime
@@ -763,11 +763,4 @@
;%0A%7D;
-%0A%0A%7D)();
|
da204ccfccac81a74aac04260a208c807dc3bbde
|
Test for streaming.
|
__tests__/twitter-client.js
|
__tests__/twitter-client.js
|
jest.unmock('../lib/twitter-client')
var Bot = require('../lib/bot')
var TwitterClient = require('../lib/twitter-client')
var bot = new Bot()
test('should default to consumer key from enviromental variable', () => {
var client = new TwitterClient(bot)
client.send(null, 'text')
expect(client.twit.post).toBeCalledWith('statuses/update', { status: 'text' });
});
test('should use enviromental variables for key, secrets and tokens', () => {
process.env.TWITTER_CONSUMER_KEY = 'key'
process.env.TWITTER_CONSUMER_SECRET = 'secret'
process.env.TWITTER_ACCESS_TOKEN = 'token'
process.env.TWITTER_ACCESS_TOKEN_SECRET = 'secret'
var client = new TwitterClient(bot)
expect(client.config.consumer_key).toEqual('key')
expect(client.config.consumer_secret).toEqual('secret')
expect(client.config.access_token).toEqual('token')
expect(client.config.access_token_secret).toEqual('secret')
process.env.TWITTER_CONSUMER_KEY = undefined
process.env.TWITTER_CONSUMER_SECRET = undefined
process.env.TWITTER_ACCESS_TOKEN = undefined
process.env.TWITTER_ACCESS_TOKEN_SECRET = undefined
});
test('should use configuration object for key, secrets and tokens', () => {
var config = {
consumer_key: 'key',
consumer_secret: 'secret',
access_token: 'token',
access_token_secret: 'secret'
}
var client = new TwitterClient(bot, config)
expect(client.config.consumer_key).toEqual('key')
expect(client.config.consumer_secret).toEqual('secret')
expect(client.config.access_token).toEqual('token')
expect(client.config.access_token_secret).toEqual('secret')
});
// var stream = client.twit.stream('statuses/filter', { track: '@' + bot.name })
//
// stream.on('tweet', function (tweet) {
//
// var session = new Session(tweet.user.id, {}, this)
//
// bot.trigger('message_received', {
// text: tweet.text
// }, session)
// })
test('posts status when sending message', () => {
var client = new TwitterClient(bot)
client.send(null, 'text')
expect(client.twit.post).toBeCalledWith('statuses/update', { status: 'text' });
});
|
JavaScript
| 0 |
@@ -1604,46 +1604,179 @@
);%0A%0A
-// var stream = client.twit.stream
+test('should listen for tweets mentioning the bot', () =%3E %7B%0A%0A var client = new TwitterClient(bot)%0A client.send(null, 'text')%0A%0A expect(client.twit.stream).toBeCalledWith
('st
@@ -1817,19 +1817,22 @@
.name %7D)
-%0A//
+;%0A%7D);%0A
%0A//
|
006adf2b7a48470de94b75c19e36e93a92ad5e7e
|
Inline regular expression
|
lib/node_modules/@stdlib/assert/is-blank-string/lib/main.js
|
lib/node_modules/@stdlib/assert/is-blank-string/lib/main.js
|
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var reWhitespace = require( '@stdlib/regexp/whitespace' );
// VARIABLES //
var RE = new RegExp( '^' + reWhitespace.REGEXP.source + '*$' );
// MAIN //
/**
* Tests if a value is a blank string (i.e., an empty string or a string consisting only of whitespace characters).
*
* @param {*} value - value to test
* @returns {boolean} boolean indicating if an input value is a blank string
*
* @example
* var bool = isBlankString( ' ' );
* // returns true
*
* @example
* var bool = isBlankString( '' );
* // returns true
*
* @example
* var bool = isBlankString( '\t\t\t' );
* // returns true
*
* @example
* var bool = isBlankString( '\r\n\r\n' );
* // returns true
*
* @example
* var bool = isBlankString( 'beep' );
* // returns false
*/
function isBlankString( value ) {
if ( !isString( value ) ) {
return false;
}
return RE.test( value );
}
// EXPORTS //
module.exports = isBlankString;
|
JavaScript
| 0.998586 |
@@ -711,148 +711,199 @@
ve;%0A
-var reWhitespace = require( '@stdlib/regexp/whitespace' );%0A%0A%0A// VARIABLES //%0A%0Avar RE = new RegExp( '%5E' + reWhitespace.REGEXP.source + '*$' )
+%0A%0A// VARIABLES //%0A%0Avar RE = /%5E%5B%5Cu0009%5Cu000A%5Cu000B%5Cu000C%5Cu000D%5Cu0020%5Cu0085%5Cu00A0%5Cu1680%5Cu2000%5Cu2001%5Cu2002%5Cu2003%5Cu2004%5Cu2005%5Cu2006%5Cu2007%5Cu2008%5Cu2009%5Cu200A%5Cu2028%5Cu2029%5Cu202F%5Cu205F%5Cu3000%5CuFEFF%5D*$/
;%0A%0A%0A
|
7ec023afb39af121ab5d614db2f67c0af5eed742
|
add button # to EventTracker events; also prevent context menu
|
event_tracker.js
|
event_tracker.js
|
class EventTracker {
constructor(dom_element) {
this.dom_element = dom_element;
this.mouseIsDown = false;
this.lastP = null;
this.lastDrag = null;
this.lastTime = null;
this.mouseDownListener = null;
this.mouseDragListener = null;
this.mouseUpListener = null;
this.mouseWheelListener = null;
this.keyPressListener = null;
this.keyUpListener = null;
this.specialKeys = {
'Tab': true,
'Escape': true,
'Delete': true,
'Backspace': true
};
this.mouseDown = (event) => {
this.mouseIsDown = true;
this.lastP = this.relCoords(event);
this.lastTime = event.timeStamp;
if (this.mouseDownListener) {
this.mouseDownListener(this.lastP);
}
window.addEventListener('mousemove', this.mouseMove);
window.addEventListener('mouseup', this.mouseUp);
};
this.mouseMove = (event) => {
const p = this.relCoords(event);
const t = event.timeStamp;
if (this.mouseIsDown) {
this.lastDrag = { x : p.x - this.lastP.x, y : p.y - this.lastP.y };
if (this.mouseDragListener) {
this.mouseDragListener(p, this.lastDrag, event.button);
}
this.lastP = p;
this.lastTime = t;
}
};
this.mouseUp = (event) => {
const p = this.relCoords(event);
const t = event.timeStamp;
this.mouseIsDown = false;
if (this.mouseUpListener) {
this.mouseUpListener(p, t - this.lastTime, this.lastDrag, event);
}
this.lastP = p;
this.lastTime = t;
window.removeEventListener('mousemove', this.mouseMove);
window.removeEventListener('mouseup', this.mouseUp);
};
this.mouseWheel = (event) => {
if (this.mouseWheelListener) {
event.preventDefault();
event.stopPropagation();
let delta = 0;
if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9
delta = event.wheelDelta / 40;
} else if ( event.detail ) { // Firefox
delta = - event.detail / 3;
}
const p = this.relCoords(event);
this.mouseWheelListener(delta, p);
}
};
this.keyPress = (event) => {
if (!(event.key in this.specialKeys) && this.keyPressListener) { this.keyPressListener(event); }
};
this.keyUp = (event) => {
if (!(event.key in this.specialKeys) && this.keyUpListener) { this.keyUpListener(event); }
};
}
setMouseDownListener(listener) {
this.mouseDownListener = listener;
return this;
}
setMouseDragListener(listener) {
this.mouseDragListener = listener;
return this;
}
setMouseUpListener(listener) {
this.mouseUpListener = listener;
return this;
}
setMouseWheelListener(listener) {
this.mouseWheelListener = listener;
return this;
}
setKeyPressListener(listener) {
this.keyPressListener = listener;
return this;
}
setKeyUpListener(listener) {
this.keyUpListener = listener;
return this;
}
relCoords(event) {
return { x : event.pageX - this.dom_element.offsetLeft,
y : event.pageY - this.dom_element.offsetTop };
}
start() {
window.addEventListener( 'keypress', this.keyPress, false );
window.addEventListener( 'keyup', this.keyUp, false );
this.dom_element.addEventListener( 'mousedown', this.mouseDown, false );
this.dom_element.addEventListener( 'mousewheel', this.mouseWheel, false );
}
};
export {EventTracker};
|
JavaScript
| 0 |
@@ -3103,16 +3103,51 @@
ffsetTop
+,%0A button: event.button
%7D;%0A %7D%0A
@@ -3450,16 +3450,131 @@
alse );%0A
+%09this.dom_element.addEventListener( 'contextmenu', (e) =%3E %7B%0A e.preventDefault();%0A return false;%0A %7D);%0A%0A
%7D%0A%0A%7D;%0A
|
79984c7730e0ff1e1bafc8cbe1029cdf8b62a358
|
add source map support for better debugging experience (#3738)
|
packages/babel-jest/src/index.js
|
packages/babel-jest/src/index.js
|
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
import type {Path, ProjectConfig} from 'types/Config';
import type {TransformOptions} from 'types/Transform';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const jestPreset = require('babel-preset-jest');
const BABELRC_FILENAME = '.babelrc';
const BABELRC_JS_FILENAME = '.babelrc.js';
const BABEL_CONFIG_KEY = 'babel';
const PACKAGE_JSON = 'package.json';
const THIS_FILE = fs.readFileSync(__filename);
let babel;
const createTransformer = (options: any) => {
const cache = Object.create(null);
const getBabelRC = filename => {
const paths = [];
let directory = filename;
while (directory !== (directory = path.dirname(directory))) {
if (cache[directory]) {
break;
}
paths.push(directory);
const configFilePath = path.join(directory, BABELRC_FILENAME);
if (fs.existsSync(configFilePath)) {
cache[directory] = fs.readFileSync(configFilePath, 'utf8');
break;
}
const configJsFilePath = path.join(directory, BABELRC_JS_FILENAME);
if (fs.existsSync(configJsFilePath)) {
// $FlowFixMe
cache[directory] = JSON.stringify(require(configJsFilePath));
break;
}
const packageJsonFilePath = path.join(directory, PACKAGE_JSON);
if (fs.existsSync(packageJsonFilePath)) {
// $FlowFixMe
const packageJsonFileContents = require(packageJsonFilePath);
if (packageJsonFileContents[BABEL_CONFIG_KEY]) {
cache[directory] = JSON.stringify(
packageJsonFileContents[BABEL_CONFIG_KEY],
);
break;
}
}
}
paths.forEach(directoryPath => (cache[directoryPath] = cache[directory]));
return cache[directory] || '';
};
options = Object.assign({}, options, {
plugins: (options && options.plugins) || [],
presets: ((options && options.presets) || []).concat([jestPreset]),
retainLines: true,
});
delete options.cacheDirectory;
delete options.filename;
return {
canInstrument: true,
getCacheKey(
fileData: string,
filename: Path,
configString: string,
{instrument}: TransformOptions,
): string {
return crypto
.createHash('md5')
.update(THIS_FILE)
.update('\0', 'utf8')
.update(fileData)
.update('\0', 'utf8')
.update(configString)
.update('\0', 'utf8')
.update(getBabelRC(filename))
.update('\0', 'utf8')
.update(instrument ? 'instrument' : '')
.digest('hex');
},
process(
src: string,
filename: Path,
config: ProjectConfig,
transformOptions: TransformOptions,
): string {
if (!babel) {
babel = require('babel-core');
}
if (babel.util && !babel.util.canCompile(filename)) {
return src;
}
const theseOptions = Object.assign({filename}, options);
if (transformOptions && transformOptions.instrument) {
theseOptions.auxiliaryCommentBefore = ' istanbul ignore next ';
// Copied from jest-runtime transform.js
theseOptions.plugins = theseOptions.plugins.concat([
[
require('babel-plugin-istanbul').default,
{
// files outside `cwd` will not be instrumented
cwd: config.rootDir,
exclude: [],
},
],
]);
}
return babel.transform(src, theseOptions).code;
},
};
};
module.exports = createTransformer();
(module.exports: any).createTransformer = createTransformer;
|
JavaScript
| 0 |
@@ -2257,16 +2257,42 @@
: true,%0A
+ sourceMaps: 'inline',%0A
%7D);%0A
|
6250b0864193caa1c2f534fcbd67360e5239e92c
|
Add new selectors
|
src/examples/selectors.js
|
src/examples/selectors.js
|
function init(cube) {
// examples of led selector syntax
cube().on(); // whole cube
cube({x: range(cube.x - 3)}).on(); // all x from 0 to cube.x - 3 - 1 -> whole
cube({x: 3, y: 7}).on(); // all x = 3, y = 7 (z is free)
cube({x: 2, y: 4, z: 1}).on(); // specific led
cube([2, 4, 1]).on(); // specific led, accepts array too
}
|
JavaScript
| 0.000001 |
@@ -26,109 +26,40 @@
//
-examples of led selector syntax%0A cube().on(); // whole cube%0A cube(%7Bx: range(cube.x - 3)%7D
+whole cube%0A cube(
).on();
+%0A%0A
//
@@ -115,23 +115,33 @@
%7Bx:
-3, y: 7
+range(cube.x - 3)
%7D).on();
//
@@ -132,24 +132,29 @@
- 3)%7D).on();
+%0A%0A
// all x =
@@ -191,29 +191,23 @@
%7Bx:
-2
+3
, y:
-4, z: 1
+7
%7D).on();
//
@@ -198,24 +198,29 @@
y: 7%7D).on();
+%0A%0A
// specific
@@ -237,58 +237,204 @@
ube(
-%5B2, 4, 1%5D).on(); // specific led, accepts array too
+%7Bx: 2, y: 4, z: 1%7D).on();%0A cube(%5B2, 4, 1%5D).on();%0A cube(2, 4, 1).on();%0A%0A // multiple specific leds%0A cube(%5B%7Bx: 1, y: 2, z: 3%7D, %7Bx: 4, y: 5, z: 6%7D%5D).on();%0A cube(%5B%5B1, 2, 3%5D, %5B4, 5, 6%5D%5D);
%0A%7D%0A
|
4e12994dab6ed4401e6f288d7f5b67610669cfa5
|
Use less restrictive assertion
|
lib/node_modules/@stdlib/string/from-code-point/lib/main.js
|
lib/node_modules/@stdlib/string/from-code-point/lib/main.js
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' );
var MAX_CODE_POINT = require( '@stdlib/constants/string/unicode-max' );
var MAX_BMP_CODE_POINT = require( '@stdlib/constants/string/unicode-max-bmp' );
// VARIABLES //
var fromCharCode = String.fromCharCode;
// Factor to rescale a code point from a supplementary plane:
var Ox10000 = 0x10000|0; // 65536
// Factor added to obtain a high surrogate:
var OxD800 = 0xD800|0; // 55296
// Factor added to obtain a low surrogate:
var OxDC00 = 0xDC00|0; // 56320
// 10-bit mask: 2^10-1 = 1023 => 0x3ff => 00000000 00000000 00000011 11111111
var Ox3FF = 1023|0;
// MAIN //
/**
* Creates a string from a sequence of Unicode code points.
*
* ## Notes
*
* - UTF-16 encoding uses one 16-bit unit for non-surrogates (U+0000 to U+D7FF and U+E000 to U+FFFF).
* - UTF-16 encoding uses two 16-bit units (surrogate pairs) for U+10000 to U+10FFFF and encodes U+10000-U+10FFFF by subtracting 0x10000 from the code point, expressing the result as a 20-bit binary, and splitting the 20 bits of 0x0-0xFFFFF as upper and lower 10-bits. The respective 10-bits are stored in two 16-bit words: a high and a low surrogate.
*
*
* @param {...NonNegativeInteger} args - sequence of code points
* @throws {Error} must provide either an array-like object of code points or one or more code points as separate arguments
* @throws {TypeError} a code point must be a nonnegative integer
* @throws {RangeError} must provide a valid Unicode code point
* @returns {string} created string
*
* @example
* var str = fromCodePoint( 9731 );
* // returns '☃'
*/
function fromCodePoint( args ) {
var len;
var str;
var arr;
var low;
var hi;
var pt;
var i;
len = arguments.length;
if ( len === 1 && isArrayLikeObject( args ) ) {
arr = arguments[ 0 ];
len = arr.length;
} else {
arr = new Array( len );
for ( i = 0; i < len; i++ ) {
arr[ i ] = arguments[ i ];
}
}
if ( len === 0 ) {
throw new Error( 'insufficient input arguments. Must provide either an array of code points or one or more code points as separate arguments.' );
}
str = '';
for ( i = 0; i < len; i++ ) {
pt = arr[ i ];
if ( !isNonNegativeInteger( pt ) ) {
throw new TypeError( 'invalid input argument. Must provide valid code points (nonnegative integers). Value: `'+pt+'`.' );
}
if ( pt > MAX_CODE_POINT ) {
throw new RangeError( 'invalid input argument. Must provide a valid code point (cannot exceed max). Value: `'+pt+'`.' );
}
if ( pt <= MAX_BMP_CODE_POINT ) {
str += fromCharCode( pt );
} else {
// Code point from a supplementary plane. Split into two 16-bit code units (surrogate pair).
pt -= Ox10000;
hi = (pt >> 10) + OxD800;
low = (pt & Ox3FF) + OxDC00;
str += fromCharCode( hi, low );
}
}
return str;
}
// EXPORTS //
module.exports = fromCodePoint;
|
JavaScript
| 0.001472 |
@@ -738,31 +738,26 @@
;%0Avar is
-ArrayLikeObject
+Collection
= requi
@@ -783,25 +783,18 @@
/is-
-array-like-object
+collection
' );
@@ -2474,23 +2474,18 @@
& is
-ArrayLikeObject
+Collection
( ar
|
17781458b3fcadd65830c03a1e1c12d47d63a92e
|
change server.info.port to static string
|
server.js
|
server.js
|
'use strict';
var Composer = require('./index');
var Hoek = require('hoek');
Composer(function(err, server) {
Hoek.assert(!err, err);
server.start(function() {
console.log('Server is listening on ' + server.info.port);
});
});
|
JavaScript
| 0.000001 |
@@ -212,28 +212,13 @@
on
-' + server.info.port
+8081'
);%0A
|
aa4ef48fe2ee4b049b1b92358188c3d07f6402db
|
Improve error handling
|
server.js
|
server.js
|
var express = require('express'),
usps = require('./lib/usps'),
config = require('./config')
/* Create App */
var app = express();
/* Config */
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
/* Routes */
app.get('/', function (req, res) {
res.render('index');
});
app.get('/rates', function(req, res, next) {
var results = [];
var shipment = {
orig:req.query.orig,
dest:req.query.dest,
type:req.query.type,
pounds:req.query.pounds,
ounces:req.query.ounces,
nonrectangular:req.query.nonrectangular,
length:req.query.length,
width:req.query.width,
height:req.query.height,
girth:req.query.girth,
value:req.query.value,
shipDate:req.query.shipDate
}
usps.queryUSPS(shipment, function(err, USPSResults) {
if (err) return next(err);
results.concat(USPSResults);
});
res.json(results);
});
/* Listen */
app.listen(config.port);
console.log("Server listening on port " + config.port);
|
JavaScript
| 0.000007 |
@@ -866,16 +866,60 @@
if (err)
+ %7B%0A console.log(err);%0A
return
@@ -925,24 +925,34 @@
next(err);%0A
+ %7D%0A
resu
|
19f1be7546f3a20624f1866c6cf42a9618be2ac9
|
Resolve merge conflict with Create3
|
frontend/src/main-components/CreateFolderContent.js
|
frontend/src/main-components/CreateFolderContent.js
|
import React, { Component } from "react";
import css from "./CreateFolderContent.css";
import supportedLang from "../sub-components/SupportedLang.json";
class CreateFolderContent extends Component {
constructor(props) {
super(props);
this.state = {
folderName: "None",
folderLang: "English",
};
this.handleFolderName = this.handleFolderName.bind(this);
this.handleFolderLang = this.handleFolderLang.bind(this);
}
handleFolderName(event) {
this.setState({ folderName: event.target.value });
}
handleFolderLang(event) {
this.setState({ folderLang: event.target.value });
}
/**
* This react component renders a form that makes a post
* request to UserFoldersServlet for folder creation.
*/
render() {
return (
<div id='container'>
<div id='innerContainer'>
<div id='folderPreview'>
<h2 id='previewFolderName'>{this.state.folderName}</h2>
<h4 id='previewFolderLang'>{this.state.folderLang}</h4>
</div>
<div id='formBox'>
<ul>
<form id='myForm' action='/userfolders' method='POST'>
<li>
<label>Folder Name: </label>
</li>
<li>
<input
id='folderName'
name='folderName'
type='text'
placeholder={this.state.folderName}
onBlur={this.handleFolderName}
required></input>
</li>
<li>
<label>Folder Language:</label>
</li>
<li>
<div id='scroll'>
<select
id='language'
name='language'
value={this.state.folderLang}
onChange={this.handleFolderLang}
required>
<option value='English'>English</option>
{
/*
* Instead of using the languageScroll sub-component, we parse the supported languages so
* the value/language-name can be displayed on the folder preview.
*/
supportedLang.languages.map((lang, i) => {
return (
<option key={i} value={lang.language}>
{lang.language}
</option>
);
})
}
</select>
</div>
</li>
<li>
<input id='submission' type='submit' value='Submit' />
</li>
</form>
</ul>
</div>
</div>
</div>
);
}
}
export default CreateFolderContent;
|
JavaScript
| 0 |
@@ -1964,329 +1964,94 @@
-%3Coption value='English'%3EEnglish%3C/option%3E%0A %7B%0A /*%0A * Instead of using the languageScroll sub-component, we parse the supported languages so%0A * the value/language-name can be displayed on the folder preview.%0A */
+%7B%0A // Parse json and display supported languages in scroll list
%0A
@@ -2114,17 +2114,16 @@
i) =%3E %7B%0A
-%0A
|
e5d67095ba70317538fea80d21a52d6ef4021402
|
add documentation
|
src/jsxc.lib.tab.js
|
src/jsxc.lib.tab.js
|
/**
* Provides communication between tabs.
*
* @namespace jsxc.tab
*/
jsxc.tab = {
CONST: {
MASTER: 'master',
SLAVE: 'slave'
},
exec: function(target, cmd, params) {
params = Array.prototype.slice.call(arguments, 2);
if (params.length === 1 && $.isArray(params[0])) {
params = params[0];
}
if (target === jsxc.tab.CONST[jsxc.master ? 'MASTER' : 'SLAVE']) {
jsxc.exec(cmd, params);
if (jsxc.master) {
return;
}
}
jsxc.storage.setUserItem('_cmd', {
target: target,
cmd: cmd,
params: params,
rnd: Math.random() // force storage event
});
},
/*jshint -W098 */
execMaster: function(cmd, params) {
var args = Array.prototype.slice.call(arguments);
args.unshift(jsxc.tab.CONST.MASTER);
jsxc.tab.exec.apply(this, args);
},
execSlave: function(cmd, params) {
var args = Array.prototype.slice.call(arguments);
args.unshift(jsxc.tab.CONST.SLAVE);
jsxc.tab.exec.apply(this, args);
}
/*jshint +W098 */
};
|
JavaScript
| 0 |
@@ -700,20 +700,142 @@
/*
-jshint -W098
+*%0A * Execute command in master tab.%0A *%0A * @param %7BString%7D cmd Command%0A * @param %7BString%5B%5D%7D params List of parameters%0A
*/%0A
@@ -854,35 +854,24 @@
r: function(
-cmd, params
) %7B%0A va
@@ -1007,19 +1007,167 @@
;%0A %7D,%0A
+%0A
+/**%0A * Execute command in all slave tabs.%0A *%0A * @param %7BString%7D cmd Command%0A * @param %7BString%5B%5D%7D params List of parameters%0A */%0A
execSlav
@@ -1178,27 +1178,16 @@
unction(
-cmd, params
) %7B%0A
@@ -1329,28 +1329,7 @@
%7D%0A
- /*jshint +W098 */%0A
%7D;%0A
|
5bc63e23b52864659221aa5d5a60000adc6c1c38
|
add description of timestampSeparator to example
|
example/index.js
|
example/index.js
|
/* global angular, console */
'use strict';
angular
.module('app', ['evaporate'])
.controller('AppCtrl', ['$scope', function ($scope) {
// this variable is used like a model for particular directive
// all parameters here are optional
$scope.evaData = {
// every file will get the following link on s3:
// http://<your_bucket>.s3.amazonaws.com/<this_value>/<upload_datetime>$<filename_with_extension>
// if you want to put the files into nested folder, just use dir: 'path/to/your/folder'
// if not specified, default value being used is: '' (matches bucket's root directory)
dir: 'tmp',
// headers which should (headersSigned) and should not (headersCommon) be signed by your private key
// for details, visit http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html
headersCommon: {
'Cache-Control': 'max-age=3600'
},
headersSigned: {
'x-amz-acl': 'public-read'
},
// custom callbacks for onProgress and onComplete events
onFileProgress: function (file) {
console.log(
'onProgress || name: %s, uploaded: %f%, remaining: %d seconds',
file.name,
file.progress,
file.timeLeft
);
},
onFileComplete: function (file) {
console.log('onComplete || name: %s', file.name);
},
onFileError: function (file, message) {
console.log('onError || message: %s', message);
}
};
}]);
|
JavaScript
| 0 |
@@ -636,16 +636,337 @@
'tmp',%0A%0A
+ // You can pick a different separator string that goes in between upload_datetime and filename_with_extension:%0A // http://%3Cyour_bucket%3E.s3.amazonaws.com/%3Cdir%3E/%3Cupload_datetime%3E%3Cthis_value%3E%3Cfilename_with_extension%3E%0A // if not specified, the default value being used is: '$'%0A timestampSeparator: '_',%0A%0A
//
|
9935a9be973e6e296baf582d3696db005f9fd294
|
Refactor whitespace
|
jquery.plugin.js
|
jquery.plugin.js
|
/*
Copyright (c) <Year> <First & Last Name>, <Your Web Site>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
;(function($){
$.fn.extend({
number: function(options) {
this.defaultOptions = {};
var settings = $.extend({}, this.defaultOptions, options);
var number = $(this).val() || $(this).text();
// Flip number
number = number.split("").reverse().join("");
// Replace last comma with dot
number = number.replace(/\,/, ".");
// Remove all other commas
number = number.replace(/\,/g, "");
// Flip number back
number = number.split("").reverse().join("");
return number;
}
});
})(jQuery);
|
JavaScript
| 0.000308 |
@@ -1116,18 +1116,16 @@
ion($)%7B%0A
-
$.fn.e
@@ -1132,20 +1132,16 @@
xtend(%7B%0A
-
numb
@@ -1164,22 +1164,16 @@
ions) %7B%0A
-
th
@@ -1197,22 +1197,16 @@
= %7B%7D;%0A%0A
-
va
@@ -1262,22 +1262,16 @@
tions);%0A
-
va
@@ -1316,37 +1316,25 @@
xt();%0A
- %0A
+%0A
// Fli
@@ -1342,22 +1342,16 @@
number%0A
-
nu
@@ -1390,30 +1390,24 @@
).join(%22%22);%0A
-
// Rep
@@ -1431,22 +1431,16 @@
ith dot%0A
-
nu
@@ -1469,30 +1469,24 @@
/%5C,/, %22.%22);%0A
-
// Rem
@@ -1506,22 +1506,16 @@
commas%0A
-
nu
@@ -1544,30 +1544,24 @@
/%5C,/g, %22%22);%0A
-
// Fli
@@ -1574,22 +1574,16 @@
er back%0A
-
nu
@@ -1632,29 +1632,17 @@
;%0A
- %0A
+%0A
re
@@ -1662,16 +1662,10 @@
- %7D%0A
+%7D%0A
%7D)
|
da76cca5b237b0083c619298bf74cae0992f7910
|
check to see callBack is function
|
jquery.rsDice.js
|
jquery.rsDice.js
|
(function($){
var MyDice = function(element, options) {
var elem = $(element);
var obj = this;
// Merge options with defaults
var settings = $.extend({
number : 6, // Number of sides for the dice
speed : 100, // Speed of dice roll
duration : 2000, // Duration of dice roll
callBack : function() {} // Callback function for when roll has finished
}, options || {});
// Public method
this.rollDice = function() {
var myNumbers = [];
// Lets create an array of numbers from our number setting
for (var i = 1; i <= settings.number; i++) {
myNumbers.push(i);
};
if ( myNumbers.length > 0 ) {
// We have some numbers to roll on our dice
} else {
if (typeof console == "object" ) {
console.log('We have no numbers to roll');
}
return false;
}
// If we have got this far, we need to roll the dice
var myInterval = setInterval(function () {
var chosen = myNumbers[Math.floor(Math.random()*myNumbers.length)];
elem.text(chosen);
}, settings.speed);
setTimeout(function(){
var finalChoice = myNumbers[Math.floor(Math.random()*myNumbers.length)];
elem.text(finalChoice);
window.clearInterval(myInterval);
settings.callBack.call(this);
}, settings.duration);
};
};
$.fn.rsDice = function(options) {
return this.each(function() {
var myDice = new MyDice(this, options);
myDice.rollDice();
});
}
}(jQuery));
|
JavaScript
| 0.000004 |
@@ -1212,16 +1212,65 @@
erval);%0A
+%0A%09%09%09%09if ( $.isFunction( settings.callBack ) ) %7B%0A%09
%09%09%09%09sett
@@ -1292,14 +1292,24 @@
all(
-this);
+obj);%0A%09%09%09%09%7D%0A%09%09%09%09
%0A%09%09%09
|
9976a0c7b47dade8f645b2f9877d1187927abb8c
|
Convert `headers` to regular property
|
app/adapters/application.js
|
app/adapters/application.js
|
import RESTAdapter from '@ember-data/adapter/rest';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
export default class ApplicationAdapter extends RESTAdapter {
@service fastboot;
namespace = 'api/v1';
@computed('fastboot.{isFastBoot,request.headers}')
get headers() {
if (this.fastboot.isFastBoot) {
return { 'User-Agent': this.fastboot.request.headers.get('User-Agent') };
}
return {};
}
handleResponse(status, headers, payload, requestData) {
if (typeof payload === 'string') {
try {
payload = JSON.parse(payload);
} catch (ignored) {
// if the payload can't be parsed as JSON then let's continue
// with the string payload
}
}
return super.handleResponse(status, headers, payload, requestData);
}
}
|
JavaScript
| 0.001646 |
@@ -49,50 +49,8 @@
t';%0A
-import %7B computed %7D from '@ember/object';%0A
impo
@@ -211,61 +211,8 @@
';%0A%0A
- @computed('fastboot.%7BisFastBoot,request.headers%7D')%0A
ge
|
fa97c8d8d25c0ee4034c1006ea63a5061b3a5d5e
|
Allow gui to be hosted with command line path
|
server.js
|
server.js
|
var fs = require('fs');
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var morgan = require('morgan');
var bodyParser = require('body-parser');
var multer = require('multer');
var uploadComplete = false;
var db = mongoose.connect('mongodb://127.0.0.1:27017/photoTest2');
//attach lister to connected event
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
mongoose.connection.once('connected', function() {
console.log("Connected to database")
});
app.use(express['static'](__dirname + '/mockpage'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(multer({dest: './testUploads',
rename: function(fieldname, filename) {
return filename;
},
onFileUploadStart: function(file) {
console.log(file.originalname + ' upload is starting...');
},
onFileUploadComplete: function(file) {
console.log(file.fieldname + ' uploaded to ' + file.path);
uploadComplete = true;
}
}));
// Creates photo DB object schema
var photoSchema = new Schema({
user_id: Number,
loc: String,
date: Date,
title: String,
caption: String
});
var Photo = mongoose.model('Photo', photoSchema);
// Get single photo by id
app.get('/api/users/:user_id/photos/:photo_id', function(req, res) {
if (req.params.user_id == 1 && req.params.photo_id == 1) {
res.setHeader('Content-type', 'image/jpg');
var file = './testUploads/IMAG01571419370672847.jpg';
fs.createReadStream(file, {encoding: "base64"}).pipe(res);
/*res.status(200).json({
'message': 'You have hit the single photo GET API!'
});*/
} else {
res.sendStatus(400);
}
});
// Get multiple photos for single user
app.get('/api/users/:user_id/photos', function(req, res) {
if (req.params.user_id != 1) {
res.status(400).json({
'message': 'Please provide a userId of 1!'
});
return;
}
Photo.find({'user_id': req.params.user_id}).sort({"updatedAt": 1}).exec(function(err, foundPhotos) {
var photoMap = {};
foundPhotos.forEach(function(photo) {
photoMap[photo._id] = photo;
});
res.status(200).json({
'message': 'You have hit the single-user multiple-photo GET API!'
});
});
});
// Get multiple photos for multiple users
app.get('/api/photos', function(req, res) {
res.status(200).json({
'message': 'You have hit the multiple-user multiple-photo GET API'
});
});
// Post a new photo on behalf of a particular user
app.post('/api/users/:user_id/photos', function(req, res) {
if (req.params.user_id != 1) {
res.status(400).json({
'message': 'Please provide a userId of 1!'
});
return;
}
if (uploadComplete == true) {
uploadComplete = false;
var oldName = req.files.userPhoto.originalname;
var oldLocation = __dirname + '/testUploads/' + oldName;
var newName = oldName.substring(0, oldName.indexOf('.' + req.files.userPhoto.extension)) + Date.now() + '.' + req.files.userPhoto.extension;
var newLocation = __dirname + '/testUploads/' + req.params.user_id + '/' + newName;
fs.rename(oldLocation, newLocation, function(error) {
if(error) {
res.send({
error: 'There was an error saving your file! Please try again!'
});
//TODO: Add delete of original file in ./testUploads
return;
}
var photo = new Photo({
user_id: req.params.user_id,
loc: newLocation,
date: new Date(),
title: 'Photo 1',
caption: 'This is a test photo'
})
photo.save();
res.status(200).json({
'message': 'You have saved a new photo DB object using the POST API!'
});
}.bind(this)
);
}
});
// Update information of a particular photo
app.put('/api/users/:user_id/photos/:photo_id', function(req, res) {
res.status(200).json({
'message': 'You have hit the one and only PUT API!'
});
});
// Delete a particular photo associated with a user
app['delete']('/api/users/:user_id/photos/:photo_id', function(req, res) {
res.status(200).json({
'message': 'You have hit the one and only DELETE API!'
});
});
// Get home page
app.get('*', function(req, res) {
res.send(process.argv[2]);
});
app.listen(3000);
console.log("App listening on port 3000");
|
JavaScript
| 0 |
@@ -4129,16 +4129,108 @@
me page%0A
+app.get('/app/', function(req, res) %7B%0A%09res.sendFile(process.argv%5B2%5D+%22app/index.html%22);%0A%7D);%0A%0A
app.get(
@@ -4264,16 +4264,20 @@
res.send
+File
(process
@@ -4284,16 +4284,30 @@
.argv%5B2%5D
++req.params%5B0%5D
);%0A%7D);%0A%0A
|
f4464c9f927b96efe77fbde20be99108236b9950
|
Remove return to add break
|
jquery.vimize.js
|
jquery.vimize.js
|
(function($){
$.fn.vimize = function(options){
var defaults = {
escKey: 'true',
searchBoxSelector: '',
homePagePath: '/',
scrollVal: $(window).height() *0.3,
selectors: {0: 'a'},
defaultSelectors: 0
};
var setting = $.extend(defaults,options);
var keyPressBuffer = '';
var intActiveCol = setting.defaultSelectors;
var arrActiveElement = {};
var $objElements = {};
var maxCols = 0;
for (var i in setting.selectors){
arrActiveElement[i] = -1;
$objElements[i] = $(setting.selectors[i]);
++maxCols;
}
console.log(setting);
// functions
var fnPageTop = function(){
$((navigator.userAgent.indexOf("Opera") != -1) ? document.compatMode == 'BackCompat' ? 'body' : 'html' :'html,body').animate({scrollTop:0}, 'slow');
return false;
};
var fnPageBottom = function(){
$((navigator.userAgent.indexOf("Opera") != -1) ? document.compatMode == 'BackCompat' ? 'body' : 'html' :'html,body').animate({scrollTop: $(document).height()-$(window).height()}, 'slow');
return false;
};
var fnScrollDown = function(){
$((navigator.userAgent.indexOf("Opera") != -1) ? document.compatMode == 'BackCompat' ? 'body' : 'html' :'html,body').animate({scrollTop: '+='+setting.scrollVal}, 'fast');
return false;
};
var fnScrollUp = function(){
$((navigator.userAgent.indexOf("Opera") != -1) ? document.compatMode == 'BackCompat' ? 'body' : 'html' :'html,body').animate({scrollTop: '-='+setting.scrollVal}, 'fast');
return false;
};
var fnActiveElement = function(n){ $($objElements[intActiveCol][n]).focus(); };
// hjkl
$(window).keydown(function(e){
if (e.keyCode == 27) { $(':focus').blur(); keyPressBuffer =''; } // esc key
var $focused = $("input:focus");
// ctrl key
if (e.ctrlKey){
switch (e.keyCode){
case 68: // ctrl+d
fnScrollDown();
break;
case 85: // ctrl+u
fnScrollUp();
break;
case 87: // ctrl+w
if ($focused.length) { $focused.val(''); }
break;
default:
break;
}
}
if ($focused.length) return;
// shift key
if (e.shiftKey){
switch (e.keyCode){
case 191: // ? (shift+/)
$(setting.searchBoxSelector).focus();
return false;
// break;
case 71: // G
fnPageBottom();
break;
case 72: // H
fnActiveElement(arrActiveElement[intActiveCol]=0);
break;
case 76: // L
fnActiveElement(arrActiveElement[intActiveCol]=($objElements[intActiveCol].length -1));
break;
case 52: // $ (shift+4)
fnActiveElement(arrActiveElement[intActiveCol]=($objElements[intActiveCol].length -1));
break;
default:
break;
}
} else if(e.keyCode == 71){ // g commands
if(keyPressBuffer != 71){ keyPressBuffer = 71; return; }
switch(e.keyCode){
case 71: // gg
fnPageTop();
break;
}
keyPressBuffer ='';
return false;
} else {
switch (e.keyCode){
case 189: // -
window.location.href = setting.homePagePath;
break;
case 68: // d
scrollBy(0,setting.scrollVal);
break;
case 85: // u
scrollBy(0,'-'+setting.scrollVal);
break;
case 191: // '/'
$(setting.searchBoxSelector).focus();
return false;
// break;
case 74: // j
if (($objElements[intActiveCol].length -1) > arrActiveElement[intActiveCol]){
fnActiveElement(++arrActiveElement[intActiveCol]);
}
break;
case 75: // k
if (arrActiveElement[intActiveCol] > 0){
fnActiveElement(--arrActiveElement[intActiveCol]);
}
break;
case 72: // h
if (intActiveCol > 0){--intActiveCol;}
if (arrActiveElement[intActiveCol] < 0){ arrActiveElement[intActiveCol] = 0; }
fnActiveElement(arrActiveElement[intActiveCol]);
break;
case 76: // l
if (intActiveCol < maxCols -1){++intActiveCol;}
if (arrActiveElement[intActiveCol] < 0){ arrActiveElement[intActiveCol] = 0; }
fnActiveElement(arrActiveElement[intActiveCol]);
break;
case 66: // b pagerに対応する?
history.back();
break;
case 78: // n << f にするべき?
history.forward();
break;
case 48: // 0
case 96: // 0(テンキー)
case 222: // ^
fnActiveElement(arrActiveElement[intActiveCol]=0);
break;
default:
break;
}
keyPressBuffer = e.keyCode;
}
});
}; //
})(jQuery);
|
JavaScript
| 0.000001 |
@@ -2201,24 +2201,52 @@
%7D%0A
+ keyPressBuffer ='';%0A
%7D%0A
if
@@ -2233,24 +2233,24 @@
'';%0A %7D%0A
-
if ($f
@@ -2431,32 +2431,35 @@
s();%0A
+ //
return false;%0A
@@ -2460,35 +2460,32 @@
lse;%0A
- //
break;%0A
@@ -2993,24 +2993,46 @@
;%0A %7D%0A
+ return false;%0A
%7D else
@@ -3704,32 +3704,35 @@
s();%0A
+ //
return false;%0A
@@ -3741,19 +3741,16 @@
- //
break;%0A
@@ -5007,32 +5007,32 @@
reak;%0A %7D%0A
-
keyPress
@@ -5051,16 +5051,38 @@
eyCode;%0A
+ return false;%0A
%7D%0A
|
6b2ad7489be92ceaf18f0487d4932328448b4237
|
update filesize limit
|
server.js
|
server.js
|
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
var port = process.env.PORT || 8080; // set the port
var database = require('./config/database'); // load the database config
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var multer = require('multer');
// configuration ===============================================================
mongoose.connect(database.url); // connect to mongoDB database on modulus.io
app.all('/', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-Within, Content-Type, Accept");
});
app.use(bodyParser({ limit: '5GB' }));
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req,file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({ storage: storage });
// models =====================================================================
var user = require('./app/models/user');
var file = require('./app/models/file');
// routes ======================================================================
var userRoutes = require('./app/routes/user');
var fileRoutes = require('./app/routes/file');
// register routes ============================================================
app.post('/user', userRoutes.createUser);
app.get('/user/:username', userRoutes.getUser);
app.put('/user/edit/:id', userRoutes.updateUser);
app.delete('/user/delete/:id', userRoutes.deleteUser);
app.post('/file/upload', upload.single('file'), fileRoutes.postFile);
app.get('/file/get/:uid/:filename', fileRoutes.getFile);
app.get('/file/download/:uid/:fileid', fileRoutes.downloadFile);
app.delete('/file/delete/:uid/:fileid', fileRoutes.deleteFile);
// listen (start app with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);
|
JavaScript
| 0.000001 |
@@ -888,9 +888,9 @@
: '5
-G
+M
B' %7D
|
e379897b341c10662f391bc0fea7ad440f291fc2
|
Fix margins
|
js/ChooseName.js
|
js/ChooseName.js
|
import { Input, Panel, PanelHeader, WideButton } from './Widgets';
export default class ChooseName extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.name = window.localStorage.name || undefined;
}
onClick(e) {
window.localStorage.name = this.name;
ws.send({cmd:'set_name', name:this.name});
this.props.back();
}
render() { return (
<Panel>
<PanelHeader color="black" bg="blue">Name Preferences</PanelHeader>
<Input label="" placeholder="Name" defaultValue={this.name}
onChange={(e) => this.name = e.target.value}/>
<WideButton color="black" bg="green" onClick={this.onClick}>
Save Preferences
</WideButton>
<WideButton color="black" bg="red" onClick={this.props.back}>
Cancel
</WideButton>
</Panel>
)}
}
|
JavaScript
| 0.000006 |
@@ -1,16 +1,21 @@
import %7B
+ Box,
Input,
@@ -34,26 +34,28 @@
Header,
-Wide
Button
+Circle
%7D from
@@ -536,17 +536,40 @@
Header%3E%0A
-%09
+ %3CBox p=%7B3%7D%3E%0A
%3CInput l
@@ -628,16 +628,20 @@
+
onChange
@@ -679,28 +679,37 @@
alue%7D/%3E%0A
-%09%3CWideButton
+ %3CButtonCircle
color=%22
@@ -750,18 +750,28 @@
Click%7D%3E%0A
-%09%09
+
Save Pre
@@ -783,35 +783,53 @@
ces%0A
-%09%3C/WideButton%3E%0A%09%3CWideButton
+ %3C/ButtonCircle%3E%0A %3CButtonCircle
col
@@ -879,30 +879,60 @@
k%7D%3E%0A
-%09%09Cancel%0A%09%3C/WideButton
+ Cancel%0A %3C/ButtonCircle%3E%0A %3C/Box
%3E%0A%3C/
|
05e8af6ed0eda7ffb981e2e8a2a638ab4e200cf5
|
Fix eaarly-return bug.
|
app/assets/party/profile.js
|
app/assets/party/profile.js
|
'use strict';
app.controller('party/profile', [
'$scope', 'displayService', 'party', 'pageService','constantService',
function ($scope, display, party, page, constants) {
var getUsers = function(volumes){
var users = {};
users.sponsors = [];
users.labGroupMembers = [];
users.nonGroupAffiliates = [];
users.otherCollaborators = [];
_(volumes).pluck('access').flatten().each(function(v){
if(v.children > 0 ){
users.sponsors.push(v);
} else if(v.parents && v.parents.length > 0 && v.party.members && v.party.members.length > 0) {
users.labGroupMembers.push(v);
} else if(v.parents && v.parents.length > 0){
users.nonGroupAffiliates.push(v);
} else {
users.otherCollaborators.push(v);
}
}).value();
console.log(users);
return users;
};
// This is a quick helper function to make sure that the isSelected
// class is set to empty and to avoid repeating code.
var unSetSelected = function(v){
v.isSelected = '';
return v;
};
var unselectAll = function(){
$scope.volumes.individual = _.map($scope.volumes.individual, unSetSelected);
$scope.volumes.collaborator = _.map($scope.volumes.collaborator, unSetSelected);
$scope.volumes.inherited = _.map($scope.volumes.inherited, unSetSelected);
$scope.users.sponsors = _.map($scope.users.sponsors, unSetSelected);
$scope.users.nonGroupAffiliates = _.map($scope.users.nonGroupAffiliates, unSetSelected);
$scope.users.labGroupMembers = _.map($scope.users.labGroupMembers, unSetSelected);
$scope.users.otherCollaborators = _.map($scope.users.otherCollaborators, unSetSelected);
};
$scope.clickVolume = function(volume) {
unselectAll();
for(var i = 0; i < volume.access.length; i += 1 ){
for (var j = 0; j < $scope.users.sponsors.length; j += 1){
if($scope.users.sponsors[j].id === volume.access[i].party.id){
$scope.users.sponsors[j].isSelected = 'userSelected';
}
}
for (var j = 0; j < $scope.users.labGroupMembers.length; j += 1){
if($scope.users.labGroupMembers[j].id === volume.access[i].party.id){
$scope.users.labGroupMembers[j].isSelected = 'userSelected';
}
}
for (var j = 0; j < $scope.users.nonGroupAffiliates.length; j += 1){
if($scope.users.nonGroupAffiliates[j].id === volume.access[i].party.id){
$scope.users.nonGroupAffiliates[j].isSelected = 'userSelected';
}
}
for (var j = 0; j < $scope.users.otherCollaborators.length; j += 1){
if($scope.users.otherCollaborators[j].id === volume.access[i].party.id){
$scope.users.otherCollaborators[j].isSelected = 'userSelected';
}
}
}
};
// This should take in a user, then select volumes on each thing.
$scope.clickUser = function(user){
unselectAll();
var iterateVolume = function(_item, i, volumeArray){
for(var j = 0; j < volumeArray[i].access.length; j += 1){
if(volumeArray[i].access[j] == user){
volumeArray[i].access[j].isSelected = 'volumeSelected';
return false;
}
}
};
_.each($scope.volumes.individual, iterateVolume);
_.each($scope.volumes.collaborator, iterateVolume);
_.each($scope.volumes.inherited, iterateVolume);
};
var getParents = function(parents) {
var tempParents = [];
_.each(parents, function(p){
if(p.member){
var v = [];
var tempThing = {
p: p,
v: v
};
tempParents.push(tempThing);
}
});
return tempParents;
};
var getVolumes = function(volumes) {
var tempVolumes = {};
tempVolumes.individual = [];
tempVolumes.collaborator = [];
tempVolumes.inherited = getParents(party.parents);
_.each(volumes, function(v){
if(v.isIndividual){
tempVolumes.individual.push(v);
} else if(tempVolumes.isCollaborator){
tempVolumes.collaborator.push(v);
} else{
for (var i=0;i<v.access.length;i++){
for (var j=0;j<tempVolumes.inherited.length;j++){
if (v.access[i].children && v.access[i].party.id === tempVolumes.inherited[j].p.party.id){
tempVolumes.inherited[j].v.push(v);
break;
}
}
}
}
});
return tempVolumes;
};
$scope.party = party;
$scope.volumes = getVolumes(party.volumes);
$scope.users = getUsers(party.volumes);
$scope.page = page;
$scope.profile = page.$location.path() === '/profile';
display.title = party.name;
console.log($scope.volumes.inherited);
}
]);
|
JavaScript
| 0 |
@@ -3277,35 +3277,8 @@
d';%0A
- return false; %0A
|
f38a1fea6cac519447845ab45c0fc6ab2794e20d
|
Add test for the hull.started event
|
spec/lib/hull_spec.js
|
spec/lib/hull_spec.js
|
/*global sinon:true, define:true, describe:true, it:true, after:true, beforeEach:true */
define(['../support/mocks/app'], function (appMock) {
"use strict";
describe('hull main module', function () {
// Mocking dependencies of lib/hull
beforeEach(appMock.createApp);
after(function () {
appMock.resetApp();
require.undef('lib/hull');
require.undef('aura/aura');
require.undef('lib/hullbase');
});
describe("Booting the application", function () {
it("should return a function", function () {
appMock.hullInit.should.be.a('Function');
});
});
describe("Evaluating the module", function () {
beforeEach(appMock.resetApp);
it("should return an object with 'app' and 'config key'", function () {
var conf = {};
appMock.hullInit(conf).should.contain.keys('config');
appMock.hullInit(conf).should.contain.keys('app');
});
it("should have an Aura application as the value of the 'app' config", function () {
var conf = {};
appMock.hullInit(conf).app.should.eql(appMock.app);
});
it("should return the config passed to the function into the 'config' property", function () {
var conf = {
foo: "FOO",
bar: "BAR",
baz: "BAZ"
};
appMock.hullInit(conf).config.should.contain.keys(Object.keys(conf));
});
it("should add a 'namespace property in the onfig and set it to 'Hull'", function () {
var conf = {};
appMock.hullInit(conf).config.should.contain.keys('namespace');
appMock.hullInit(conf).config.namespace.should.eql('hull');
});
});
describe("should give feedback", function () {
beforeEach(appMock.resetApp);
it("should throw an exception if the init fails and no errback is provided", function (done) {
appMock.initDeferred.always(function () { done(); });
try {
appMock.hullInit({});
} catch (e) {
done();
}
appMock.initDeferred.reject();
});
it("should execute the errback in case of error", function () {
appMock.app.start.returns(appMock.initDeferred);
var errb = sinon.spy();
appMock.hullInit({}, null, errb);
appMock.initDeferred.reject();
errb.should.have.been.called;
});
it("should execute the callback in case of success", function () {
appMock.app.start.returns(appMock.initDeferred);
var cb = sinon.spy();
appMock.hullInit({}, cb);
appMock.initDeferred.resolve();
cb.should.have.been.called;
cb.should.have.been.calledWith(window.Hull);
});
});
});
});
|
JavaScript
| 0.000006 |
@@ -2688,32 +2688,380 @@
Hull);%0A %7D);
+%0A%0A it(%22should trigger an event when the app is started%22, function () %7B%0A appMock.app.start.returns(appMock.initDeferred);%0A appMock.sandbox.emit = sinon.spy();%0A appMock.hullInit(%7B%7D);%0A appMock.initDeferred.resolve();%0A cb.should.have.been.called;%0A cb.should.have.been.calledWith('hull.started');%0A %7D);
%0A %7D);%0A%0A %7D);%0A
|
d8753a70ed3dad4fa3024135bcaeb88269e4da69
|
remove empty line.
|
examples/Root.js
|
examples/Root.js
|
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import Board from '../lib/Board'
import TextWidget from '../lib/widgets/TextWidget'
import ClockWidget from '../lib/widgets/ClockWidget'
import '../stylus/style.styl'
import '../stylus/widget.styl'
document.addEventListener('DOMContentLoaded', (event) => {
ReactDOM.render(
(
<Board layoutType={'static'} cols={12} rowHeight={210}>
<TextWidget key="1" _grid={{x: 0, y: 0, w: 6, h: 2, static: true}} className='widget text-widget'
title={'Text Widget'} body={'I am a TextWidget !'} moreinfo={'more info'}>
</TextWidget>
<ClockWidget key="2" _grid={{x: 6, y: 0, w: 3, h: 2, static: true}}>1</ClockWidget>
<TextWidget key="3" _grid={{x: 9, y: 0, w: 3, h: 4, static: true}} title={'6'} body={''}></TextWidget>
<TextWidget key="4" _grid={{x: 0, y: 2, w: 3, h: 2, static: true}} title={'4'} body={''}></TextWidget>
<TextWidget key="5" _grid={{x: 3, y: 2, w: 6, h: 2, static: true}} title={'5'} body={''}></TextWidget>
</Board>
),
document.getElementById('root')
)
})
|
JavaScript
| 0.000501 |
@@ -831,17 +831,16 @@
Widget%3E%0A
-%0A
|
46924430441a011b105a6874f72061ddd2c9fe02
|
Fix name of readFile test
|
spec/readFile.spec.js
|
spec/readFile.spec.js
|
var path = require('path'),
fs = require('fs'),
crypto = require('crypto');
describe("readFile functionality", function() {
var _this = this;
require('./harness.js')(_this);
it("creates a directory", function(done) {
var fname = "testDir";
var resolved = path.resolve(_this.tempdir, fname);
crypto.pseudoRandomBytes(128 * 1024, function(err, data) {
if (err) throw err;
fs.writeFile(resolved, data, function(err) {
if (err) throw err;
_this.wd.readFile(fname, function(err, rdata) {
expect(err).toBe(null);
expect(rdata.toString()).toBe(data.toString());
done();
});
});
});
});
});
|
JavaScript
| 0.000024 |
@@ -196,27 +196,20 @@
it(%22
-c
rea
-te
+d
s a
-directory
+file
%22, f
|
989da02309d6a40155f2569609d01c910c11e4b5
|
document "kebab" menu icon
|
js/PhetButton.js
|
js/PhetButton.js
|
// Copyright 2013-2018, University of Colorado Boulder
/**
* The button that pops up the PhET menu, which appears in the bottom right of the home screen and on the right side
* of the navbar.
*
* @author Sam Reid (PhET Interactive Simulations)
*/
define( function( require ) {
'use strict';
// modules
var Image = require( 'SCENERY/nodes/Image' );
var inherit = require( 'PHET_CORE/inherit' );
var joist = require( 'JOIST/joist' );
var JoistA11yStrings = require( 'JOIST/JoistA11yStrings' );
var JoistButton = require( 'JOIST/JoistButton' );
var Node = require( 'SCENERY/nodes/Node' );
var Path = require( 'SCENERY/nodes/Path' );
var PhetButtonIO = require( 'JOIST/PhetButtonIO' );
var PhetMenu = require( 'JOIST/PhetMenu' );
var Property = require( 'AXON/Property' );
var Shape = require( 'KITE/Shape' );
var UpdateCheck = require( 'JOIST/UpdateCheck' );
// a11y strings
var phetString = JoistA11yStrings.phet.value;
// images
// The logo images are loaded from the brand which is selected via query parameter (during requirejs mode)
// or a grunt option (during the build), please see initialize-globals.js window.phet.chipper.brand for more
// details
var brightLogoMipmap = require( 'mipmap!BRAND/logo.png' ); // on a black navbar
var darkLogoMipmap = require( 'mipmap!BRAND/logo-on-white.png' ); // on a white navbar
// Accommodate logos of any height by scaling them down proportionately.
// The primary logo is 108px high and we have been scaling it at 0.28 to make it look good even on higher resolution
// displays. The following math scales up the logo to 108px high so the rest of the layout code will work smoothly
// Scale to the same height as the PhET logo, so that layout code works correctly.
// height of the PhET logo, brand/phet/images/logo.png or brand/adapted-from-phet/images/logo.png
var PHET_LOGO_HEIGHT = 108;
var PHET_LOGO_SCALE = 0.28; // scale applied to the PhET logo
assert && assert( Array.isArray( brightLogoMipmap ), 'logo must be a mipmap' );
var LOGO_SCALE = PHET_LOGO_SCALE / brightLogoMipmap[ 0 ].height * PHET_LOGO_HEIGHT;
/**
* @param {Sim} sim
* @param {Property.<Color|string>} backgroundFillProperty
* @param {Tandem} tandem
* @constructor
*/
function PhetButton( sim, backgroundFillProperty, tandem ) {
var self = this;
var phetMenu = new PhetMenu( sim, tandem.createTandem( 'phetMenu' ), {
showSaveAndLoad: sim.options.showSaveAndLoad,
closeCallback: function() {
phetMenu.hide();
}
} );
/**
* Sim.js handles scaling the popup menu. This code sets the position of the popup menu.
* @param {number} width
* @param {number} height
*/
function onResize( width, height ) {
var bounds = sim.boundsProperty.value;
var screenBounds = sim.screenBoundsProperty.value;
var scale = sim.scaleProperty.value;
phetMenu.right = bounds.right / scale - 2 / scale;
var navBarHeight = bounds.height - screenBounds.height;
phetMenu.bottom = screenBounds.bottom / scale + navBarHeight / 2 / scale;
}
// sim.bounds are null on init, but we will get the callback when it is sized for the first time
sim.resizedEmitter.addListener( onResize );
var options = {
highlightExtensionWidth: 6,
highlightExtensionHeight: 5,
highlightCenterOffsetY: 4,
listener: function() {
phetMenu.show();
},
phetioType: PhetButtonIO,
phetioDocumentation: 'The button that appears at the right side of the navigation bar, which shows a menu when pressed',
// a11y
tagName: 'button',
innerContent: phetString
};
// The PhET Label, which is the PhET logo
var logoImage = new Image( brightLogoMipmap, {
scale: LOGO_SCALE,
pickable: false
} );
var optionsShape = new Shape();
var optionsCircleRadius = 2.5;
for ( var i = 0; i < 3; i++ ) {
var circleOffset = i * 3.5 * optionsCircleRadius;
optionsShape.arc( 0, circleOffset, optionsCircleRadius, 0, 2 * Math.PI, false );
}
var optionsButton = new Path( optionsShape, {
left: logoImage.width + 8,
bottom: logoImage.bottom,
pickable: false
} );
// The icon combines the PhET label and the thre horizontal bars in the right relative positions
var icon = new Node( { children: [ logoImage, optionsButton ] } );
JoistButton.call( this, icon, backgroundFillProperty, tandem, options );
// No need to unlink, as the PhetButton exists for the lifetime of the sim
Property.multilink( [ backgroundFillProperty, sim.showHomeScreenProperty, UpdateCheck.stateProperty ],
function( backgroundFill, showHomeScreen, updateState ) {
var backgroundIsWhite = backgroundFill !== 'black' && !showHomeScreen;
var outOfDate = updateState === 'out-of-date';
optionsButton.fill = backgroundIsWhite ? ( outOfDate ? '#0a0' : '#222' ) : ( outOfDate ? '#3F3' : 'white' );
logoImage.image = backgroundIsWhite ? darkLogoMipmap : brightLogoMipmap;
} );
// added for phet-io, when toggling pickability, hide the option dots to prevent the queueing
// no need to be removed because the PhetButton exists for the lifetime of the sim.
this.on( 'pickability', function() {
optionsButton.visible = self.pickable !== false; // null should still have visible kabab dots
} );
// a11y - add a listener that opens the menu on 'click' and 'reset', and closes it on escape and if the
// button receives focus again
this.addInputListener( {
click: function() {
// open and set focus on the first item
phetMenu.show();
phetMenu.items[ 0 ].focus();
}
} );
// a11y - add an attribute that lets the user know the button opens a menu
this.setAccessibleAttribute( 'aria-haspopup', true );
}
joist.register( 'PhetButton', PhetButton );
return inherit( JoistButton, PhetButton );
} );
|
JavaScript
| 0 |
@@ -3844,24 +3844,214 @@
e%0A %7D );%0A%0A
+ // The %22kebab%22 menu icon, 3 dots stacked vertically%0A // See https://ux.stackexchange.com/questions/115468/what-the-difference-between-the-2-menu-icons-3-dots-kebab-and-3-lines-hambur%0A
var opti
|
42797650946dbb63744fba10364626ee84846aa4
|
Improve echo example
|
examples/echo.js
|
examples/echo.js
|
#!/usr/bin/env node
// This bot echoes back whatever you send to it.
// Usage: ./echo.js <auth token>
var botgram = require("botgram");
var bot = botgram(process.argv[2]);
bot.message(function (msg, reply, next) {
reply.text("You said:");
reply.message(msg);
});
|
JavaScript
| 0.000013 |
@@ -236,16 +236,26 @@
aid:%22);%0A
+ try %7B%0A
reply.
@@ -268,12 +268,75 @@
e(msg);%0A
+ %7D catch (err) %7B%0A reply.text(%22Couldn't resend that.%22);%0A %7D%0A
%7D);%0A
|
9004ccf06e22cb81259d4209282c45e49eeda930
|
Update timeout for 1.6.x branch
|
webdrivertest/test/datepicker/datepicker.visual.js
|
webdrivertest/test/datepicker/datepicker.visual.js
|
/*global describe, it, browser, require */
describe('datepicker', function () {
'use strict';
it('should match the baseline screenshot when the datepickers are closed', function (done) {
var result,
common = require('../common');
result = browser.url('/datepicker/fixtures/test.full.html');
common.compareScreenshot({
browserResult: result,
prefix: common.getPrefix(browser),
screenshotName: 'datepicker_closed',
selector: '#screenshot-datepickers',
done: done
});
});
it('should match the baseline screenshot when the datepicker is open', function (done) {
var result,
common = require('../common');
result = browser.url('/datepicker/fixtures/test.full.html')
.click('#screenshot-datepicker .bb-date-field-calendar-button')
.waitForVisible('ul.uib-datepicker-popup');
common.compareScreenshot({
browserResult: result,
prefix: common.getPrefix(browser),
screenshotName: 'datepicker_open',
selector: '#screenshot-datepicker',
done: done
});
});
it('should match the baseline screenshot when the datepicker is appended to body and open', function (done) {
var result,
common = require('../common');
result = browser.url('/datepicker/fixtures/test.full.html')
.click('#screenshot-datepicker-append-to-body .bb-date-field-calendar-button')
.waitForVisible('ul.uib-datepicker-popup');
common.compareScreenshot({
browserResult: result,
prefix: common.getPrefix(browser),
screenshotName: 'datepicker_open_append',
selector: '#screenshot-datepicker-append-to-body',
done: done
});
});
});
|
JavaScript
| 0 |
@@ -930,32 +930,38 @@
atepicker-popup'
+, 3000
);%0A%0A comm
@@ -1595,16 +1595,22 @@
r-popup'
+, 3000
);%0A%0A
|
b1fe9b79f0c0a212c8773b0d472bf8dcdb95d0ab
|
consolidate tests to check creation success and snapshot storage path default
|
test/MssqlSnapshot.create.spec.js
|
test/MssqlSnapshot.create.spec.js
|
import fs from 'fs';
import MssqlSnapshot from '../src/MssqlSnapshot';
import databaseConfig from '../src/databaseConfig';
import {deleteSnapshot, getPhysicalPath} from './testUtilities';
describe('when creating a named sql snapshot', function() {
let target = null;
beforeEach(() => target = new MssqlSnapshot({}));
it('it throws when no snapshot name is supplied', () => {
const fn = () => target.create();
fn.should.throw('No snapshot name supplied.');
});
});
describe('when creating a named sql snapshot with valid configuration', function() {
let target = null;
const dbConfig = databaseConfig();
const snapshotName = 'mssql-snapshot-testdb-when-creating';
beforeEach(() => target = new MssqlSnapshot(dbConfig));
afterEach(() => deleteSnapshot(snapshotName));
it('it returns a success message once created', function() {
return target.create(snapshotName).then(result => {
result.length.should.eql(1);
result.should.eql([{Success: `${snapshotName} was successfully created.`}]);
});
});
it('it saves the snapshot file to the default location when none is specified', function() {
return target.create(snapshotName).then(() => {
getPhysicalPath(dbConfig.database, snapshotName).then(result => fs.existsSync(result).should.eql(true));
});
});
});
|
JavaScript
| 0 |
@@ -683,32 +683,36 @@
eforeEach(() =%3E
+%7B%0A%09%09
target = new Mss
@@ -731,16 +731,20 @@
bConfig)
+;%0A%09%7D
);%0A%0A%09aft
@@ -834,16 +834,53 @@
created
+ and the snapshot file exists on disk
', funct
@@ -1057,164 +1057,8 @@
%5D);%0A
-%09%09%7D);%0A%09%7D);%0A%0A%09it('it saves the snapshot file to the default location when none is specified', function() %7B%0A%09%09return target.create(snapshotName).then(() =%3E %7B%0A
%09%09%09g
@@ -1106,30 +1106,32 @@
tName).then(
-result
+filePath
=%3E fs.exist
@@ -1140,31 +1140,16 @@
ync(
-result).should.eql(true
+filePath
));%0A
|
b9df6264b2f750b1c14213aa22b4ba5a3da2c0c8
|
format #360
|
js/ToggleNode.js
|
js/ToggleNode.js
|
// Copyright 2018, University of Colorado Boulder
/**
* Display one of N nodes based on a given Property. Maintains the bounds of the union of children for layout.
* Supports null and undefined as possible values. Will not work correctly if the children are changed externally
* after instantiation (manages its own children and their visibility).
*
* @author Sam Reid (PhET Interactive Simulations)
*/
define( function( require ) {
'use strict';
// modules
var inherit = require( 'PHET_CORE/inherit' );
var Node = require( 'SCENERY/nodes/Node' );
var sun = require( 'SUN/sun' );
/**
* @param {Object[]} elements - Array of {value:{Object}, node:{Node}}
* @param {Property.<Object>} valueProperty
* @param {Object} [options]
* @constructor
*/
function ToggleNode( elements, valueProperty, options ) {
assert && assert( Array.isArray( elements ), 'elements should be an array' );
if ( assert ) {
elements.forEach( function( element ) {
var keys = _.keys( element );
assert( keys.length === 2, 'each element should have two keys' );
assert( keys[ 0 ] === 'value' || keys[ 1 ] === 'value', 'element should have a value key' );
assert( element.node instanceof Node, 'element.node should be a node' );
} );
}
options = _.extend( {
// By default, line up the centers of all nodes with the center of the first node. NOTE this is different than
// in ToggleNode
alignChildren: ToggleNode.CENTER
}, options );
var valueChangeListener = function( value ) {
var matchCount = 0;
for ( var i = 0; i < elements.length; i++ ) {
var element = elements[ i ];
var visible = element.value === value;
element.node.visible = visible;
if ( visible ) {
matchCount++;
}
}
assert && assert( matchCount === 1, 'Wrong number of matches: ' + matchCount );
};
valueProperty.link( valueChangeListener );
options.children = _.map( elements, 'node' );
options.alignChildren( options.children );
Node.call( this, options );
// @private
this.disposeToggleNode = function() {
valueProperty.unlink( valueChangeListener );
};
}
sun.register( 'ToggleNode', ToggleNode );
return inherit( Node, ToggleNode, {
/**
* Make eligible for garbage collection.
* @public
*/
dispose: function() {
this.disposeToggleNode();
Node.prototype.dispose.call( this );
}
}, {
/**
* Center the latter nodes on the x center of the first node.
* @param {Node[]} children
* @public
*/
HORIZONTAL: function( children ) {
for ( var i = 1; i < children.length; i++ ) {
children[ i ].centerX = children[ 0 ].centerX;
}
},
/**
* Center the latter nodes on the y center of the first node.
* @param {Node[]} children
* @public
*/
VERTICAL: function( children ) {
for ( var i = 1; i < children.length; i++ ) {
children[ i ].centerY = children[ 0 ].centerY;
}
},
/**
* Center the latter nodes on the x,y center of the first node.
* @param {Node[]} children
* @public
*/
CENTER: function( children ) {
for ( var i = 1; i < children.length; i++ ) {
children[ i ].center = children[ 0 ].center;
}
}
} );
} );
|
JavaScript
| 0 |
@@ -830,24 +830,25 @@
options ) %7B%0A
+%0A
assert &
@@ -1290,24 +1290,25 @@
%7D );%0A %7D%0A
+%0A
options
@@ -1410,17 +1410,25 @@
st node.
-
+%0A //
NOTE th
@@ -1447,25 +1447,16 @@
ent than
-%0A //
in Togg
|
939c92ab6f26752759ccb440dd6fc4eea1ea9c8d
|
Update server logic to use router and controller
|
server.js
|
server.js
|
const express = require('express'),
mongoose = require('mongoose'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
app = express(),
config = require('./app/config/config');
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
mongoose.connect(config.db);
mongoose.connection.on('connected', () => { console.log('Mongoose default connection open to ' + config.db); });
app.listen(config.port, (err) => {
if (err) { throw err; }
console.log("App listening on port " + config.port);
});
|
JavaScript
| 0 |
@@ -448,16 +448,52 @@
ride());
+%0Arequire('./app/routes/route')(app);
%0A%0Amongoo
|
f67c20c71185cc1287c3e38efe218406c07a0097
|
Remove useless functions
|
src/public/js/view/editPoiMarkerModal.js
|
src/public/js/view/editPoiMarkerModal.js
|
define([
'underscore',
'backbone',
'marionette',
'bootstrap',
'templates',
'text!icons.json',
],
function (
_,
Backbone,
Marionette,
Bootstrap,
templates,
icons
) {
'use strict';
return Marionette.ItemView.extend({
template: JST['editPoiMarkerModal.html'],
behaviors: {
'l20n': {},
'modal': {},
},
ui: {
'modal': '#edit_poi_marker_modal',
'colorButtons': '.colorButtons .btn',
'shapeButtons': '.shapeButtons .btn',
'closeButton': '.close_btn',
},
events: {
'mouseover @ui.colorButtons': 'onOverColorButtons',
'mouseleave @ui.colorButtons': 'onLeaveColorButtons',
'click @ui.colorButtons': 'onClickColorButtons',
'mouseover @ui.shapeButtons': 'onOverShapeButtons',
'mouseleave @ui.shapeButtons': 'onLeaveShapeButtons',
'click @ui.shapeButtons': 'onClickShapeButtons',
'submit': 'onSubmit',
'reset': 'onReset',
},
initialize: function () {
var self = this;
this._radio = Backbone.Wreqr.radio.channel('global');
this._oldModel = this.model.clone();
this._icons = JSON.parse(icons);
},
onRender: function () {
this.ui.colorButtons
.filter( '.'+ this.model.get('markerColor') )
.find('i')
.addClass('fa-check');
this.ui.shapeButtons
.filter( '.'+ this.model.get('markerShape') )
.addClass('active');
},
close: function () {
this.triggerMethod('close');
},
onReset: function () {
this.model.set( this._oldModel.toJSON() );
this.close();
},
onSubmit: function (e) {
e.preventDefault();
var self = this;
this._radio.commands.execute('map:updatePoiLayerIcons', this.model);
this.model.save({}, {
'success': function () {
self._oldModel = self.model.clone();
self.close();
},
'error': function () {
// FIXME
console.error('nok');
},
});
},
onOverColorButtons: function (e) {
},
onLeaveColorButtons: function (e) {
},
onClickColorButtons: function (e) {
$('i', this.ui.colorButtons).removeClass('fa-check');
e.target.querySelector('i').classList.add('fa-check');
this.model.set('markerColor', e.target.dataset.color);
},
onOverShapeButtons: function (e) {
},
onLeaveShapeButtons: function (e) {
},
onClickShapeButtons: function (e) {
this.ui.shapeButtons.removeClass('active');
e.target.classList.add('active');
this.model.set('markerShape', e.target.dataset.shape);
},
});
});
|
JavaScript
| 0.000326 |
@@ -515,271 +515,46 @@
%09%09%09'
-mouseover @ui.colorButtons': 'onOverColorButtons',%0A%09%09%09'mouseleave @ui.colorButtons': 'onLeaveColorButtons',%0A%09%09%09'click @ui.colorButtons': 'onClickColorButtons',%0A%0A%09%09%09'mouseover @ui.shapeButtons': 'onOverShapeButtons',%0A%09%09%09'mouseleave @ui.shapeButtons': 'onLeaveShape
+click @ui.colorButtons': 'onClickColor
Butt
@@ -1623,97 +1623,8 @@
%7D,%0A%0A
-%09%09onOverColorButtons: function (e) %7B%0A%0A%09%09%7D,%0A%0A%09%09onLeaveColorButtons: function (e) %7B%0A%0A%09%09%7D,%0A%0A
%09%09on
@@ -1843,97 +1843,8 @@
%7D,%0A%0A
-%09%09onOverShapeButtons: function (e) %7B%0A%0A%09%09%7D,%0A%0A%09%09onLeaveShapeButtons: function (e) %7B%0A%0A%09%09%7D,%0A%0A
%09%09on
|
f8df9e0cd670f2bb88c4638dec30d26bbab72119
|
fix exchange name
|
js/btctradeim.js
|
js/btctradeim.js
|
'use strict';
// ---------------------------------------------------------------------------
const coinegg = require ('./coinegg.js');
const { ExchangeError } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class btctradeim extends coinegg {
describe () {
return this.deepExtend (super.describe (), {
'id': 'btctradeim',
'name': 'CoolCoin',
'countries': 'HK',
'urls': {
'logo': 'https://www.btctrade.im/static/images/logo.png',
'api': {
'web': 'https://www.btctrade.im/coin',
'rest': 'https://api.btctrade.im/api/v1',
},
'www': 'https://www.btctrade.im/',
'doc': 'https://www.btctrade.im/help.api.html',
'fees': 'https://www.btctrade.im/spend.price.html',
},
'fees': {
'trading': {
'maker': 0.2 / 100,
'taker': 0.2 / 100,
},
'funding': {
'withdraw': {
'BTC': 0.001,
},
},
},
});
}
async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let response = await this.fetch2 (path, api, method, params, headers, body);
if (api ==='web') {
return response;
}
let data = this.safeValue (response, 'data');
if (data) {
let code = this.safeString (response, 'code');
if (code !== '0') {
let message = this.safeString (response, 'msg', 'Error');
throw new ExchangeError (message);
}
return data;
}
return response;
}
};
|
JavaScript
| 0.000144 |
@@ -447,16 +447,19 @@
': '
-CoolCoin
+BtcTrade.im
',%0A
|
8c0ffea385559090d32e9c8daba4215a21279f5c
|
Fix issue displaying completed games on last day of month.
|
_includes/js/application.js
|
_includes/js/application.js
|
(function() {
var Time = {
MINUTES_IN_HOUR : 60,
MILLISECONDS_IN_MINUTE : 60000,
OFFSETS : [300, 240, 300, 240, 300, 240, 300, 240, 300, 240, 300, 240,
300, 240, 300, 240, 300, 240, 300, 240, 300, 240, 300],
UNTILS : [1268550000000, 1289109600000, 1299999600000, 1320559200000,
1331449200000, 1352008800000, 1362898800000, 1383458400000,
1394348400000, 1414908000000, 1425798000000, 1446357600000,
1457852400000, 1478412000000, 1489302000000, 1509861600000,
1520751600000, 1541311200000, 1552201200000, 1572760800000,
1583650800000, 1604210400000, null],
formatDate: function(date) {
return new Intl.DateTimeFormat(undefined, {
month : "long",
day : "numeric",
weekday : "long"
}).format(date);
},
formatTime: function(time) {
return new Intl.DateTimeFormat(undefined, {
hour : "numeric",
minute : "numeric"
}).format(time);
},
offset: function() {
var target = Date.now(),
untils = this.UNTILS,
offsets = this.OFFSETS,
offset,
offsetNext,
offsetPrev;
for (var index = 0; index < untils.length - 1; index++) {
offset = offsets[index];
offsetNext = offsets[index + 1];
offsetPrev = offsets[index ? index - 1 : index];
if (offset < offsetNext && false) {
offset = offsetNext;
} else if (offset > offsetPrev && true) {
offset = offsetPrev;
}
if (target < untils[index] - (offset * this.MILLISECONDS_IN_MINUTE)) {
return offsets[index] / this.MINUTES_IN_HOUR;
}
}
return offsets[untils.length - 1] / this.MINUTES_IN_HOUR;
}
};
var now = new Date(),
empty = document.querySelector(".empty"),
hours = now.getUTCHours(),
slice = Array.prototype.slice,
offset = Time.offset(),
sections = slice.call(document.querySelectorAll("section"));
if (navigator.platform.match(/Win/)) {
document.querySelector("header h1 a").innerHTML = "Hockey";
}
if (hours < offset) {
now.setUTCHours(hours - offset);
}
var year = now.getUTCFullYear(),
month = now.getUTCMonth() + 1,
day = now.getUTCDate(),
limit = 7,
count = 1;
sections.forEach(function(section) {
section.classList.remove("week");
});
var activeSections = sections.filter(function(section) {
if (!section) {
return false;
}
var time = section.querySelector("h1 time");
if (!time) {
return false;
}
if (!section.querySelector("table tbody")) {
section.parentNode.removeChild(section);
return false;
}
var parts = time.getAttribute("datetime").split("-"),
sectionYear = parseInt(parts[0], 10),
sectionMonth = parseInt(parts[1], 10),
sectionDay = parseInt(parts[2].split("T")[0], 10);
return (sectionYear > year) ||
(sectionYear >= year && sectionMonth > month) ||
(sectionYear >= year && sectionMonth >= month && sectionDay >= day - 1);
});
if (activeSections.length === 0) {
var header = empty.querySelector("h1"),
difference = Math.round(
(new Date("9/16/2019").getTime() - Date.now()) /
1000 / 60 / 60 / 24
),
duration = "in " + difference + " days";
if (Intl.RelativeTimeFormat) {
duration = new Intl.RelativeTimeFormat({ style: "narrow" }).format(difference, "day");
}
header.innerText = "Hockey " + duration + ".";
empty.classList.remove("hidden");
return;
} else if (empty) {
empty.parentNode.removeChild(empty);
}
activeSections.forEach(function(section, index) {
if (!section.querySelector("tr")) {
return;
} else if (count > limit && window.location.pathname === "/") {
return;
}
count++;
if (window.Intl && window.Intl.DateTimeFormat) {
var time = section.querySelector("h1 time");
parts = time.getAttribute("datetime").split("-"),
sectionYear = parseInt(parts[0], 10),
sectionMonth = parseInt(parts[1], 10),
sectionDay = parseInt(parts[2].split("T")[0], 10);
if (sectionYear === year && sectionMonth === month && sectionDay === day) {
time.innerText = "Today";
} else if (sectionYear === year && sectionMonth === month && sectionDay === day - 1) {
time.innerText = "Yesterday";
} else {
time.innerText = Time.formatDate(
new Date(time.getAttribute("datetime"))
);
}
slice.call(section.querySelectorAll("th time")).forEach(function(time) {
var date = new Date(time.getAttribute("datetime"));
time.textContent = Time.formatTime(date);
});
}
section.classList.add("week");
});
window.addEventListener("load", function(e) {
if (!window.applicationCache) {
return;
}
window.applicationCache.addEventListener("updateready", function(e) {
if (window.applicationCache.status !== window.applicationCache.UPDATEREADY) {
return;
}
if (window.scrollY === 0 || confirm("An updated schedule is available. Load it?")) {
window.location.reload();
}
}, false);
}, false);
})();
|
JavaScript
| 0 |
@@ -2809,32 +2809,33 @@
ar parts
+
= time.getAttrib
@@ -2875,32 +2875,33 @@
sectionYear
+
= parseInt(parts
@@ -2923,32 +2923,33 @@
sectionMonth
+
= parseInt(parts
@@ -2971,32 +2971,33 @@
sectionDay
+
= parseInt(parts
@@ -3014,24 +3014,78 @@
%22T%22)%5B0%5D, 10)
+,%0A previousMonth = month === 1 ? 12 : month - 1
;%0A%0A retur
@@ -3251,16 +3251,99 @@
%3E= day -
+ 1) %7C%7C%0A (sectionYear %3E= year && sectionMonth === previousMonth && day ===
1);%0A %7D
|
e532da58345a99c7e9776854c5b2634c24985cb8
|
Fix invalid token response
|
server.js
|
server.js
|
var request = require('request');
var http = require('http');
var user = process.env.PACKAGIST_USER;
var token = process.env.PACKAGIST_TOKEN;
var url = process.env.PACKAGIST_URL || 'https://packagist.org';
var port = process.env.APP_PORT || 80;
var hooktoken = process.env.WEBHOOK_TOKEN;
http.createServer(function (req, res) {
var body = '';
req.on('data', function (data) {
body += data;
if (body.length > 1e6) {
req.connection.destroy();
}
});
req.on('end', function () {
var data = [];
data = body ? JSON.parse(body) : [];
if (!data.hasOwnProperty('token') || data.token !== hooktoken) {
res.status(401);
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ error: 'Invalid token' }));
console.log('Invalid token!');
} else {
request({
url: url + '/api/update-package?username=' + encodeURIComponent(user) + '&apiToken=' + encodeURIComponent(token),
method: "POST",
headers: {
"content-type": "application/json",
},
json: {"repository":{"url":data.event.repo.url}}
}, function (error, resp, body) {
res.writeHead(resp.statusCode, resp.headers);
resp.on('data', function (chunk) {
res.write(chunk);
});
resp.on('end', function (chunk) {
res.end();
});
console.log(resp.statusCode);
if (202 !== resp.statusCode || 200 !== resp.statusCode) {
console.log(body);
}
});
}
});
}).listen(port);
|
JavaScript
| 0.002414 |
@@ -645,41 +645,24 @@
res.
-status(401);%0A res.setHeader(
+writeHead(401, %7B
'Con
@@ -671,17 +671,17 @@
nt-Type'
-,
+:
'applic
@@ -691,16 +691,17 @@
on/json'
+%7D
);%0A
@@ -709,12 +709,13 @@
res.
-send
+write
(JSO
@@ -756,16 +756,29 @@
n' %7D));%0A
+%09 res.end();
%0A c
|
3f46073913f92e2344afd5c43bf337bee3abf959
|
Fix npm watch error on webpack < 1.12.12
|
js/commonMenu.js
|
js/commonMenu.js
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict'
const AppConfig = require('./constants/appConfig')
const AppActions = require('../js/actions/appActions')
const messages = require('../js/constants/messages')
const electron = require('electron')
let app
if (process.type === 'browser') {
app = electron.app
} else {
app = electron.remote.app
}
/**
* Sends a message to the web contents of the focused window.
* @param {Object} focusedWindow the focusedWindow if any
* @param {Array} message message and arguments to send
* @return {boolean} whether the message was sent
*/
module.exports.sendToFocusedWindow = (focusedWindow, message) => {
if (focusedWindow) {
focusedWindow.webContents.send.apply(focusedWindow.webContents, message)
return true
} else {
return false
}
}
module.exports.quitMenuItem = {
label: 'Quit ' + AppConfig.name,
accelerator: 'Command+Q',
click: app.quit
}
module.exports.newTabMenuItem = {
label: 'New Tab',
accelerator: 'CmdOrCtrl+T',
click: function (item, focusedWindow) {
if (!module.exports.sendToFocusedWindow(focusedWindow, [messages.SHORTCUT_NEW_FRAME])) {
// no active windows
AppActions.newWindow()
}
}
}
module.exports.newPrivateTabMenuItem = {
label: 'New Private Tab',
accelerator: 'CmdOrCtrl+Alt+T',
click: function (item, focusedWindow) {
module.exports.sendToFocusedWindow(focusedWindow, [messages.SHORTCUT_NEW_FRAME, undefined, { isPrivate: true }])
}
}
module.exports.newPartitionedTabMenuItem = {
label: 'New Partitioned Session',
accelerator: 'CmdOrCtrl+Alt+S',
click: function (item, focusedWindow) {
module.exports.sendToFocusedWindow(focusedWindow, [messages.SHORTCUT_NEW_FRAME, undefined, { isPartitioned: true }])
}
}
module.exports.newWindowMenuItem = {
label: 'New Window',
accelerator: 'CmdOrCtrl+N',
click: () => AppActions.newWindow()
}
module.exports.separatorMenuItem = {
type: 'separator'
}
module.exports.printMenuItem = {
label: 'Print...',
accelerator: 'CmdOrCtrl+P',
click: function (item, focusedWindow) {
module.exports.sendToFocusedWindow(focusedWindow, [messages.SHORTCUT_ACTIVE_FRAME_PRINT])
}
}
module.exports.findOnPageMenuItem = {
label: 'Find on page...',
accelerator: 'CmdOrCtrl+F',
click: function (item, focusedWindow) {
module.exports.sendToFocusedWindow(focusedWindow, [messages.SHORTCUT_ACTIVE_FRAME_SHOW_FINDBAR])
}
}
|
JavaScript
| 0.000084 |
@@ -372,21 +372,84 @@
sages')%0A
-const
+%0Alet electron%0Atry %7B%0A electron = require('electron')%0A%7D catch (e) %7B%0A
electro
@@ -444,32 +444,39 @@
%7B%0A electron =
+global.
require('electro
@@ -479,16 +479,19 @@
ctron')%0A
+%7D%0A%0A
let app%0A
|
cc921981753c0a42a5b6df5463a5768a4f058bea
|
add error handler
|
server.js
|
server.js
|
var moment = require('moment');// datetime
var redis = require('redis');
var publisherClient = redis.createClient();
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 app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('view options',{ layout: 'layout' });
// 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('/', index);
//app.use('/users', users);
app.get('/', function(req, res){
res.render('index', { title: 'express'} );
});
app.get('/sse/:symbol', function(req, res) {
var availableSymbols = ["USEURUSD"]
// let request last as long as possible
// req.socket.setTimeout(Infinity);
req.socket.setNoDelay(true);
var symbol = "USEURUSD"
var messageCount = 0;
var subscriber = redis.createClient();
var key = ["Z", symbol, moment().startOf('week').startOf('day').format('x')].join("_");
var args = [key, parseInt(moment().startOf('day').format('x')), parseInt(moment().format('x'))];
publisherClient.zrangebyscore(args, function(err, response) {
if (err) throw err;
messageCount++;
var data = {};
data[symbol] = response;
//console.log(data);
res.write('id: ' + messageCount + '\n');
res.write('data: ' + JSON.stringify(data) + '\n');
res.write('\n\n');
});
subscriber.subscribe(symbol);
// In case we encounter an error...print it out to the console
subscriber.on("error", function(err) {
console.log("Redis Error: " + err);
});
// When we receive a message from the redis connection
subscriber.on("message", function(channel, message) {
messageCount++; // Increment our message count
var data = {messageCount: messageCount};
data[channel]= message;
res.write('id: ' + messageCount + '\n');
res.write('data: ' + JSON.stringify( data ) + '\n');
res.write('\n\n'); // Note the extra newline
});
//send headers for event-stream connection
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// The 'close' event is fired when a user closes their browser window.
// In that situation we want to make sure our redis channel subscription
// is properly shut down to prevent memory leaks...and incorrect subscriber
// counts to the channel.
req.on("close", function() {
subscriber.unsubscribe();
subscriber.quit();
});
});
app.get('/fire-event/:event_name', function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('All clients have received "' + req.params.event_name + '"');
res.end();
});
// 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');
//});
app.listen(8080);
module.exports = app;
|
JavaScript
| 0.000001 |
@@ -3185,34 +3185,32 @@
o error handler%0A
-//
app.use(function
@@ -3228,18 +3228,16 @@
next) %7B%0A
-//
var er
@@ -3264,18 +3264,16 @@
ound');%0A
-//
err.st
@@ -3284,18 +3284,16 @@
= 404;%0A
-//
next(e
@@ -3297,18 +3297,16 @@
t(err);%0A
-//
%7D);%0A%0A//
@@ -3319,18 +3319,16 @@
handler%0A
-//
app.use(
@@ -3359,18 +3359,16 @@
next) %7B%0A
-//
// set
@@ -3412,18 +3412,16 @@
lopment%0A
-//
res.lo
@@ -3448,18 +3448,16 @@
essage;%0A
-//
res.lo
@@ -3518,18 +3518,16 @@
r : %7B%7D;%0A
-//
// ren
@@ -3545,18 +3545,16 @@
or page%0A
-//
res.st
@@ -3578,18 +3578,16 @@
%7C 500);%0A
-//
res.re
@@ -3601,18 +3601,16 @@
rror');%0A
-//
%7D);%0A%0Aapp
|
2951fefef9394bbed2d0c89994e5b01f77df456b
|
change tooltip prop name to stop deprecation warning (#3186)
|
react/features/base/toolbox/components/ToolboxItem.web.js
|
react/features/base/toolbox/components/ToolboxItem.web.js
|
// @flow
import Tooltip from '@atlaskit/tooltip';
import React, { Fragment } from 'react';
import AbstractToolboxItem from './AbstractToolboxItem';
import type { Props } from './AbstractToolboxItem';
/**
* Web implementation of {@code AbstractToolboxItem}.
*/
export default class ToolboxItem extends AbstractToolboxItem<Props> {
/**
* Handles rendering of the actual item. If the label is being shown, which
* is controlled with the `showLabel` prop, the item is rendered for its
* display in an overflow menu, otherwise it will only have an icon, which
* can be displayed on any toolbar.
*
* @protected
* @returns {ReactElement}
*/
_renderItem() {
const {
onClick,
showLabel
} = this.props;
const props = {
'aria-label': this.accessibilityLabel,
className: showLabel ? 'overflow-menu-item' : 'toolbox-button',
onClick
};
const elementType = showLabel ? 'li' : 'div';
// eslint-disable-next-line no-extra-parens
const children = (
<Fragment>
{ this._renderIcon() }
{ showLabel && this.label }
</Fragment>
);
return React.createElement(elementType, props, children);
}
/**
* Helper function to render the item's icon.
*
* @private
* @returns {ReactElement}
*/
_renderIcon() {
const { iconName, tooltipPosition, showLabel } = this.props;
const icon = <i className = { iconName } />;
const elementType = showLabel ? 'span' : 'div';
const className
= showLabel ? 'overflow-menu-item-icon' : 'toolbox-icon';
const iconWrapper
= React.createElement(elementType, { className }, icon);
const tooltip = this.tooltip;
const useTooltip = !showLabel && tooltip && tooltip.length > 0;
if (useTooltip) {
return (
<Tooltip
description = { tooltip }
position = { tooltipPosition }>
{ iconWrapper }
</Tooltip>
);
}
return iconWrapper;
}
}
|
JavaScript
| 0 |
@@ -2023,19 +2023,15 @@
-description
+content
= %7B
|
ad4d4da8b6ae05dcd44fb764a6c6ccb1cabfae8b
|
fix who's coming
|
js/contact_me.js
|
js/contact_me.js
|
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val().toString();
var email = $("input#email").val().toString();
var n_total = $("select#n_people").val();
var shuttle = $("select#shuttle").val();
var coming = $("textarea#whos_coming").val().toString();
var food = $("textarea#food").val().toString();
var message = $("textarea#message").val().toString();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
var ajaxC = function(){
return $.ajax({
url: "https://4rfwi08t6c.execute-api.us-east-1.amazonaws.com/prod/rsvp",
type: "POST",
'Content-Type': 'application/json',
crossDomain: true,
cors: true,
data: {
Name: "'".concat(name),
Email: email,
N: n_total,
Shuttle: shuttle,
Message: "'".concat(message),
Coming: "'".concat(whos_coming),
Food: "'".concat(food),
key: "1cLu_f2PuSCCfMLhbMcFQJLfV2A1tZEV9QCJm0Ax2yWM",
sheet : "RSVP",
Time: new Date(Date.now())
},
cache: false,
dataFiler: function(data){
console.log("hi");
},
success: function(data) {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Thanks so much for your RSVP! </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#rsvpForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", Alex goofed on setting something up...please email [email protected].");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#rsvpForm').trigger("reset");
},
}
);//end ajax call
}
ajaxC().fail(function(){ console.log("failure")});
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Thanks so much for your RSVP! </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#rsvpForm').trigger("reset");
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
|
JavaScript
| 0.000006 |
@@ -1602,21 +1602,16 @@
.concat(
-whos_
coming),
|
452250db0db465b1f1db877f7231eca3e642e47f
|
change the submit button label to conform to the design
|
src/foam/nanos/auth/resetPassword/ForgotPasswordView.js
|
src/foam/nanos/auth/resetPassword/ForgotPasswordView.js
|
/**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.auth.resetPassword',
name: 'ForgotPasswordView',
extends: 'foam.u2.View',
documentation: 'Forgot Password Resend View',
imports: [
'notify',
'resetPasswordToken',
'stack',
'theme'
],
css: `
^ .sizeCenter {
max-width: 30vw;
margin: 6% auto;
}
^ .center {
text-align: center;
}
^ .top-bar {
background: /*%LOGOBACKGROUNDCOLOUR%*/ #202341;
width: 100%;
height: 8vh;
border-bottom: solid 1px #e2e2e3
}
^ .top-bar img {
height: 4vh;
padding-top: 2vh;
display: block;
margin: 0 auto;
}
^ .title-top {
font-size: 2.5em;
padding-top: 2vh;
font-weight: bold;
}
`,
requires: [
'foam.nanos.auth.User',
'foam.u2.detail.SectionView'
],
sections: [
{
name: 'emailPasswordSection',
title: '',
help: `Enter your account email and we will send you an email with a link to create a new one.`
}
],
properties: [
{
class: 'EMail',
name: 'email',
section: 'emailPasswordSection',
required: true
}
],
messages: [
{ name: 'INSTRUC_ONE', message: 'Password reset instructions were sent to' },
{ name: 'INSTRUC_TWO', message: 'Please check your inbox to continue.' },
{ name: 'REDIRECTION_TO', message: 'Back to Sign in' },
{ name: 'TITLE', message: 'Forgot your password?' },
{ name: 'ACTION_PRESS', message: 'click' }
],
methods: [
function initE() {
this.SUPER();
let logo = this.theme.largeLogo ? this.theme.largeLogo : this.theme.logo;
this
.addClass(this.myClass())
.startContext({ data: this })
.start().addClass('top-bar')
.start('img')
.attr('src', logo)
.end()
.end()
.start().addClass('sizeCenter')
.start('h1').addClass('title-top').add(this.TITLE).end()
.start(this.SectionView, {
data: this,
sectionName: 'emailPasswordSection'
}).end()
.start().addClass('center').br().br()
.start(this.SEND_EMAIL, { size: 'LARGE' }).end()
.br().br()
.start().addClass('link')
.add(this.REDIRECTION_TO)
.on(this.ACTION_PRESS, () => {
this.stack.push({ class: 'foam.u2.view.LoginView', mode_: 'SignIn' }, this);
})
.end()
.end()
.end()
.endContext();
}
],
actions: [
{
name: 'sendEmail',
label: 'Send reset password email',
isEnabled: function(errors_) {
return ! errors_;
},
code: function(X) {
var user = this.User.create({ email: this.email });
this.resetPasswordToken.generateToken(null, user).then((_) => {
this.notify(`${this.INSTRUC_ONE} ${this.email}. ${this.INSTRUC_TWO}`);
this.stack.push({ class: 'foam.u2.view.LoginView', mode_: 'SignIn' }, this);
})
.catch((err) => {
this.notify(err.message, 'error');
});
}
}
]
});
|
JavaScript
| 0 |
@@ -2753,32 +2753,13 @@
: 'S
-end reset password email
+ubmit
',%0A
|
64ef6d6bed99d552e44e444f4d8364009d597c81
|
add stats color.
|
server.js
|
server.js
|
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
contentBase: 'src',
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(3000, 'localhost', function (err, result) {
if (err) {
console.log(err);
}
console.log('Listening at localhost:3000');
});
|
JavaScript
| 0 |
@@ -265,16 +265,49 @@
ck: true
+,%0A stats: %7B%0A colors: true%0A %7D
%0A%7D).list
|
78df8f04984e007e1b1a01f446285bccd2c59511
|
Update contact_me.js
|
js/contact_me.js
|
js/contact_me.js
|
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
type: 'POST',
url: "https://mandrillapp.com/api/1.0/messages/send.json",
dataType: 'json',
data: {
key: 'h7nP27VyRFNZ8MTSaqmW6g',
message: {
text: message + "\n\n" + "Phone: " + phone,
subject: "Contact Engineers",
from_email: drooids.__globals__.senderEmail,
from_name: name,
to: drooids.__globals__.contactEmails,
}
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
|
JavaScript
| 0 |
@@ -1133,16 +1133,45 @@
%22%5Cn%5Cn%22 +
+ %22Email: %22 + email + %22%5Cn%5Cn%22 +
%22Phone:
|
e64d1ef89a3fe5063c0b624ab6f218e749c51e2e
|
Fix generic inside value
|
generator.js
|
generator.js
|
var util = require('util');
var ptype = function (inter, nogeneric) {
var sequence = false;
var generic = false;
if (typeof inter !== 'string') {
sequence = inter.sequence;
generic = inter.generic;
type = inter.idlType;
if (Array.isArray(type)) {
type = 'any';
}
} else {
type = inter;
}
if (type === 'byte' || type === 'octet' || type === 'short'
|| type === 'unsigned short' || type === 'long' || type === 'unsigned long'
|| type === 'long long' || type === 'unsigned long long' || type === 'float'
|| type === 'unresticted float' || type === 'double' || type === 'unrestricted double') {
type = 'number'
}
if (type === 'DOMString' || type === 'ByteString ' || type === 'USVString') {
type = 'string'
}
if (type === 'boolean') {
type = 'bool'
}
if (type === 'any') {
type = "?";
}
if (type === 'EventHandler') {
type = "fn(event)";
}
if (/[A-Z]/.test(type[0])) {
type = `+${type}`;
}
if (sequence || generic === 'sequence') {
type = `[${ptype(type)}]`;
}
if (generic && generic !== 'sequence') {
type = `+${generic}`;
if (!nogeneric) {
type += `[value=${ptype(type)}]`;
}
}
return type;
};
var method = function (inter) {
"use strict";
var args = [];
for (let arg of inter.arguments) {
args.push(`${arg.name}: ${ptype(arg.idlType, true)}`)
}
var type = `fn(${args.join(', ')})`;
var rtn = ptype(inter.interface);
if (rtn && rtn !== 'void') {
type += ` -> ${rtn}`
}
return {
"!type": type
};
};
var prop = function (inter) {
"use strict";
var type = inter.interface ? ptype(inter.interface) : null;
var def = {};
if (type) {
def["!type"] = type;
}
if (inter.members) {
for (let m of inter.members) {
let name = m.name;
let inter = member(m);
def[name] = inter;
}
}
return def;
};
var cons = function (inter) {
"use strict";
var args = [];
for (let arg of inter.arguments) {
args.push(`${arg.name}: ${ptype(arg.idlType)}`)
}
var type = `fn(${args.join(', ')})`;
let proto = {};
for (let m of inter.members) {
let name = m.name;
let inter = member(m);
proto[name] = inter;
}
return {
"!type": type,
"prototype": proto
}
};
var member = function (inter) {
"use strict";
if (inter.type === 'method') {
return method(inter);
}
if (inter.type === 'prop') {
return prop(inter);
}
if (inter.type === 'cons') {
return cons(inter);
}
};
var generator = {
run: function (data) {
"use strict";
var def = {
"!name": "webidl",
"!define": {}
};
for (let inter of data) {
var name = inter.name;
if (inter.nointerface) {
def['!define'][name] = member(inter);
} else {
def[name] = member(inter);
}
}
// console.log(util.inspect(def, {showHidden: false, depth: null}));
console.log(JSON.stringify(def, null, 2));
}
};
module.exports = generator;
|
JavaScript
| 0.00001 |
@@ -61,19 +61,51 @@
ogeneric
-) %7B
+info) %7B%0A %22use strict%22;%0A var type;
%0A var s
@@ -949,24 +949,27 @@
ent)%22;%0A %7D%0A
+ //
if (/%5BA-Z%5D/
@@ -985,24 +985,27 @@
e%5B0%5D)) %7B%0A
+ //
type = %60+$%7B
@@ -1001,17 +1001,16 @@
type = %60
-+
$%7Btype%7D%60
@@ -1008,24 +1008,27 @@
%60$%7Btype%7D%60;%0A
+ //
%7D%0A if (seq
@@ -1132,32 +1132,54 @@
= 'sequence') %7B%0A
+ let itype = type;%0A
type = %60+$%7Bg
@@ -1206,16 +1206,20 @@
ogeneric
+info
) %7B%0A
@@ -1236,32 +1236,33 @@
%60%5Bvalue=$%7Bptype(
+i
type)%7D%5D%60;%0A %7D%0A
|
128a7b1a7b0d07e4843b870a3ab07c22456fe2dd
|
Switch DIG subject field to be a String rather than EMail type.
|
src/foam/nanos/dig/DIG.js
|
src/foam/nanos/dig/DIG.js
|
/**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.dig',
name: 'DIG',
extends: 'foam.nanos.http.DefaultHttpParameters',
documentation: 'Data Integration Gateway - Perform DAO operations against a web service',
requires: ['foam.net.web.HTTPRequest'],
tableColumns: [
'id',
'daoKey',
'cmd',
'format',
'owner'
],
searchColumns: [],
constants: [
{
name: 'MAX_URL_SIZE',
value: 2000,
type: 'Integer'
}
],
properties: [
'id',
{
class: 'String',
name: 'daoKey',
label: 'DAO',
view: function(_, X) {
var E = foam.mlang.Expressions.create();
return foam.u2.view.ChoiceView.create({
dao: X.nSpecDAO
.where(E.ENDS_WITH(foam.nanos.boot.NSpec.ID, 'DAO'))
.orderBy(foam.nanos.boot.NSpec.ID),
objToChoice: function(nspec) {
return [nspec.id, nspec.id];
}
});
},
value: 'accountDAO'
},
'cmd',
'format',
{
class: 'String',
name: 'dao',
hidden: true,
transient: true,
postSet: function(old, nu) {
this.daoKey = nu;
}
},
{
class: 'String',
name: 'q',
label: 'Query'
},
{
class: 'String',
name: 'key'
},
{
class: 'EMail',
displayWidth: 100,
name: 'email'
},
{
class: 'EMail',
displayWidth: 100,
name: 'subject'
},
'data',
{
class: 'foam.nanos.fs.FileProperty',
name: 'dataFile',
label: 'DataFile',
documentation: 'dig file to put data',
view: { class: 'foam.nanos.dig.DigFileUploadView', data: this.dataFile$ },
},
{
class: 'URL',
name: 'postURL',
hidden: true
},
{
name: 'snippet',
label: 'Snippet',
documentation: 'show a specific type of request would look like in a given language.',
view: { class: 'foam.nanos.dig.DigSnippetView' },
expression: function(key, data, email, subject, daoKey, cmd, format, q, dataFile) {
var query = false;
var url = "/service/dig";
if ( daoKey ) {
url += query ? "&" : "?";
query = true;
url += "dao=" + daoKey;
}
if ( cmd ) {
url += query ? "&" : "?";
query = true;
url += "cmd=" + cmd.name.toLowerCase();
}
if ( format ) {
url += query ? "&" : "?";
query = true;
url += "format=" + format.name.toLowerCase();
}
if ( key ) {
url += query ? "&" : "?";
query = true;
url += "id=" + key;
}
if ( email ) {
url += query ? "&" : "?";
query = true;
url += "email=" + email;
}
if ( subject ) {
url += query ? "&" : "?";
query = true;
url += "subject=" + encodeURIComponent(subject);
}
if ( q ) {
url += query ? "&" : "?";
query = true;
url += "q=" + encodeURIComponent(q);
}
this.postURL = url;
if ( dataFile ) {
url += query ? "&" : "?";
query = true;
url += "&fileaddress=" + encodeURIComponent(dataFile.address);
}
if ( data ) {
if ( data.length + url.length < this.MAX_URL_SIZE ) {
url += query ? "&" : "?";
query = true;
url += "data=" + encodeURIComponent(data);
}
}
return url;
}
},
{
class: 'String',
name: 'result',
value: 'No Request Sent Yet.',
view: { class: 'foam.u2.tag.TextArea', rows: 5, cols: 120 },
visibility: 'RO'
}
],
actions: [
{
name: 'postButton',
label: 'Send Request',
code: async function() {
var req = this.HTTPRequest.create({
url: window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + this.postURL + "&sessionId=" + localStorage.defaultSession,
method: 'POST',
payload: this.data,
}).send();
var resp = await req.then(async function(resp) {
var temp = await resp.payload.then(function(result) {
return result;
});
return temp;
}, async function(error) {
var temp = await error.payload.then(function(result) {
return result;
});
return temp;
});
this.result = resp;
}
}
]
});
|
JavaScript
| 0 |
@@ -1498,37 +1498,38 @@
%7B%0A class: '
-EMail
+String
',%0A display
|
d755850d8a7bf1d0609e9b72edee7f81fb187f4e
|
Update AbsoluteId.js
|
lib/AbsoluteId.js
|
lib/AbsoluteId.js
|
/*
/* This program is free software: you can redistribute it and/or modify
/* it under the terms of the GNU Affero General Public License, version 3,
/* as published by the Free Software Foundation.
/*
/* This program is distributed in the hope that it will be useful,
/* but WITHOUT ANY WARRANTY; without even the implied warranty of
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/* GNU Affero General Public License for more details.
/*
/* You should have received a copy of the GNU Affero General Public License
/* along with this program. If not, see <http://www.gnu.org/licenses/>.
/*
/* The Original Code is "Pillars.js Modelator" aka "Modelator"
/*
/* The Initial Developer of the Original Code is Francisco Javier Gallego Martín <bifuer.at.gmail.com>.
/* Copyright (c) 2014-2017 Francisco Javier Gallego Martín.
/*/
/* jslint node: true, esnext: true */
"use strict";
const config = {
lastTimeStamp : 0,
server : 1,
process : 1,
counter : 0
};
const pad = function(hex, length){
return (hex.length < length? "0".repeat(length - hex.length) : '') + hex;
};
const absoluteId = module.exports = function(){
const timeStamp = Date.now();
if(config.lastTimeStamp !== timeStamp){
config.counter = 0;
}
config.lastTimeStamp = timeStamp;
const nid = [
config.server,
config.process,
timeStamp,
config.counter
].map(function(int){return int.toString(16);});
nid[0] = pad(nid[0], 3);
nid[1] = pad(nid[1], 3);
nid[2] = pad(nid[2], 11);
nid[3] = pad(nid[3], 4);
config.counter++;
return nid.join('');
};
absoluteId.config = config;
|
JavaScript
| 0 |
@@ -1,886 +1,4 @@
-/*%0A/* This program is free software: you can redistribute it and/or modify%0A/* it under the terms of the GNU Affero General Public License, version 3,%0A/* as published by the Free Software Foundation.%0A/*%0A/* This program is distributed in the hope that it will be useful,%0A/* but WITHOUT ANY WARRANTY; without even the implied warranty of%0A/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A/* GNU Affero General Public License for more details.%0A/*%0A/* You should have received a copy of the GNU Affero General Public License%0A/* along with this program. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0A/*%0A/* The Original Code is %22Pillars.js Modelator%22 aka %22Modelator%22%0A/*%0A/* The Initial Developer of the Original Code is Francisco Javier Gallego Mart%C3%ADn %3Cbifuer.at.gmail.com%3E.%0A/* Copyright (c) 2014-2017 Francisco Javier Gallego Mart%C3%ADn.%0A/*/%0A%0A
/* j
@@ -31,16 +31,16 @@
true */%0A
+
%22use str
@@ -728,16 +728,16 @@
');%0A%7D;%0A%0A
-
absolute
@@ -755,8 +755,9 @@
config;
+%0A
|
f00470eebd10ad651382b8a3b507157e8c404655
|
update example
|
examples/h5bp.js
|
examples/h5bp.js
|
var path = require('path');
var Boilerplate = require('../');
var inspect = require('stringify-object');
function stringify(config) {
return inspect(config, {
singleQuotes: true,
indent: ' '
});
}
var h5bp = new Boilerplate({
options: {
cwd: 'vendor/h5bp/dist'
},
root: {src: ['{.*,*.*}'], dest: 'src/'},
css: {src: ['css/*.css'], dest: 'src/'},
doc: {src: ['doc/*.md'], dest: 'src/'},
js: {src: ['js/**/*.js'], dest: 'src/'}
});
console.log(stringify(h5bp))
|
JavaScript
| 0.000001 |
@@ -17,24 +17,91 @@
re('path');%0A
+var get = require('get-value');%0Avar set = require('set-value');%0A//
var Boilerpl
@@ -165,16 +165,94 @@
ject');%0A
+var Target = require('expand-target');%0Avar Config = require('expand-config');%0A
%0A%0Afuncti
@@ -351,16 +351,891 @@
%7D);%0A%7D%0A%0A
+// var boilerplate = new Boilerplate();%0A%0A%0Afunction Boilerplate(options) %7B%0A Base.call(this);%0A this.options = options %7C%7C %7B%7D;%0A this.configs = %7B%7D;%0A%7D%0A%0ABoilerplate.prototype.option = function(key, value) %7B%0A set(this.options, key, value);%0A return this;%0A%7D;%0A%0ABoilerplate.prototype.target = function(name, config) %7B%0A this.targets%5Bname%5D = new Target(config);%0A return this;%0A%7D;%0A%0ABoilerplate.prototype.scaffold = function(name, config) %7B%0A this.scaffolds%5Bname%5D = new Scaffold(config);%0A return this;%0A%7D;%0A%0ABoilerplate.prototype.config = function(name, config) %7B%0A this.configs%5Bname%5D = new Config(config);%0A return this;%0A%7D;%0A%0ABoilerplate.prototype.expand = function(config, context) %7B%0A return expand(config, context);%0A%7D;%0A%0Avar boilerplate = new Boilerplate();%0A%0Aboilerplate.config(%7B%0A templates: %7B%0A partials: %7B%0A src: %5B'docs/**/*.*'%5D%0A %7D%0A %7D%0A%7D);%0A%0Aconsole.log(boilerplate);%0A%0A%0A//
var h5bp
@@ -1255,16 +1255,19 @@
plate(%7B%0A
+//
option
@@ -1267,24 +1267,27 @@
options: %7B%0A
+//
cwd: 've
@@ -1306,13 +1306,219 @@
st'%0A
+//
%7D,%0A
+// templates: %7B%0A// partials: %7B%0A// options: %7B%0A// renameKey: function () %7B%0A%0A// %7D%0A// %7D,%0A// cwd: '',%0A// src: %5B'*.hbs'%5D%0A// %7D,%0A// partials: %5B%5D,%0A// %7D,%0A//
ro
@@ -1556,16 +1556,19 @@
src/'%7D,%0A
+//
css: %7B
@@ -1602,16 +1602,19 @@
src/'%7D,%0A
+//
doc: %7B
@@ -1647,16 +1647,19 @@
src/'%7D,%0A
+//
js: %7Bs
@@ -1692,21 +1692,27 @@
'src/'%7D%0A
+//
%7D);%0A%0A
+//
console.
|
611e30da769eabd45d5eed83670fe8627ceb1a56
|
add semi-colons.
|
server.js
|
server.js
|
/**
* Moraine Server.
*
* @author Jackson
* @type {*|exports|module.exports}
*/
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello Moraine')
})
app.listen(8000)
|
JavaScript
| 0.004348 |
@@ -110,16 +110,17 @@
xpress')
+;
%0Avar app
@@ -131,16 +131,17 @@
xpress()
+;
%0A%0Aapp.ge
@@ -202,11 +202,13 @@
ne')
+;
%0A%7D)
+;
%0A%0Aap
@@ -221,9 +221,10 @@
en(8000)
+;
%0A
|
aa5e99ad87ec2d1fc900f84eaa1937faec8fadbb
|
proper token
|
widgets/authentication/_LoginRegisterSignInPane.js
|
widgets/authentication/_LoginRegisterSignInPane.js
|
define([
'dojo/text!./templates/_LoginRegisterSignInPane.html',
'dojo/_base/declare',
'dojo/on',
'ijit/widgets/authentication/_LoginRegisterPaneMixin'
], function(
template,
declare,
on,
LoginRegisterPaneMixin
) {
// summary:
// The sign in pane for the LoginRegistration widget.
return declare([LoginRegisterPaneMixin], {
templateString: template,
baseClass: 'login-register-sign-in-pane',
xhrMethod: 'POST',
getData: function() {
// summary:
// gets the data from the form as an object suitable for
// submission to the web service
console.log('ijit/widgets/authentication/_LoginRegisterSignInPane:getData', arguments);
return {
email: this.emailTxt.value,
password: this.passwordTxt.value,
persist: this.rememberMeChbx.checked
};
},
onSubmitReturn: function(returnValue) {
// summary:
// callback for sign in xhr
// returnValue: JSON Object
console.log('ijit/widgets/authentication/_LoginRegisterSignInPane:onSubmitReturn', arguments);
this.parentWidget.token = returnValue.result.token.token;
this.parentWidget.tokenExpireDate = new Date(returnValue.result.token.expires);
returnValue.result.user.token = returnValue.result.token;
returnValue.result.user.tokenExpireDate = returnValue.result.tokenExpireDate;
this.parentWidget.user = returnValue.result.user;
this.parentWidget.hideDialog();
//this emits a buttugly object. change it to on.emit to see the other
//pretty option. It breaks the tests though.
this.emit('sign-in-success', returnValue.result);
},
onSubmitError: function() {
// summary:
// description
console.log('ijit/widgets/authentication/_LoginRegisterSignInPane:onSubmitError', arguments);
this.parentWidget.forgotPane.emailTxt.value = this.emailTxt.value;
this.parentWidget.forgotPane.submitBtn.disabled = false;
this.inherited(arguments);
}
});
});
|
JavaScript
| 0.999005 |
@@ -1428,33 +1428,32 @@
token =
-returnValue.resul
+this.parentWidge
t.token;
@@ -1507,33 +1507,32 @@
eDate =
-returnValue.resul
+this.parentWidge
t.tokenE
|
4a0bb5913f6435693aed808c7eb55e42d7384a55
|
update listener
|
server.js
|
server.js
|
var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url");
var Firebase = require("firebase")
my_http.createServer(function(request,response){
var my_path = url.parse(request.url).pathme;
var full_path = path.join(process.cwd(),my_path);
path.exists(full_path, function(exists){
if(!exists){
response.writeHeader(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
}
else{
// a reference here doesn't open a connection until r/w ops are invoked
var fb = new Firebase("https://improvplusplus.firebaseio.com")
}
});
})
my_http.createServer(function(request,response){
var my_path = url.parse(request.url).pathname;
}).listen(3000,0.0.0.0);
|
JavaScript
| 0 |
@@ -820,14 +820,16 @@
000,
+'
0.0.0.0
+'
);%0A
|
cb70e180e0ec9a08d445d2a64fd0c141f21a4170
|
add topojson plugin for map demo
|
ember-cli-build.js
|
ember-cli-build.js
|
/* jshint node: true */
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
var writer = require('broccoli-caching-writer');
var md = require('commonmark');
var fs = require('fs');
var path = require('path');
var Parser = md.Parser;
var HtmlRenderer = md.HtmlRenderer;
var DocWriter = function DocWriter(inputNodes, options) {
options = options || {};
writer.call(this, inputNodes, {
annotation: options.annotation
});
this.parser = new Parser();
this.renderer = new HtmlRenderer();
};
DocWriter.prototype = Object.create(writer.prototype);
DocWriter.prototype.constructor = DocWriter;
DocWriter.prototype.build = function() {
// Read 'foo.txt' from the third input node
var inputBuffer = fs.readFileSync(path.join(this.inputPaths[0], 'guides/guides.md'), 'utf8');
var outputBuffer = this.parser.parse(inputBuffer);
// Write to 'bar.txt' in this node's output
fs.writeFileSync(path.join(this.outputPath, 'guides.html'), this.renderer.render(outputBuffer));
};
/*
This Brocfile specifes the options for the dummy test app of this
addon, located in `/tests/dummy`
This Brocfile does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's Brocfile
*/
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
d3: {
plugins: {
'mbostock': [ 'sankey' ],
'emeeks': [ 'adjacency-matrix' ]
}
},
sassOptions: {
extension: 'scss'
}
});
app.import('bower_components/bootstrap/dist/css/bootstrap.css');
app.import('bower_components/github-markdown-css/github-markdown.css');
app.import('bower_components/bootstrap/dist/js/bootstrap.js');
return app.toTree(new DocWriter([ 'docs' ]));
};
|
JavaScript
| 0 |
@@ -1418,16 +1418,28 @@
'sankey'
+, 'topojson'
%5D,%0A
|
30a7612117276e47dfe8ed0e52efbab9ba57f71f
|
Update rfid.js
|
examples/rfid.js
|
examples/rfid.js
|
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
/*********************************************
This basic RFID example listens for an RFID
device to come within range of the module,
then logs its UID to the console.
*********************************************/
var tessel = require('tessel');
var rfidlib = require('../');// Replace '../' with 'rfid-pn532' in your own code
var rfid = rfidlib.use(tessel.port['A']);
rfid.on('ready', function (version) {
console.log('Ready to read RFID card');
rfid.on('data', function(card) {
console.log('UID:', card.uid.toString('hex'));
});
});
rfid.on('error', function (err) {
console.error(err);
});
|
JavaScript
| 0.000001 |
@@ -376,16 +376,17 @@
('../');
+
// Repla
|
90e4a74f19842bf0ab4a720eb9de5eae61b4b210
|
update console messages
|
server.js
|
server.js
|
/**
* Module dependencies
*/
var tessel = require('tessel')
, config = require('./config')
, climate = require('climate-si7005').use(tessel.port[config.climate.port])
, net = require('net');
/**
* TCP server
*/
var client, connect = function () {
client = net.connect(config.socket.port, config.socket.host, function () {
console.log('Tessel connected to host: ', config.socket);
client.on('close', function () {
reconnect();
});
client.on('data', function (data) {
console.log(data.toString());
});
client.setTimeout(config.socket.timeout, function () {
console.log('Tessel connection will be closed due to inactivity');
client.destroy();
});
});
client.on('error', function (err) {
console.error(err);
reconnect();
});
}, reconnect = function () {
console.log('Tessel connection closed. Re-connecting in ' + ( config.socket.offset / 1000 ) + ' seconds');
setTimeout(connect, config.socket.offset); // retry connection
};
console.log('Connecting in ' + ( config.socket.offset / 1000 ) + ' seconds', config.socket);
setTimeout(connect, config.socket.offset);
/**
* Climate module
*/
// functions
var climateData = {
create: function (data) {
data = data || {};
climate.readTemperature('f', function (err, temp) {
if (err) return console.error(err);
data.temperature = temp.toFixed(4);
climate.readHumidity(function (err, humid) { // sync reads; async reads distort reporting on one or both values
if (err) return console.error(err);
data.humidity = humid.toFixed(4);
data.createdAt = new Date().getTime();
});
});
setTimeout(function () {
if (!!client && !!client.write) client.write(JSON.stringify(data));
climateData.update(data);
}, config.socket.interval);
},
noop: function () {},
update: function () {}
};
// events
climate.on('error', function (err) {
console.error('Climate module error', err);
climateData.update = climateData.noop;
});
climate.on('ready', function () {
console.log('Connected to si7005 climate module');
climateData.update = climateData.create;
climateData.create();
});
|
JavaScript
| 0.000001 |
@@ -343,32 +343,25 @@
onsole.log('
-Tessel c
+C
onnected to
@@ -607,32 +607,25 @@
onsole.log('
-Tessel c
+C
onnection wi
@@ -622,16 +622,24 @@
nection
+to host
will be
@@ -662,17 +662,34 @@
activity
-'
+: ', config.socket
);%0A
@@ -854,16 +854,9 @@
og('
-Tessel c
+C
onne
@@ -861,16 +861,24 @@
nection
+to host
closed.
@@ -941,17 +941,34 @@
seconds
-'
+: ', config.socket
);%0A set
@@ -1046,32 +1046,40 @@
log('Connecting
+to host
in ' + ( config.
@@ -1112,16 +1112,18 @@
seconds
+:
', confi
|
c0d97121977903bea3fe03b802cc964a4ebec13d
|
add support for geocodingQueryParams (#269)
|
src/geocoders/opencage.js
|
src/geocoders/opencage.js
|
import L from 'leaflet';
import { getJSON } from '../util';
export var OpenCage = L.Class.extend({
options: {
serviceUrl: 'https://api.opencagedata.com/geocode/v1/json'
},
initialize: function(apiKey) {
this._accessToken = apiKey;
},
geocode: function(query, cb, context) {
getJSON(
this.options.serviceUrl,
{
key: this._accessToken,
q: query
},
function(data) {
var results = [],
latLng,
latLngBounds,
loc;
if (data.results && data.results.length) {
for (var i = 0; i < data.results.length; i++) {
loc = data.results[i];
latLng = L.latLng(loc.geometry);
if (loc.annotations && loc.annotations.bounds) {
latLngBounds = L.latLngBounds(
L.latLng(loc.annotations.bounds.northeast),
L.latLng(loc.annotations.bounds.southwest)
);
} else {
latLngBounds = L.latLngBounds(latLng, latLng);
}
results.push({
name: loc.formatted,
bbox: latLngBounds,
center: latLng
});
}
}
cb.call(context, results);
}
);
},
suggest: function(query, cb, context) {
return this.geocode(query, cb, context);
},
reverse: function(location, scale, cb, context) {
getJSON(
this.options.serviceUrl,
{
key: this._accessToken,
q: [location.lat, location.lng].join(',')
},
function(data) {
var results = [],
latLng,
latLngBounds,
loc;
if (data.results && data.results.length) {
for (var i = 0; i < data.results.length; i++) {
loc = data.results[i];
latLng = L.latLng(loc.geometry);
if (loc.annotations && loc.annotations.bounds) {
latLngBounds = L.latLngBounds(
L.latLng(loc.annotations.bounds.northeast),
L.latLng(loc.annotations.bounds.southwest)
);
} else {
latLngBounds = L.latLngBounds(latLng, latLng);
}
results.push({
name: loc.formatted,
bbox: latLngBounds,
center: latLng
});
}
}
cb.call(context, results);
}
);
}
});
export function opencage(apiKey) {
return new OpenCage(apiKey);
}
|
JavaScript
| 0 |
@@ -204,19 +204,61 @@
n(apiKey
-) %7B
+, options) %7B%0A L.setOptions(this, options);
%0A thi
@@ -338,58 +338,23 @@
-getJSON(%0A this.options.serviceUrl,%0A
+var params =
%7B%0A
-
@@ -385,18 +385,16 @@
,%0A
-
q: query
@@ -394,34 +394,137 @@
: query%0A
- %7D,%0A
+%7D;%0A params = L.extend(params, this.options.geocodingQueryParams);%0A getJSON(this.options.serviceUrl, params,
function(da
@@ -521,34 +521,32 @@
unction(data) %7B%0A
-
var result
@@ -557,34 +557,32 @@
%5B%5D,%0A
-
latLng,%0A
la
@@ -561,34 +561,32 @@
latLng,%0A
-
latLngBo
@@ -591,34 +591,32 @@
Bounds,%0A
-
loc;%0A if
@@ -602,34 +602,32 @@
loc;%0A
-
-
if (data.results
@@ -645,34 +645,32 @@
sults.length) %7B%0A
-
for (var
@@ -711,34 +711,32 @@
++) %7B%0A
-
-
loc = data.resul
@@ -734,34 +734,32 @@
ata.results%5Bi%5D;%0A
-
latLng
@@ -787,34 +787,32 @@
try);%0A
-
if (loc.annotati
@@ -836,34 +836,32 @@
tions.bounds) %7B%0A
-
latL
@@ -893,34 +893,32 @@
(%0A
-
L.latLng(loc.ann
@@ -951,34 +951,32 @@
,%0A
-
-
L.latLng(loc.ann
@@ -1006,39 +1006,35 @@
st)%0A
-
);%0A
-
%7D else
@@ -1040,34 +1040,32 @@
e %7B%0A
-
-
latLngBounds = L
@@ -1097,38 +1097,34 @@
Lng);%0A
- %7D%0A
+%7D%0A
result
@@ -1124,34 +1124,32 @@
results.push(%7B%0A
-
name
@@ -1169,34 +1169,32 @@
ed,%0A
-
bbox: latLngBoun
@@ -1201,34 +1201,32 @@
ds,%0A
-
center: latLng%0A
@@ -1216,34 +1216,32 @@
center: latLng%0A
-
%7D);%0A
@@ -1242,38 +1242,34 @@
%7D);%0A
- %7D%0A
+%7D%0A
%7D%0A
cb.c
@@ -1248,34 +1248,32 @@
%7D%0A %7D%0A
-
cb.call(co
@@ -1289,32 +1289,25 @@
sults);%0A
- %7D%0A
+%7D
);%0A %7D,%0A%0A s
@@ -2477,16 +2477,25 @@
e(apiKey
+, options
) %7B%0A re
@@ -2518,13 +2518,22 @@
e(apiKey
+, options
);%0A%7D%0A
|
7dc1a2c0680cd895b06edb6f5d14bc175038e49e
|
clean up server.js
|
server.js
|
server.js
|
var pg = require('pg');
var express = require('express'),
port = process.env.PORT || 3000,
app = express();
// var pg = require('pg');
// app.get('/db', function (request, response) {
// pg.connect(process.env.DATABASE_URL, function(err, client, done) {
// client.query('SELECT * FROM users', function(err, result) {
// done();
// if (err)
// { console.error(err); response.send('Error ' + err); }
// else
// { response.render('pages/db', {results: result.rows} ); }
// });
// });
// });
// Place.fetchAll = function(){
// $.getJSON('/data', function (result) {
// console.log('Scott was here');
// result.rows.forEach(function(item) {
// if (item.category){
// item.category = JSON.parse(item.category)
// }
// var place = new Place(item);
// Place.all.push(place);
//
// });
// });
// };
// var pg = require('pg');
// app.get('/data', function () {
// console.log('yes jesssss visited data');
// pg.defaults.ssl = true;
// pg.connect(process.env.DATABASE_URL, function(err, client) {
// if (err) throw err;
// console.log('Connected to postgres! Getting schemas...');
//
// client
// .query('SELECT * FROM users;')
// .on('row', function(row) {
// console.log(JSON.stringify(row));
// });
// });
// });
app.get('/data', function (req, res) {
var connectionString = process.env.DATABASE_URL;
var client = new pg.Client(connectionString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres');
}
client.query('select * from users', function(err, result) {
if(err) {
return console.error('error running query', err);
}
res.send(result);
client.end();
});
});
});
// app.get('/public/db', function (request, response) {
// pg.connect(process.env.DATABASE_URL, function(err, client, done) {
// client.query('SELECT * FROM users', function(err, result) {
// done();
// if (err)
// { console.error(err); response.send('Error ' + err); }
// else
// {console.log('No error jessica!');}
// // { response.render('pages/db', {results: result.rows} ); }
// });
// });
//
// });
app.get('/data', function (req, res) {
var connectionString = process.env.DATABASE_URL;
var client = new pg.Client(connectionString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres');
}
client.query('select * from users', function(err, result) {
if(err) {
return console.error('error running query', err);
}
res.send(result);
client.end();
});
});
});
app.use(express.static(__dirname + '/public/'));
app.get('*', function(request, response) {
console.log('New request:', request.url);
response.sendFile('/public/index.html', { root: '.' });
});
app.listen(port, function() {
console.log('Server started on port ' + port + '!');
});
|
JavaScript
| 0.000001 |
@@ -109,2155 +109,8 @@
();%0A
-// var pg = require('pg');%0A%0A// app.get('/db', function (request, response) %7B%0A// pg.connect(process.env.DATABASE_URL, function(err, client, done) %7B%0A// client.query('SELECT * FROM users', function(err, result) %7B%0A// done();%0A// if (err)%0A// %7B console.error(err); response.send('Error ' + err); %7D%0A// else%0A// %7B response.render('pages/db', %7Bresults: result.rows%7D ); %7D%0A// %7D);%0A// %7D);%0A// %7D);%0A// Place.fetchAll = function()%7B%0A// $.getJSON('/data', function (result) %7B%0A// console.log('Scott was here');%0A// result.rows.forEach(function(item) %7B%0A// if (item.category)%7B%0A// item.category = JSON.parse(item.category)%0A// %7D%0A// var place = new Place(item);%0A// Place.all.push(place);%0A//%0A// %7D);%0A// %7D);%0A// %7D;%0A// var pg = require('pg');%0A// app.get('/data', function () %7B%0A// console.log('yes jesssss visited data');%0A// pg.defaults.ssl = true;%0A// pg.connect(process.env.DATABASE_URL, function(err, client) %7B%0A// if (err) throw err;%0A// console.log('Connected to postgres! Getting schemas...');%0A//%0A// client%0A// .query('SELECT * FROM users;')%0A// .on('row', function(row) %7B%0A// console.log(JSON.stringify(row));%0A// %7D);%0A// %7D);%0A// %7D);%0A%0Aapp.get('/data', function (req, res) %7B%0A%0A var connectionString = process.env.DATABASE_URL;%0A%0A var client = new pg.Client(connectionString);%0A client.connect(function(err) %7B%0A if(err) %7B%0A return console.error('could not connect to postgres');%0A %7D%0A client.query('select * from users', function(err, result) %7B%0A if(err) %7B%0A return console.error('error running query', err);%0A %7D%0A res.send(result);%0A client.end();%0A %7D);%0A %7D);%0A%0A%7D);%0A// app.get('/public/db', function (request, response) %7B%0A// pg.connect(process.env.DATABASE_URL, function(err, client, done) %7B%0A// client.query('SELECT * FROM users', function(err, result) %7B%0A// done();%0A// if (err)%0A// %7B console.error(err); response.send('Error ' + err); %7D%0A// else%0A// %7Bconsole.log('No error jessica!');%7D%0A// // %7B response.render('pages/db', %7Bresults: result.rows%7D ); %7D%0A// %7D);%0A// %7D);%0A//%0A// %7D);%0A
%0Aapp
@@ -144,16 +144,17 @@
, res) %7B
+%0A
%0A var c
|
25969e20f812e56531a591eba207eabee15a69aa
|
add status code to index.html response
|
server.js
|
server.js
|
"use strict";
var http = require("http");
var fs = require("fs");
var increasePrefix = require("./increase-prefix");
var keyRange = require("./key-range");
var ecstatic = require("ecstatic");
var generateQrCode = require("./generate-qr-code");
function trimTrailingSlash (text) {
return text.replace(/\/$/, "");
}
function renderUrl(key) {
return "http://" + (process.argv[3] || "localhost") + "/" + key.replace("!", "");
}
function internalServerError(res) {
res.statusCode = 500;
res.end("Internal Server Error");
}
function notFound(res) {
res.statusCode = 404;
res.end("Not Found");
}
function redirectTo(res, url) {
res.writeHead(301, {
'Location': url
});
res.end();
}
function addNewKeys(prefix) {
if (!prefix) {
prefix = "0";
} else {
prefix = (parseInt(prefix, 36) + 1).toString(36);
}
return {
prefix: prefix,
keys: keyRange(prefix)
};
}
module.exports = function server(prefix, keys, db) {
function insert(url, cb) {
var batch = db.batch();
if (keys.length === 0) {
var newKeys = addNewKeys(prefix);
keys = newKeys.keys;
prefix = newKeys.prefix;
batch.put("!!prefix", prefix);
}
var key = keys.pop();
batch.put(key, url)
.put(url, key)
.write(function (err) {
cb(err, key);
});
}
function handlePost(req, res) {
var body = "";
req.on("data", function (data) {
body += data.toString();
}).on("end", function () {
body = trimTrailingSlash(body);
db.get(body, function (err, data) {
if (err && err.name === "NotFoundError") {
return insert(body, function (err, key) {
if (err) console.error(err);
res.statusCode = 200;
res.end(renderUrl(key));
});
}
if (err) {
console.error(err);
return internalServerError(res);
}
if (data) {
res.statusCode = 200;
return res.end(renderUrl(data));
}
});
});
}
function handleGet(req, res) {
var key = req.url.split("/")[1];
db.get("!" + key, function (err, data) {
if (err) {
if (err.name == "NotFoundError") {
return notFound(res);
}
console.error(err);
return internalServerError(res);
}
redirectTo(res, data);
});
}
function handleRequest(req, res) {
if (req.method == "POST") {
return handlePost(req, res);
}
if (req.url == "/") {
res.writeHead("Content-type", "text/html");
return fs.createReadStream("./index.html").pipe(res);
}
if (req.url.indexOf("/qr-codes/") === 0) {
generateQrCode(req.url, function (err, pngStream) {
if (err) {
console.error(err);
return internalServerError(res);
}
pngStream.pipe(res);
});
}
handleGet(req, res);
}
var staticd = ecstatic({
root: __dirname + "/public",
handleError: false,
cache: 3600,
showDir: false,
autoIndex: false,
defaultExt: "html"
});
return http.createServer(function (req, res) {
staticd(req, res, function () {
handleRequest(req, res);
});
});
};
|
JavaScript
| 0.000001 |
@@ -2913,16 +2913,22 @@
iteHead(
+200, %7B
%22Content
@@ -2933,17 +2933,17 @@
nt-type%22
-,
+:
%22text/h
@@ -2946,16 +2946,17 @@
xt/html%22
+%7D
);%0A
|
12223d2a37214097aed9350886680172b4424b91
|
Fix Express problem
|
server.js
|
server.js
|
var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var fallback = require('express-history-api-fallback')
var app = express();
app.set('port', (process.env.PORT || 3000));
var root = __dirname + '/dist'
app.use('/', express.static(root));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(fallback('index.html', { root: root }))
app.listen(app.get('port'), function() {
console.log('Server started: http://localhost:' + app.get('port') + '/');
});
|
JavaScript
| 0.000004 |
@@ -307,24 +307,60 @@
tic(root));%0A
+app.use('*', express.static(root));%0A
app.use(body
@@ -422,24 +422,27 @@
: true%7D));%0A%0A
+//
app.use(fall
|
a2ab6f1fbe7a9af036f86afc851e62ea349f75c7
|
clear cache
|
server.js
|
server.js
|
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.listen(app.get('port'), function() {
console.log('The server is running at ' + app.get('port'));
});
|
JavaScript
| 0.000001 |
@@ -31,19 +31,22 @@
');%0Avar
-app
+server
= expre
@@ -52,19 +52,22 @@
ess();%0A%0A
-app
+server
.set('po
@@ -100,19 +100,22 @@
5000));%0A
-app
+server
.use(exp
@@ -156,19 +156,137 @@
);%0A%0A
-app
+server.get('/', function(request, response)%7B%0A response.sendFile('public/project.html', %7B root: __dirname %7D);%0A%7D);%0A%0Aserver
.listen(
app.
@@ -281,19 +281,22 @@
.listen(
-app
+server
.get('po
@@ -311,17 +311,16 @@
nction()
-
%7B%0A cons
@@ -361,11 +361,14 @@
' +
-app
+server
.get
|
ee7d1e3d5f4537c26b571aab6c7384bf7894b9d2
|
Exclude phet-io-client-guides from lint, see https://github.com/phetsims/phet-io/issues/1815
|
js/grunt/lint.js
|
js/grunt/lint.js
|
// Copyright 2017-2022, University of Colorado Boulder
/**
* Runs the lint rules on the specified files.
*
* @author Sam Reid (PhET Interactive Simulations)
* @author Michael Kauzmann (PhET Interactive Simulations)
*/
// modules
const _ = require( 'lodash' ); // eslint-disable-line require-statement-match
const { ESLint } = require( 'eslint' ); // eslint-disable-line
const fs = require( 'fs' );
const grunt = require( 'grunt' );
const crypto = require( 'crypto' );
// constants
const EXCLUDE_PATTERNS = [ // patterns that have no code that should be linted
'../babel',
'../decaf',
'../phet-android-app',
'../phet-info',
'../phet-io-website',
'../phet-io-wrapper-arithmetic',
'../phet-io-wrapper-hookes-law-energy',
'../phet-ios-app',
'../qa',
'../smithers',
'../tasks'
];
/**
* Lints the specified repositories.
* @public
*
* @returns {Promise} - results from linting files, see ESLint.lintFiles
*/
const lint = async ( patterns, options ) => {
options = _.assignIn( {
cache: true,
format: false, // append an extra set of rules for formatting code.
fix: false, // whether fixes should be written to disk
warn: true // whether errors should reported with grunt.warn
}, options );
// filter out all unlintable pattern. An unlintable repo is one that has no `js` in it, so it will fail when trying to
// lint it. Also, if the user doesn't have some repos checked out, those should be skipped
patterns = patterns.filter( pattern => !EXCLUDE_PATTERNS.includes( pattern ) &&
fs.existsSync( pattern ) );
const hash = crypto.createHash( 'md5' )
.update( patterns.join( ',' ) )
.digest( 'hex' );
const eslintConfig = {
// optional auto-fix
fix: options.fix,
// Caching only checks changed files or when the list of rules is changed. Changing the implementation of a
// custom rule does not invalidate the cache. Caches are declared in .eslintcache files in the directory where
// grunt was run from.
cache: options.cache,
// Where to store the target-specific cache file
cacheLocation: `../chipper/eslint/cache/${hash}.eslintcache`,
ignorePath: '../chipper/eslint/.eslintignore',
resolvePluginsRelativeTo: '../chipper/',
// Our custom rules live here
rulePaths: [ '../chipper/eslint/rules' ],
extensions: [ '.js', '.ts' ]
};
if ( options.format ) {
eslintConfig.baseConfig = {
extends: [ '../chipper/eslint/format_eslintrc.js' ]
};
}
const eslint = new ESLint( eslintConfig );
grunt.verbose.writeln( `linting: ${patterns.join( ', ' )}` );
// 2. Lint files. This doesn't modify target files.
const results = await eslint.lintFiles( patterns );
// 3. Modify the files with the fixed code.
if ( options.fix ) {
await ESLint.outputFixes( results );
}
// 4. Parse the results.
const totalWarnings = _.sum( results.map( result => result.warningCount ) );
const totalErrors = _.sum( results.map( result => result.errorCount ) );
// 5. Output results on errors.
if ( totalWarnings + totalErrors > 0 ) {
const formatter = await eslint.loadFormatter( 'stylish' );
const resultText = formatter.format( results );
console.log( resultText );
options.warn && grunt.fail.warn( `${totalErrors} errors and ${totalWarnings} warnings` );
}
return results;
};
// Mark the version so that the pre-commit hook will only try to use the promise-based API, this means
// it won't run lint precommit hook on SHAs before the promise-based API
lint.chipperAPIVersion = 'promises1';
module.exports = lint;
|
JavaScript
| 0.000001 |
@@ -634,16 +634,46 @@
-info',%0A
+ '../phet-io-client-guides',%0A
'../ph
|
c4af8405f9e7276a0fbe2e29e4f8cc71b162d5dc
|
Use `base_url` http header (rollback) when no BASE_PATH env var provided (#23)
|
server.js
|
server.js
|
/* jshint node: true, browser: false */
'use strict';
// CREATE HTTP SERVER AND PROXY
const path = require('path');
const express = require('express');
const app = express();
const basePath = path.join('/', process.env.BASE_PATH||'/', '/');
if(!process.env.BASE_PATH) console.error(`WARNING: environment BASE_PATH not set. USING default`);
app.set('views', __dirname + '/app');
app.set('view engine', 'ejs');
// LOAD CONFIGURATION
app.set('port', process.env.PORT || 8000);
// CONFIGURE /APP/* ROUTES
const appRoutes = new express.Router();
appRoutes.use('/app', require('serve-static')(__dirname + '/app_build'));
appRoutes.use('/app', require('serve-static')(__dirname + '/app'));
appRoutes.all('/app/*', (req, res) => res.status(404).send());
appRoutes.get('/*', (req, res) => res.render('template', { baseUrl: basePath }));
// START SERVER
app.use(basePath, appRoutes);
if(basePath!='/') app.use('/', appRoutes); // temps support for transition to Traefik 2 / AWS ALB
app.listen(app.get('port'), function () {
console.log('Server listening on %j', this.address());
});
|
JavaScript
| 0 |
@@ -201,22 +201,42 @@
= p
-ath.join('/',
+rocess.env.BASE_PATH ? toBasePath(
proc
@@ -256,19 +256,16 @@
PATH
-%7C%7C'/', '/')
+) : null
;%0A%0Ai
@@ -351,16 +351,49 @@
. USING
+'base_url' http header or '/' as
default%60
@@ -844,24 +844,97 @@
req, res) =%3E
+ %7B %0A const baseUrl = toBasePath(basePath %7C%7C req.headers.base_url);%0A
res.render(
@@ -960,19 +960,29 @@
rl:
-basePath
+urlSafe(baseUrl)
%7D)
+%0A%7D
);%0A%0A
@@ -1010,228 +1010,359 @@
use(
-b
+toB
asePath
-, appRoutes);%0A%0Aif(basePath!='/') app.use('/', appRoutes); // temps support for transition to Traefik 2 / AWS ALB%0A%0Aapp.listen(app.get('port'), function () %7B%0A%09console.log('Server listening on %25j', this.address());%0A%7D);%0A
+(basePath), appRoutes);%0A%0Aapp.listen(app.get('port'), function () %7B%0A%09console.log('Server listening on %25j', this.address());%0A%7D);%0A%0Afunction toBasePath(dir) %7B%0A return path.join('/', dir %7C%7C '/', '/');%0A%7D%0A%0Afunction urlSafe(dir) %7B%0A var parts = dir.split('/').map(o=%3EencodeURIComponent(o));%0A return path.join.apply(null, parts.map(o=%3Eo%7C%7C'/'));%0A%7D
|
d1c131ee4b08ef9439901fc64aa2948818d8f9ca
|
fix skybox refs
|
Sources/Interaction/Misc/DeviceOrientationToCamera/example/index.js
|
Sources/Interaction/Misc/DeviceOrientationToCamera/example/index.js
|
import 'vtk.js/Sources/favicon';
// Load the rendering pieces we want to use (for both WebGL and WebGPU)
import 'vtk.js/Sources/Rendering/Profiles/Geometry';
import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
import vtkHttpDataSetReader from 'vtk.js/Sources/IO/Core/HttpDataSetReader';
import vtkFullScreenRenderWindow from 'vtk.js/Sources/Rendering/Misc/FullScreenRenderWindow';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import vtkCubeSource from 'vtk.js/Sources/Filters/Sources/CubeSource';
import vtkTexture from 'vtk.js/Sources/Rendering/Core/Texture';
import vtkDeviceOrientationToCamera from 'vtk.js/Sources/Interaction/Misc/DeviceOrientationToCamera';
// ----------------------------------------------------------------------------
// Standard rendering code setup
// ----------------------------------------------------------------------------
const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
background: [0, 0, 0],
});
const renderer = fullScreenRenderer.getRenderer();
const renderWindow = fullScreenRenderer.getRenderWindow();
const interactor = fullScreenRenderer.getInteractor();
// ----------------------------------------------------------------------------
// Example code
// ----------------------------------------------------------------------------
let cameraListenerId = -1;
let nbTextureLoaded = 0;
const texture = vtkTexture.newInstance();
const texturePathList = [
`${__BASE_PATH__}/data/skybox/mountains/px.vti`,
`${__BASE_PATH__}/data/skybox/mountains/nx.vti`,
`${__BASE_PATH__}/data/skybox/mountains/py.vti`,
`${__BASE_PATH__}/data/skybox/mountains/ny.vti`,
`${__BASE_PATH__}/data/skybox/mountains/pz.vti`,
`${__BASE_PATH__}/data/skybox/mountains/nz.vti`,
];
const cube = vtkCubeSource.newInstance();
cube.setGenerate3DTextureCoordinates(true);
const mapper = vtkMapper.newInstance();
mapper.setInputConnection(cube.getOutputPort());
const actor = vtkActor.newInstance();
actor.getProperty().setDiffuse(0.0);
actor.getProperty().setAmbient(1.0);
actor.setMapper(mapper);
actor.addTexture(texture);
function render() {
renderer.resetCameraClippingRange();
renderWindow.render();
}
function dataReady() {
const bounds = renderer.computeVisiblePropBounds();
const scale = 500;
cube.setBounds(
bounds[0] * scale,
bounds[1] * scale,
bounds[2] * scale,
bounds[3] * scale,
bounds[4] * scale,
bounds[5] * scale
);
renderer.addActor(actor);
renderer.getActiveCamera().setPhysicalViewUp(0, -1, 0);
renderer.getActiveCamera().setPhysicalViewNorth(0, 0, 1);
renderer.getActiveCamera().setFocalPoint(0, 0, 1);
renderer.getActiveCamera().setPosition(0, 0, -50);
renderer.getActiveCamera().setViewAngle(80);
renderer.resetCameraClippingRange();
render();
}
function loadTexture(url, index) {
const reader = vtkHttpDataSetReader.newInstance({ fetchGzip: true });
reader.setUrl(url, { loadData: true }).then(() => {
const dataset = reader.getOutputData();
const scalarName = dataset.getPointData().getArrayByIndex(0).getName();
dataset.getPointData().setActiveScalars(scalarName);
texture.setInputData(dataset, index);
nbTextureLoaded += 1;
if (nbTextureLoaded === texturePathList.length) {
dataReady();
}
});
}
/* eslint-disable no-alert */
function validateMotionDetectionAgain() {
if (!vtkDeviceOrientationToCamera.isDeviceOrientationSupported()) {
vtkDeviceOrientationToCamera.removeCameraToSynchronize(cameraListenerId);
vtkDeviceOrientationToCamera.removeWindowListeners();
alert('No motion have been detected. Freeing the camera.');
}
}
// Trigger the loading of the texture in parallel
texturePathList.forEach(loadTexture);
// If device support motion bind it to the camera
if (vtkDeviceOrientationToCamera.isDeviceOrientationSupported()) {
vtkDeviceOrientationToCamera.addWindowListeners();
cameraListenerId = vtkDeviceOrientationToCamera.addCameraToSynchronize(
interactor,
renderer.getActiveCamera(),
renderer.resetCameraClippingRange
);
} else {
alert(
'Your device does not support motion detection so regular interaction will be available'
);
}
/* eslint-enable no-alert */
setTimeout(validateMotionDetectionAgain, 100);
|
JavaScript
| 0 |
@@ -153,16 +153,102 @@
etry';%0A%0A
+import 'vtk.js/Sources/IO/Core/DataAccessHelper/HttpDataAccessHelper'; // HTTP + zip%0A%0A
import v
@@ -1570,14 +1570,17 @@
ins/
-px.vti
+right.jpg
%60,%0A
@@ -1624,14 +1624,16 @@
ins/
-nx.vti
+left.jpg
%60,%0A
@@ -1677,14 +1677,18 @@
ins/
-py.vti
+bottom.jpg
%60,%0A
@@ -1732,14 +1732,15 @@
ins/
-ny.vti
+top.jpg
%60,%0A
@@ -1784,14 +1784,17 @@
ins/
-pz.vti
+front.jpg
%60,%0A
@@ -1838,14 +1838,16 @@
ins/
-nz.vti
+back.jpg
%60,%0A%5D
|
2107175a2a77f716e98236dd6138f461b39dbac9
|
Add note to future self that we still need to scope the history request to the current request
|
_temp/hud/src/repository.js
|
_temp/hud/src/repository.js
|
'use strict';
var $ = require('$jquery');
var messageProcessor = require('./util/request-message-processor');
var process = (function() {
var getIndex = function(messages) {
var index = {}
for (var i = 0; i < messages.length; i++) {
var message = messages[i];
for (var x = 0; x < message.types.length; x++) {
var type = message.types[x];
if (!index[type]) {
index[type] = [];
}
index[type].push(message);
}
}
return index;
};
var getPayload = function(index) {
var processItem = messageProcessor.getTypeMessageItem;
var processList = messageProcessor.getTypeMessageList;
return messageProcessor.getTypeMessages(index, {
'begin-request': processItem,
'environment': processItem,
'user-identification': processItem,
//'browser-navigation-timing': processItem,
'after-action-invoked': processItem,
'after-action-view-invoked': processItem,
'after-execute-command': processList,
'end-request': processItem
});
}
var getModel = (function() {
var add = function(model, item, name) {
model[name] = {
'data': item,
'name': name
};
}
var strategies = {
environment: function(payload) {
var environment = payload.environment || {};
var userIdentification = payload.userIdentification || {};
var result = {};
result.serverName = environment.serverName;
result.serverTime = environment.serverTime;
result.serverTimezoneOffset = environment.serverTimezoneOffset;
result.serverDaylightSavingTime = environment.serverDaylightSavingTime;
result.user = userIdentification.username;
return result;
},
mvc: function(payload) {
var afterActionInvoked = payload.afterActionInvoked || {};
var afterActionViewInvoked = payload.afterActionViewInvoked || {};
var result = {};
result.actionName = afterActionInvoked.actionName;
result.controllerName = afterActionInvoked.actionControllerName;
result.actionExecutionTime = afterActionInvoked.actionInvokedDuration;
result.viewRenderTime = afterActionViewInvoked.viewDuration;
// result.viewName = '';
// result.childActionCount = 0;
// result.childViewCount = 0;
// result.matchedRouteName = 0;
return result;
},
sql: function(payload) {
var afterExecuteCommand = payload.afterExecuteCommand || [];
var result = {};
result.queryCount = afterExecuteCommand.length;
// result.connectionCount = 0;
// result.transactionCount = 0;
// result.connectionOpenTime = 0;
result.queryExecutionTime = 0;
for (var i = 0; i < afterExecuteCommand.length; i++) {
result.queryExecutionTime += afterExecuteCommand[i].commandDuration;
}
return result;
},
request: function(payload) {
var beginRequest = payload.beginRequest || {};
var endRequest = payload.endRequest || {};
//var browserNavigationTiming = payload.browserNavigationTiming || {};
var result = {};
result.requestMethod = beginRequest.requestMethod;
result.requestUrl = beginRequest.requestUrl;
result.requestPath = beginRequest.requestPath;
result.requestQueryString = beginRequest.requestQueryString;
result.responseContentLength = endRequest.responseContentLength;
result.responseContentType = endRequest.responseContentType;
result.responseStatusCode = endRequest.responseStatusCode;
result.responseStatusText = endRequest.responseStatusText;
result.responseDuration = endRequest.responseDuration;
return result;
},
timings: function(payload) {
return [];
}
};
return function(payload) {
var model = {};
add(model, strategies.environment(payload), 'environment');
add(model, strategies.mvc(payload), 'mvc');
add(model, strategies.sql(payload), 'sql');
add(model, strategies.request(payload), 'request');
add(model, strategies.timings(payload), 'timings');
return model;
};
})();
return function(messages) {
var index = getIndex(messages);
var payload = getPayload(index);
var model = getModel(payload);
return model;
};
})();
var getData = function(callback) {
// TODO: need to use message history template here instead of it being hard coded
$.getJSON('/glimpse/message-history/?types=environment,user-identification,end-request,begin-request,after-action-invoked,after-action-view-invoked,after-execute-command', null, function(data) {
var model = process(data);
callback(model);
});
}
module.exports = {
getData: getData
};
|
JavaScript
| 0 |
@@ -4228,16 +4228,71 @@
d coded%0A
+%09// TODO: currently not targetting current request!!!!%0A
%09$.getJS
|
5fa17a11021b21c80d869f21abbb8521ab2b0973
|
removed false positive
|
helper/rss.js
|
helper/rss.js
|
var request = require( 'request' );
var parseString = require('xml2js').parseString;
module.exports = {
load: function( url, cb ){
var self = this;
request.get(url, function(status, response) {
if( response.headers[ 'content-type' ].indexOf( 'text/xml;' ) === 0 ){
self.parseXml( response.body, cb );
} else {
cb( { err: 500, message: 'Wrong contenttype of rss-response'} );
}
}, function(){
cb( { err: 500, message: 'RSS Request went wrong'} );
});
},
parseXml: function( rss, cb ){
var self = this;
parseString( rss, { explicitArray: false, charkey: 'content' }, function( err, result ){
if( err ){
cb( { err: 500, message: 'Parsing RSS went wrong'} );
} else {
cb( { podcast: result.rss.channel});
}
});
}
};
|
JavaScript
| 0.999997 |
@@ -407,19 +407,94 @@
unction(
-)%7B%0A
+err, res)%7B%0A%09%09%09if(!err, res) %7B%0A%09%09%09%09self.parseXml( res.body, cb );%0A%09%09%09%7D else %7B%0A%09
%09%09%09cb( %7B
@@ -542,16 +542,21 @@
ng'%7D );%0A
+%09%09%09%7D%0A
%09%09%7D);%0A%09%7D
|
ab3c323f333996ac73157a634434d44186c2caef
|
Increase token size
|
database.js
|
database.js
|
const loki = require("lokijs");
let db = new loki("data.js");
let messages = db.addCollection("messages");
let sessions = db.addCollection("sessions"):
let _exports = module.exports = {};
function clean_message(msg) {
delete msg.secret;
msg.timestamp = (new Date()).getTime() / 1000;
}
_exports.store_message = function (msg) {
messages.insert( clean_message(msg) );
}
_exports.get_messages = function (timestamp) {
return messages.find( {"time" : {"$gte" : timestamp} } );
}
_exports.get_session = function (token) {
return sessions.find( {"token" : token} );
}
_exports.generate_session = function (session) {
token = require('crypto').randomBytes(16).toString('hex');
if ( _exports.get_session(token) ) {
return _exports.generate_session(session);
}
session.token = token;
sessions.insert( session );
return token;
}
|
JavaScript
| 0.000001 |
@@ -660,10 +660,10 @@
tes(
-1
6
+4
).to
|
5c30878babea4c6827271f54742618d53f76bc80
|
Fix datetime problem
|
helpers/db.js
|
helpers/db.js
|
module.exports = function (options) {
/**
* Module options
*/
var client = require('mysql').createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'itineraris'
});
var replaceAll = function (replace, value, object) {
console.log(parseInt(object));
if (parseInt(object) != NaN)
return object;
else
return object.replace(new RegExp(replace, 'g'), value);
};
var all = function (entity, callback) {
client.query('SELECT * FROM ' + entity, function (error, results, fields) {
callback(error, results, fields);
});
};
var byFields = function (entity, properties, callback) {
var values = '';
for (var property in properties) {
if (properties.hasOwnProperty(property)) {
if (property == 'multiple') {
values += '(';
for (var multipleProperty in properties['multiple']) {
values += multipleProperty + '=\'' + properties['multiple'][multipleProperty] + '\' OR ';
}
values = values.substr(0, values.length - 4);
values += ') AND ';
}
else {
values += property + '=\'' + properties[property] + '\'';
values += ' AND ';
}
}
}
if (values.length > 0)
values = values.substr(0, values.length - 5);
client.query('SELECT * FROM ' + entity + ' WHERE ' + values, function (error, results, fields) {
callback(error, results, fields);
});
};
var addArray = function (entity, arrayOfProperties, callback) {
var array = [];
var errorr = {};
var fieldss = {};
arrayOfProperties.forEach(function (element) {
add(entity, element, function (error, results, fields) {
element['id'] = results.insertId;
array.push(element);
errorr = error;
fieldss = fields;
if(array.length == arrayOfProperties.length)
callback(errorr, array, fieldss);
});
});
};
var add = function (entity, properties, callback) {
var columns = '';
var values = '';
for (var property in properties) {
if (properties.hasOwnProperty(property)) {
columns += property + ', ';
values += '\'' + replaceAll("'", "''", properties[property]) + '\', ';
}
}
if (columns.length > 0)
columns = columns.substr(0, columns.length - 2);
if (values.length > 0)
values = values.substr(0, values.length - 2);
console.log(columns);
console.log(values);
client.query('INSERT INTO ' + entity + ' (' + columns + ') VALUES (' + values + ')', function (error, results, fields) {
callback(error, results, fields);
});
};
var updateArray = function (entity, arrayOfProperties, callback) {
var array = [];
var errorr = {};
var fieldss = {};
arrayOfProperties.forEach(function (element) {
var id = element.id;
delete element.id;
console.log(element);
console.log(id);
update(entity, element, { id: id }, function (error, results, fields) {
array.push(element);
errorr = error;
fieldss = fields;
if(array.length == arrayOfProperties.length)
callback(errorr, array, fieldss);
});
});
};
var update = function (entity, properties, whereProperties, callback) {
var values = '';
var whereClause = '';
for (var property in properties) {
if (properties.hasOwnProperty(property)) {
values += property + '=\'' + replaceAll("'", "''", properties[property]) + '\', ';
}
}
for (var property in whereProperties) {
if (whereProperties.hasOwnProperty(property)) {
whereClause += property + '=\'' + replaceAll("'", "''", whereProperties[property]) + '\' AND ';
}
}
if (values.length > 0)
values = values.substr(0, values.length - 2);
if (whereClause.length > 0)
whereClause = whereClause.substr(0, whereClause.length - 5);
console.log(values);
console.log(whereClause);
client.query('UPDATE ' + entity + ' SET ' + values + ' WHERE ' + whereClause, function (error, results, fields) {
callback(error, results, fields);
});
};
var remove = function (entity, properties, callback) {
var values = '';
for (var property in properties) {
if (properties.hasOwnProperty(property)) {
values += property + '=\'' + replaceAll("'", "''", properties[property]) + '\' AND ';
}
}
if (values.length > 0)
values = values.substr(0, values.length - 5);
client.query('DELETE FROM ' + entity + ' WHERE ' + values, function (error, results, fields) {
callback(error, results, fields);
});
};
return {
"open": function open() {
client.connect();
},
"all": all,
"addArray": addArray,
"updateArray": updateArray,
"add": add,
"update": update,
"remove": remove,
"byFields": byFields,
/**
* Allow disconnection
*/
"close": function disconnect(callback) {
client.end(callback);
}
};
};
|
JavaScript
| 0.99998 |
@@ -187,16 +187,37 @@
neraris'
+,%0A%09%09timezone: '+0000'
%0A%09%7D);%0A%0A%09
@@ -273,47 +273,14 @@
) %7B%0A
-%09%09console.log(parseInt(object));%0A%0A
%09%09if
+(
(par
@@ -296,15 +296,23 @@
ect)
+ + '')
!=
+'
NaN
+'
)%0A%09%09
@@ -2253,56 +2253,8 @@
);%0A%0A
-%09%09console.log(columns);%0A%09%09console.log(values);%0A%0A
%09%09cl
@@ -2646,57 +2646,8 @@
d;%0A%0A
-%09%09%09console.log(element);%0A%09%09%09console.log(id);%0A%09%09%09%0A
%09%09%09u
@@ -3561,60 +3561,8 @@
);%0A%0A
-%09%09console.log(values);%0A%09%09console.log(whereClause);%0A%0A
%09%09cl
|
30fcb8bdd47bfbbc277bc4c114263f5f198f303c
|
delete test log
|
server.js
|
server.js
|
// -----------------------------------------------------------------------------
// server configuration
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// requirements
var americano = require( 'americano' );
var logger = require( './server/models/logger' );
logger.info( 'zdsqkfsj' );
// -----------------------------------------------------------------------------
// launch americano server
americano.start({
name: process.env.NAME || "",
port: process.env.PORT || 9200
});
|
JavaScript
| 0.000001 |
@@ -321,89 +321,8 @@
);%0A
-var logger = require( './server/models/logger' );%0A%0A%0Alogger.info( 'zdsqkfsj' );
%0A//
|
d0b0423b2d4ef343d09bb27063d8b8162fb7d466
|
Refactor solution to use regex and map
|
day10/10.js
|
day10/10.js
|
// look for groups of matching characters
// pass each group to say() and concatenate returns
var look = function(lookString) {
var i = 0;
var j = 1;
var sayString = '';
while (i < lookString.length) {
while (lookString[i] === lookString[j]) {
j++;
}
sayString += say(lookString.slice(i,j));
i += (j - i);
}
return sayString;
}
// convert a group of matching characters to
// the replacement sequence
var say = function(group) {
var output = 0;
return '' + group.length + group[0];
}
// run look-and-say on a given input n times and
// print the result's length to the console.
var lookAndSay = function(input, n) {
var lastString = input;
for (var i = 0; i < n; i++) {
lastString = look(lastString);
}
console.log(lastString.length);
}
lookAndSay('1321131112', 50);
|
JavaScript
| 0 |
@@ -1,12 +1,12 @@
//
-l
+L
ook for
@@ -38,412 +38,94 @@
ters
+.
%0A//
-pass each group to say() and concatenate returns%0Avar look = function(lookString) %7B%0A var i = 0;%0A var j = 1;%0A var sayString = '';%0A%0A while (i %3C lookString.length) %7B%0A while (lookString%5Bi%5D === lookString%5Bj%5D) %7B%0A j++;%0A %7D%0A sayString += say(lookString.slice(i,j));%0A i += (j - i);%0A %7D%0A%0A return sayString;%0A%7D%0A%0A// convert a group of matching characters to%0A// the replacement sequence%0Avar say
+Map the conversion function to each.%0A// Join & return the new string.%0Avar convert
= f
@@ -132,21 +132,21 @@
unction(
-group
+input
) %7B%0A va
@@ -151,57 +151,92 @@
var
-output = 0;%0A return '' + group.length + group%5B0%5D
+groups = input.match(/(%5Cd)%5C1*/g);%0A return groups.map(s =%3E s.length + s%5B0%5D).join('')
;%0A%7D%0A
@@ -398,36 +398,19 @@
ut;%0A
- for (var i = 0; i %3C n; i++
+%0A while (n
) %7B%0A
@@ -426,20 +426,23 @@
tring =
-look
+convert
(lastStr
@@ -447,16 +447,25 @@
tring);%0A
+ n--;%0A
%7D%0A%0A c
|
0415e5c6a3688dcaf79163262b25b2a4101213e0
|
修改页面刷新3
|
app/controllers/RoomCtrl.js
|
app/controllers/RoomCtrl.js
|
angular.module('chatMod').controller('RoomCtrl',function($scope,$http,$rootScope,$routeParams,$location){
/*
* 1 在控制器中注入$routeParams 这是一个对象,key是路径占位符,值就是路径里占位符对应的字符串
* 2 评出url /rooms/真实id 调用后台接口得到room对象
* 3 后台编写一个路由响应这个请求 app.get('/rooms/:_id')
* 4 通过Room模型的findById方法传入id,得到room对象并返回客户端
* 5 客户端拿到room赋给$scope.room
*
* */
var _id = $routeParams.id;
$http({
url:`/rooms/${_id}`,
method:'GET'
}).success(function(result){
console.log(result);
if(result.err==1){
$rootScope.errMsg = result.msg;
}else{
$scope.room = result.data;
}
});
/*
* 开始聊天
* 1 在后台引入socket.io 监听客户端的连接请求
* 2 在前台连接后台的socketio服务器
* 3 在前台发送消息给后台,后台保存当前房间里messages数组中,并且通过所有的客户端添加此消息
*
* */
var socket = io.connect(`/`);
//本机测试使用ws://localhost:9090/ 服务器使用IP地址47.88.150.99
//或者使用`/`, 或者window.location
socket.on('message',function(msgObj){
//console.log(msgObj);
$scope.room.messages.push(msgObj);
$scope.room.messages = $scope.room.messages.filter(function(item){
return true;
});
/*$scope.room.users = $scope.room.users.filter(function(item){
return true;
});*/
$scope.content = '';
//$scope.room.users.push(msgObj.user);
});
$scope.send = function(){
socket.send({
user:$rootScope.user,
content:$scope.content
});
};
});
angular.module('chatMod').directive('keyDown',function(){
return {
link:function(scope,element,attrs){
element.keydown(function(event){
console.log(event.keyCode);
if(event.keyCode==13){
/*
* 在scope作用域下调用方法
* */
scope.$eval(attrs.keyDown);
}
});
}
}
});
|
JavaScript
| 0 |
@@ -987,32 +987,61 @@
le.log(msgObj);%0A
+ console.log('%E6%8E%A5%E6%94%B6%E4%BF%A1%E6%81%AF');%0A
$scope.r
@@ -1059,32 +1059,61 @@
s.push(msgObj);%0A
+ console.log('%E5%88%B7%E6%96%B0%E4%BF%A1%E6%81%AF');%0A
$scope.r
@@ -1188,32 +1188,32 @@
return true;%0A
-
%7D);%0A
@@ -1200,32 +1200,61 @@
ue;%0A %7D);%0A
+ console.log('%E5%88%B7%E6%96%B0%E5%AE%8C%E6%AF%95');%0A
/*$scope
@@ -1898,24 +1898,65 @@
* */%0A
+ console.log('%E5%8F%91%E9%80%81%E4%BF%A1%E6%81%AF');%0A
|
bed042d5ccc83a9b5092e839cad97e5190c57bec
|
Fix TrackerReports
|
lib/Models/trackerReports.js
|
lib/Models/trackerReports.js
|
/**
* TrackerReports module
* @module Tuleap/Models/trackerReports
*/
'use strict';
/**
* Standard request cb
* @callback requestCallback
* @param {Error} Error
* @param {object} Data
*/
var Utils = require('../utils.js');
var Debug = require('debug')('Tuleap:TrackerReports');
/**
* @class
* @param {object} client - API client
* @constructor
*/
var TrackerReports = function (client) {
this.path = '/tracker_reports/';
this.client = client;
};
/**
* Endpoint: GET /tracker_reports/{id}
* https://tuleap.net/api/explorer/#!/tracker_reports/retrieveId
* Get the definition of the given report.
*
* @param {object} query - Query parameters
* @param {number} query.id - Tracker id
* @param {requestCallback} cb - The callback function
* @returns {object} - Request object
*/
TrackerReports.prototype.report = function (query, cb) {
Debug('Report query:' + query);
return this.client
.get(
this.path + query.id,
{},
function (err, res, data) {
cb.apply(null, Utils.resParse(err, res, data));
}
);
};
/**
* Endpoint: GET /tracker_reports/{id}/artifacts
* https://tuleap.net/api/explorer/#!/tracker_reports/retrieveArtifacts
* Get artifacts matching criteria of a report.
*
* @param {object} query - Query parameters
* @param {number} query.id - Tracker id
* @param {number} [query.limit=100] - Results limit
* @param {number} [query.offset=0] - Results offset
* @param {requestCallback} cb - The callback function
* @returns {object} - Request object
*/
TrackerReports.prototype.artifacts = function (query, cb) {
Debug('Artifacts query:', query);
var qr = {
values: 'all',
limit: query.limit || 100,
offset: query.offset || 0
};
return this.client
.get(
this.path + query.id + '/artifacts',
{query: qr},
function (err, res, data) {
cb.apply(null, Utils.resParse(err, res, data));
}
);
};
/**
* TrackerReports module exported
*
* @type {TrackerReports}
*/
module.exports = TrackerReports;
|
JavaScript
| 0 |
@@ -398,16 +398,75 @@
ient) %7B%0A
+%09if (!client) %7B%0A%09%09throw new Error('No client object.');%0A%09%7D%0A
%09this.pa
|
fb12120ecb5b64639922f9a13d41fffa67e19bbd
|
Add semicolon
|
js/lights-out.js
|
js/lights-out.js
|
var numRows = 4
var numCols = 4
var matrix = [
[undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined]
]
var solution = [
[undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined]
]
var showSolution = false
function getLightId(row, col) {
return "#light-" + row + "-" + col
}
function setLightColor(row, col) {
var color;
if (matrix[row][col]) {
color = "pink"
} else {
color = "gray"
}
var lightId = getLightId(row, col);
$(lightId).css("background-color", color)
}
for (var row = 0; row < numRows; row++) {
for (var col = 0; col < numCols; col++) {
matrix[row][col] = Math.random() < 0.5
setLightColor(row, col)
}
}
if (showSolution) {
solve();
}
function above(row) {
if (row == 0) {
return numRows -1
} else {
return row - 1
}
}
function below(row) {
if (row == numRows - 1) {
return 0
} else {
return row + 1
}
}
function left(col) {
if (col == 0) {
return numCols -1
} else {
return col - 1
}
}
function right(col) {
if (col == numCols - 1) {
return 0
} else {
return col + 1
}
}
function lightSwitch(row, col) {
matrix[row][col] = !matrix[row][col]
setLightColor(row, col)
}
function checkWin() {
var anyLightOn = false
for (var row = 0; row < numRows; row++) {
for (var col = 0; col < numCols; col++) {
if (matrix[row][col]) {
anyLightOn = true;
}
}
}
return !anyLightOn;
}
function lightClick(row, col) {
lightSwitch(row, col)
lightSwitch(above(row), col)
lightSwitch(below(row), col)
lightSwitch(row, left(col))
lightSwitch(row, right(col))
if (checkWin()) {
alert("You win!")
}
if (showSolution) {
solve();
}
}
function solutionSwitch(row, col) {
solution[row][col] = !solution[row][col]
}
function solutionClick(row, col) {
solutionSwitch(row, col)
solutionSwitch(above(row), col)
solutionSwitch(below(row), col)
solutionSwitch(row, left(col))
solutionSwitch(row, right(col))
}
function solve() {
solution = [
[false, false, false, false],
[false, false, false, false],
[false, false, false, false],
[false, false, false, false]
]
for (var row = 0; row < numRows; row++) {
for (var col = 0; col < numCols; col++) {
if (matrix[row][col]) {
solutionClick(row, col)
}
}
}
for (var row = 0; row < numRows; row++) {
for (var col = 0; col < numCols; col++) {
var lightId = getLightId(row, col)
if (solution[row][col]) {
$(lightId).text("click me")
} else {
$(lightId).text("")
}
}
}
}
function hideSolution() {
for (var row = 0; row < numRows; row++) {
for (var col = 0; col < numCols; col++) {
var lightId = getLightId(row, col)
$(lightId).text("")
}
}
}
function showHideSolution() {
showSolution = !showSolution;
if (showSolution) {
solve();
$("#showHideButton").text("Hide solution")
} else {
hideSolution();
$("#showHideButton").text("Show solution")
}
}
|
JavaScript
| 0.999999 |
@@ -1628,16 +1628,17 @@
= false
+;
%0A%0A fo
|
8b0e8d59864b860f6bab8653699be9c7d7821f06
|
Tweak some action-button tests
|
test/addons/action-button.test.js
|
test/addons/action-button.test.js
|
import React from 'react'
import ActionButton from '../../src/addons/action-button'
import Action from '../../src/action'
import {mount} from 'enzyme'
describe('actions', function () {
it('passes the value property as parameters into the action', function () {
let button = mount(<ActionButton action="test" value={true} />, {
context: {
send: (type, params) => new Action(type).resolve(params)
}
})
let action = button.instance().click()
expect(action.command.toString()).toEqual('test')
expect(action.payload).toBe(true)
})
})
describe('callbacks', function () {
it('executes onOpen when that action completes', function () {
let onOpen = jest.fn()
let button = mount(<ActionButton action="test" onOpen={n => onOpen(n)} />, {
context: {
send: () => new Action(n => n).open(true)
}
})
button.simulate('click')
expect(onOpen).toHaveBeenCalledWith(true)
})
it('executes onDone when that action completes', function () {
let onDone = jest.fn()
let button = mount(<ActionButton action="test" onDone={n => onDone(n)} />, {
context: {
send: () => new Action(n => n).resolve(true)
}
})
button.simulate('click')
expect(onDone).toHaveBeenCalledWith(true)
})
it('executes onError when that action completes', function () {
let onError = jest.fn()
let button = mount(<ActionButton action="test" onError={n => onError(n)} />, {
context: {
send: () => new Action(n => n).reject('bad')
}
})
button.simulate('click')
expect(onError).toHaveBeenCalledWith('bad')
})
it('executes onUpdate when that action sends an update', function () {
let onUpdate = jest.fn()
let action = new Action(n => n)
let button = mount(<ActionButton action="test" onUpdate={n => onUpdate(n)} />, {
context: {
send: () => action
}
})
button.simulate('click')
action.update('loading')
expect(onUpdate).toHaveBeenCalledWith('loading')
})
it('does not execute onDone if not given an action', function () {
let onDone = jest.fn()
mount(<ActionButton action="test" onDone={n => onDone(n)} />, {
context: {
send: () => true
}
}).simulate('click')
expect(onDone).not.toHaveBeenCalled()
})
it('does not execute onDone if not given an action', function () {
let onError = jest.fn()
mount(<ActionButton action="test" onError={n => onError(n)} />, {
context: {
send: () => true
}
}).simulate('click')
expect(onError).not.toHaveBeenCalled()
})
it('does not execute onUpdate if not given an action', function () {
let onUpdate = jest.fn()
mount(<ActionButton action="test" onUpdate={n => onUpdate(n)} />, {
context: {
send: () => true
}
}).simulate('click')
expect(onUpdate).not.toHaveBeenCalled()
})
it('passes along onClick', function () {
let handler = jest.fn()
let wrapper = mount(<ActionButton onClick={handler} />, {
context: {
send: () => {}
}
})
wrapper.simulate('click')
expect(handler).toHaveBeenCalled()
})
})
describe('manual operation', function () {
it('click can be called directly on the component instance', function () {
let onDone = jest.fn()
let button = mount(<ActionButton action="test" onDone={n => onDone(n)} />, {
context: {
send: () => new Action(n => n).resolve(true)
}
})
button.instance().click()
expect(onDone).toHaveBeenCalledWith(true)
})
it('can pass in send manually', function () {
const send = jest.fn()
const button = mount(<ActionButton send={send} />)
button.simulate('click')
expect(send).toHaveBeenCalled()
})
})
describe('rendering', function () {
it('can render with another tag name', function () {
let wrapper = mount(<ActionButton tag="a" action="wut" />)
expect(wrapper.getDOMNode().tagName).toBe('A')
})
it('uses the button type when set as a button', function () {
let wrapper = mount(<ActionButton action="wut" />)
expect(wrapper.getDOMNode().type).toBe('button')
})
it('does not pass the type attribute for non-buttons', function () {
let wrapper = mount(<ActionButton tag="a" action="wut" />)
expect(wrapper.getDOMNode().getAttribute('type')).toBe(null)
})
})
|
JavaScript
| 0.000001 |
@@ -250,32 +250,82 @@
, function () %7B%0A
+ let action = n =%3E n%0A let send = jest.fn()%0A%0A
let button =
@@ -376,242 +376,102 @@
ue%7D
-/%3E, %7B%0A context: %7B%0A send: (type, params) =%3E new Action(type).resolve(params)%0A %7D%0A %7D)%0A%0A let action = button.instance().click()%0A%0A expect(action.command.toString()).toEqual('test')%0A expect(action.payload).toBe(
+send=%7Bsend%7D /%3E)%0A%0A button.instance().click()%0A%0A expect(send).toHaveBeenCalledWith(action,
true
@@ -2257,36 +2257,37 @@
s not execute on
-Done
+Error
if not given an
|
e56ff49bb83575d9270223752f1c664643f5f7e5
|
fix JSDoc.
|
lib/BlobObject.js
|
lib/BlobObject.js
|
/**
* @module BlobObject
* @private
* @mixin
* @description Exports BlobObject class.
*/
import Super from './Super';
import Promise from './Promise';
import constructors from './constants/constructors';
import {
isArray, isFunction,
toStringTag, Symbol, defineProperties
} from './helpers';
/**
* @typedef {{ buffer: String, binary: String, dataURL: String, text: String }} methods
* @private
* @description List of read blob methods.
*/
const methods = {
buffer: 'ArrayBuffer',
binary: 'BinaryString',
dataURL: 'DataURL',
text: 'Text'
};
const URL = global.URL;
/**
* @typedef {('buffer'|'binary'|'dataURL'|'text')} ReadBlobMethod
* @public
* @description Enum type of read blob methods.
*/
/**
* @typedef {ArrayBuffer|ArrayBufferView|Blob|String} BlobParts
* @public
* @description Allowed blob parts.
*/
/**
* @callback ReaderEventListener
* @public
* @param {Event} e - Fired event.
* @param {FileReader} reader - FileReader.
*/
/**
* @class BlobObject
* @extends Super
* @public
* @param {Blob} blob - Blob to wrap.
* @returns {BlobObject} Instance of BlobObject.
* @description Wrap of a blob.
*
* @example
* new BlobObject(new Blob(['{"foo":"bar"}'], { type: 'application/json' }));
*/
export class BlobObject extends Super {
/**
* @member {Blob} BlobObject#$
* @public
* @description Original Blob.
*/
/**
* @method BlobObject#readAs
* @public
* @param {ReadBlobMethod} method - Method that is used for reading from blob.
* @param {ReaderEventListener} [progress] - Progress listener.
* @returns {Promise} Promise that could be aborted.
* @description Method for reading from blobs.
*
* @example
* new BlobObject(new Blob(['{"foo":"bar"}'], { type: 'application/json' }))
* .readAs('text')
* .then((value) => {
* console.log(value); // '{"foo":"bar"}'
* });
*/
readAs(method, progress) {
if (!methods[method]) {
throw new Error('1st argument must be one of following values: buffer, binary, dataURL, text');
}
let reader = new FileReader();
let toReject;
if (isFunction(progress)) {
reader.onprogress = function (e) {
progress(e, this);
};
}
const promise = new Promise((resolve, reject) => {
toReject = reject;
reader.onerror = () => {
if (reader) {
reject(new Error('Reading error'));
}
};
reader.onload = () => {
resolve(reader.result);
};
reader[`readAs${ methods[method] }`](this.$);
});
promise.abort = function abort() {
toReject(new Error('Reading was aborted'));
reader.abort();
reader = null;
return this;
};
return promise;
}
/**
* @method BlobObject#saveAs
* @public
* @param {String} [name] - Name that is used for saving file.
* @returns {BlobObject} Returns this.
* @description Method for saving blobs.
*
* @example
* new BlobObject(new Blob(['{"foo":"bar"}'], { type: 'application/json' }))
* .saveAs('blob.json');
*/
saveAs(name = 'download') {
const anchor = document.createElement('a');
anchor.href = URL.createObjectURL(this.$);
anchor.setAttribute('download', name);
anchor.click();
return this;
}
}
defineProperties(BlobObject.prototype, {
[Symbol.toStringTag]: 'BlobObject'
});
constructors[1].push({
check: (blob) => /^(Blob|File)$/.test(toStringTag(blob)),
cls: BlobObject
});
/**
* @function blob
* @public
* @param {(BlobParts[]|BlobParts)} blobParts - Blob parts that are passed to
* [Blob]{@link https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob} constructor.
* @param {Object} [options] - Options that are passed to
* [Blob]{@link https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob} constructor.
* @returns {BlobObject} New instance of BlobObject.
* @description Function for creating blobs not involving BlobObject and Blob constructors.
*/
export function blob(blobParts, options) {
if (!isArray(blobParts)) {
blobParts = [blobParts];
}
return new BlobObject(new Blob(blobParts, options));
}
export default BlobObject;
|
JavaScript
| 0 |
@@ -1295,23 +1295,16 @@
@member
- %7BBlob%7D
BlobObj
@@ -1309,16 +1309,34 @@
bject#$%0A
+ * @type %7BBlob%7D%0A
* @pu
|
0040c5b94d5f981afe6cfc31d468ea23f87135f8
|
update license info for highlight
|
lib/Highlight/highlight.js
|
lib/Highlight/highlight.js
|
jQuery.fn.highlight = function(start,end) {
function innerHighlight(node, start, end) {
var skip = 0;
if (node.nodeType == 3) {
if (start >= 0 && start < node.data.length && end >= 0 && end <= node.data.length) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(start);
var endbit = middlebit.splitText(end-start)//pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
innerHighlight(node.childNodes[0], start, end);
}
return skip;
}
return this.each(function() {
innerHighlight(this, start, end);
});
};
jQuery.fn.removeHighlight = function() {
console.log('remove')
return this.find("span.highlight").each(function() {
this.parentNode.firstChild.nodeName;
with (this.parentNode) {
replaceChild(this.firstChild, this);
normalize();
}
}).end();
};
Highlight = {}
Highlight.highlight = function(node, start, end, options){
if (node.nodeType == 3) {
if (start >= 0 && start < node.data.length && end >= 0 && end <= node.data.length) {
var spannode = document.createElement('span');
spannode.className = options.highlightClass + ' highlight';
var middlebit = node.splitText(start);
var endbit = middlebit.splitText(end-start)
var middleclone = middlebit.cloneNode(true);
// if(start===end){
// var div = document.createElement('div')
// div.style.width = 3;
// div.style.height = 3;
// div.style.display = 'inline'
// spannode.appendChild(div)
// }
// else{
spannode.appendChild(middleclone);
// }
middlebit.parentNode.replaceChild(spannode, middlebit);
}
}
}
Highlight.removeHighlight = function(node) {
jQuery(node).find("span.highlight").each(function() {
this.parentNode.firstChild.nodeName;
with (this.parentNode) {
replaceChild(this.firstChild, this);
normalize();
}
});
};
|
JavaScript
| 0 |
@@ -1,16 +1,256 @@
+/*%0A%0Ahighlight v3%0A%0AHighlights arbitrary terms.%0A%0A%3Chttp://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html%3E%0A%0AMIT license.%0A%0AJohann Burkard%0A%3Chttp://johannburkard.de%3E%0A%3Cmailto:[email protected]%3E%0A%0A*/%0A%0A
jQuery.fn.highli
|
9ade0bebbf3f2bc761f822b41d5ff1b4fa26890a
|
change default checkbox style. Remove radius
|
era/ui/checkbox.js
|
era/ui/checkbox.js
|
Ui.Togglable.extend('Ui.CheckBox',
/**Ui.CheckBox#*/
{
graphic: undefined,
contentBox: undefined,
hbox: undefined,
content: undefined,
text: undefined,
/**
* @constructs
* @class
* @extends Ui.Togglable
*/
constructor: function(config) {
this.addEvents('change');
this.setPadding(3);
this.hbox = new Ui.HBox();
this.append(this.hbox);
this.graphic = new Ui.CheckBoxGraphic();
this.hbox.append(this.graphic);
this.connect(this, 'down', this.onCheckBoxDown);
this.connect(this, 'up', this.onCheckBoxUp);
this.connect(this, 'toggle', this.onCheckBoxToggle);
this.connect(this, 'untoggle', this.onCheckBoxUntoggle);
this.connect(this, 'focus', this.onCheckFocus);
this.connect(this, 'blur', this.onCheckBlur);
},
getValue: function() {
return this.getIsToggled();
},
setValue: function(value) {
if(value)
this.toggle();
else
this.untoggle();
},
setText: function(text) {
if(text === undefined) {
if(this.contentBox != undefined) {
this.hbox.remove(this.contentBox);
this.contentBox = undefined;
}
this.text = undefined;
this.content = undefined;
}
else {
if(this.text != undefined) {
this.text = text;
this.contentBox.setText(this.text);
}
else {
if(this.content != undefined) {
this.hbox.remove(this.contentBox);
this.content = undefined;
}
this.text = text;
this.contentBox = new Ui.Text({ margin: 8, text: this.text });
this.hbox.append(this.contentBox, true);
}
}
},
getText: function() {
return this.text;
},
/**
*#@+ @private
*/
onCheckFocus: function() {
this.graphic.setColor(this.getStyleProperty('focusColor'));
},
onCheckBlur: function() {
this.graphic.setColor(this.getStyleProperty('color'));
},
onCheckBoxDown: function() {
this.graphic.setIsDown(true);
},
onCheckBoxUp: function() {
this.graphic.setIsDown(false);
},
onCheckBoxToggle: function() {
this.graphic.setIsChecked(true);
this.fireEvent('change', this, true);
},
onCheckBoxUntoggle: function() {
this.graphic.setIsChecked(false);
this.fireEvent('change', this, false);
}
/**#@-*/
},
/**Ui.CheckBox#*/
{
onStyleChange: function() {
this.graphic.setRadius(this.getStyleProperty('radius'));
if(this.getHasFocus())
this.graphic.setColor(this.getStyleProperty('focusColor'));
else
this.graphic.setColor(this.getStyleProperty('color'));
this.graphic.setCheckColor(this.getStyleProperty('checkColor'));
},
setContent: function(content) {
content = Ui.Element.create(content);
if(content === undefined) {
if(this.contentBox != undefined) {
this.hbox.remove(this.contentBox);
this.contentBox = undefined;
}
this.text = undefined;
this.content = undefined;
}
else {
if(this.text != undefined) {
this.hbox.remove(this.contentBox);
this.text = undefined;
}
if(this.content != undefined)
this.contentBox.remove(this.content);
else {
this.contentBox = new Ui.LBox({ padding: 8 });
this.hbox.append(this.contentBox);
}
this.content = content;
this.contentBox.append(this.content);
}
}
},
/**Ui.CheckBox*/
{
style: {
color: new Ui.Color({ r: 1, g: 1, b: 1 }),
focusColor: '#f6ddc8',
checkColor: new Ui.Color({ r: 0, g: 0.6, b: 0 }),
radius: 5
}
});
|
JavaScript
| 0 |
@@ -2197,67 +2197,8 @@
) %7B%0A
-%09%09this.graphic.setRadius(this.getStyleProperty('radius'));%0A
%09%09if
@@ -3108,42 +3108,17 @@
or:
-new Ui.Color(%7B r: 1, g: 1, b: 1 %7D)
+'#444444'
,%0A%09%09
@@ -3137,12 +3137,12 @@
'#f6
-ddc8
+caa2
',%0A%09
@@ -3194,21 +3194,8 @@
0 %7D)
-,%0A%09%09radius: 5
%0A%09%7D%0A
|
f97b8161208cd43a25b8b3d0f5fcce92c109aff3
|
Allow removal of list items
|
src/inputs/Array/Array.js
|
src/inputs/Array/Array.js
|
/* eslint-disable import/no-extraneous-dependencies */
import React, {PropTypes} from 'react'
import FormBuilderPropTypes from '../../FormBuilderPropTypes'
import ItemForm from './ItemForm'
import ItemPreview from './ItemPreview'
import ArrayContainer from './ArrayContainer'
import DropDownButton from 'part:@sanity/components/buttons/dropdown'
import Button from 'part:@sanity/components/buttons/default'
import Fieldset from 'part:@sanity/components/fieldsets/default'
import EditItemPopOver from 'part:@sanity/components/edititem/popover'
import DefaultList from 'part:@sanity/components/lists/default'
import GridList from 'part:@sanity/components/lists/grid'
import {SortableContainer, SortableElement} from 'react-sortable-hoc'
const SortableDefaultList = SortableContainer(DefaultList)
const SortableItem = SortableElement(props => {
return (
<div disabled={props.disabled} key={props.index}>
{props.children}
</div>
)
})
export default class Arr extends React.Component {
static displayName = 'Array';
static valueContainer = ArrayContainer;
static propTypes = {
type: FormBuilderPropTypes.type,
field: FormBuilderPropTypes.field,
value: PropTypes.instanceOf(ArrayContainer),
level: PropTypes.number,
onChange: PropTypes.func,
description: PropTypes.string
};
static defaultProps = {
onChange() {}
};
static contextTypes = {
formBuilder: PropTypes.object
};
state = {
addItemField: null,
editIndex: -1
};
handleAddBtnClick = () => {
if (this.props.type.of.length > 1) {
this.setState({selectType: true})
return
}
this.append(this.createValueForField(this.props.type.of[0]))
this.setState({
selectType: false,
editIndex: this.props.value.length
})
}
insert(itemValue, position, atIndex) {
const {onChange, value} = this.props
if (value.isEmpty()) {
onChange({
patch: {
type: 'set',
value: [itemValue]
}
})
return
}
onChange({
patch: {
path: [atIndex],
type: 'insert',
position: position,
items: [itemValue]
}
})
}
prepend(value) {
this.insert(value, 'before', 0)
}
append(value) {
this.insert(value, 'after', -1)
}
createValueForField(field) {
return {_type: field.type}
}
handleRemoveItem = index => {
if (index === this.state.editIndex) {
this.setState({editIndex: -1})
}
const patch = {
type: 'unset',
path: [index]
}
this.props.onChange({patch})
}
handleClose = () => {
const {editIndex} = this.state
const itemValue = this.props.value.at(editIndex)
if (itemValue.isEmpty()) {
this.handleRemoveItem(editIndex)
}
this.setState({editIndex: -1})
}
handleDropDownAction = menuItem => {
this.append(this.createValueForField(menuItem.field))
}
renderSelectType() {
const {type} = this.props
const items = type.of.map((field, i) => {
return {
title: field.title || field.type,
index: `action${i}`,
field: field
}
})
return (
<DropDownButton items={items} ripple inverted kind="add" onAction={this.handleDropDownAction}>
New {this.props.field.title}
</DropDownButton>
)
}
handleItemChange = (event, index) => {
const {onChange} = this.props
// Rewrite patch by prepending the item index to its path
onChange({
patch: {
...event.patch,
path: [index, ...(event.patch.path || [])]
}
})
}
handleItemEdit = index => {
this.setState({editIndex: index})
}
handleMove = event => {
this.props.onChange({
patch: {
type: 'move',
value: {from: event.oldIndex, to: event.newIndex}
}
})
}
handleItemEnter = () => {
this.setState({editIndex: -1})
}
renderEditItemForm(index) {
const itemValue = this.props.value.at(index)
const itemField = this.getItemField(itemValue)
return (
<EditItemPopOver title={itemField.title} onClose={this.handleClose}>
<ItemForm
focus
index={index}
field={itemField}
level={this.props.level + 1}
value={itemValue}
onChange={this.handleItemChange}
onEnter={this.handleItemEnter}
onRemove={this.handleRemoveItem}
/>
</EditItemPopOver>
)
}
getItemField(item) {
const {type} = this.props
return type.of.find(ofType => ofType.type === item.context.field.type)
}
renderItem = (item, index) => {
const {type} = this.props
const {editIndex} = this.state
const itemField = this.getItemField(item)
if (!itemField) {
return (
<div>
<p>Invalid type: <pre>{JSON.stringify(item.context.field.type)}</pre></p>
<p>Only allowed types are: <pre>{JSON.stringify(type.of)}</pre></p>
</div>
)
}
return (
<SortableItem key={index} disabled={editIndex > 0} index={index}>
<ItemPreview
index={index}
field={itemField}
value={item}
onEdit={this.handleItemEdit}
onRemove={this.handleRemoveItem}
/>
{editIndex === index && this.renderEditItemForm(editIndex)}
</SortableItem>
)
}
renderList() {
const {value, type} = this.props
if (type.options && type.options.view == 'grid') {
return <GridList renderItem={this.renderItem} items={value.value} />
}
return (
<SortableDefaultList
lockAxis="y"
distance={5}
onSortEnd={this.handleMove}
renderItem={this.renderItem}
items={value.value}
/>
)
}
render() {
const {field, level} = this.props
return (
<Fieldset legend={field.title} description={field.description} level={level}>
{this.renderList()}
<div>
{
this.props.type.of.length == 1
&& <Button onClick={this.handleAddBtnClick} ripple kind="add">
Add
</Button>
}
{
this.props.type.of.length > 1 && this.renderSelectType()
}
</div>
</Fieldset>
)
}
}
|
JavaScript
| 0.000007 |
@@ -4022,16 +4022,121 @@
mValue)%0A
+ const actions = %5B%7Bkind: 'danger', title: 'Remove', handleClick: () =%3E this.handleRemoveItem(index)%7D%5D%0A
retu
@@ -4162,16 +4162,34 @@
mPopOver
+ actions=%7Bactions%7D
title=%7B
|
c183004332bda8738c64bc40d0be49a33ef67654
|
Update AnimatedMarker.js
|
src/AnimatedMarker.js
|
src/AnimatedMarker.js
|
L.AnimatedMarker = L.Marker.extend({
options: {
// meters
distance: 200,
// ms
interval: 1000,
// animate on add?
autoStart: true,
// callback onend
onEnd: function(){},
clickable: false
},
initialize: function (latlngs, options) {
this.setLine(latlngs);
L.Marker.prototype.initialize.call(this, latlngs[0], options);
},
// Breaks the line up into tiny chunks (see options) ONLY if CSS3 animations
// are not supported.
_chunk: function(latlngs) {
var i,
len = latlngs.length,
chunkedLatLngs = [];
for (i=1;i<len;i++) {
var cur = latlngs[i-1],
next = latlngs[i],
dist = cur.distanceTo(next),
factor = this.options.distance / dist,
dLat = factor * (next.lat - cur.lat),
dLng = factor * (next.lng - cur.lng);
if (dist > this.options.distance) {
while (dist > this.options.distance) {
cur = new L.LatLng(cur.lat + dLat, cur.lng + dLng);
dist = cur.distanceTo(next);
chunkedLatLngs.push(cur);
}
} else {
chunkedLatLngs.push(cur);
}
}
return chunkedLatLngs;
},
onAdd: function (map) {
L.Marker.prototype.onAdd.call(this, map);
// Start animating when added to the map
if (this.options.autoStart) {
this.start();
}
},
animate: function() {
var self = this,
len = this._latlngs.length,
speed = this.options.interval;
// Normalize the transition speed from vertex to vertex
if (this._i < len) {
speed = this._latlngs[this._i-1].distanceTo(this._latlngs[this._i]) / this.options.distance * this.options.interval;
}
// Only if CSS3 transitions are supported
if (L.DomUtil.TRANSITION) {
if (this._icon) { this._icon.style[L.DomUtil.TRANSITION] = ('all ' + speed + 'ms linear'); }
if (this._shadow) { this._shadow.style[L.DomUtil.TRANSITION] = 'all ' + speed + 'ms linear'; }
}
// Move to the next vertex
this.setLatLng(this._latlngs[this._i]);
this._i++;
// Queue up the animation to the next next vertex
this._tid = setTimeout(function(){
if (self._i === len) {
self.options.onEnd.apply(self, Array.prototype.slice.call(arguments));
} else {
self.animate();
}
}, speed);
},
// Start the animation
start: function() {
if (!this._i) {
this._i = 1;
}
this.animate();
},
// Stop the animation in place
stop: function() {
if (this._tid) {
clearTimeout(this._tid);
}
},
setLine: function(latlngs){
if (L.DomUtil.TRANSITION) {
// No need to to check up the line if we can animate using CSS3
this._latlngs = latlngs;
} else {
// Chunk up the lines into options.distance bits
this._latlngs = this._chunk(latlngs);
this.options.distance = 10;
this.options.interval = 30;
}
}
});
L.animatedMarker = function (latlngs, options) {
return new L.AnimatedMarker(latlngs, options);
};
|
JavaScript
| 0 |
@@ -1136,24 +1136,65 @@
%7D%0A %7D
+%0A chunkedLatLngs.push(latlngs%5Blen-1%5D);
%0A%0A return
|
b91f8e12e419b6b0688735c5b54cf8eca12f4851
|
Increase time trigger off to one minute
|
src/rules-engine/triggers/TimeTrigger.js
|
src/rules-engine/triggers/TimeTrigger.js
|
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.*
*/
const Events = require('../Events');
const Trigger = require('./Trigger');
/**
* An abstract class for triggers whose input is a single property
*/
class TimeTrigger extends Trigger {
constructor(desc) {
super();
this.time = desc.time;
this.sendOn = this.sendOn.bind(this);
this.sendOff = this.sendOff.bind(this);
}
/**
* @return {TriggerDescription}
*/
toDescription() {
return Object.assign(
super.toDescription(),
{time: this.time}
);
}
async start() {
this.scheduleNext();
}
scheduleNext() {
const parts = this.time.split(':');
const hours = parseInt(parts[0], 10);
const minutes = parseInt(parts[1], 10);
// Time is specified in UTC
const nextTime = new Date();
nextTime.setUTCHours(hours, minutes, 0, 0);
if (nextTime.getTime() < Date.now()) {
// NB: this will wrap properly into the next month/year
nextTime.setDate(nextTime.getDate() + 1);
}
if (this.timeout) {
clearTimeout(this.timeout);
}
this.timeout = setTimeout(this.sendOn,
nextTime.getTime() - Date.now());
}
sendOn() {
this.emit(Events.STATE_CHANGED, {on: true, value: Date.now()});
this.timeout = setTimeout(this.sendOff, 10 * 1000);
}
sendOff() {
this.emit(Events.STATE_CHANGED, {on: false, value: Date.now()});
this.scheduleNext();
}
stop() {
clearTimeout(this.timeout);
this.timeout = null;
}
}
module.exports = TimeTrigger;
|
JavaScript
| 0 |
@@ -1471,17 +1471,17 @@
endOff,
-1
+6
0 * 1000
|
82be0875dde1c93527f4c877a73347d7ecaeb563
|
Delete files uploaded when cancel button clicked
|
src/main/web/florence/js/functions/_loadTableBuilder.js
|
src/main/web/florence/js/functions/_loadTableBuilder.js
|
function loadTableBuilder(pageData, onSave, table) {
var pageUrl = pageData.uri;
var html = templates.tableBuilder(table);
var uploadedNotSaved = {uploaded: false, saved: false, table: ""};
$('body').append(html);
if (table) {
renderTable(table.uri);
}
$('#upload-table-form').submit(function (event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
var table = buildJsonObjectFromForm();
var path = table.uri;
var xlsPath = path + ".xls";
var htmlPath = path + ".html";
// send xls file to zebedee
$.ajax({
url: "/zebedee/content/" + Florence.collection.id + "?uri=" + xlsPath,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
createTableHtml();
uploadedNotSaved.uploaded = true;
uploadedNotSaved.table = path;
}
});
function createTableHtml() {
$.ajax({
url: "/zebedee/table/" + Florence.collection.id + "?uri=" + xlsPath,
type: 'POST',
success: function (html) {
saveTableJson();
saveTableHtml(html);
}
});
}
function saveTableHtml(data) {
$.ajax({
url: "/zebedee/content/" + Florence.collection.id + "?uri=" + htmlPath,
type: 'POST',
data: data,
processData: false,
success: function () {
renderTable(path);
}
});
}
return false;
});
function renderTable(path) {
var uri = path + "/table";
var iframeMarkup = '<iframe id="preview-frame" frameBorder ="0" scrolling = "yes" src="' + uri + '"></iframe>';
console.log(iframeMarkup);
$('#table').html(iframeMarkup);
document.getElementById('preview-frame').height = "500px";
document.getElementById('preview-frame').width = "100%";
}
$('.btn-table-builder-cancel').on('click', function () {
$('.table-builder').stop().fadeOut(200).remove();
if (uploadedNotSaved.uploaded === true && uploadedNotSaved.saved === false) {
//delete any files associated with the table.
_(table.files).each(function (file) {
var fileToDelete = path + '/' + file.filename;
deleteContent(Florence.collection.id, fileToDelete,
onSuccess = function () {
console.log("deleted table file: " + fileToDelete);
});
});
}
});
function saveTableJson() {
table = buildJsonObjectFromForm();
var tableJson = table.uri + ".json";
$.ajax({
url: "/zebedee/content/" + Florence.collection.id + "?uri=" + tableJson,
type: 'POST',
data: JSON.stringify(table),
processData: false,
contentType: 'application/json',
success: function () {
addTableToPageJson(table);
uploadedNotSaved.saved = true;
}
});
}
function addTableToPageJson(table) {
if (!pageData.tables) {
pageData.tables = []
} else {
var existingTable = _.find(pageData.tables, function (existingTable) {
return existingTable.filename === table.filename;
});
if (existingTable) {
existingTable.title = table.title;
return;
}
}
pageData.tables.push({title: table.title, filename: table.filename, uri: table.uri});
}
$('.btn-table-builder-create').on('click', function () {
saveTableJson();
if (onSave) {
onSave(table.filename, '<ons-table path="' + table.uri + '" />');
}
$('.table-builder').stop().fadeOut(200).remove();
});
function buildJsonObjectFromForm() {
if (!table) {
table = {};
}
table.type = 'table';
table.title = $('#table-title').val();
table.filename = table.filename ? table.filename : StringUtils.randomId();
table.uri = pageUrl + "/" + table.filename;
if (table.title === '') {
table.title = '[Title]';
}
table.files = [];
table.files.push({type: 'download-xls', filename: table.filename + '.xls'});
table.files.push({type: 'html', filename: table.filename + '.html'});
return table;
}
}
|
JavaScript
| 0.000001 |
@@ -180,19 +180,8 @@
alse
-, table: %22%22
%7D;%0A
@@ -310,37 +310,8 @@
) %7B%0A
- event.preventDefault();%0A%0A
@@ -775,18 +775,8 @@
on (
-returndata
) %7B%0A
@@ -806,89 +806,8 @@
();%0A
- uploadedNotSaved.uploaded = true;%0A uploadedNotSaved.table = path;%0A
@@ -1346,16 +1346,60 @@
(path);%0A
+ uploadedNotSaved.uploaded = true;%0A
@@ -1872,24 +1872,53 @@
nction () %7B%0A
+ console.log(%22got here%22);%0A
$('.tabl
@@ -2047,17 +2047,16 @@
%7B%0A
-
//delete
@@ -2099,17 +2099,126 @@
.%0A
-_
+//add table.json to file%0A table.files.push(%7B%22type%22:%22json%22,%22filename%22: table.filename + '.json'%7D);%0A $
(table.f
@@ -2238,16 +2238,23 @@
nction (
+index,
file) %7B%0A
@@ -2282,18 +2282,21 @@
ete = pa
-th
+geUrl
+ '/' +
@@ -2899,47 +2899,8 @@
e);%0A
- uploadedNotSaved.saved = true;%0A
@@ -3443,24 +3443,58 @@
ableJson();%0A
+ uploadedNotSaved.saved = true;
%0A if (onS
|
7e28b2c4aa363ef3d307a4184accc0a0001f2034
|
remove args e from loaded failure callback.
|
ads/xlift.js
|
ads/xlift.js
|
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {loadScript, validateData} from '../3p/3p';
/**
* @param {!Window} global
* @param {!Object} data
*/
export function xlift(global, data) {
validateData(data, ['mediaid']);
global.xliftParams = data;
const d = global.document.createElement('div');
d.id = '_XL_recommend';
global.document.getElementById('c').appendChild(d);
d.addEventListener("SuccessLoadedXliftAd", function(e) {
global.context.renderStart(e.detail.adSizeInfo);
});
d.addEventListener("FailureLoadedXliftAd", function(e) {
global.context.noContentAvailable();
});
loadScript(global, 'https://cdn.x-lift.jp/resources/common/xlift_amp.js', () => {
global.XliftAmpHelper.show();
}, () => {
global.context.noContentAvailable();
}) ;
}
|
JavaScript
| 0 |
@@ -989,17 +989,17 @@
istener(
-%22
+'
SuccessL
@@ -1002,33 +1002,33 @@
essLoadedXliftAd
-%22
+'
, function(e) %7B%0A
@@ -1018,32 +1018,33 @@
', function(e) %7B
+
%0A global.cont
@@ -1108,17 +1108,17 @@
istener(
-%22
+'
FailureL
@@ -1129,17 +1129,17 @@
dXliftAd
-%22
+'
, functi
@@ -1141,17 +1141,16 @@
unction(
-e
) %7B%0A
|
15f90ca53f843c22d8f5c08ac23bc7927ae7d18f
|
Use Math.PI instead of 3.14
|
app/d3/PieChartDirective.js
|
app/d3/PieChartDirective.js
|
/**
* Created by rerobins on 11/12/14.
*/
var d3Module = d3Module || angular.module('d3');
d3Module.directive('piechart', ['d3Service','$window', function(d3Service, $window) {
function link(scope, element, attrs) {
scope.render = function (data) {
if (!scope.data) {
return;
}
d3Service.get().then(function (d3) {
/**
* data is :
*
* [{label: 'Some label', value: 100},..]
*/
console.log(scope.data);
var svg = d3.select(element[0]);
var width = parseInt(svg.style('width')),
height = parseInt(svg.style('height')),
radius = Math.min(width/2, height/2);
var color = d3.scale.category10();
var graphic = svg.append('g')
.data([scope.data])
.attr('transform', 'translate('+ (width/2) + ', ' + (height/2) + ')');
var pie = d3.layout.pie()
.value(function(d) { return d.value; })
.sort(null)
.endAngle(-3.14 * 2);
var arc = d3.svg.arc()
.outerRadius(radius * 0.8)
.innerRadius(0.4 * radius);
var arcs = graphic.selectAll('g')
.data(pie)
.enter()
.append('g');
arcs.append('path')
.attr('fill', function(d, i) {
return color(i);
}).attr('d', function(d) {
return arc(d);
});
// add the text
arcs.append("svg:text")
.attr("transform", function(d){
d.innerRadius = 0;
d.outerRadius = radius;
return "translate(" + arc.centroid(d) + ")";
}).attr("text-anchor", "middle")
.text( function(d, i) {
return data[i].value;
}
);
});
};
scope.$watch(function() {
return element[0].offsetWidth;
}, function() {
scope.render(scope.data);
});
scope.$watch('data', function (newVals, oldVals) {
console.log("data has been updated", newVals);
return scope.render(newVals);
}, true);
}
return {
link: link,
scope: {
data: '='
}
};
}]);
|
JavaScript
| 0.000497 |
@@ -1194,16 +1194,19 @@
gle(
--3.14
+Math.PI
*
+-
2);%0A
|
0edecafab341079e4dc097e9f2cefeb7d2f2dc69
|
Update homepage links
|
src/App/Header/Nav.js
|
src/App/Header/Nav.js
|
import React from 'react';
import { connect } from 'react-redux';
import { getConfigByName } from 'App/Config/entities';
function mapStateToProps(state) {
const radarEnabled = getConfigByName(state, 'radar.enabled');
return {
radarEnabled
};
}
function Nav({ radarEnabled }) {
return (<ul className="nav">
{/* <li><LoginLink /></li> */}
{radarEnabled && <li><a href="/radar">Tech Radar</a></li>}
<li><a href="/resume.pdf">Résumé</a></li>
<li><a href="https://github.com/shaine">GitHub</a></li>
<li><a href="https://github.com/pulls?q=is%3Apr+author%3Ashaine+is%3Aclosed+is%3Apublic">OSS Contributions</a></li>
<li><a href="https://twitter.com/ShaineHatch">T̅ͮ̄̂͌̏͂witter</a></li>
<li><a href="https://www.linkedin.com/in/shaine/">LinkedIn</a></li>
<li><a href="/public/archer.jpg">Cat Photo</a></li>
</ul>);
}
export default connect(mapStateToProps)(Nav);
|
JavaScript
| 0.000001 |
@@ -330,114 +330,8 @@
v%22%3E%0A
- %7B/* %3Cli%3E%3CLoginLink /%3E%3C/li%3E */%7D%0A %7BradarEnabled && %3Cli%3E%3Ca href=%22/radar%22%3ETech Radar%3C/a%3E%3C/li%3E%7D%0A
@@ -368,32 +368,32 @@
R%C3%A9sum%C3%A9%3C/a%3E%3C/li%3E%0A
+
%3Cli%3E%3Ca h
@@ -568,86 +568,8 @@
li%3E%0A
- %3Cli%3E%3Ca href=%22https://twitter.com/ShaineHatch%22%3ET%CC%85%CD%AE%CC%84%CC%82%CD%8C%CC%8F%CD%82witter%3C/a%3E%3C/li%3E%0A
@@ -644,68 +644,8 @@
li%3E%0A
- %3Cli%3E%3Ca href=%22/public/archer.jpg%22%3ECat Photo%3C/a%3E%3C/li%3E%0A
|
5df5c69ec6a1235d5b08702d24e3a1f613be8280
|
Remove unused imports in areaOfStudy
|
app/elements/areaOfStudy.js
|
app/elements/areaOfStudy.js
|
import _ from 'lodash'
import Immutable from 'immutable'
import React from 'react/addons'
import {State, Navigation} from 'react-router'
import studentActions from '../flux/studentActions'
import RequirementSet from './requirementSet'
let cx = React.addons.classSet
let AreaOfStudy = React.createClass({
mixins: [State, Navigation],
propTypes: {
area: React.PropTypes.shape({
id: React.PropTypes.string.isRequired,
title: React.PropTypes.string.isRequired,
result: React.PropTypes.bool.isRequired,
progress: React.PropTypes.shape({
at: React.PropTypes.number.isRequired,
of: React.PropTypes.number.isRequired,
word: React.PropTypes.string,
}).isRequired,
type: React.PropTypes.string,
details: React.PropTypes.arrayOf(React.PropTypes.object),
})
},
toggle() {
this.setState({expanded: !this.state.expanded})
},
componentWillReceiveProps(nextProps) {
this.setState({
reqSets: this.makeReqSets(),
})
},
componentWillMount() {
this.setState({
reqSets: this.makeReqSets(),
})
},
getInitialState() {
return {
expanded: false,
reqSets: this.makeReqSets(),
}
},
makeReqSets() {
let reqSets = _.map(this.props.area.details, (reqset) =>
React.createElement(RequirementSet, Object.assign({key: reqset.title}, reqset)))
return reqSets
},
render() {
// console.log(`render areaOfStudy for ${this.props.area.id}`)
let header = React.createElement('header',
{className: 'summary', onClick: this.toggle},
React.createElement('h1', null, this.props.area.title),
React.createElement('progress', {
value: this.props.area.progress.at,
max: this.props.area.progress.of,
className: this.props.area.progress.word,
}))
let classes = cx({
'area-of-study': true,
open: this.state.expanded,
})
return React.createElement('div',
{key: this.props.area.id, className: classes},
header,
this.state.expanded ? this.state.reqSets : null)
},
})
export default AreaOfStudy
|
JavaScript
| 0 |
@@ -27,163 +27,29 @@
ort
-Immutable from 'immutable'%0Aimport React from 'react/addons'%0Aimport %7BState, Navigation%7D from 'react-router'%0A%0Aimport studentActions from '../flux/studentActi
+React from 'react/add
ons'
|
febfb7f8b62279c3e57700171318f0c8dfb33534
|
fix typo
|
httpServer.js
|
httpServer.js
|
var http = require("http");
var fs = require("fs");
var url = require("url");
var path = require("path");
var mime = require("mime");
var mkdirp = require('mkdirp');
var async = require('async');
var sSourceDir = ".";
var sShadowDir;
if (process.argv.length > 2) {
sSourceDir = process.argv[2];
}
if (process.argv.length > 3) {
sShadowDir = process.argv[3];
mkdirp(sShadowDir, function(err) { if (err) {console.log("Error creating shadow dir: " + err); sShadowDir = null;}})
}
var breakOutRegex = new RegExp("/*\\/\\.\\.\\/*/");
console.log("start server");
//write file to disk
function writeFile(sPath, req, res) {
var fullBody = '';
//read chunks of data and store it in buffer
req.on('data', function(chunk) {
fullBody += chunk.toString();
});
//after transmission, write file to disk
req.on('end', function() {
fs.writeFile(sPath, fullBody, function (err) {
if (err) {
// throw err;
console.log(err);
return;
}
console.log("saved " + sPath);
res.writeHead(200, "OK");
res.end();
});
});
}
function _readFile(sPath, res) {
fs.readFile(sPath, 'utf8', function (err,data) {
if (err) {
res.writeHead(404);
res.end("File not found!\n");
return console.log(err);
}
res.writeHead(200, {'content-type': mime.lookup(sPath)});
res.end(data);
});
}
function _readShadowFile(sPath, res) {
var sShadowPath = path.join(sShadowDir, sPath),
sSourcePath = path.join(sSourceDir, sPath);
fs.access(sShadowPath, fs.R_OK, function(err) {
if (err)
_readFile(sSourcePath, res);
else {
async.map([sSourcePath, sShadowPath], fs.stat, function(err, results){
if (err)
console.log("Error reading file stats");
else if (results[0].mtime > results[1].mtime)
_readFile(sSourcePath, res);
else {
_readFile(sShadowPath, res);
console.log("Loading from ShadowPath");
}
});
}
});
}
var readFile = sShadowDir ? _readShadowFile : function(sPath, res) {return _readFile(path.join(sSourceDir, sPath), res)};
http.createServer(function (req, res) {
var oUrl = url.parse(req.url, true, false);
console.log(oUrl.pathname);
var sPath = path.normalize(oUrl.pathname);
if (breakOutRegex.test(sPath) == true) {
res.writeHead(500);
res.end("Your not allowed to access files outside the pages storage area\n");
return;
}
var sSourcePath = path.join(sSourceDir, sPath);
if (req.method == "GET") {
readFile(sPath, res)
} else if (req.method == "PUT") {
//writes go to shadow dir if selected
if (sShadowDir) {
var sShadowPath = path.join(sShadowDir, sPath);
mkdirp(path.dirname(sShadowPath), function(err) {
if (err) {
console.log("error creating path " + sShadowPath);
} else {
writeFile(sShadowPath, req, res);
}
});
} else {
writeFile(sSourcePath, req, res);
}
} else if (req.method == "OPTIONS") {
console.log("doing a stat on " + sSourcePath);
// statFile was called by client
if (sSourcePath.slice(-1) === path.sep) {
// a dir was requested
fs.readdir(sSourcePath, function(err, files) {
var dir = {
type: "directory",
content: []
}
files.forEach(function(filename) {
fs.stat(path.join(sSourcePath, filename), function(err,statObj) {
if (statObj.isDirectory()) {
dir.content.push({
type: "directory",
name: filename,
size: 0
});
} else {
dir.content.push({
type: "file",
name: filename,
size: statObj.size
});
}
// is there a better way for synchronization???
if (dir.content.length === files.length) {
var data = JSON.stringify(dir);
console.log(data);
// github return text/plain, therefore we need to do the same
res.writeHead(200, {'content-type': 'text/plain'});
res.end(data);
}
});
});
});
} else {
res.writeHead(200, {'content-type': 'text/plain'});
res.end('stat on file not implemented yet');
}
}
}).listen(8080);
|
JavaScript
| 0.999991 |
@@ -3713,13 +3713,14 @@
tent
+s
: %5B%5D%0A
-
@@ -3971,32 +3971,33 @@
dir.content
+s
.push(%7B%0A
@@ -4231,16 +4231,17 @@
.content
+s
.push(%7B%0A
@@ -4516,16 +4516,16 @@
tion???%0A
-
@@ -4555,16 +4555,17 @@
.content
+s
.length
|
74bb4607bd932efbad1f63318eb92e1c3c74c91e
|
Fix lint error
|
app/elements/studentList.js
|
app/elements/studentList.js
|
import React from 'react'
import {Link} from 'react-router'
import studentActions from '../flux/studentActions'
let StudentList = React.createClass({
shouldComponentUpdate(nextProps, nextState) {
return nextProps.students !== this.props.students
},
render() {
let students = this.props.students
.map((student) =>
React.createElement('li', {key: student.id},
React.createElement(Link,
{
className: 'student-list--student',
to: 'student',
params: {id: student.id}
},
student.name)))
.toList()
// students = students.push(React.createElement('li', {key: 'new-student'},
// React.createElement(Link,
// {
// className: 'student-list--student',
// to: 'add-student',
// },
// 'Add Student')))
students = students.push(React.createElement('li', {key: 'new-student'},
React.createElement('button',
{
className: 'student-list--student',
onClick: studentActions.initStudent,
},
'Add Student')))
return React.createElement('ul', {className: 'student-list'}, students.toJS())
},
})
export default StudentList
|
JavaScript
| 0.000035 |
@@ -502,16 +502,17 @@
dent.id%7D
+,
%0A%09%09%09%09%09%09%7D
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.