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
|
---|---|---|---|---|---|---|---|
5820fe49afacdd065aeceef1b84875ef9e51ae54
|
add helper to create extract-text-webpack-plugin instances compatible with webpack 1/2
|
test/utils/index.js
|
test/utils/index.js
|
const merge = require('deepmerge');
const ExtractPlugin = require('extract-text-webpack-plugin');
const { isWebpack1 } = require('../../lib/utils');
const { loaderPath } = require('../_config');
const createCompiler = require('./create-compiler');
/**
* @param {Object} [config]
* @return {Promise<Compilation>}
*/
function compile(config) {
return createCompiler(config).then(compiler => compiler.run());
}
/**
* @param {Object} [config]
* @return {Promise<Compilation>}
*/
function compileAndNotReject(config) {
return createCompiler(config).then(compiler => compiler.run(false));
}
function rules(...data) {
return {
[isWebpack1 ? 'loaders' : 'rules']: [...data]
};
}
function rule(data) {
if (isWebpack1) {
data.query = data.options;
delete data.options;
}
return data;
}
function multiRule(data) {
if (isWebpack1) {
data.loaders = data.use.map((ruleData) => {
return typeof ruleData !== 'string' ?
`${ruleData.loader}?${JSON.stringify(ruleData.options)}` :
ruleData;
});
delete data.use;
}
return data;
}
function loaderRule(opts) {
const options = merge({}, opts || {});
return rule({
test: /\.svg$/,
loader: loaderPath,
options
});
}
function extractCSSRule() {
// webpack 1 compat
const use = isWebpack1 ?
ExtractPlugin.extract('css-loader').split('!') :
ExtractPlugin.extract('css-loader');
return multiRule({
test: /\.css$/,
use
});
}
function extractHTMLRule() {
return rule({
test: /\.html$/,
loader: ExtractPlugin.extract('html-loader')
});
}
module.exports.rule = rule;
module.exports.rules = rules;
module.exports.multiRule = multiRule;
module.exports.loaderRule = loaderRule;
module.exports.extractCSSRule = extractCSSRule;
module.exports.compile = compile;
module.exports.compileAndNotReject = compileAndNotReject;
module.exports.createCompiler = createCompiler;
module.exports.extractHTMLRule = extractHTMLRule;
|
JavaScript
| 0.000001 |
@@ -38,24 +38,28 @@
onst Extract
+Text
Plugin = req
@@ -1096,22 +1096,19 @@
unction
-loader
+svg
Rule(opt
@@ -1239,96 +1239,613 @@
%0A%7D%0A%0A
-function extractCSSRule() %7B%0A // webpack 1 compat%0A const use = isWebpack1 ?%0A
+/**%0A * @see for webpack 1 - https://github.com/webpack-contrib/extract-text-webpack-plugin/blob/webpack-1/README.md#api%0A * @see for webpack 2 - https://github.com/webpack-contrib/extract-text-webpack-plugin#options%0A * @param %7Bstring%7D filename%0A * @param %7BObject%7D %5Boptions%5D%0A * @return %7BExtractTextPlugin%7D%0A */%0Afunction extractPlugin(filename, options) %7B%0A // webpack 1 compat%0A if (isWebpack1) %7B%0A return new ExtractTextPlugin(filename, options);%0A %7D%0A%0A let args = filename;%0A if (typeof options !== 'object') %7B%0A args = Object.assign(%7B%7D, options);%0A args.filename = filename;%0A %7D%0A%0A return new
Extract
Plug
@@ -1844,76 +1844,354 @@
ract
+Text
Plugin
-.extract('css-loader').split('!') :%0A
+(args);%0A%7D%0A%0A/**%0A * @see for webpack 1 - https://github.com/webpack-contrib/extract-text-webpack-plugin/blob/webpack-1/README.md#api%0A * @see for webpack 2 - https://github.com/webpack-contrib/extract-text-webpack-plugin#options%0A * @param %7B
Extract
+Text
Plugin
-.extract(
+%7D plugin%0A * @return %7BRule%7D%0A */%0Afunction extractCSSRule(plugin) %7B%0A const loader =
'css
@@ -2198,20 +2198,41 @@
-loader'
-)
;%0A%0A
+ // webpack 1 compat%0A
return
@@ -2271,16 +2271,101 @@
%0A use
+: isWebpack1 ?%0A plugin.extract(loader).split('!') :%0A plugin.extract(loader)
%0A %7D);%0A%7D
@@ -2391,16 +2391,22 @@
TMLRule(
+plugin
) %7B%0A re
@@ -2454,16 +2454,9 @@
er:
-ExtractP
+p
lugi
@@ -2604,75 +2604,21 @@
rts.
-loaderRule = loaderRule;%0Amodule.exports.extractCSSRule = extractCSS
+svgRule = svg
Rule
@@ -2805,12 +2805,106 @@
ctHTMLRule;%0A
+module.exports.extractCSSRule = extractCSSRule;%0Amodule.exports.extractPlugin = extractPlugin;%0A
|
6921911a133ae9c1a776bd4826e1e81fd20c9bc4
|
Increase ammo
|
examples/entity/shooter/src/Blaster.js
|
examples/entity/shooter/src/Blaster.js
|
/**
* @author Mugen87 / https://github.com/Mugen87
*/
import { GameEntity, Ray, Vector3 } from '../../../../build/yuka.module.js';
import world from './World.js';
const intersectionPoint = new Vector3();
const target = new Vector3();
class Blaster extends GameEntity {
constructor( owner = null ) {
super( owner );
this.owner = owner;
this.status = STATUS.READY;
this.roundsLeft = 12;
this.roundsPerClip = 12;
this.ammo = 12;
this.maxAmmo = 96;
// times are in seconds
this.shotTime = 0.2;
this.reloadTime = 1.5;
this.muzzleFireTime = 0.1;
this.currentTime = 0;
this.endTimeShot = Infinity;
this.endTimeReload = Infinity;
this.endTimeMuzzleFire = Infinity;
this.animations = new Map();
this.sounds = new Map();
this.muzzleSprite = null;
this.ui = {
roundsLeft: document.getElementById( 'roundsLeft' ),
ammo: document.getElementById( 'ammo' )
};
this.updateUI();
}
update( delta ) {
this.currentTime += delta;
// check reload
if ( this.currentTime >= this.endTimeReload ) {
const toReload = this.roundsPerClip - this.roundsLeft;
if ( this.ammo >= toReload ) {
this.roundsLeft = this.roundsPerClip;
this.ammo -= toReload;
} else {
this.roundsLeft += this.ammo;
this.ammo = 0;
}
this.status = STATUS.READY;
this.updateUI();
this.endTimeReload = Infinity;
}
// check muzzle fire
if ( this.currentTime >= this.endTimeMuzzleFire ) {
this.muzzleSprite.visible = false;
this.endTimeMuzzleFire = Infinity;
}
// check shoot
if ( this.currentTime >= this.endTimeShot ) {
if ( this.roundsLeft === 0 ) {
this.status = STATUS.EMPTY;
} else {
this.status = STATUS.READY;
}
this.endTimeShot = Infinity;
}
return this;
}
reload() {
if ( ( this.status === STATUS.READY || this.status === STATUS.EMPTY ) && this.ammo > 0 ) {
this.status = STATUS.RELOAD;
// audio
const audio = this.sounds.get( 'reload' );
if ( audio.isPlaying === true ) audio.stop();
audio.play();
// animation
const animation = this.animations.get( 'reload' );
animation.stop();
animation.play();
//
this.endTimeReload = this.currentTime + this.reloadTime;
}
return this;
}
shoot() {
if ( this.status === STATUS.READY ) {
this.status = STATUS.SHOT;
// audio
const audio = this.sounds.get( 'shot' );
if ( audio.isPlaying === true ) audio.stop();
audio.play();
// animation
const animation = this.animations.get( 'shot' );
animation.stop();
animation.play();
// muzzle fire
this.muzzleSprite.visible = true;
this.muzzleSprite.material.rotation = Math.random() * Math.PI;
this.endTimeMuzzleFire = this.currentTime + this.muzzleFireTime;
// adjust ammo
const owner = this.owner;
const head = owner.head;
const ray = new Ray();
// first calculate a ray that represents the actual look direction from the head position
ray.origin.extractPositionFromMatrix( head.worldMatrix );
owner.getDirection( ray.direction );
// determine closest intersection point with world object
const result = world.intersectRay( ray, intersectionPoint );
// now calculate the distance to the closest intersection point. if no point was found,
// choose a point on the ray far away from the origin
const distance = ( result === null ) ? 1000 : ray.origin.distanceTo( intersectionPoint );
// now let's change the origin to the weapon's position.
target.copy( ray.origin ).add( ray.direction.multiplyScalar( distance ) );
ray.origin.extractPositionFromMatrix( this.worldMatrix );
ray.direction.subVectors( target, ray.origin ).normalize();
//
world.addBullet( owner, ray );
this.roundsLeft --;
this.endTimeShot = this.currentTime + this.shotTime;
this.updateUI();
}
return this;
}
updateUI() {
this.ui.roundsLeft.textContent = this.roundsLeft;
this.ui.ammo.textContent = this.ammo;
}
}
const STATUS = Object.freeze( {
READY: 'ready', // the blaster is ready for the next action
SHOT: 'shot', // the blaster is firing
RELOAD: 'reload', // the blaster is reloading
EMPTY: 'empty' // the blaster is empty
} );
export { Blaster };
|
JavaScript
| 0.000001 |
@@ -438,18 +438,18 @@
.ammo =
-12
+48
;%0A%09%09this
|
3f0a8068312e397031b4df4a427221c8a6b2e6d8
|
fix del instance
|
deleteInstance.js
|
deleteInstance.js
|
'use strict';
var Instance = require('sivart-GCE/Instance');
var Auth = require('sivart-GCE/Auth');
var zone = 'us-central1-a';
var instanceName = require('os').hostname();
var exec = require('child_process').exec;
exec('users',
function (error, stdout) {
if (stdout) {
console.log('Not deleting instance someone is logged in: ' + stdout);
} else {
if (error) {
console.log('exec error: ' + error);
}
console.log('No one logged in - deleting');
var sivartSlave = Instance.Factory(slave, instanceName);
sivartSlave.delete(function() {
// bye bye!
});
}
});
|
JavaScript
| 0.000003 |
@@ -527,13 +527,15 @@
ory(
+'
slave
+'
, in
|
f069efb0d79b7b9adadc30005d7c832543a68db5
|
Fix cinematic camera example
|
examples/js/cameras/CinematicCamera.js
|
examples/js/cameras/CinematicCamera.js
|
/**
* @author mrdoob / http://mrdoob.com/
* @author greggman / http://games.greggman.com/
* @author zz85 / http://www.lab4games.net/zz85/blog
* @author kaypiKun
*/
THREE.CinematicCamera = function( fov, aspect, near, far ) {
THREE.PerspectiveCamera.call( this, fov, aspect, near, far );
this.type = "CinematicCamera";
this.postprocessing = { enabled : true };
this.shaderSettings = {
rings: 3,
samples: 4
};
this.material_depth = new THREE.MeshDepthMaterial();
// In case of cinematicCamera, having a default lens set is important
this.setLens();
this.initPostProcessing();
};
THREE.CinematicCamera.prototype = Object.create( THREE.PerspectiveCamera.prototype );
THREE.CinematicCamera.prototype.constructor = THREE.CinematicCamera;
// providing fnumber and coc(Circle of Confusion) as extra arguments
THREE.CinematicCamera.prototype.setLens = function ( focalLength, filmGauge, fNumber, coc ) {
// In case of cinematicCamera, having a default lens set is important
if ( focalLength === undefined ) focalLength = 35;
if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
this.setFocalLength( focalLength );
// if fnumber and coc are not provided, cinematicCamera tries to act as a basic PerspectiveCamera
if ( fNumber === undefined ) fNumber = 8;
if ( coc === undefined ) coc = 0.019;
this.fNumber = fNumber;
this.coc = coc;
// fNumber is focalLength by aperture
this.aperture = focalLength / this.fNumber;
// hyperFocal is required to calculate depthOfField when a lens tries to focus at a distance with given fNumber and focalLength
this.hyperFocal = ( focalLength * focalLength ) / ( this.aperture * this.coc );
};
THREE.CinematicCamera.prototype.linearize = function ( depth ) {
var zfar = this.far;
var znear = this.near;
return - zfar * znear / ( depth * ( zfar - znear ) - zfar );
};
THREE.CinematicCamera.prototype.smoothstep = function ( near, far, depth ) {
var x = this.saturate( ( depth - near ) / ( far - near ) );
return x * x * ( 3 - 2 * x );
};
THREE.CinematicCamera.prototype.saturate = function ( x ) {
return Math.max( 0, Math.min( 1, x ) );
};
// function for focusing at a distance from the camera
THREE.CinematicCamera.prototype.focusAt = function ( focusDistance ) {
if ( focusDistance === undefined ) focusDistance = 20;
var focalLength = this.getFocalLength();
// distance from the camera (normal to frustrum) to focus on
this.focus = focusDistance;
// the nearest point from the camera which is in focus (unused)
this.nearPoint = ( this.hyperFocal * this.focus ) / ( this.hyperFocal + ( this.focus - focalLength ) );
// the farthest point from the camera which is in focus (unused)
this.farPoint = ( this.hyperFocal * this.focus ) / ( this.hyperFocal - ( this.focus - focalLength ) );
// the gap or width of the space in which is everything is in focus (unused)
this.depthOfField = this.farPoint - this.nearPoint;
// Considering minimum distance of focus for a standard lens (unused)
if ( this.depthOfField < 0 ) this.depthOfField = 0;
this.sdistance = this.smoothstep( this.near, this.far, this.focus );
this.ldistance = this.linearize( 1 - this.sdistance );
this.postprocessing.bokeh_uniforms[ 'focalDepth' ].value = this.ldistance;
};
THREE.CinematicCamera.prototype.initPostProcessing = function () {
if ( this.postprocessing.enabled ) {
this.postprocessing.scene = new THREE.Scene();
this.postprocessing.camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, - 10000, 10000 );
this.postprocessing.scene.add( this.postprocessing.camera );
var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat };
this.postprocessing.rtTextureDepth = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, pars );
this.postprocessing.rtTextureColor = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, pars );
var bokeh_shader = THREE.BokehShader;
this.postprocessing.bokeh_uniforms = THREE.UniformsUtils.clone( bokeh_shader.uniforms );
this.postprocessing.bokeh_uniforms[ "tColor" ].value = this.postprocessing.rtTextureColor.texture;
this.postprocessing.bokeh_uniforms[ "tDepth" ].value = this.postprocessing.rtTextureDepth.texture;
this.postprocessing.bokeh_uniforms[ "manualdof" ].value = 0;
this.postprocessing.bokeh_uniforms[ "shaderFocus" ].value = 0;
this.postprocessing.bokeh_uniforms[ "fstop" ].value = 2.8;
this.postprocessing.bokeh_uniforms[ "showFocus" ].value = 1;
this.postprocessing.bokeh_uniforms[ "focalDepth" ].value = 0.1;
//console.log( this.postprocessing.bokeh_uniforms[ "focalDepth" ].value );
this.postprocessing.bokeh_uniforms[ "znear" ].value = this.near;
this.postprocessing.bokeh_uniforms[ "zfar" ].value = this.near;
this.postprocessing.bokeh_uniforms[ "textureWidth" ].value = window.innerWidth;
this.postprocessing.bokeh_uniforms[ "textureHeight" ].value = window.innerHeight;
this.postprocessing.materialBokeh = new THREE.ShaderMaterial( {
uniforms: this.postprocessing.bokeh_uniforms,
vertexShader: bokeh_shader.vertexShader,
fragmentShader: bokeh_shader.fragmentShader,
defines: {
RINGS: this.shaderSettings.rings,
SAMPLES: this.shaderSettings.samples
}
} );
this.postprocessing.quad = new THREE.Mesh( new THREE.PlaneBufferGeometry( window.innerWidth, window.innerHeight ), this.postprocessing.materialBokeh );
this.postprocessing.quad.position.z = - 500;
this.postprocessing.scene.add( this.postprocessing.quad );
}
};
THREE.CinematicCamera.prototype.renderCinematic = function ( scene, renderer ) {
if ( this.postprocessing.enabled ) {
renderer.clear();
// Render scene into texture
scene.overrideMaterial = null;
renderer.render( scene, camera, this.postprocessing.rtTextureColor, true );
// Render depth into texture
scene.overrideMaterial = this.material_depth;
renderer.render( scene, camera, this.postprocessing.rtTextureDepth, true );
// Render bokeh composite
renderer.render( this.postprocessing.scene, this.postprocessing.camera );
}
};
|
JavaScript
| 0.00045 |
@@ -5325,16 +5325,69 @@
.samples
+,%0A%09%09%09%09DEPTH_PACKING: this.material_depth.depthPacking
%0A%09%09%09%7D%0A%09%09
|
f4e0f4fcfdd9539246573e50797fc761e58351fe
|
Fix bad regexp :(
|
packages/ember-views/lib/core.js
|
packages/ember-views/lib/core.js
|
// ==========================================================================
// Project: Ember - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
// Portions ©2008-2011 Apple Inc. All rights reserved.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
ember_assert("Ember requires jQuery 1.6 or 1.7", window.jQuery && window.jQuery().jquery.match(/^1\.[67](\.\d+)?(pre|rc\d))?$/));
Ember.$ = window.jQuery;
|
JavaScript
| 0.000053 |
@@ -505,17 +505,17 @@
pre%7Crc%5Cd
-)
+?
)?$/));%0A
|
98233c5469c8fc87494b2fbde9df855084888f95
|
Fix typo in test call
|
packages/enchannel/test/index.js
|
packages/enchannel/test/index.js
|
const expect = require('chai').expect;
const sinon = require('sinon');
const enchannel = require('../');
describe('isChildMessage', function() {
it('knows child', function() {
const parent = { header: { msg_id: 'a'} };
const child = { parent_header: { msg_id: 'a'} };
expect(enchannel.isChildMessage(parent, child)).to.be.true;
});
it('knows non-child', function() {
const parent = { header: { msg_id: 'a'} };
const child = { parent_header: { msg_id: 'b'} };
expect(enchannel.isChildMessage(parent, child)).to.be.false;
});
it('handle malformed parent', function() {
const parent = 'oops';
const child = { parent_header: { msg_id: 'b'} };
expect(enchannel.isChildMessage(null, parent, child)).to.be.false;
});
it('handle malformed child', function() {
const parent = { header: { msg_id: 'a'} };
const child = 'oops';
expect(enchannel.isChildMessage(parent, child)).to.be.false;
});
});
describe('createMessage', function() {
it('makes a msg', function() {
const msg = enchannel.createMessage('a', 'b', 'c');
expect(msg).to.be.an('object');
expect(msg.header).to.be.an('object');
expect(msg.header.username).to.equal('a');
expect(msg.header.session).to.equal('b');
expect(msg.header.msg_type).to.equal('c');
});
});
function spoofChannels() {
const shell = {
next: sinon.spy(),
complete: sinon.spy(),
filter: () => shell,
map: () => shell,
subscribe: cb => cb.call(shell),
};
return channels = {
shell,
iopub: { complete: sinon.spy() },
stdin: { complete: sinon.spy() },
control: { complete: sinon.spy() },
heartbeat: { complete: sinon.spy() },
};
}
describe('shutdownRequest', function() {
it('shutdowns channels', function() {
const channels = spoofChannels();
enchannel.shutdownRequest('a', 'b', channels);
expect(channels.shell.complete.called).to.be.true;
expect(channels.iopub.complete.called).to.be.true;
expect(channels.stdin.complete.called).to.be.true;
expect(channels.control.complete.called).to.be.true;
expect(channels.heartbeat.complete.called).to.be.true;
});
it('handles missing heartbeat', function() {
const channels = spoofChannels();
channels.heartbeat = undefined;
enchannel.shutdownRequest('a', 'b', channels);
expect(channels.shell.complete.called).to.be.true;
expect(channels.iopub.complete.called).to.be.true;
expect(channels.stdin.complete.called).to.be.true;
expect(channels.control.complete.called).to.be.true;
});
});
|
JavaScript
| 0.000275 |
@@ -717,14 +717,8 @@
age(
-null,
pare
|
089ddb894356390607c5ec4e7e4694268d376143
|
add documentation to the http-header configuration
|
config/http-headers.js
|
config/http-headers.js
|
/* eslint-disable max-len */
const config = {
contentSecurityPolicy: {
corsDefault: {
defaultSrc: "default-src 'self' 'unsafe-inline' blob: data:",
scriptSrc: "data: blob: 'self' 'unsafe-inline'",
objectSrc: '',
},
corsSiteSpecific: {
'^/$': {
defaultSrc: 'https://www10-fms.hpi.uni-potsdam.de https://blog.schul-cloud.org https://play.google.com https://s3.hidrive.strato.com https://schul-cloud-hpi.s3.hidrive.strato.com',
scriptSrc: "'unsafe-eval'",
},
'^/about': {
defaultSrc: 'https://www10-fms.hpi.uni-potsdam.de https://schul-cloud-hpi.s3.hidrive.strato.com https://play.google.com',
scriptSrc: "'unsafe-eval'",
},
'^/administration': {
defaultSrc: 'https://fonts.gstatic.com',
scriptSrc: "'unsafe-eval'",
},
'^/calendar': {
scriptSrc: "'unsafe-eval'",
},
'^/content': {
defaultSrc: '*',
scriptSrc: '*',
objectSrc: '*',
},
'^/community': {
defaultSrc: 'https://play.google.com',
},
'^/files': {
defaultSrc: 'https://vjs.zencdn.net',
},
'^/homework': {
defaultSrc: 'https://fonts.gstatic.com',
scriptSrc: "'unsafe-eval'",
},
'^/rocketChat': {
defaultSrc: 'https://scchat.schul-cloud.org',
},
},
},
accessControlAllowOrigin: {
'^/rocketChat/authGet': 'https://scchat.schul-cloud.org',
},
additionalSecurityHeader: {
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
'X-Frame-Options': 'sameorigin',
'X-Content-Type-Options': 'nosniff',
'X-XSS-Protection': '1; mode=block',
'Referrer-Policy': 'same-origin',
'Feature-Policy': "vibrate 'self'; speaker *; fullscreen *; sync-xhr *; notifications 'self'; push 'self'; geolocation 'self'; midi 'self'; microphone 'self'; camera 'self'; magnetometer 'self'; gyroscope 'self'; payment 'none';",
},
};
module.exports = config;
|
JavaScript
| 0 |
@@ -45,32 +45,144 @@
%7B%0A%09
-contentSecurityPolicy: %7B
+// Settings for HTTP Content-Security-Policy Header%0A%09contentSecurityPolicy: %7B%0A%09%09// Default Content-Security-Policy Header for every site
%0A%09%09c
@@ -335,16 +335,297 @@
',%0A%09%09%7D,%0A
+%09%09/*%0A%09%09%09Content-Security-Policy Header (added to default header) depending on the site%0A%09%09%09site is matched with called website URL and regex key within corsSiteSpecific%0A%09%09%09use * as value for defaultSrc, scriptSrc, objectSrc to ignore corsDefault and allow any external content%0A%09%09*/%0A
%09%09corsSi
@@ -1629,99 +1629,581 @@
%7D,%0A%09
-accessControlAllowOrigin: %7B%0A%09%09'%5E/rocketChat/authGet': 'https://scchat.schul-cloud.org',%0A%09%7D,
+/*%0A%09%09Access-Control-Allow-Origin header depending on the site%0A%09%09site is matched with called website URL and regex key within accessControlAllowOrigin%0A%09%09several allowed origins per route can be added by seperation with %7C%0A%09%09if several regex match the URL routes will be joined%0A%09%09if no regex is given for URLs the Access-Control-Allow-Origin will not be set%0A%09*/%0A%09accessControlAllowOrigin: %7B%0A%09%09'%5E/rocketChat/authGet': 'https://scchat.schul-cloud.org',%0A%09%7D,%0A%09// Additional default Security header can be set - key reprensents the HTTP header and the value the value of the header
%0A%09ad
|
988fe4cefd6eb140cf5909dbb31b5acced0e46bb
|
Add `tryParse()`
|
packages/loquat-prim/lib/prim.js
|
packages/loquat-prim/lib/prim.js
|
/*
* loquat-prim / prim.js
* copyright (c) 2016 Susisu
*/
/**
* @module prim
*/
"use strict";
module.exports = _core => {
function end() {
return Object.freeze({
map,
pure,
ap,
left,
right,
bind,
then,
fail,
mzero,
mplus,
label,
labels,
unexpected
});
}
const ErrorMessageType = _core.ErrorMessageType;
const ErrorMessage = _core.ErrorMessage;
const ParseError = _core.ParseError;
const LazyParseError = _core.LazyParseError;
const Result = _core.Result;
const Parser = _core.Parser;
/**
* @function module:prim.map
* @static
* @param {AbstractParser} parser
* @param {function} func
* @returns {AbstractParser}
*/
function map(parser, func) {
return new Parser(state => {
let res = parser.run(state);
return res.succeeded
? new Result(res.consumed, true, res.err, func(res.val), res.state)
: res;
});
}
/**
* @function module:prim.pure
* @static
* @param {*} val
* @returns {AbstractParser}
*/
function pure(val) {
return new Parser(state => Result.esuc(ParseError.unknown(state.pos), val, state));
}
/**
* @function module:prim.ap
* @static
* @param {AbstractParser} parserA
* @param {AbstractParser} parserB
* @returns {AbstractParser}
*/
function ap(parserA, parserB) {
return bind(parserA, valA =>
bind(parserB, valB =>
pure(valA(valB))
)
);
}
const former = x => () => x;
const latter = () => y => y;
/**
* @function module:prim.left
* @static
* @param {AbstractParser} parserA
* @param {AbstractParser} parserB
* @returns {AbstractParser}
*/
function left(parserA, parserB) {
return ap(map(parserA, former), parserB);
}
/**
* @function module:prim.right
* @static
* @param {AbstractParser} parserA
* @param {AbstractParser} parserB
* @returns {AbstractParser}
*/
function right(parserA, parserB) {
return ap(map(parserA, latter), parserB);
}
/**
* @function module:prim.bind
* @static
* @param {AbstractParser} parser
* @param {function} func
* @returns {AbstractParser}
*/
function bind(parser, func) {
return new Parser(state => {
let resA = parser.run(state);
if (resA.succeeded) {
let parserB = func(resA.val);
let resB = parserB.run(resA.state);
return new Result(
resA.consumed || resB.consumed,
resB.succeeded,
resB.consumed ? resB.err : ParseError.merge(resA.err, resB.err),
resB.val,
resB.state
);
}
else {
return resA;
}
});
}
/**
* @function module:prim.then
* @static
* @param {AbstractParser} parserA
* @param {AbstractParser} parserB
* @returns {AbstracParser}
*/
function then(parserA, parserB) {
return bind(parserA, () => parserB);
}
/**
* @function module:prim.fail
* @static
* @param {string} msgStr
* @returns {AbstractParser}
*/
function fail(msgStr) {
return new Parser(state => Result.eerr(
new ParseError(state.pos, [new ErrorMessage(ErrorMessageType.MESSAGE, msgStr)])
));
}
/**
* @constant module:prim.mzero
* @static
* @type {AbstractParser}
*/
const mzero = new Parser(state => Result.eerr(ParseError.unknown(state.pos)));
/**
* @function module:prim.mplus
* @static
* @param {AbstractParser} parserA
* @param {AbstractParser} parserB
* @returns {AbstractParser}
*/
function mplus(parserA, parserB) {
return new Parser(state => {
let resA = parserA.run(state);
if (!resA.consumed && !resA.succeeded) {
let resB = parserB.run(state);
return new Result(
resB.consumed,
resB.succeeded,
resB.consumed ? resB.err : ParseError.merge(resA.err, resB.err),
resB.val,
resB.state
);
}
else {
return resA;
}
});
}
/**
* @function module:prim.label
* @static
* @param {AbstractParser} parser
* @param {string} labelStr
* @returns {AbstractParser}
*/
function label(parser, labelStr) {
return labels(parser, [labelStr]);
}
/**
* @function module:prim.labels
* @static
* @param {AbstractParser} parser
* @param {Array.<string>} labelStrs
* @returns {AbstractParser}
*/
function labels(parser, labelStrs) {
function setExpects(err) {
return err.setSpecificTypeMessages(ErrorMessageType.EXPECT, labelStrs.length === 0 ? [""] : labelStrs);
}
return new Parser(state => {
let res = parser.run(state);
if (res.consumed) {
return res;
}
else {
let err = res.err;
return new Result(
false,
res.succeeded,
res.succeeded
? new LazyParseError(() => err.isUnknown() ? err : setExpects(err))
: setExpects(err),
res.val,
res.state
);
}
});
}
/**
* @function module:prim.unexpected
* @static
* @param {string} msgStr
* @returns {AbstractParser}
*/
function unexpected(msgStr) {
return new Parser(state => Result.eerr(
new ParseError(
state.pos,
[new ErrorMessage(ErrorMessageType.UNEXPECT, msgStr)]
)
));
}
return end();
};
|
JavaScript
| 0 |
@@ -412,24 +412,46 @@
unexpected
+,%0A tryParse
%0A %7D);
@@ -6289,24 +6289,405 @@
));%0A %7D%0A%0A
+ /**%0A * @function module:prim.tryParse%0A * @static%0A * @param %7BAbstractParser%7D parser%0A * @returns %7BAbstractParser%7D%0A */%0A function tryParse(parser) %7B%0A return new Parser(state =%3E %7B%0A let res = parser.run(state);%0A return res.consumed && !res.succeeded%0A ? Result.eerr(res.err)%0A : res;%0A %7D);%0A %7D%0A%0A
return e
|
8c33b93419c298814b10f65f36dc963652878441
|
resolve utility; set options.fatal true
|
packages/oas-resolver/resolve.js
|
packages/oas-resolver/resolve.js
|
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const util = require('util');
const yaml = require('js-yaml');
const fetch = require('node-fetch');
const resolver = require('./index.js');
let argv = require('yargs')
.string('output')
.alias('o','output')
.describe('output','file to output to')
.default('output','resolved.yaml')
.count('quiet')
.alias('q','quiet')
.describe('quiet','reduce verbosity')
.count('verbose')
.default('verbose',2)
.alias('v','verbose')
.describe('verbose','increase verbosity')
.demand(1)
.argv;
let filespec = argv._[0];
let options = {resolve: true};
options.verbose = argv.verbose;
if (argv.quiet) options.verbose = options.verbose - argv.quiet;
function main(str,source,options){
let input = yaml.safeLoad(str,{json:true});
resolver.resolve(input,source,options)
.then(function(options){
fs.writeFileSync(argv.output,yaml.safeDump(options.openapi,{lineWidth:-1}),'utf8');
})
.catch(function(err){
console.warn(err);
});
}
if (filespec && filespec.startsWith('http')) {
console.log('GET ' + filespec);
fetch(filespec, {agent:options.agent}).then(function (res) {
if (res.status !== 200) throw new Error(`Received status code ${res.status}`);
return res.text();
}).then(function (body) {
main(body,filespec,options);
}).catch(function (err) {
console.warn(err);
});
}
else {
fs.readFile(filespec,'utf8',function(err,data){
if (err) {
console.warn(err);
}
else {
main(data,filespec,options);
}
});
}
|
JavaScript
| 0.999987 |
@@ -743,16 +743,38 @@
v.quiet;
+%0Aoptions.fatal = true;
%0A%0Afuncti
|
334c928f6137737ba9c398e917f22fa413dd660a
|
Add solc settings for optimizer to config
|
packages/truffle-config/index.js
|
packages/truffle-config/index.js
|
var fs = require("fs");
var _ = require("lodash");
var path = require("path");
var Provider = require("truffle-provider");
var TruffleError = require("truffle-error");
var Module = require('module');
var findUp = require("find-up");
var originalrequire = require("original-require");
var DEFAULT_CONFIG_FILENAME = "truffle.js";
var BACKUP_CONFIG_FILENAME = "truffle-config.js"; // For Windows + Command Prompt
function Config(truffle_directory, working_directory, network) {
var self = this;
var default_tx_values = {
gas: 4712388,
gasPrice: 100000000000, // 100 Shannon,
from: null
};
this._values = {
truffle_directory: truffle_directory || path.resolve(path.join(__dirname, "../")),
working_directory: working_directory || process.cwd(),
network: network,
networks: {},
verboseRpc: false,
gas: null,
gasPrice: null,
from: null,
build: null,
resolver: null,
artifactor: null,
ethpm: {
ipfs_host: "ipfs.infura.io",
ipfs_protocol: "https",
registry: "0x8011df4830b4f696cd81393997e5371b93338878",
install_provider_uri: "https://ropsten.infura.io/truffle"
},
logger: {
log: function() {},
}
};
var props = {
// These are already set.
truffle_directory: function() {},
working_directory: function() {},
network: function() {},
networks: function() {},
verboseRpc: function() {},
build: function() {},
resolver: function() {},
artifactor: function() {},
ethpm: function() {},
logger: function() {},
build_directory: function() {
return path.join(self.working_directory, "build");
},
contracts_directory: function() {
return path.join(self.working_directory, "contracts");
},
contracts_build_directory: function() {
return path.join(self.build_directory, "contracts");
},
migrations_directory: function() {
return path.join(self.working_directory, "migrations");
},
test_directory: function() {
return path.join(self.working_directory, "test");
},
test_file_extension_regexp: function() {
return /.*\.(js|es|es6|jsx|sol)$/
},
example_project_directory: function() {
return path.join(self.truffle_directory, "example");
},
network_id: {
get: function() {
try {
return self.network_config.network_id;
} catch (e) {
return null;
}
},
set: function(val) {
throw new Error("Do not set config.network_id. Instead, set config.networks and then config.networks[<network name>].network_id");
}
},
network_config: {
get: function() {
var network = self.network;
if (network == null) {
throw new Error("Network not set. Cannot determine network to use.");
}
var conf = self.networks[network];
if (conf == null) {
config = {};
}
conf = _.extend({}, default_tx_values, conf);
return conf;
},
set: function(val) {
throw new Error("Don't set config.network_config. Instead, set config.networks with the desired values.");
}
},
from: {
get: function() {
try {
return self.network_config.from;
} catch (e) {
return default_tx_values.from;
}
},
set: function(val) {
throw new Error("Don't set config.from directly. Instead, set config.networks and then config.networks[<network name>].from")
}
},
gas: {
get: function() {
try {
return self.network_config.gas;
} catch (e) {
return default_tx_values.gas;
}
},
set: function(val) {
throw new Error("Don't set config.gas directly. Instead, set config.networks and then config.networks[<network name>].gas")
}
},
gasPrice: {
get: function() {
try {
return self.network_config.gasPrice;
} catch (e) {
return default_tx_values.gasPrice;
}
},
set: function(val) {
throw new Error("Don't set config.gasPrice directly. Instead, set config.networks and then config.networks[<network name>].gasPrice")
}
},
provider: {
get: function() {
if (!self.network) {
return null;
}
var options = self.network_config;
options.verboseRpc = self.verboseRpc;
return Provider.create(options);
},
set: function(val) {
throw new Error("Don't set config.provider directly. Instead, set config.networks and then set config.networks[<network name>].provider")
}
}
};
Object.keys(props).forEach(function(prop) {
self.addProp(prop, props[prop]);
});
};
Config.prototype.addProp = function(key, obj) {
Object.defineProperty(this, key, {
get: obj.get || function() {
return this._values[key] || obj();
},
set: obj.set || function(val) {
this._values[key] = val;
},
configurable: true,
enumerable: true
});
};
Config.prototype.normalize = function(obj) {
var clone = {};
Object.keys(obj).forEach(function(key) {
try {
clone[key] = obj[key];
} catch (e) {
// Do nothing with values that throw.
}
});
return clone;
}
Config.prototype.with = function(obj) {
var normalized = this.normalize(obj);
var current = this.normalize(this);
return _.extend({}, current, normalized);
};
Config.prototype.merge = function(obj) {
var self = this;
var clone = this.normalize(obj);
// Only set keys for values that don't throw.
Object.keys(obj).forEach(function(key) {
try {
self[key] = clone[key];
} catch (e) {
// Do nothing.
}
});
return this;
};
Config.default = function() {
return new Config();
};
Config.detect = function(options, filename) {
// Only attempt to detect the backup if a specific file wasn't asked for.
var checkBackup = false;
if (filename == null) {
filename = DEFAULT_CONFIG_FILENAME;
checkBackup = true;
}
var file = findUp.sync(filename, {cwd: options.working_directory || options.workingDirectory});
if (file == null) {
if (checkBackup == true) {
return this.detect(options, BACKUP_CONFIG_FILENAME);
} else {
throw new TruffleError("Could not find suitable configuration file.");
}
}
return this.load(file, options);
};
Config.load = function(file, options) {
var config = new Config();
config.working_directory = path.dirname(path.resolve(file));
// The require-nocache module used to do this for us, but
// it doesn't bundle very well. So we've pulled it out ourselves.
delete require.cache[Module._resolveFilename(file, module)];
var static_config = originalrequire(file);
config.merge(static_config);
config.merge(options);
return config;
};
module.exports = Config;
|
JavaScript
| 0 |
@@ -1146,24 +1146,111 @@
fle%22%0A %7D,%0A
+ solc: %7B%0A optimizer: %7B%0A enabled: true,%0A runs: 200%0A %7D%0A %7D,%0A
logger:
@@ -1607,24 +1607,49 @@
ction() %7B%7D,%0A
+ solc: function() %7B%7D,%0A
logger:
|
de75d6623dd645127607b50c49ed1ef698072442
|
Use type coercion methods from vega-util.
|
packages/vega-loader/src/type.js
|
packages/vega-loader/src/type.js
|
export var typeParsers = {
boolean: toBoolean,
integer: toNumber,
number: toNumber,
date: toDate,
string: toString
};
var typeTests = [
isBoolean,
isInteger,
isNumber,
isDate
];
var typeList = [
'boolean',
'integer',
'number',
'date'
];
export function inferType(values, field) {
var tests = typeTests.slice(),
value, i, n, j;
for (i=0, n=values.length; i<n; ++i) {
value = field ? values[i][field] : values[i];
for (j=0; j<tests.length; ++j) {
if (isValid(value) && !tests[j](value)) {
tests.splice(j, 1); --j;
}
}
if (tests.length === 0) return 'string';
}
return typeList[typeTests.indexOf(tests[0])];
}
export function inferTypes(data, fields) {
return fields.reduce(function(types, field) {
return types[field] = inferType(data, field), types;
}, {});
}
// -- Type Coercion ----
function toNumber(_) {
return _ == null || _ === '' ? null : +_;
}
function toBoolean(_) {
return _ == null || _ === '' ? null : !_ || _ === 'false' ? false : !!_;
}
function toDate(_, parser) {
return _ == null || _ === '' ? null
: (parser ? parser(_) : Date.parse(_));
}
function toString(_) {
return _ == null || _ === '' ? null : _ + '';
}
// -- Type Checks ----
function isValid(_) {
return _ != null && _ === _;
}
function isBoolean(_) {
return _ === 'true' || _ === 'false' || _ === true || _ === false;
}
function isDate(_) {
return !isNaN(Date.parse(_));
}
function isNumber(_) {
return !isNaN(+_) && !(_ instanceof Date);
}
function isInteger(_) {
return isNumber(_) && (_=+_) === ~~_;
}
|
JavaScript
| 0 |
@@ -1,12 +1,78 @@
+import %7BtoBoolean, toDate, toNumber, toString%7D from 'vega-util';%0A%0A
export var t
@@ -917,394 +917,8 @@
%0A%7D%0A%0A
-// -- Type Coercion ----%0A%0Afunction toNumber(_) %7B%0A return _ == null %7C%7C _ === '' ? null : +_;%0A%7D%0A%0Afunction toBoolean(_) %7B%0A return _ == null %7C%7C _ === '' ? null : !_ %7C%7C _ === 'false' ? false : !!_;%0A%7D%0A%0Afunction toDate(_, parser) %7B%0A return _ == null %7C%7C _ === '' ? null%0A : (parser ? parser(_) : Date.parse(_));%0A%7D%0A%0Afunction toString(_) %7B%0A return _ == null %7C%7C _ === '' ? null : _ + '';%0A%7D%0A%0A
// -
|
a8a16d973b2937c7a302420964c4a996791dc885
|
Add signal dereference utility method.
|
packages/vega-parser/src/util.js
|
packages/vega-parser/src/util.js
|
import {isObject} from 'vega-util';
export function Entry(type, value, params, parent) {
this.id = -1;
this.type = type;
this.value = value;
this.params = params;
if (parent) this.parent = parent;
}
export function entry(type, value, params, parent) {
return new Entry(type, value, params, parent);
}
export function operator(value, params) {
return entry('operator', value, params);
}
// -----
export function ref(op) {
var ref = {$ref: op.id};
// if operator not yet registered, cache ref to resolve later
if (op.id < 0) (op.refs = op.refs || []).push(ref);
return ref;
}
export var tupleidRef = {
$tupleid: 1,
toString: function() { return ':_tupleid_:'; }
};
export function fieldRef(field, name) {
return name ? {$field: field, $name: name} : {$field: field};
}
export var keyFieldRef = fieldRef('key');
export function compareRef(fields, orders) {
return {$compare: fields, $order: orders};
}
export function keyRef(fields, flat) {
var ref = {$key: fields};
if (flat) ref.$flat = true;
return ref;
}
// -----
export var Ascending = 'ascending';
export var Descending = 'descending';
export function sortKey(sort) {
return !isObject(sort) ? ''
: (sort.order === Descending ? '-' : '+')
+ aggrField(sort.op, sort.field);
}
export function aggrField(op, field) {
return (op && op.signal ? '$' + op.signal : op || '')
+ (op && field ? '_' : '')
+ (field && field.signal ? '$' + field.signal : field || '');
}
// -----
export var Scope = 'scope';
export var View = 'view';
export function isSignal(_) {
return _ && _.signal;
}
export function value(specValue, defaultValue) {
return specValue != null ? specValue : defaultValue;
}
|
JavaScript
| 0 |
@@ -1704,12 +1704,71 @@
ultValue;%0A%7D%0A
+%0Aexport function deref(v) %7B%0A return v && v.signal %7C%7C v;%0A%7D%0A
|
4733f7cb4cd4bfef09ee5d5bfd5fc2527f3c9725
|
update function doc
|
lib/api/util/file-export.js
|
lib/api/util/file-export.js
|
'use strict';
const csvTransform = require('stream-transform');
const csvStringify= require('csv-stringify');
/**
* Generate an export file from a query.
* Options can be found here https://csv.js.org
* @param {Object} opts The options object.
* @param {Array} opts.columns An array of key and header objects to use as the column header.
* @param {Object} opts.query Mongoose query object.
* @param {Object} opts.req HTTP request object.
* @param {Object} opts.res HTTP response object.
* @param {String} [opts.extension='csv'] The name of the file extension.
* @param {Function} opts.format Format function that takes the result of the query and returns the file string.
* @param {String} opts.name The name of the file.
* @return {Void} Send back a CSV file.
*/
const generateExport = (opts) => {
const options = Object.assign({
extension: 'csv',
name: 'export',
transform: (doc) => doc,
}, opts);
if (!options.req) {
throw new Error('req is a required property');
}
if (!options.res) {
throw new Error('res is a required property');
}
if (!options.query) {
throw new Error('query is a required property');
}
options.res.setHeader('Content-disposition', `attachment; filename=${options.name}.${options.extension}`);
if (options.contentType) {
options.res.setHeader('Content-Type', options.contentType);
}
options.query.lean()
.cursor()
.pipe(csvTransform(options.transform))
.pipe(csvStringify({
columns: options.columns,
header: true,
}))
.pipe(options.res);
};
module.exports = { generateExport };
|
JavaScript
| 0.000001 |
@@ -727,16 +727,96 @@
e file.%0A
+ * @param %7BFunction%7D opts.transform A transform function to pass to the stream.%0A
* @retu
|
3c9a9a21b4e1f985250983a5cac8b7cd993fc2e7
|
Fix some logic in one of the queries for the candy management.
|
pgt/routes/pokemonCandy.js
|
pgt/routes/pokemonCandy.js
|
var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('../data/pokemon.sqlite');
/* GET home page. */
router.get('/:userId', function(req, res, next) {
var userId = req.params.userId;
//select pdex,name,userEvCandy as candy from pokemon left join userCandy on pdex = userEvBase where userId = 1 and pdex in ( select evBase from pokemon group by evBase );
var query = 'select pdex as userPdex,name as userPname,userEvCandy as userCount,userId from pokemon left join userCandy on pdex = userEvBase ';
query += 'where userId = ? and pdex in ( select evBase from pokemon group by evBase ) order by userPname';
try {
db.all(query,[ userId ], function(err,rows) {
// need to break the table into chunks
var tableChunks = [];
var len = rows.length;
var pertable = 20;
var i = 0;
for (i=0; i < len; i+=pertable){
tableChunks.push(rows.slice(i,i+pertable));
}
res.render('pokemonCandy', { title: 'Pokemon GO Evolve Tracking - Pokemon Candy', tableChunks: tableChunks, rows: rows });
});
} catch(exception) {
console.log("Error with DB, need to reload page");
}
});
router.get('/', function(req, res, next) {
res.send("Missing userId argument");
});
module.exports = router;
|
JavaScript
| 0.000207 |
@@ -442,16 +442,125 @@
Base );%0A
+ // select name from pokemon where pdex in ( select evBase from pokemon where evLevel = 1) order by name;%0A
var
@@ -771,31 +771,33 @@
pokemon
-group by evBase
+where evLevel = 1
) order
|
07a102438775cd855a0b3435fad9bcdb603e97bf
|
Access window correctly in log-message component
|
client/app/pods/components/log-panel/component.js
|
client/app/pods/components/log-panel/component.js
|
//
// Copyright 2009-2014 Ilkka Oksanen <[email protected]>
//
// 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.
//
/* globals $ */
import Mobx from 'mobx';
import { next } from '@ember/runloop';
import { computed } from '@ember/object';
import { gt } from '@ember/object/computed';
import Component from '@ember/component';
import moment from 'moment';
import windowStore from '../../../stores/WindowStore';
import { dispatch } from '../../../utils/dispatcher';
const { autorun } = Mobx;
export default Component.extend({
classNames: ['flex-column', 'flex-1'],
classNameBindings: ['enabled:visible:hidden'],
loading: true,
enabled: true,
window: null,
$dateInput: null,
currentDate: null,
// Temporary solution, pagination is coming
tooManyMessages: gt('sortedLogMessages', 999),
init() {
this._super();
this.set('currentDate', new Date());
const window = windowStore.windows.get(this.windowId);
autorun(() => this.set('logMessages', window.sortedLogMessages));
},
friendlyDate: computed('currentDate', function() {
return moment(this.currentDate).format('dddd, MMMM Do YYYY');
}),
actions: {
nextDay() {
this._seek(1);
},
previousDay() {
this._seek(-1);
},
exit() {
this.set('enabled', false);
this.sendAction('compress');
}
},
didInsertElement() {
this.$().velocity('slideDown', {
duration: 700,
easing: 'easeInOutQuad',
display: 'flex'
});
this.$dateInput = this.$('.logs-date');
this.$dateInput.datepicker({
autoclose: true,
todayHighlight: true,
weekStart: 1
});
this.$dateInput.datepicker().on('changeDate', () => {
this.set('currentDate', this.$dateInput.datepicker('getDate'));
this._fetchData();
});
this._seek(0);
},
_seek(days) {
const newDate = moment(this.currentDate)
.add(days, 'd')
.toDate();
this.set('currentDate', newDate);
this.$dateInput.datepicker('update', newDate);
this._fetchData();
},
_fetchData() {
// Beginning and end of the selected day in unix time format
const date = this.currentDate;
const epochTsStart = moment(date)
.startOf('day')
.unix();
const epochTsEnd = moment(date)
.endOf('day')
.unix();
this.set('loading', true);
dispatch('FETCH_MESSAGE_RANGE', {
window: this.window,
start: epochTsStart,
end: epochTsEnd,
successCb: () => {
this.set('loading', false);
this._loadImages();
}
});
},
_loadImages() {
next(this, function() {
this.$('img[data-src]').each(function() {
const $img = $(this);
$img.attr('src', $img.data('src'));
});
});
}
});
|
JavaScript
| 0.000001 |
@@ -1394,68 +1394,8 @@
);%0A%0A
- const window = windowStore.windows.get(this.windowId);%0A%0A
@@ -1432,16 +1432,21 @@
sages',
+this.
window.s
|
ad0721e27c07bcacb0745a12d6ee3bc9270112c0
|
Fix hasHMM issue in AnalysesList
|
client/src/js/samples/components/Analyses/List.js
|
client/src/js/samples/components/Analyses/List.js
|
import React from "react";
import { map, sortBy } from "lodash-es";
import { connect } from "react-redux";
import { Alert, FormControl, FormGroup, InputGroup, ListGroup } from "react-bootstrap";
import { Link } from "react-router-dom";
import AnalysisItem from "./Item";
import CreateAnalysis from "./Create";
import { analyze } from "../../actions";
import { getCanModify } from "../../selectors";
import {listReadyIndexes} from "../../../indexes/actions";
import { fetchHmms } from "../../../hmm/actions";
import { Icon, Button, LoadingPlaceholder, NoneFound, Flex, FlexItem } from "../../../base";
const AnalysesToolbar = ({ onClick, isDisabled }) => (
<div className="toolbar">
<FormGroup>
<InputGroup>
<InputGroup.Addon>
<Icon name="search" />
</InputGroup.Addon>
<FormControl type="text" />
</InputGroup>
</FormGroup>
<Button
icon="plus-square"
tip="New Analysis"
bsStyle="primary"
onClick={onClick}
disabled={isDisabled}
/>
</div>
);
class AnalysesList extends React.Component {
constructor (props) {
super(props);
this.state = {
show: false
};
}
componentDidMount () {
this.props.onFetchHMMs();
this.props.onListReadyIndexes();
}
render () {
if (this.props.analyses === null || this.props.hmms.documents === null || this.props.indexes === null) {
return <LoadingPlaceholder margin="37px" />;
}
// The content that will be shown below the "New Analysis" form.
let listContent;
if (this.props.analyses.length) {
// The components that detail individual analyses.
listContent = map(sortBy(this.props.analyses, "timestamp").reverse(), (document, index) =>
<AnalysisItem key={index} {...document} />
);
} else {
listContent = <NoneFound noun="analyses" noListGroup />;
}
let hmmAlert;
if (!this.props.hmms.status.installed) {
hmmAlert = (
<Alert bsStyle="warning">
<Flex alignItems="center">
<Icon name="info-circle" />
<FlexItem pad={5}>
<span>The HMM data is not installed. </span>
<Link to="/hmm">Install HMMs</Link>
<span> to use in further NuV analyses.</span>
</FlexItem>
</Flex>
</Alert>
);
}
return (
<div>
{hmmAlert}
{this.props.canModify ?
<AnalysesToolbar
onClick={() => this.setState({show: true})}
/> : null}
<ListGroup>
{listContent}
</ListGroup>
<CreateAnalysis
id={this.props.detail.id}
show={this.state.show}
onHide={() => this.setState({show: false})}
onSubmit={this.props.onAnalyze}
hasHmm={!!this.props.hmms.total_count && this.props.hmms.status.installed}
refIndexes={this.props.indexes}
/>
</div>
);
}
}
const mapStateToProps = (state) => ({
detail: state.samples.detail,
analyses: state.samples.analyses,
indexes: state.samples.readyIndexes,
hmms: state.hmms,
canModify: getCanModify(state)
});
const mapDispatchToProps = (dispatch) => ({
onAnalyze: (sampleId, references, algorithm) => {
map(references, (entry) =>
dispatch(analyze(sampleId, entry.refId, algorithm))
);
},
onFetchHMMs: () => {
dispatch(fetchHmms());
},
onListReadyIndexes: () => {
dispatch(listReadyIndexes());
}
});
export default connect(mapStateToProps, mapDispatchToProps)(AnalysesList);
|
JavaScript
| 0 |
@@ -3283,39 +3283,8 @@
=%7B!!
-this.props.hmms.total_count &&
this
|
d2978300ca66efd701f6c2017516247d7a9d4b08
|
method position
|
client/src/pages/AnswerQuestion/AnswerQuestion.js
|
client/src/pages/AnswerQuestion/AnswerQuestion.js
|
import React from 'react'
import {
Container,
} from 'react-grid-system'
import { RaisedButton } from 'material-ui'
import axios from 'axios'
import isEqual from 'lodash.isequal'
import Question from '../../components/Question'
import {
MultipleChoiceQuestion,
MultipleSelectionQuestion,
} from '../../utils/constant'
class AnswerQuestion extends React.Component {
constructor() {
super()
this.state = {
questionList: [],
isSubmitting: false,
}
}
updateSelectedAnswer = index => value => this.setState((state) => {
const questionList = state.questionList.slice()
questionList[index].selected = value
questionList[index].isWrong = false
return {
...state,
questionList,
}
})
componentDidMount() {
axios.get('/api/questions').then(({ data }) => {
this.setState((state) => ({
...state,
questionList: data.map((question) => ({
...question,
selected: question.kind === MultipleChoiceQuestion ? null : [],
isWrong: false,
}))
}))
})
}
submit = () => {
this.state.questionList.forEach((question) => {
if (question.kind === MultipleChoiceQuestion) {
if (question.selected !== question.correctAnswers) question.isWrong = true
} else if (question.kind === MultipleSelectionQuestion) {
if (!isEqual(question.correctAnswers.sort(), question.selected.sort())) question.isWrong = true
}
})
if (this.state.questionList.some(({ isWrong }) => isWrong)) return
alert('Your answer is correct!')
}
render() {
return (
<Container>
{
this.state.questionList.map((value, index) => (
<Question
{...value}
key={value._id}
updateSelectedAnswer={this.updateSelectedAnswer(index)}
/>
))
}
<RaisedButton
label="Submit"
fullWidth={true}
primary={true}
disabled={this.state.isSubmitting}
onClick={this.submit}
/>
</Container>
)
}
}
export default AnswerQuestion
|
JavaScript
| 0.999929 |
@@ -482,273 +482,10 @@
%7D%0A
-%0A
-updateSelectedAnswer = index =%3E value =%3E this.setState((state) =%3E %7B%0A const questionList = state.questionList.slice()%0A questionList%5Bindex%5D.selected = value%0A questionList%5Bindex%5D.isWrong = false%0A%0A return %7B%0A ...state,%0A questionList,%0A %7D%0A %7D)%0A
%0A c
@@ -815,16 +815,281 @@
%7D)%0A %7D%0A%0A
+ updateSelectedAnswer = index =%3E value =%3E this.setState((state) =%3E %7B%0A const questionList = state.questionList.slice()%0A questionList%5Bindex%5D.selected = value%0A questionList%5Bindex%5D.isWrong = false%0A%0A return %7B%0A ...state,%0A questionList,%0A %7D%0A %7D)%0A%0A
submit
|
33cf9c67d0971c0264f7ebaefb78f27abd23b7ef
|
Enable release notes per library.
|
src/sap.ui.core/src/sap/ui/core/util/LibraryInfo.js
|
src/sap.ui.core/src/sap/ui/core/util/LibraryInfo.js
|
/*!
* ${copyright}
*/
// Provides class sap.ui.core.util.LibraryInfo
sap.ui.define(['jquery.sap.global', 'sap/ui/base/Object', 'jquery.sap.script'],
function(jQuery, BaseObject/* , jQuerySap */) {
"use strict";
/**
* Provides library information.
* @class Provides library information.
*
* @extends sap.ui.base.Object
* @author SAP SE
* @version ${version}
* @constructor
* @private
* @alias sap.ui.core.util.LibraryInfo
*/
var LibraryInfo = BaseObject.extend("sap.ui.core.util.LibraryInfo", {
constructor : function() {
BaseObject.apply(this);
this._oLibInfos = {};
},
destroy : function() {
BaseObject.prototype.destroy.apply(this, arguments);
this._oLibInfos = {};
},
getInterface : function() {
return this;
}
});
LibraryInfo.prototype._loadLibraryMetadata = function(sLibraryName, fnCallback) {
sLibraryName = sLibraryName.replace(/\//g, ".");
if (this._oLibInfos[sLibraryName]) {
jQuery.sap.delayedCall(0, window, fnCallback, [this._oLibInfos[sLibraryName]]);
return;
}
var sUrl = jQuery.sap.getModulePath(sLibraryName, '/'),
that = this;
jQuery.ajax({
url : sUrl + ".library",
dataType : "xml",
error : function(xhr, status, e) {
jQuery.sap.log.error("failed to load library details from '" + sUrl + ".library': " + status + ", " + e);
that._oLibInfos[sLibraryName] = {name: sLibraryName, data: null, url: sUrl};
fnCallback(that._oLibInfos[sLibraryName]);
},
success : function(oData, sStatus, oXHR) {
that._oLibInfos[sLibraryName] = {name: sLibraryName, data: oData, url: sUrl};
fnCallback(that._oLibInfos[sLibraryName]);
}
});
};
LibraryInfo.prototype._getLibraryInfo = function(sLibraryName, fnCallback) {
this._loadLibraryMetadata(sLibraryName, function(oData){
var result = {libs: [], library: oData.name, libraryUrl: oData.url};
if (oData.data) {
var $data = jQuery(oData.data);
result.vendor = $data.find("vendor").text();
result.copyright = $data.find("copyright").text();
result.version = $data.find("version").text();
result.documentation = $data.find("documentation").text();
}
fnCallback(result);
});
};
LibraryInfo.prototype._getThirdPartyInfo = function(sLibraryName, fnCallback) {
this._loadLibraryMetadata(sLibraryName, function(oData){
var result = {libs: [], library: oData.name, libraryUrl: oData.url};
if (oData.data) {
var $Libs = jQuery(oData.data).find("appData").find("thirdparty").children();
$Libs.each(function(i, o){
if (o.nodeName === "lib") {
var $Lib = jQuery(o);
var $license = $Lib.children("license");
result.libs.push({
displayName: $Lib.attr("displayName"),
homepage: $Lib.attr("homepage"),
license: {
url: $license.attr("url"),
type: $license.attr("type"),
file: oData.url + $license.attr("file")
}
});
}
});
}
fnCallback(result);
});
};
LibraryInfo.prototype._getDocuIndex = function(sLibraryName, fnCallback) {
this._loadLibraryMetadata(sLibraryName, function(oData){
var lib = oData.name,
libUrl = oData.url,
result = {"docu": {}, library: lib, libraryUrl: libUrl};
if (!oData.data) {
fnCallback(result);
return;
}
var $Doc = jQuery(oData.data).find("appData").find("documentation");
var sUrl = $Doc.attr("indexUrl");
if (!sUrl) {
fnCallback(result);
return;
}
if ($Doc.attr("resolve") == "lib") {
sUrl = oData.url + sUrl;
}
jQuery.ajax({
url : sUrl,
dataType : "json",
error : function(xhr, status, e) {
jQuery.sap.log.error("failed to load library docu from '" + sUrl + "': " + status + ", " + e);
fnCallback(result);
},
success : function(oData, sStatus, oXHR) {
oData.library = lib;
oData.libraryUrl = libUrl;
fnCallback(oData);
}
});
});
};
return LibraryInfo;
}, /* bExport= */ true);
|
JavaScript
| 0.000022 |
@@ -2159,16 +2159,108 @@
text();%0A
+%09%09%09%09result.releasenotes = $data.find(%22releasenotes%22).attr(%22url%22); // in the appdata section%0A
%09%09%09%7D%0A%09%09%09
|
101e963e78dbf9b764aa494a61bbbd5e213d1630
|
update i18n js
|
src/main/webapp/resources/js/saleassistant.i18n.js
|
src/main/webapp/resources/js/saleassistant.i18n.js
|
(function($) {
var sale_assistant = window.sale_assistant = window.sale_assistant || {};
sale_assistant.zh = sale_assistant.zh || {};
$.extend(true, sale_assistant.zh, {
"ID": "编号",
"Client Name" : "客户姓名",
"Birthday" : "出生日期",
"Client":"客户姓名",
"Zipcode": "邮编",
"Phone": "联系电话",
"Default Address": "默认地址",
"Unknown": "未知",
"Male": "男",
"Female": "女",
"Address": "地址"
});
sale_assistant.client = sale_assistant.client || {};
sale_assistant.client.zh = sale_assistant.client.zh || {};
$.extend(true, sale_assistant.client.zh, {
"Name" : "客户姓名",
"Birthday" : "出生日期",
"Wangwang":"淘宝旺旺",
"QQ": "QQ",
"QQ Name": "QQ 名称",
"Gender": "性别",
"Phone": "联系电话",
"Address": "地址"
});
sale_assistant.l = function(string, module, locale) {
locale = locale || "zh";
codes = sale_assistant[locale];
commonCodes = sale_assistant[locale];
if (module) {
if (sale_assistant[module] && sale_assistant[module][locale]) {
codes = sale_assistant[module][locale];
}
}
if (codes && codes[string]) {
return codes[string];
}
if (commonCodes && commonCodes[string]) {
return commonCodes[string];
}
return string;
};
})(jQuery);
|
JavaScript
| 0 |
@@ -451,32 +451,150 @@
%22Address%22: %22%E5%9C%B0%E5%9D%80%22
+,%0A %22Code%22 : %22%E7%BC%96%E7%A0%81%22,%0A %22Name%22 : %22%E5%90%8D%E7%A7%B0%22,%0A %22Note%22 : %22%E5%A4%87%E6%B3%A8%22,%0A %22note%22 : %22%E5%A4%87%E6%B3%A8%22,%0A %22Chinese%22 : %22%E4%B8%AD%E6%96%87%22
%0A %7D);%0A %0A
|
78261eeded2f602550277044ca2a32f976632b51
|
fix install controller
|
controllers/install.js
|
controllers/install.js
|
var util = require('util');
var config = require('../config');
module.exports.install = function(res, req) {
var url = 'https://www.facebook.com/dialog/pagetab?app_id=%s&redirect_uri=%s';
var urlFormat = util.format(url, config.facebook.id, 'http://facebook.com');
res.redirect(urlFormat);
}
|
JavaScript
| 0 |
@@ -97,14 +97,14 @@
n(re
-s
+q
, re
-q
+s
) %7B%0A
@@ -278,16 +278,21 @@
edirect(
+301,
urlForma
|
d449f20b9f2b365aa4436882330057a260517304
|
Fix travis build
|
tests/index-test.js
|
tests/index-test.js
|
import expect from 'expect'
import React from 'react'
import {render, unmountComponentAtNode} from 'react-dom'
import Component from 'src/'
describe('Component', () => {
let node
beforeEach(() => {
node = document.createElement('div')
})
afterEach(() => {
unmountComponentAtNode(node)
})
it('displays a welcome message', () => {
render(<Component/>, node, () => {
expect(node.innerHTML).toContain('Welcome to React components')
})
})
})
|
JavaScript
| 0 |
@@ -116,50 +116,120 @@
ort
-Component from 'src/'%0A%0Adescribe('Component
+%7B FetchingBasicExample %7D from '../demo/src/demo-containers/fetching-basic'%0A%0Adescribe('FetchingBasicExample tests
', (
@@ -384,34 +384,24 @@
it('
-displays a welcome message
+renders demo app
', (
@@ -419,25 +419,37 @@
render(%3C
-Component
+FetchingBasicExample
/%3E, node
@@ -493,46 +493,16 @@
).to
-Contain('Welcome to React components')
+Exist();
%0A
|
53d03a183251c6071875880259956488ad831ab6
|
ADD dummy update url params
|
resources/js/src/app/services/ItemListService.js
|
resources/js/src/app/services/ItemListService.js
|
var ApiService = require("services/ApiService");
// var NotificationService = require("services/NotificationService");
var ResourceService = require("services/ResourceService");
var UrlService = require("services/UrlService");
module.exports = (function($)
{
var searchParams =
{
searchString: "",
itemsPerPage: 20,
orderBy : "itemName",
orderByKey : "ASC",
page : 1,
facets : "",
categoryId : null,
template : ""
};
return {
getItemList : getItemList,
setSearchString: setSearchString,
setItemsPerPage: setItemsPerPage,
setOrderBy : setOrderBy,
setPage : setPage,
setSearchParams: setSearchParams,
setFacets : setFacets,
setCategoryId : setCategoryId
};
function getItemList()
{
if (searchParams.categoryId || searchParams.searchString.length >= 3)
{
UrlService.setUrlParams(searchParams);
var url = searchParams.categoryId ? "/rest/io/category" : "/rest/io/item/search";
searchParams.template = searchParams.categoryId ? "Ceres::Category.Item.CategoryItem" : "Ceres::ItemList.ItemListView";
_setIsLoading(false);
ApiService.get(url, searchParams)
.done(function(response)
{
_setIsLoading(false);
ResourceService.getResource("itemList").set(response);
ResourceService.getResource("facets").set(response.facets);
})
.fail(function(response)
{
_setIsLoading(false);
NotificationService.error("Error while searching").closeAfter(5000);
});
}
}
function _setIsLoading(isLoading)
{
ResourceService.getResource("itemSearch").set(searchParams);
ResourceService.getResource("isLoading").set(isLoading);
}
/**
* ?searchString=searchString&itemsPerPage=itemsPerPage&orderBy=orderBy&orderByKey=orderByKey&page=page
* @param urlParams
*/
function setSearchParams(urlParams)
{
var queryParams = UrlService.getUrlParams(urlParams);
for (var key in queryParams)
{
searchParams[key] = queryParams[key];
}
}
function setSearchString(searchString)
{
searchParams.searchString = searchString;
searchParams.page = 1;
}
function setItemsPerPage(itemsPerPage)
{
searchParams.itemsPerPage = itemsPerPage;
}
function setOrderBy(orderBy)
{
searchParams.orderBy = orderBy.split("_")[0];
searchParams.orderByKey = orderBy.split("_")[1];
}
function setPage(page)
{
searchParams.page = page;
}
function setFacets(facets)
{
searchParams.facets = facets.toString();
}
function setCategoryId(categoryId)
{
searchParams.categoryId = categoryId;
}
})(jQuery);
|
JavaScript
| 0.000001 |
@@ -545,24 +545,256 @@
%7D;%0A%0A
+ // var urlParams =%0A // %7B%0A // query: %22Sofa%22,%0A // categoryId: 1,%0A // items: 20,%0A // orderBy: %22itemName_ASC%22,%0A // page: 1,%0A // facets: %221,2,3%22%0A // %7D;%0A%0A
return %7B
@@ -794,16 +794,16 @@
eturn %7B%0A
-
@@ -1103,16 +1103,17 @@
tegoryId
+,
%0A %7D;%0A
@@ -1250,44 +1250,25 @@
-UrlService.setUrlParams(searchParams
+_updateUrlParams(
);%0A%0A
@@ -3301,16 +3301,62 @@
%0A %7D%0A%0A
+ function _updateUrlParams()%0A %7B%0A%0A %7D%0A%0A
%7D)(jQuer
|
36fee8013a8702bc2f7d315c1c9bf0a06e6ab09f
|
Use ol.vec.Mat4.makeTransform2D in ol.renderer.canvas.ImageLayer
|
src/ol/renderer/canvas/canvasimagelayerrenderer.js
|
src/ol/renderer/canvas/canvasimagelayerrenderer.js
|
goog.provide('ol.renderer.canvas.ImageLayer');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.vec.Mat4');
goog.require('ol.Image');
goog.require('ol.ImageState');
goog.require('ol.ViewHint');
goog.require('ol.layer.Image');
goog.require('ol.renderer.Map');
goog.require('ol.renderer.canvas.Layer');
/**
* @constructor
* @extends {ol.renderer.canvas.Layer}
* @param {ol.renderer.Map} mapRenderer Map renderer.
* @param {ol.layer.Image} imageLayer Single image layer.
*/
ol.renderer.canvas.ImageLayer = function(mapRenderer, imageLayer) {
goog.base(this, mapRenderer, imageLayer);
/**
* @private
* @type {?ol.Image}
*/
this.image_ = null;
/**
* @private
* @type {!goog.vec.Mat4.Number}
*/
this.imageTransform_ = goog.vec.Mat4.createNumber();
};
goog.inherits(ol.renderer.canvas.ImageLayer, ol.renderer.canvas.Layer);
/**
* @inheritDoc
*/
ol.renderer.canvas.ImageLayer.prototype.getImage = function() {
return goog.isNull(this.image_) ?
null : this.image_.getImageElement();
};
/**
* @protected
* @return {ol.layer.Image} Single image layer.
*/
ol.renderer.canvas.ImageLayer.prototype.getImageLayer = function() {
return /** @type {ol.layer.Image} */ (this.getLayer());
};
/**
* @inheritDoc
*/
ol.renderer.canvas.ImageLayer.prototype.getImageTransform = function() {
return this.imageTransform_;
};
/**
* @inheritDoc
*/
ol.renderer.canvas.ImageLayer.prototype.prepareFrame =
function(frameState, layerState) {
var view2DState = frameState.view2DState;
var viewCenter = view2DState.center;
var viewResolution = view2DState.resolution;
var viewRotation = view2DState.rotation;
var image;
var imageLayer = this.getImageLayer();
var imageSource = imageLayer.getImageSource();
var hints = frameState.viewHints;
if (!hints[ol.ViewHint.ANIMATING] && !hints[ol.ViewHint.INTERACTING]) {
image = imageSource.getImage(
frameState.extent, viewResolution, view2DState.projection);
if (!goog.isNull(image)) {
var imageState = image.getState();
if (imageState == ol.ImageState.IDLE) {
goog.events.listenOnce(image, goog.events.EventType.CHANGE,
this.handleImageChange, false, this);
image.load();
} else if (imageState == ol.ImageState.LOADED) {
this.image_ = image;
}
}
}
if (!goog.isNull(this.image_)) {
image = this.image_;
var imageExtent = image.getExtent();
var imageResolution = image.getResolution();
var imageTransform = this.imageTransform_;
goog.vec.Mat4.makeIdentity(imageTransform);
goog.vec.Mat4.translate(imageTransform,
frameState.size[0] / 2, frameState.size[1] / 2, 0);
goog.vec.Mat4.rotateZ(imageTransform, viewRotation);
goog.vec.Mat4.scale(
imageTransform,
imageResolution / viewResolution,
imageResolution / viewResolution,
1);
goog.vec.Mat4.translate(
imageTransform,
(imageExtent[0] - viewCenter[0]) / imageResolution,
(viewCenter[1] - imageExtent[3]) / imageResolution,
0);
this.updateAttributions(frameState.attributions, image.getAttributions());
this.updateLogos(frameState, imageSource);
}
};
|
JavaScript
| 0.000003 |
@@ -333,16 +333,45 @@
ayer');%0A
+goog.require('ol.vec.Mat4');%0A
%0A%0A%0A/**%0A
@@ -2456,17 +2456,16 @@
image_;%0A
-%0A
var
@@ -2554,127 +2554,41 @@
-var imageTransform = this.imageTransform_;%0A goog.vec.Mat4.makeIdentity(imageTransform);%0A goog.vec.Mat4.translate(
+ol.vec.Mat4.makeTransform2D(this.
imag
@@ -2589,32 +2589,33 @@
s.imageTransform
+_
,%0A frameS
@@ -2659,118 +2659,8 @@
/ 2,
- 0);%0A goog.vec.Mat4.rotateZ(imageTransform, viewRotation);%0A goog.vec.Mat4.scale(%0A imageTransform,
%0A
@@ -2697,24 +2697,16 @@
olution,
-%0A
imageRe
@@ -2744,63 +2744,20 @@
-1);%0A goog.vec.Mat4.translate(%0A imageTransform
+viewRotation
,%0A
@@ -2876,23 +2876,11 @@
tion
-,%0A 0
);%0A
-%0A
@@ -3005,11 +3005,12 @@
e);%0A %7D%0A
+%0A
%7D;%0A
|
8ae60f5a33288d9d1e4f0daf0c77626f63682b7e
|
fix spaces
|
src/vs/code/electron-browser/workbench/workbench.js
|
src/vs/code/electron-browser/workbench/workbench.js
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const perf = require('../../../base/common/performance');
perf.mark('renderer/started');
const bootstrapWindow = require('../../../../bootstrap-window');
// Setup shell environment
process['lazyEnv'] = getLazyEnv();
// Load workbench main JS, CSS and NLS all in parallel. This is an
// optimization to prevent a waterfall of loading to happen, because
// we know for a fact that workbench.desktop.main will depend on
// the related CSS and NLS counterparts.
bootstrapWindow.load([
'vs/workbench/workbench.desktop.main',
'vs/nls!vs/workbench/workbench.desktop.main',
'vs/css!vs/workbench/workbench.desktop.main'
],
function (workbench, configuration) {
perf.mark('didLoadWorkbenchMain');
return process['lazyEnv'].then(function () {
perf.mark('main/startup');
// @ts-ignore
return require('vs/workbench/electron-browser/desktop.main').main(configuration);
});
}, {
removeDeveloperKeybindingsAfterLoad: true,
canModifyDOM: function (windowConfig) {
showPartsSplash(windowConfig);
},
beforeLoaderConfig: function (windowConfig, loaderConfig) {
loaderConfig.recordStats = true;
},
beforeRequire: function () {
perf.mark('willLoadWorkbenchMain');
}
});
/**
* @param {{
* partsSplashPath?: string,
* highContrast?: boolean,
* defaultThemeType?: string,
* extensionDevelopmentPath?: string[],
* folderUri?: object,
* workspace?: object
* }} configuration
*/
function showPartsSplash(configuration) {
perf.mark('willShowPartsSplash');
let data;
if (typeof configuration.partsSplashPath === 'string') {
try {
data = JSON.parse(require('fs').readFileSync(configuration.partsSplashPath, 'utf8'));
} catch (e) {
// ignore
}
}
// high contrast mode has been turned on from the outside, e.g. OS -> ignore stored colors and layouts
if (data && configuration.highContrast && data.baseTheme !== 'hc-black') {
data = undefined;
}
// developing an extension -> ignore stored layouts
if (data && configuration.extensionDevelopmentPath) {
data.layoutInfo = undefined;
}
// minimal color configuration (works with or without persisted data)
let baseTheme, shellBackground, shellForeground;
if (data) {
baseTheme = data.baseTheme;
shellBackground = data.colorInfo.editorBackground;
shellForeground = data.colorInfo.foreground;
} else if (configuration.highContrast || configuration.defaultThemeType === 'hc') {
baseTheme = 'hc-black';
shellBackground = '#000000';
shellForeground = '#FFFFFF';
} else if (configuration.defaultThemeType === 'vs') {
baseTheme = 'vs';
shellBackground = '#FFFFFF';
shellForeground = '#000000';
} else {
baseTheme = 'vs-dark';
shellBackground = '#1E1E1E';
shellForeground = '#CCCCCC';
}
const style = document.createElement('style');
style.className = 'initialShellColors';
document.head.appendChild(style);
style.innerHTML = `body { background-color: ${shellBackground}; color: ${shellForeground}; margin: 0; padding: 0; }`;
if (data && data.layoutInfo) {
// restore parts if possible (we might not always store layout info)
const { id, layoutInfo, colorInfo } = data;
const splash = document.createElement('div');
splash.id = id;
splash.className = baseTheme;
if (layoutInfo.windowBorder) {
splash.style.position = 'relative';
splash.style.height = 'calc(100vh - 2px)';
splash.style.width = 'calc(100vw - 2px)';
splash.style.border = '1px solid var(--window-border-color)';
splash.style.setProperty('--window-border-color', colorInfo.windowBorder);
if (layoutInfo.windowBorderRadius) {
splash.style.borderRadius = layoutInfo.windowBorderRadius;
}
}
// ensure there is enough space
layoutInfo.sideBarWidth = Math.min(layoutInfo.sideBarWidth, window.innerWidth - (layoutInfo.activityBarWidth + layoutInfo.editorPartMinWidth));
if (configuration.folderUri || configuration.workspace) {
// folder or workspace -> status bar color, sidebar
splash.innerHTML = `
<div style="position: absolute; width: 100%; left: 0; top: 0; height: ${layoutInfo.titleBarHeight}px; background-color: ${colorInfo.titleBarBackground}; -webkit-app-region: drag;"></div>
<div style="position: absolute; height: calc(100% - ${layoutInfo.titleBarHeight}px); top: ${layoutInfo.titleBarHeight}px; ${layoutInfo.sideBarSide}: 0; width: ${layoutInfo.activityBarWidth}px; background-color: ${colorInfo.activityBarBackground};"></div>
<div style="position: absolute; height: calc(100% - ${layoutInfo.titleBarHeight}px); top: ${layoutInfo.titleBarHeight}px; ${layoutInfo.sideBarSide}: ${layoutInfo.activityBarWidth}px; width: ${layoutInfo.sideBarWidth}px; background-color: ${colorInfo.sideBarBackground};"></div>
<div style="position: absolute; width: 100%; bottom: 0; left: 0; height: ${layoutInfo.statusBarHeight}px; background-color: ${colorInfo.statusBarBackground};"></div>
`;
} else {
// empty -> speical status bar color, no sidebar
splash.innerHTML = `
<div style="position: absolute; width: 100%; left: 0; top: 0; height: ${layoutInfo.titleBarHeight}px; background-color: ${colorInfo.titleBarBackground}; -webkit-app-region: drag;"></div>
<div style="position: absolute; height: calc(100% - ${layoutInfo.titleBarHeight}px); top: ${layoutInfo.titleBarHeight}px; ${layoutInfo.sideBarSide}: 0; width: ${layoutInfo.activityBarWidth}px; background-color: ${colorInfo.activityBarBackground};"></div>
<div style="position: absolute; width: 100%; bottom: 0; left: 0; height: ${layoutInfo.statusBarHeight}px; background-color: ${colorInfo.statusBarNoFolderBackground};"></div>
`;
}
document.body.appendChild(splash);
}
perf.mark('didShowPartsSplash');
}
/**
* @returns {Promise<void>}
*/
function getLazyEnv() {
// @ts-ignore
const ipc = require('electron').ipcRenderer;
return new Promise(function (resolve) {
const handle = setTimeout(function () {
resolve();
console.warn('renderer did not receive lazyEnv in time');
}, 10000);
ipc.once('vscode:acceptShellEnv', function (event, shellEnv) {
clearTimeout(handle);
bootstrapWindow.assign(process.env, shellEnv);
// @ts-ignore
resolve(process.env);
});
ipc.send('vscode:fetchShellEnv');
});
}
|
JavaScript
| 0.000656 |
@@ -1635,18 +1635,17 @@
lean,%0A *
-
+%09
defaultT
|
e817cf35bae9c6076847b50524e3e141d90ad965
|
make page context more dynaimic
|
scripts/content.js
|
scripts/content.js
|
var pageContext;
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
var data = request.data || {};
if (!request || !request.action) {
sendResponse({ data: data, success: false });
}
switch (request.action) {
case "getContext":
sendResponse({ data: pageContext, success: true });
break;
case "showField":
if (!request.data || !request.data.field) {
sendResponse({ data: data, success: false });
}
var spinner = new ajaxLoader($("body"));
var element = $("span:contains('" + request.data.field + "')")
if (element && element.length > 0) {
var widgetElement = element.closest(".widget");
if (widgetElement.length > 0 && widgetElement[0].id) {
//inject a script
var script = document.createElement('script');
script.textContent = "formLayoutConfiguration.expandCollapse('" + widgetElement[0].id.replace("widget", "") + "', false);";
(document.head || document.documentElement).appendChild(script);
script.remove();
}
if (spinner) {
spinner.remove();
}
element.fadeOut(300)
.fadeIn(300)
.fadeOut(300)
.fadeIn(300)
.fadeOut(300)
.fadeIn(300)
.fadeOut(300)
.fadeIn(300)
.fadeOut(300)
.fadeIn(300);
}
if (spinner) {
spinner.remove();
}
break;
default:
sendResponse({ data: data, success: false });
break;
}
});
var s = document.createElement('script');
s.src = chrome.extension.getURL('scripts/pageScript.js');
(document.head || document.documentElement).appendChild(s);
s.onload = function() {
s.remove();
};
// Event listener
document.addEventListener('asseticExtension_context', function(e) {
if (!e || !e.detail) {
return;
}
pageContext = e.detail;
});
}
});
});
}
|
JavaScript
| 0.000001 |
@@ -281,16 +281,100 @@
ntext%22:%0A
+ if (!pageContext) %7B%0A getContext%0A %7D else %7B%0A
@@ -425,24 +425,38 @@
s: true %7D);%0A
+ %7D%0A
@@ -1489,36 +1489,32 @@
-
.fadeOut(300)%0A
@@ -1752,33 +1752,44 @@
;%0A%0A %7D
-%0A
+ else %7B%0A
if (
@@ -1807,32 +1807,36 @@
+
spinner.remove()
@@ -1829,32 +1829,50 @@
inner.remove();%0A
+ %7D%0A
%7D%0A
@@ -1997,14 +1997,69 @@
%7D);%0A
-%0A
var
-s
+contextScript;%0A%0Afunction getContext() %7B%0A contextScript
= d
@@ -2091,17 +2091,33 @@
ript');%0A
-s
+ contextScript
.src = c
@@ -2152,25 +2152,25 @@
pts/
-pageScrip
+getContex
t.js');%0A
(doc
@@ -2165,16 +2165,20 @@
t.js');%0A
+
(documen
@@ -2229,55 +2229,39 @@
ild(
-s);%0As.onload = function() %7B%0A s.remove();%0A%7D;%0A
+contextScript);%0A%7D%0AgetContext();
%0A//
@@ -2424,45 +2424,70 @@
il;%0A
-%0A%7D);%0A%0A %7D%0A %7D
+ if (contextScript) %7B%0A contextScript.remove(
);%0A %7D
);%0A%7D
@@ -2482,12 +2482,12 @@
);%0A %7D
-);
%0A%7D
+);
|
2e04db7faf7d179031ad7ac97e63270fbce50326
|
Add TileBody.onNewTarget callback
|
src/tilemap/component/TileBody.js
|
src/tilemap/component/TileBody.js
|
import Component from "../../Component"
import Vector2 from "../../math/Vector2"
const point = new Vector2()
const direction = new Vector2()
class TileBody extends Component
{
constructor() {
super()
this.x = 0
this.y = 0
this.speed = 60
this.speedX = 0
this.speedY = 0
this.targetX = 0
this.targetY = 0
this._target = false
this._path = null
this.onTargetDone = null
}
onEnable() {
this.targetX = this.parent.x
this.targetY = this.parent.y
this.parent.parent.getTileFromWorld(this.targetX, this.targetY, point)
this.x = point.x
this.y = point.y
}
update(tDelta) {
this.speedX = 0
this.speedY = 0
if(this._target) {
let speed = this.speed * tDelta
direction.set(this.targetX - this.parent.x, this.targetY - this.parent.y)
const distance = direction.length()
if(distance <= speed) {
speed = distance
if(this._path && this._path.length > 0) {
const node = this._path.pop()
this.target(node.x, node.y)
}
else {
this._target = false
}
}
direction.normalize()
this.speedX = direction.x * speed
this.speedY = direction.y * speed
this.parent.move(this.speedX, this.speedY)
if(!this._target) {
this.speedX = 0
this.speedY = 0
this._target = false
if(this.onTargetDone) {
this.onTargetDone()
}
}
}
}
target(x, y) {
this.parent.parent.getWorldFromTile(x, y, point)
this.x = x
this.y = y
this.targetX = point.x
this.targetY = point.y
this._target = true
}
path(path) {
this._path = path
if(!this._target && path && path.length > 0) {
const node = path.pop()
this.target(node.x, node.y)
}
}
}
export default TileBody
|
JavaScript
| 0 |
@@ -359,16 +359,42 @@
= null%0A
+%09%09this.onNewTarget = null%0A
%09%09this.o
@@ -1372,24 +1372,79 @@
get(x, y) %7B%0A
+%09%09if(this.onNewTarget) %7B%0A%09%09%09this.onNewTarget(x, y)%0A%09%09%7D%0A
%09%09this.paren
|
38a1f81007bc289060d5abeea101032e85028ae2
|
clean up pass on scrollview
|
tests/karma-main.js
|
tests/karma-main.js
|
var tests = [
'tests/vendor/jasmine/jasmine-jquery',
// Load mocks and vendor init
//'tests/mocks/init',
// 'tests/spec/rich-application',
// 'tests/spec/rich-autolayout-constraints',
// 'tests/spec/rich-autolayout-modifiers',
// 'tests/spec/rich-autolayout-utils',
// 'tests/spec/rich-autolayout',
// 'tests/spec/rich-collectionview',
// 'tests/spec/rich-itemview-events',
// 'tests/spec/rich-region',
'tests/spec/rich-scrollview',
// 'tests/spec/rich-utils',
// 'tests/spec/rich-vfl',
// 'tests/spec/rich-view-animate',
// 'tests/spec/rich-view-className',
// 'tests/spec/rich-view-constraints',
// 'tests/spec/rich-view-core',
// 'tests/spec/rich-view-size',
// 'tests/spec/rich-view-subviews',
// 'tests/spec/rich-view-zindex',
];
requirejs.config({
baseUrl: '/base',
shim: {
'tests/vendor/jasmine/jasmine-jquery': {
'deps': ['jquery']
},
},
deps: tests,
callback: function(){
jasmine.getFixtures().fixturesPath = '/base/tests/fixtures';
window.__karma__.start();
}
});
|
JavaScript
| 0 |
@@ -110,27 +110,24 @@
/init',%0A%0A
- //
'tests/spec
@@ -145,27 +145,24 @@
cation',%0A
- //
'tests/spec
@@ -187,35 +187,32 @@
onstraints',%0A
- //
'tests/spec/ric
@@ -235,27 +235,24 @@
ifiers',%0A
- //
'tests/spec
@@ -271,35 +271,32 @@
yout-utils',%0A
- //
'tests/spec/ric
@@ -309,27 +309,24 @@
layout',%0A
- //
'tests/spec
@@ -343,35 +343,32 @@
ectionview',%0A
- //
'tests/spec/ric
@@ -382,35 +382,32 @@
iew-events',%0A
- //
'tests/spec/ric
@@ -450,27 +450,24 @@
llview',%0A
- //
'tests/spec
@@ -479,27 +479,24 @@
-utils',%0A
- //
'tests/spec
@@ -506,27 +506,24 @@
ch-vfl',%0A
- //
'tests/spec
@@ -542,27 +542,24 @@
nimate',%0A
- //
'tests/spec
@@ -580,27 +580,24 @@
ssName',%0A
- //
'tests/spec
@@ -620,27 +620,24 @@
raints',%0A
- //
'tests/spec
@@ -653,27 +653,24 @@
w-core',%0A
- //
'tests/spec
@@ -686,27 +686,24 @@
w-size',%0A
- //
'tests/spec
@@ -727,19 +727,16 @@
ws',%0A
- //
'tests/
|
7bd97fcefa14fd48472e152d6e7c497d33a61c6f
|
validate state size argument
|
scripts/extract.js
|
scripts/extract.js
|
var async = require('async');
var fs = require('fs');
var util = require('util');
var argv = require('minimist')(process.argv.slice(2), {
alias: {
v: 'verbose',
t: 'transform',
n: 'state-size'
},
boolean: 'verbose'
});
if (argv.transform && ! Array.isArray(argv.transform))
argv.transform = [argv.transform];
var extract = require('../lib/extract');
var extractStream = extract.bind(null, {
stateSize: argv['state-size']
});
var loadDone = function(err, markovs) {
if (argv.verbose) console.error('merging');
var markov = markovs.reduce(function(markov, other) {
return markov ? markov.merge(other) : other;
}, null);
if (markov) process.stdout.write(JSON.stringify(markov.save()));
};
var transforms = argv.transform && argv.transform.map(function(spec) {
// jshint evil:true, unused:false
var match = /^(\w+)(\(.*\))?$/.exec(spec);
if (!match) throw new Error(util.format('invalid transform %j', spec));
var Transform = require('../lib/stream/' + match[1] );
var create = new Function(['Transform'], 'return new Transform' + (match[2] || '()') + ';');
return function(stream) {
var transform = create(Transform);
stream.pipe(transform);
return transform;
};
});
var loadQ = async.queue(function load(path, done) {
var stream = fs.createReadStream(path, {
encoding: 'utf8'
});
if (argv.verbose) console.error('extracting', path);
if (transforms)
transforms.forEach(function(transform) {stream = transform(stream);});
if (argv.verbose) stream.on('end', function() {
console.error('extracted', path);
});
extractStream(stream, done);
}, 32);
async.parallel(
argv._.map(function(path) {
return loadQ.push.bind(loadQ, path);
}), loadDone);
|
JavaScript
| 0.000002 |
@@ -344,16 +344,142 @@
form%5D;%0A%0A
+var stateSize = argv%5B'state-size'%5D;%0Aif (typeof stateSize !== 'number') %7B%0A throw new Error('invalid state-size option');%0A%7D%0A%0A
var extr
@@ -507,24 +507,24 @@
/extract');%0A
-
var extractS
@@ -567,34 +567,25 @@
teSize:
-argv%5B'
state
--s
+S
ize
-'%5D
%0A%7D);%0Avar
|
1ef7eb807dcf8d9a11f7f5d616aa64b40c742585
|
Simplify merge utility
|
src/utilities/functional/merge.js
|
src/utilities/functional/merge.js
|
'use strict';
const { throwError } = require('../error');
const merge = function (type, objA, ...objects) {
if (objects.length === 0) { return objA; }
if (objects.length === 1) {
return simpleMerge({ objA, objects, type });
}
return recursiveMerge({ objA, objects, type });
};
const simpleMerge = function ({ objA, objects, type }) {
const [objB] = objects;
validateInputType({ objA, objB });
validateInputSameTypes({ objA, objB });
if (Array.isArray(objA) && Array.isArray(objB)) {
return mergeMap[type].array({ arrayA: objA, arrayB: objB });
}
if (objA.constructor === Object) {
return mergeObjects({ objA, objB, type });
}
};
const validateInputType = function ({ objA, objB }) {
const isInvalidType =
(objA.constructor !== Object && !Array.isArray(objA)) ||
(objB.constructor !== Object && !Array.isArray(objB));
if (!isInvalidType) { return; }
const message = `'deepMerge' utility cannot merge together objects with arrays: ${objA} and ${objB}`;
throwError(message);
};
const validateInputSameTypes = function ({ objA, objB }) {
const isDifferentTypes =
(objA.constructor === Object && objB.constructor !== Object) ||
(objA.constructor !== Object && objB.constructor === Object);
if (!isDifferentTypes) { return; }
const message = `'deepMerge' utility can only merge together objects or arrays: ${objA} and ${objB}`;
throwError(message);
};
const mergeObjects = function ({ objA, objB, type }) {
return Object.entries(objB).reduce(
(newObjA, [objBKey, objBVal]) =>
mergeObjectProp({ objA: newObjA, objBKey, objBVal, type }),
objA,
);
};
const mergeObjectProp = function ({ objA, objBKey, objBVal, type }) {
const objAVal = objA[objBKey];
const shouldDeepMerge = objAVal &&
objBVal &&
((Array.isArray(objAVal) && Array.isArray(objBVal)) ||
(objAVal.constructor === Object && objBVal.constructor === Object));
const newVal = shouldDeepMerge
? mergeMap[type].top(objAVal, objBVal)
: objBVal;
return { ...objA, [objBKey]: newVal };
};
const concatArrays = function ({ arrayA, arrayB }) {
return [...arrayA, ...arrayB];
};
const recursiveMerge = function ({ objA, objects, type }) {
const newObjA = mergeMap[type].top(objA, objects[0]);
const newObjects = objects.slice(1);
return mergeMap[type].top(newObjA, ...newObjects);
};
// Deep merge objects and arrays (concatenates for arrays)
const deepMerge = merge.bind(null, 'deep');
// Deep merge objects and arrays (merge for arrays)
const mergeMap = {
deep: {
top: deepMerge,
array: concatArrays,
},
},
};
module.exports = {
deepMerge,
};
|
JavaScript
| 0.000003 |
@@ -12,299 +12,78 @@
';%0A%0A
-const %7B throwError %7D = require('../error');%0A%0Aconst merge = function (type, objA, ...objects) %7B%0A if (objects.length === 0) %7B return objA; %7D%0A%0A if (objects.length === 1) %7B%0A return simpleMerge(%7B objA, objects, type %7D);%0A %7D%0A%0A return recursiveMerge(%7B objA, objects, type %7D);%0A%7D;%0A
+// Like Lodash merge() but faster and does not mutate input
%0Aconst
-simple
+deep
Merg
@@ -88,34 +88,32 @@
rge = function (
-%7B
objA, objects, t
@@ -109,1665 +109,309 @@
obj
-ects, type %7D) %7B%0A const %5BobjB%5D = objects;%0A%0A validateInputType(%7B objA, objB %7D);%0A validateInputSameTypes(%7B objA, objB %7D);%0A%0A if (Array.isArray(objA) && Array.isArray(objB)) %7B%0A return mergeMap%5Btype%5D.array(%7B arrayA: objA, arrayB: objB %7D);%0A %7D%0A%0A if (objA.constructor === Object) %7B%0A return mergeObjects(%7B objA, objB, type %7D);%0A %7D%0A%7D;%0A%0Aconst validateInputType = function (%7B objA, objB %7D) %7B%0A const isInvalidType =%0A (objA.constructor !== Object && !Array.isArray(objA)) %7C%7C%0A (objB.constructor !== Object && !Array.isArray(
+B, ...objects) %7B%0A if (objects.length %3E 0) %7B%0A const newObjA = deepMerge(objA,
objB)
-)
;%0A
-if (!isInvalidType) %7B return; %7D%0A%0A const message = %60'deepMerge' utility cannot merge together objects with arrays: $%7BobjA%7D and $%7BobjB%7D%60;%0A throwError(message);%0A%7D;%0A%0Aconst validateInputSameTypes = function (%7B objA, objB %7D) %7B%0A const isDifferentTypes =%0A (objA.constructor === Object && objB.constructor !== Object) %7C%7C%0A (objA.constructor !== Object && objB.constructor === Object);%0A if (!isDifferentTypes) %7B return; %7D%0A%0A const message = %60'deepMerge' utility can only merge together objects or arrays: $%7BobjA%7D and $%7BobjB%7D%60;%0A throwError(message);%0A%7D;%0A%0Aconst mergeObjects = function (%7B objA, objB, type %7D) %7B%0A return Object.entries(objB).reduce(%0A (newObjA, %5BobjBKey, objBVal%5D) =%3E%0A mergeObjectProp(%7B objA: newObjA, objBKey, objBVal, type %7D),%0A objA,%0A );%0A%7D;%0A%0Aconst mergeObjectProp = function (%7B objA, objBKey, objBVal, type %7D) %7B%0A const objAVal = objA%5BobjBKey%5D;%0A const shouldDeepMerge = objAVal &&%0A objBVal &&%0A ((Array.isArray(objAVal) && Array.isArray(objBVal)) %7C%7C%0A (objAVal.constructor === Object && objBVal.constructor === Object));%0A const newVal = shouldDeepMerge%0A ? mergeMap%5Btype%5D.top(objAVal
+ return deepMerge(newObjA, ...objects);%0A %7D%0A%0A if (!isObjectTypes(objA, objB)) %7B return objB; %7D%0A%0A const rObjB = Object.entries(objB).map((%5BobjBKey, objBVal%5D) =%3E %7B%0A const newObjBVal = deepMerge(objA%5BobjBKey%5D
, ob
@@ -420,43 +420,22 @@
Val)
+;
%0A
-: objBVal;%0A return %7B ...objA,
+return %7B
%5Bob
@@ -449,71 +449,24 @@
new
+ObjB
Val %7D;%0A
-%7D;%0A%0Aconst concatArrays = function (%7B arrayA, arrayB %7D) %7B
+ %7D);
%0A r
@@ -475,57 +475,66 @@
urn
-%5B...arrayA, ...arrayB%5D
+Object.assign(%7B%7D, objA, ...rObjB)
;%0A%7D;%0A%0A
-%0A
const
-recursiveMerge
+isObjectTypes
= f
@@ -542,18 +542,16 @@
nction (
-%7B
objA, ob
@@ -555,416 +555,101 @@
obj
-ects, type %7D) %7B%0A const newObjA = mergeMap%5Btype%5D.top(
+B) %7B%0A return
objA
-,
+ &&
obj
-ects%5B0%5D);%0A const newObjects = objects.slice(1);%0A return mergeMap%5Btype%5D.top(newObjA, ...newObjects);%0A%7D;%0A%0A// Deep merge objects and arrays (concatenates for arrays)%0Aconst deepMerge = merge.bind(null, 'deep');%0A%0A// Deep merge objects and arrays (merge for arrays)%0A%0Aconst mergeMap = %7B%0A deep: %7B%0A top: deepMerge,%0A array: concatArrays,%0A %7D,%0A %7D,
+A.constructor === Object &&%0A objB && objB.constructor === Object;
%0A%7D;%0A
|
fa2901c6b0180308d5f3d48e35bdab1687660d18
|
Remove straggler System.import
|
src/validations/html/slowparse.js
|
src/validations/html/slowparse.js
|
import Validator from '../Validator';
const errorMap = {
ATTRIBUTE_IN_CLOSING_TAG: error => ({
reason: 'attribute-in-closing-tag',
payload: {tag: error.closeTag.name},
}),
CLOSE_TAG_FOR_VOID_ELEMENT: error => ({
reason: 'close-tag-for-void-element',
payload: {tag: error.closeTag.name},
}),
EMPTY_TITLE_ELEMENT: () => ({
reason: 'empty-title-element',
suppresses: ['missing-title'],
}),
HTML_CODE_IN_CSS_BLOCK: () => ({reason: 'html-in-css-block'}),
INVALID_ATTR_NAME: error => ({
reason: 'invalid-attribute-name',
payload: {attribute: error.attribute.name.value},
suppresses: ['lower-case-attribute-name'],
}),
INVALID_TAG_NAME: (error, source) => {
const tagName = error.openTag.name;
if (tagName === '') {
const tagMatch = /^<\s+([A-Za-z0-9-]+)/.exec(
source.slice(error.openTag.start),
);
if (tagMatch) {
return {
reason: 'space-before-tag-name',
payload: {tag: tagMatch[1]},
suppresses: ['unexpected-close-tag'],
};
}
}
return {
reason: 'invalid-tag-name',
payload: {tag: error.openTag.name},
};
},
UNSUPPORTED_ATTR_NAMESPACE: error => ({
reason: 'invalid-attribute-name',
payload: {attribute: error.attribute.name.value},
suppresses: ['lower-case-attribute-name'],
}),
MULTIPLE_ATTR_NAMESPACES: error => ({
reason: 'invalid-attribute-name',
payload: {attribute: error.attribute.name.value},
suppresses: ['lower-case-attribute-name'],
}),
SELF_CLOSING_NON_VOID_ELEMENT: error => ({
reason: 'self-closing-non-void-element',
payload: {tag: error.name},
}),
UNCLOSED_TAG: error => ({
reason: 'unclosed-tag',
payload: {tag: error.openTag.name},
}),
UNEXPECTED_CLOSE_TAG: error => ({
reason: 'unexpected-close-tag',
payload: {tag: error.closeTag.name},
}),
UNTERMINATED_ATTR_VALUE: error => ({
reason: 'unterminated-attribute-value',
payload: {attribute: error.attribute.name.value, tag: error.openTag.name},
}),
UNTERMINATED_OPEN_TAG: error => ({
reason: 'unterminated-open-tag',
payload: {tag: error.openTag.name},
suppresses: ['attribute-value', 'lower-case', 'lower-case-attribute-name'],
}),
UNTERMINATED_CLOSE_TAG: error => ({
reason: 'unterminated-close-tag',
payload: {tag: error.closeTag.name},
suppresses: ['unclosed-tag'],
}),
UNTERMINATED_COMMENT: () => ({reason: 'unterminated-comment'}),
UNBOUND_ATTRIBUTE_VALUE: error => ({
reason: 'unbound-attribute-value',
payload: {value: error.value},
suppresses: ['attribute-value', 'lower-case-attribute-name'],
}),
};
function findChildNode({childNodes}, nodeName) {
for (const node of childNodes) {
if (node.nodeName === nodeName) {
return node;
}
}
return null;
}
function emptyTitleElementDetector(_, root) {
const html = findChildNode(root, 'HTML');
const head = html ? findChildNode(html, 'HEAD') : null;
const title = head ? findChildNode(head, 'TITLE') : null;
return (title && !title.childNodes.length) ?
{type: 'EMPTY_TITLE_ELEMENT', cursor: title.parseInfo.openTag.end} :
null;
}
const errorDetectors = [emptyTitleElementDetector];
class SlowparseValidator extends Validator {
constructor(source) {
super(source, 'html', errorMap);
}
async _getRawErrors() {
const {Slowparse} = await System.import('../linters');
let error;
try {
({error} = Slowparse.HTML(document, this._source, {errorDetectors}));
} catch (e) {
error = null;
}
if (error !== null) {
return [error];
}
return [];
}
_keyForError(error) {
return error.type;
}
_locationForError(error) {
const lines = this._source.slice(0, error.cursor).split('\n');
const row = lines.length - 1;
const column = lines[row].length - 1;
return {row, column};
}
}
export default source => new SlowparseValidator(source).getAnnotations();
|
JavaScript
| 0 |
@@ -30,16 +30,62 @@
idator';
+%0Aimport importLinters from '../importLinters';
%0A%0Aconst
@@ -3463,34 +3463,22 @@
ait
-System.import('../l
+importL
inters
-'
+(
);%0A
|
b52a730f9bba9e1b0ef4e83fb3b219e34931d613
|
Rename function
|
src/renderer/webgl/pipelines/BitmapMaskPipeline.js
|
src/renderer/webgl/pipelines/BitmapMaskPipeline.js
|
/**
* @author Richard Davey <[email protected]>
* @author Felipe Alfonso <@bitnenfer>
* @copyright 2022 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var Class = require('../../../utils/Class');
var GetFastValue = require('../../../utils/object/GetFastValue');
var ShaderSourceFS = require('../shaders/BitmapMask-frag.js');
var ShaderSourceVS = require('../shaders/BitmapMask-vert.js');
var WEBGL_CONST = require('../const');
var WebGLPipeline = require('../WebGLPipeline');
/**
* @classdesc
* The Bitmap Mask Pipeline handles all of the bitmap mask rendering in WebGL for applying
* alpha masks to Game Objects. It works by sampling two texture on the fragment shader and
* using the fragments alpha to clip the region.
*
* The fragment shader it uses can be found in `shaders/src/BitmapMask.frag`.
* The vertex shader it uses can be found in `shaders/src/BitmapMask.vert`.
*
* The default shader attributes for this pipeline are:
*
* `inPosition` (vec2, offset 0)
*
* The default shader uniforms for this pipeline are:
*
* `uResolution` (vec2)
* `uMainSampler` (sampler2D)
* `uMaskSampler` (sampler2D)
* `uInvertMaskAlpha` (bool)
*
* @class BitmapMaskPipeline
* @extends Phaser.Renderer.WebGL.WebGLPipeline
* @memberof Phaser.Renderer.WebGL.Pipelines
* @constructor
* @since 3.0.0
*
* @param {Phaser.Types.Renderer.WebGL.WebGLPipelineConfig} config - The configuration options for this pipeline.
*/
var BitmapMaskPipeline = new Class({
Extends: WebGLPipeline,
initialize:
function BitmapMaskPipeline (config)
{
config.fragShader = GetFastValue(config, 'fragShader', ShaderSourceFS),
config.vertShader = GetFastValue(config, 'vertShader', ShaderSourceVS),
config.batchSize = GetFastValue(config, 'batchSize', 1),
config.vertices = GetFastValue(config, 'vertices', [ -1, 1, -1, -7, 7, 1 ]),
config.attributes = GetFastValue(config, 'attributes', [
{
name: 'inPosition',
size: 2,
type: WEBGL_CONST.FLOAT
}
]);
WebGLPipeline.call(this, config);
},
boot: function ()
{
WebGLPipeline.prototype.boot.call(this);
this.set1i('uMainSampler', 0);
this.set1i('uMaskSampler', 1);
},
resize: function (width, height)
{
WebGLPipeline.prototype.resize.call(this, width, height);
this.set2f('uResolution', width, height);
},
/**
* Binds necessary resources and renders the mask to a separated framebuffer.
* The framebuffer for the masked object is also bound for further use.
*
* @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#beginMask
* @since 3.0.0
*
* @param {Phaser.Display.Masks.BitmapMask} mask - The BitmapMask instance that called beginMask.
* @param {Phaser.GameObjects.GameObject} maskedObject - GameObject masked by the mask GameObject.
* @param {Phaser.Cameras.Scene2D.Camera} camera - The camera rendering the current mask.
*/
beginMask: function (mask, maskedObject, camera)
{
this.renderer.enableBitmapMask(mask, camera);
},
/**
* The masked game objects framebuffer is unbound and its texture
* is bound together with the mask texture and the mask shader and
* a draw call with a single quad is processed. Here is where the
* masking effect is applied.
*
* @method Phaser.Renderer.WebGL.Pipelines.BitmapMaskPipeline#endMask
* @since 3.0.0
*
* @param {Phaser.Display.Masks.BitmapMask} mask - The BitmapMask instance that called endMask.
* @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to render to.
* @param {Phaser.Renderer.WebGL.RenderTarget} [renderTarget] - Optional WebGL RenderTarget.
*/
endMask: function (mask, camera, renderTarget)
{
var gl = this.gl;
var renderer = this.renderer;
// The renderable Game Object that is being used for the bitmap mask
var bitmapMask = mask.bitmapMask;
if (bitmapMask && gl)
{
renderer.drawBitmapMask(bitmapMask, camera, this);
if (renderTarget)
{
this.set2f('uResolution', renderTarget.width, renderTarget.height);
}
this.set1i('uInvertMaskAlpha', mask.invertAlpha);
// Finally, draw a triangle filling the whole screen
gl.drawArrays(this.topology, 0, 3);
if (renderTarget)
{
this.set2f('uResolution', this.width, this.height);
}
renderer.resetTextures();
}
}
});
module.exports = BitmapMaskPipeline;
|
JavaScript
| 0.000005 |
@@ -3191,14 +3191,13 @@
rer.
-enable
+begin
Bitm
|
6906d1f6d5f05e14ffabeb05540533a8958fb6e6
|
use better variable names in enrichment.js relates to #481
|
src/server/enrichment-map/enrichment/enrichment.js
|
src/server/enrichment-map/enrichment/enrichment.js
|
/*
documentation for enrichment
sample request URL: http://localhost:3000/api/enrichment/?genes=HCFC1 ATM
parameter:
genes - [string] a list of gene symbols delimited by whitespace
return:
[vector of Object] relevant info for valid genes
*/
const request = require('request');
const csv = require('csvtojson');
const fs = require('fs');
const _ = require('lodash');
const path = require("path");
// remove #WARNING and #INFO
const parseBody = (body) => {
// remove the second line
const lines = body.split('\n');
lines.slice(0, 1);
const str1 = body.split('\n').slice(0, 1).join("\n");
let str2 = body.split('\n').slice(2).join("\n"); // concatenate at last
// remove lines starting with #
const str3 = str2.replace(/^#.*$/mg, "");
const str4 = (str1 + '\n').concat(str3);
return str4;
}
const enrichment = (query, userSetting) => {
const promise = new Promise( (resolve, reject) => {
const defaultSetting = {
"output": "mini",
"organism": "hsapiens",
"significant": "1",
"sort_by_structure": "1",
"ordered_query": "0",
"as_ranges": "0",
"no_iea": "1",
"underrep": "0",
"hierfiltering": "none",
"user_thr": "1",
"min_set_size": "5",
"max_set_size": "200",
"threshold_algo": "fdr",
"domain_size_type": "annotated",
"custbg_cb": "none",
"sf_GO:BP": "1",
"sf_REAC": "1",
"query": query
};
const formData = _.assign({}, defaultSetting, userSetting);
request.post({ url: "https://biit.cs.ut.ee/gprofiler_archive3/r1741_e90_eg37/web/", formData: formData }, (err, httpResponse, body) => {
if (err) {
reject(err);
}
fs.writeFileSync("outputFile", parseBody(body));
// convert csv to json, extract "term id"
let collection = [];
let ret = {};
csv({ delimiter: "\t" })
.fromFile("outputFile")
.on('json', (jsonObj) => {
collection.push(jsonObj);
})
.on('done', (error) => {
_.forEach(collection, (elem) => {
ret[elem["term ID"]] = {signf: elem["signf"], pvalue: elem["p-value"], T: elem["T"]};
ret[elem["term ID"]]["Q&T"] = elem["Q&T"];
ret[elem["term ID"]]["Q&T/Q"] = elem["Q&T/Q"];
ret[elem["term ID"]]["Q&T/T"] = elem["Q&T/T"];
ret[elem["term ID"]]["t type"] = elem["t type"];
ret[elem["term ID"]]["t group"] = elem["t group"];
ret[elem["term ID"]]["t name"] = elem["t name"];
ret[elem["term ID"]]["t depth"] = elem["t depth"];
ret[elem["term ID"]]["Q&T list"] = elem["Q&T list"];
});
fs.unlinkSync(path.resolve(__dirname, "outputFile"));
resolve(ret);
});
});
});
return promise;
};
module.exports = {enrichment};
// enrichment(['ATM']).then(function (results) {
// console.log(results);
// });
|
JavaScript
| 0 |
@@ -435,20 +435,46 @@
arse
-Body = (body
+GProfilerResponse = (gProfilerResponse
) =%3E
@@ -520,20 +520,33 @@
lines =
-body
+gProfilerResponse
.split('
@@ -587,20 +587,33 @@
str1 =
-body
+gProfilerResponse
.split('
@@ -654,20 +654,33 @@
str2 =
-body
+gProfilerResponse
.split('
@@ -865,16 +865,17 @@
str4;%0A%7D
+;
%0A%0A%0Aconst
@@ -1679,20 +1679,33 @@
sponse,
-body
+gProfilerResponse
) =%3E %7B%0A
@@ -1796,17 +1796,43 @@
arse
-Body(body
+GProfilerResponse(gProfilerResponse
));%0A
|
afb0e743f0c556c9bcbace669df76502d40b2897
|
remove ghost comment
|
iot-industrial-internet/src/main/webapp/information_sources/information_source_controllers.js
|
iot-industrial-internet/src/main/webapp/information_sources/information_source_controllers.js
|
/*
* IoT - Industrial Internet Framework
* Apache License Version 2.0, January 2004
* Released as a part of Helsinki University
* Software Engineering Lab in summer 2015
*/
/* global informationSources */
informationSources.controller('InformationSourcesController', ['$scope', 'InformationSource', function($scope, InformationSource) {
$scope.sources = InformationSource.query();
$scope.deleteSource = function(id) {
InformationSource.delete({sourceid: id}, function() {
$scope.sources = InformationSource.query();
}, function(error) {
showError(error.data.message);
});
};
}]);
informationSources.controller('InformationSourceController', ['$scope', '$routeParams', 'InformationSource', 'Sensor',
function($scope, $routeParams, InformationSource, Sensor) {
$scope.source = InformationSource.get({sourceid: $routeParams.sourceid});
$scope.sensors = Sensor.query({sourceid: $routeParams.sourceid}, function(value, headers) {
});
}]);
informationSources.controller('SensorController', ['$scope', '$routeParams', 'Sensor', 'Readout', function($scope, $routeParams, Sensor, Readout) {
$scope.sensor = Sensor.get({sensorid: $routeParams.sensorid});
$scope.readouts = Readout.query({sensorid: $routeParams.sensorid});
//Function to allow reading of sensor.active value into the UI properly
$scope.boolToStr = function(arg) {
return arg ? 'true' : 'false'
};
$scope.filter = function() {
$scope.readouts = Readout.query({sensorid: $routeParams.sensorid, more: $scope.more, less: $scope.less});
};
$scope.save = function() {
// console.log($scope.sensor);
$scope.sensor.$edit({sensorid: $routeParams.sensorid}, function() {
$scope.sensor = Sensor.get({sensorid: $routeParams.sensorid});
});
};
}]);
informationSources.controller('AddInformationSourceController', ['$scope', 'InformationSource', '$location', function($scope, InformationSource, $location) {
$scope.types = ['XML', 'JSON'];
$scope.is = new InformationSource();
$scope.back = function() {
window.history.back();
};
$scope.submit = function() {
$scope.is.readFrequency = $scope.readFrequency_s * 1000;
$scope.is.readInterval = $scope.radioModel;
$scope.is.startDate = $scope.startDate;
$scope.is.endDate = $scope.endDate;
// $scope.is.startDate = $scope.startDate + $scope.time;
$scope.is.$save({}, function() {
$location.path('/sources');
},
function(error) {
showError(error.data.message);
});
};
$scope.today = function() {
$scope.startDate = new Date();
};
$scope.today();
$scope.toggleMin = function() {
$scope.minDate = $scope.minDate ? null : new Date();
};
$scope.toggleMin();
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
$scope.radioModel = 'Never';
}]);
informationSources.controller('EditInformationSourceController', ['$scope', 'InformationSource', '$location', '$routeParams', function($scope, InformationSource, $location, $routeParams) {
$scope.types = ['XML', 'JSON'];
$scope.is = InformationSource.get({sourceid: $routeParams.sourceid}, function() {
$scope.readFrequency_s = $scope.is.readFrequency / 1000;
$scope.startDate = $scope.is.startDate;
$scope.endDate = $scope.is.endDate;
$scope.radioModel = $scope.is.readInterval;
});
$scope.back = function() {
window.history.back();
};
$scope.submit = function() {
$scope.is.readFrequency = $scope.readFrequency_s * 1000;
$scope.is.readInterval = $scope.radioModel;
$scope.is.startDate = $scope.startDate;
$scope.is.endDate = $scope.endDate;
// $scope.is.startDate = $scope.startDate + $scope.time;
$scope.is.$edit({}, function() {
$location.path('/sources');
},
function(error) {
showError(error.data.message);
});
};
$scope.toggleMin = function() {
$scope.minDate = $scope.minDate ? null : new Date();
};
$scope.toggleMin();
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
}]);
|
JavaScript
| 0 |
@@ -1166,16 +1166,27 @@
eadout',
+ '$window',
functio
@@ -1224,16 +1224,25 @@
Readout
+, $window
) %7B%0A
@@ -1925,67 +1925,28 @@
$
-scope.sensor = Sensor.get(%7Bsensorid: $routeParams.sensorid%7D
+window.history.back(
);%0A
|
c6c0736e20f4d88ff928d035115131d54576260d
|
Add first Vue component test
|
test/javascript/components/ResourceSection.test.js
|
test/javascript/components/ResourceSection.test.js
|
import ResourceSection from 'components/ResourceSection';
test('hello world', () => {
expect('hello world').toMatch(/hello world/);
});
|
JavaScript
| 0 |
@@ -4,133 +4,1388 @@
ort
-ResourceSection from 'components/ResourceSection';%0A%0Atest('hello world', () =%3E %7B%0A expect('hello world').toMatch(/hello world/
+%7B parseNode %7D from '../test_helpers';%0Aimport %7B mount,%0A createLocalVue %7D from '@vue/test-utils';%0A%0Aimport Vuex from 'vuex';%0Aimport annotations from %22store/modules/annotations%22;%0Aimport annotations_ui from %22store/modules/annotations_ui%22;%0Aimport footnotes_ui from %22store/modules/footnotes_ui%22;%0Aimport resources_ui from %22store/modules/resources_ui%22;%0A%0Aimport ResourceSection from 'components/ResourceSection';%0A%0Aconst localVue = createLocalVue();%0AlocalVue.use(Vuex);%0A%0Adescribe('ResourceSection', () =%3E %7B%0A let store;%0A%0A beforeEach(() =%3E %7B%0A store = new Vuex.Store(%7B%0A modules: %7Bannotations,%0A annotations_ui,%0A footnotes_ui,%0A resources_ui%7D%0A %7D);%0A %7D);%0A%0A test('correctly places an annotation', () =%3E %7B%0A const annotation = %7B%0A %22id%22: 352630,%0A %22resource_id%22: 63432,%0A %22start_paragraph%22: 0,%0A %22end_paragraph%22: 0,%0A %22start_offset%22: 1,%0A %22end_offset%22: 5,%0A %22kind%22: %22link%22,%0A %22content%22: %22http://google.com/%22,%0A %22created_at%22: %222019-02-11T19:16:03.604Z%22,%0A %22updated_at%22: %222019-02-11T19:16:03.604Z%22%0A %7D;%0A%0A store.commit('annotations/append', %5Bannotation%5D);%0A%0A const wrapper = mount(ResourceSection, %7Bstore, localVue, propsData: %7B%0A index: 0,%0A el: parseNode('%3Cdiv%3EHello world%3C/div%3E')%0A %7D%7D);%0A%0A expect(wrapper.find(%60a%5Bhref=%22$%7Bannotation.content%7D%22%5D%60).text()).toEqual('ello');%0A %7D
);%0A%7D
|
5e0887538903781041d985f17a3d5b4665be355f
|
Fix comments
|
test/web/controllers/WebHooksWebController.test.js
|
test/web/controllers/WebHooksWebController.test.js
|
'use strict';
// ------- Imports -------------------------------------------------------------
const test = require('ava');
const chai = require('chai');
const RabbitManagement = require('../../../src/lib/RabbitManagement');
const HooksHelper = require('../../helpers/HooksHelper');
// ------- Init ----------------------------------------------------------------
chai.should();
test.beforeEach(HooksHelper.startBlinkWebApp);
test.afterEach(HooksHelper.stopBlinkWebApp);
// ------- Tests ---------------------------------------------------------------
/**
* GET /api/v1/webhooks
*/
test('GET /api/v1/webhooks should respond with JSON list available webhooks', async (t) => {
const res = await t.context.supertest.get('/api/v1/webhooks')
.auth(t.context.config.app.auth.name, t.context.config.app.auth.password);
res.status.should.be.equal(200);
// Check response to be json
res.header.should.have.property('content-type');
res.header['content-type'].should.match(/json/);
// Check response.
res.body.should.have.property('customerio')
.and.have.string('/api/v1/webhooks/customerio');
res.body.should.have.property('gambit-chatbot-mdata')
.and.have.string('/api/v1/webhooks/gambit-chatbot-mdata');
});
/**
* POST /api/v1/webhooks/customerio
*/
test('POST /api/v1/webhooks/customerio should publish message to customer-io queue', async (t) => {
const data = {
data: {
campaign_id: '0',
customer_id: 'example_customer',
email_address: '[email protected]',
email_id: 'example_email',
subject: 'Example Email',
template_id: '0',
},
event_id: 'abc123',
event_type: 'example_webhook',
timestamp: 1491337360,
};
const res = await t.context.supertest.post('/api/v1/webhooks/customerio')
.auth(t.context.config.app.auth.name, t.context.config.app.auth.password)
.send(data);
res.status.should.be.equal(200);
// Check response to be json
res.header.should.have.property('content-type');
res.header['content-type'].should.match(/json/);
// Check response.
res.body.should.have.property('ok', true);
// Check that the message is queued.
const rabbit = new RabbitManagement(t.context.config.amqpManagement);
// TODO: queue cleanup to make sure that it's not OLD message.
const messages = await rabbit.getMessagesFrom('customer-io-webhook', 1);
messages.should.be.an('array').and.to.have.lengthOf(1);
messages[0].should.have.property('payload');
const payload = messages[0].payload;
const messageData = JSON.parse(payload);
messageData.should.have.property('data');
messageData.data.should.be.eql(data);
});
/**
* POST /api/v1/webhooks/gambit-mdata
*/
test('POST /api/v1/webhooks/gambit-chatbot-mdata should validate incoming message', async (t) => {
// Test empty message
const responseToEmptyPayload = await t.context.supertest
.post('/api/v1/webhooks/gambit-chatbot-mdata')
.auth(t.context.config.app.auth.name, t.context.config.app.auth.password)
.send({});
responseToEmptyPayload.status.should.be.equal(422);
responseToEmptyPayload.body.should.have.property('ok', false);
responseToEmptyPayload.body.should.have.property('message')
.and.have.string('"phone" is required');
// Test one of [keyword, args, mms_image_url] presence rule
const testOneOfPayload = {
phone: '15555225222',
profile_id: '167181555',
message_id: '841415468',
// Empty should be treated as not present
keyword: '',
args: '',
mms_image_url: '',
};
const responseToTestOneOfPayload = await t.context.supertest
.post('/api/v1/webhooks/gambit-chatbot-mdata')
.auth(t.context.config.app.auth.name, t.context.config.app.auth.password)
.send(testOneOfPayload);
responseToTestOneOfPayload.status.should.be.equal(422);
responseToTestOneOfPayload.body.should.have.property('ok', false);
responseToTestOneOfPayload.body.should.have.property('message')
.and.have.string('must contain at least one of [keyword, args, mms_image_url]');
// Test one of [keyword, args, mms_image_url] presence rule
const minimalViablePayload = {
phone: '15555225222',
profile_id: '167181555',
message_id: '841415468',
keyword: 'BLINKMEUP',
};
const responseToMinimalViablePayload = await t.context.supertest
.post('/api/v1/webhooks/gambit-chatbot-mdata')
.auth(t.context.config.app.auth.name, t.context.config.app.auth.password)
.send(minimalViablePayload);
responseToMinimalViablePayload.status.should.be.equal(200);
responseToMinimalViablePayload.body.should.have.property('ok', true);
// Test empty message
// TODO: factory test data generator?
const fullPayload = {
phone: '15555225222',
carrier: 'tmobile',
profile_id: '167181555',
profile_first_name: 'Sergii',
profile_last_name: 'Tkachenko',
profile_email: '[email protected]',
profile_street1: 'FL 1',
profile_street2: '',
profile_city: 'New York',
profile_state: 'NY',
profile_postal_code: '10010',
profile_age: '',
profile_birthdate: '2000-01-01',
profile_birthyear: '',
profile_cause: '',
profile_college_gradyear: '',
profile_ctd_completed: '',
profile_ctd_day1: '',
profile_ctd_day2: '',
profile_ctd_day3: '',
profile_ctd_start: '',
profile_date_of_birth: '2000-01-01',
profile_edutype: '',
profile_gambit_chatbot_response: 'Hi it\'s Freddie from DoSomething...',
profile_sfw_day3: '',
profile_source: 'Niche',
profile_texting_frequency: '',
args: '',
keyword: 'BLINKMEUP',
timestamp: '2017-04-19T13:35:56Z',
message_id: '841415468',
mdata_id: '14372',
mms_image_url: '',
phone_number_without_country_code: '15555225222',
};
const responseToFullPayload = await t.context.supertest
.post('/api/v1/webhooks/gambit-chatbot-mdata')
.auth(t.context.config.app.auth.name, t.context.config.app.auth.password)
.send(fullPayload);
responseToFullPayload.status.should.be.equal(200);
responseToFullPayload.body.should.have.property('ok', true);
});
// ------- End -----------------------------------------------------------------
|
JavaScript
| 0 |
@@ -2676,16 +2676,24 @@
/gambit-
+chatbot-
mdata%0A *
@@ -3435,16 +3435,23 @@
/ Empty
+string
should b
|
99bb8926eeb70a870ea30843bc053d6675324752
|
Fix bug with creating footer
|
tools/removeDemo.js
|
tools/removeDemo.js
|
// This script removes demo app files
import rimraf from "rimraf";
import fs from "fs";
import colors from "colors";
/* eslint-disable no-console */
const pathsToRemove = [
"./source/modules/demo",
"./source/modules/header-presentation",
"./source/modules/header/*",
"./source/modules/footer/*",
"./source/pages/index.pug",
"./source/pages/buttons.pug",
"./source/pages/components.pug",
"./source/pages/forms.pug",
"./source/pages/typography.pug",
"./source/pages/docs.pug",
"./source/pages/faq.pug",
"./source/static/assets/favicons/*",
"./source/static/assets/fonts/*",
"./source/static/assets/images/content/*",
"./source/static/assets/icons/*",
"./source/static/assets/sprite/*",
"./tools/removeDemo.js" // this file
];
const filesToCreate = [
{
path: "./source/pages/home.pug",
content: `extends ../layouts/default
include ../modules/footer/footer
include ../modules/header/header
block head
- title = "Home page"
block header
+header()
block main
h1 Home page
block footer
+footer()
`
},
{
path: "./source/modules/header/header.pug",
content: `mixin header(data)
header.header&attributes(attributes)
//-
`
},
{
path: "./source/modules/header/header.styl",
content: ".header\n\t//\n"
},
{
path: "./source/pages/index.pug",
content: `extends ../layouts/default
include ../modules/_page-list/_page-list
block head
- title = "Pages list"
style
:stylus
@import "../static/styles/core/variables.styl"
@import "../static/styles/_variables.styl"
@import "../static/styles/core/mixins.styl"
@import "../static/styles/_mixins.styl"
@import "../modules/_page-list/_page-list.styl"
block page
+page-list(pageList.data)
`
},
{
path: "./source/modules/footer.pug",
content: `mixin footer(data)
footer.footer&attributes(attributes)
p © You copyright
`
},
{
path: "./source/modules/stylus.pug",
content: `mixin footer(data)
.footer
//
`
}
];
function removePath(path, callback) {
rimraf(path, error => {
if (error) throw new Error(error);
callback();
});
}
function createFile(file) {
fs.writeFile(file.path, file.content, error => {
if (error) throw new Error(error);
});
}
function removePackageJsonScriptEntry(scriptName) {
const packageJsonPath = "./package.json";
let fileData = fs.readFileSync(packageJsonPath);
let content = JSON.parse(fileData);
delete content.scripts[scriptName];
fs.writeFileSync(packageJsonPath, JSON.stringify(content, null, 2) + "\n");
}
let numPathsRemoved = 0;
pathsToRemove.map(path => {
removePath(path, () => {
numPathsRemoved++;
if (numPathsRemoved === pathsToRemove.length) {
// All paths have been processed
// Now we can create files since we're done deleting.
filesToCreate.map(file => createFile(file));
}
});
});
removePackageJsonScriptEntry("remove-demo");
console.log(colors.green("Demo app removed."));
|
JavaScript
| 0 |
@@ -1770,16 +1770,23 @@
s/footer
+/footer
.pug%22,%0A
@@ -1923,18 +1923,26 @@
les/
-stylus.pug
+footer/footer.styl
%22,%0A
|
22118f629b931fc8f237a353b4ef04b3e8d024e2
|
exit builder on complete
|
packages/core/lib/index.js
|
packages/core/lib/index.js
|
const build = require("./builder")
const startRouter = require("./router")
const path = require("path")
const fs = require('fs')
const copyDirectory = require("./utils/copyDirectory")
const debug = require('debug')('core')
const mkdirp = require('mkdirp');
const slash = require("./utils/fixPathSlashes")
var getHash = function(str){
return require("crypto").createHash('sha1').update(str).digest('hex')
}
function setupEnvVariables(sourcePath){
// Load environment variables from .env file if present
require('dotenv').config({path: path.resolve(sourcePath, '.env')})
// Default env variables.
process.env.SOURCEPATH = slash(sourcePath)
const DEFAULTBUILDPATH = path.join( require("os").tmpdir(), "zeroservertmp", getHash(process.env.SOURCEPATH) )
process.env.PORT = process.env.PORT || 3000
process.env.SESSION_TTL = process.env.SESSION_TTL || 1000 * 60 * 60 * 24 * 365 // 1 year
process.env.SESSION_SECRET = process.env.SESSION_SECRET || 'k3yb0Ard c@t'
process.env.BUILDPATH = slash(process.env.BUILDPATH || DEFAULTBUILDPATH)
// create the build folder if not present already
mkdirp.sync(process.env.BUILDPATH)
}
// npmi module sometime prevents Ctrl+C to shut down server. This helps do that.
if (process.platform === "win32") {
var rl = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
rl.on("SIGINT", function () {
process.emit("SIGINT");
});
}
process.on("SIGINT", function () {
//graceful shutdown
process.exit();
});
function server(path){
setupEnvVariables(path)
var updateManifestFn = startRouter(/*manifest, forbiddenFiles,*/ process.env.BUILDPATH)
return new Promise((resolve, reject)=>{
build(path, process.env.BUILDPATH, (manifest, forbiddenFiles, filesUpdated)=>{
updateManifestFn(manifest, forbiddenFiles, filesUpdated)
resolve()
})
})
}
// Build beforehand
const fork = require('child_process').fork;
const bundlerProgram = require.resolve("zero-bundler-process")
var getLambdaID = function(entryFile){
return require("crypto").createHash('sha1').update(entryFile).digest('hex')
}
function getBundleInfo(endpointData){
return new Promise(async (resolve, reject)=>{
const entryFilePath = endpointData[1]
const lambdaID = getLambdaID(endpointData[0])
if (!bundlerProgram) return resolve(false)
const parameters = [endpointData[0], endpointData[1], endpointData[2], "zero-builds/" + lambdaID];
const options = {
stdio: [ 0, 1, 2, 'ipc' ]
};
const child = fork(bundlerProgram, parameters, options);
child.on('message', message => {
resolve(message)
})
})
}
function builder(sourcePath){
//process.env.BUILDPATH = path.join(sourcePath, "zero-builds")
process.env.ISBUILDER = "true"
process.env.NODE_ENV = "production"
var bundleInfoMap = {}
setupEnvVariables(sourcePath)
return new Promise((resolve, reject)=>{
build(sourcePath, process.env.BUILDPATH, async (manifest, forbiddenFiles, filesUpdated)=>{
//console.log(manifest)
for(var i in manifest.lambdas){
var endpointData = manifest.lambdas[i]
var lambdaID = getLambdaID(endpointData[0])
console.log(`[${(~~i+1)}/${manifest.lambdas.length}] Building`, endpointData[0], lambdaID)
var info = await getBundleInfo(endpointData)
bundleInfoMap[lambdaID] = {info} //the router needs the data at .info of each key
}
debug("bundleInfo", bundleInfoMap)
fs.writeFileSync(path.join(process.env.BUILDPATH, "/zero-builds/build-info.json"), JSON.stringify(bundleInfoMap), 'utf8')
// copy zero-builds folder to local folder
copyDirectory(path.join(process.env.BUILDPATH, "/zero-builds"), path.join(process.env.SOURCEPATH, "/zero-builds"))
}, true)
})
}
module.exports = {
server: server,
build: builder
}
|
JavaScript
| 0 |
@@ -3767,16 +3767,64 @@
lds%22))%0A%0A
+ // exit the process%0A process.exit()%0A%0A
%0A %7D,
|
41e814b691be85cc2399bdf377b3ef87010694a1
|
Optimize return
|
carty.js
|
carty.js
|
'use strict';
var extend = require('extend');
var emitter = require('./util/emitter');
var toFloat = require('./util/toFloat');
function isTypeOf(type, item) {
return typeof item === type;
}
var isString = isTypeOf.bind(null, typeof "");
var isUndefined = isTypeOf.bind(null, typeof undefined);
var isFunction = isTypeOf.bind(null, typeof isTypeOf);
var isObject = isTypeOf.bind(null, typeof {});
function getValue(value, context, args) {
if (isFunction(value)) {
value = value.apply(context, args || []);
}
return value;
}
function getFloat(value, context, args) {
return toFloat(getValue(value, context, args));
}
function getOption(options, key) {
if (arguments.length === 1) {
return extend({}, options);
}
return key && !isUndefined(options[key]) ? options[key] : null;
}
var _defaultOptions = {
store: null,
currency: 'USD',
shipping: null,
tax: null
};
var _defaultAttributes = {
quantity: 1,
price: 0
};
function createItem(attr) {
if (isFunction(attr)) {
attr = attr();
}
if (isString(attr)) {
attr = {id: attr};
}
if (!isObject(attr) || (!attr.label && !attr.id)) {
throw 'Item must be a string or an object with at least an id or label attribute.';
}
var _attr = extend({}, _defaultAttributes, attr);
function item() {
return extend({}, _attr);
}
item.id = function() {
return _attr.id || _attr.label;
};
item.label = function() {
return _attr.label || _attr.id;
};
item.quantity = function() {
return toFloat(_attr.quantity);
};
item.price = function() {
return toFloat(_attr.price);
};
item.currency = function() {
return _attr.currency;
};
item.shipping = function() {
return toFloat(_attr.shipping);
};
item.tax = function() {
return toFloat(_attr.tax);
};
item.equals = function(otherItem) {
try {
return createItem(otherItem).id() === item.id();
} catch (e) {
return false;
}
};
return item;
}
function createCart(options) {
var _options = extend({}, _defaultOptions, options);
var _store = _options.store;
var _items = [];
function cart() {
return _items.slice(0);
}
var emit = emitter(cart);
cart.option = getOption.bind(cart, _options);
cart.size = function() {
return _items.length;
};
cart.has = function(item) {
return !!has(item);
};
cart.get = function(item) {
var found = has(item);
return !found ? null : found.item;
};
cart.add = function(item) {
add(item);
return cart;
};
cart.remove = function(item) {
remove(item);
return cart;
};
cart.clear = function() {
clear();
return cart;
};
cart.each = function(callback, context) {
_items.every(function(item, index) {
return false !== callback.call(context, item, index, cart);
});
return cart;
};
cart.quantity = function () {
return cart().reduce(function (previous, item) {
return previous + item.quantity();
}, 0);
};
cart.total = function () {
return cart().reduce(function (previous, item) {
return previous + (item.price() * item.quantity());
}, 0);
};
cart.shipping = function () {
if (!cart.size()) {
return 0;
}
return cart().reduce(function (previous, item) {
return previous + item.shipping();
}, getFloat(_options.shipping, cart));
};
cart.tax = function () {
if (!cart.size()) {
return 0;
}
return cart().reduce(function (previous, item) {
return previous + item.tax();
}, getFloat(_options.tax, cart));
};
cart.grandTotal = function () {
return cart.total() + cart.tax() + cart.shipping();
};
function load() {
if (!_store || !_store.enabled()) {
return;
}
return _store.load(function(items) {
_items = items.map(function(attr) {
return createItem(attr);
});
});
}
function save() {
if (!emit('save')) {
return;
}
if (!_store || !_store.enabled()) {
return emit('saved');;
}
_store.save(_items.map(function(item) {
return item();
}), function() {
emit('saved');
});
}
function clear() {
if (!emit('clear')) {
return;
}
_items.length = 0;
if (!_store || !_store.enabled()) {
return emit('cleared');
}
_store.clear(function() {
emit('cleared');
});
}
function has(attr) {
var checkItem, found = false;
try {
checkItem = createItem(attr);
} catch (e) {
return false;
}
_items.every(function(item, index) {
if (checkItem.equals(item)) {
found = {item: item, index: index};
}
return !found;
});
return found;
}
function add(attr) {
var item = createItem(attr);
if (!emit('add', item)) {
return;
}
var existing = has(item);
if (existing) {
item = createItem(extend({}, existing.item(), item(), {
quantity: existing.item.quantity() + item.quantity()
}));
}
if (item.quantity() <= 0) {
remove(item);
return;
}
if (existing) {
_items[existing.index] = item;
} else {
_items.push(item);
}
save();
emit('added', item);
}
function remove(attr) {
var existing = has(attr);
if (!existing || !emit('remove', existing.item)) {
return;
}
_items.splice(existing.index, 1);
save();
emit('removed', existing.item);
}
load();
return cart;
}
function carty(options) {
return createCart(options);
}
carty.option = getOption.bind(carty, _defaultOptions);
module.exports = carty;
|
JavaScript
| 0.000101 |
@@ -5722,32 +5722,39 @@
) %7B%0A
+return
remove(item);%0A
@@ -5751,36 +5751,16 @@
(item);%0A
- return;%0A
|
33558c42a9c3ef66ba4b7e5b16df3c79765f731a
|
Add ip filter
|
src/DebugBar/Resources/openhandler.js
|
src/DebugBar/Resources/openhandler.js
|
if (typeof(PhpDebugBar) == 'undefined') {
// namespace
var PhpDebugBar = {};
PhpDebugBar.$ = jQuery;
}
(function($) {
var csscls = function(cls) {
return PhpDebugBar.utils.csscls(cls, 'phpdebugbar-openhandler-');
};
PhpDebugBar.OpenHandler = PhpDebugBar.Widget.extend({
className: 'phpdebugbar-openhandler',
defaults: {
items_per_page: 20
},
render: function() {
var self = this;
this.$el.appendTo('body').hide();
this.$closebtn = $('<a href="javascript:"><i class="fa fa-times"></i></a>');
this.$table = $('<tbody />');
$('<div>PHP DebugBar | Open</div>').addClass(csscls('header')).append(this.$closebtn).appendTo(this.$el);
$('<table><thead><tr><th>Load</th><th>Method</th><th>URL</th><th>Date</th><th>IP</th></tr></thead></table>').append(this.$table).appendTo(this.$el);
this.$actions = $('<div />').addClass(csscls('actions')).appendTo(this.$el);
this.$closebtn.on('click', function() {
self.hide();
});
this.$loadmorebtn = $('<a href="javascript:">Load more</a>')
.appendTo(this.$actions)
.on('click', function() {
self.find(self.last_find_request, self.last_find_request.offset + self.get('items_per_page'), self.handleFind.bind(self));
});
this.$showonlycurrentbtn = $('<a href="javascript:">Show only current URL</a>')
.appendTo(this.$actions)
.on('click', function() {
self.$table.empty();
self.find({uri: window.location.pathname}, 0, self.handleFind.bind(self));
});
this.$showallbtn = $('<a href="javascript:">Show all</a>')
.appendTo(this.$actions)
.on('click', function() {
self.refresh();
});
this.$clearbtn = $('<a href="javascript:">Delete all</a>')
.appendTo(this.$actions)
.on('click', function() {
self.clear(function() {
self.hide();
});
});
this.addSearch();
this.$overlay = $('<div />').addClass(csscls('overlay')).hide().appendTo('body');
this.$overlay.on('click', function() {
self.hide();
});
},
refresh: function() {
this.$table.empty();
this.$loadmorebtn.show();
this.find({}, 0, this.handleFind.bind(this));
},
addSearch: function(){
var self = this;
var searchBtn = $('<button />')
.text('Search')
.on('click', function(e) {
self.$table.empty();
var search = {};
var a = $(this).parent().serializeArray();
$.each(a, function() {
if(this.value){
search[this.name] = this.value;
}
});
self.find(search, 0, self.handleFind.bind(self));
e.preventDefault();
});
$('<form />')
.append('<br/><b>Filter results</b><br/>')
.append('Method: <select name="method"><option></option><option>GET</option><option>POST</option><option>PUT</option><option>DELETE</option></select><br/>')
.append('Uri: <input type="text" name="uri"><br/>')
.append('IP: <input type="text" name="ip"><br/>')
.append(searchBtn)
.appendTo(this.$actions);
},
handleFind: function(data) {
var self = this;
$.each(data, function(i, meta) {
var a = $('<a href="javascript:" />')
.text('Load dataset')
.on('click', function(e) {
self.hide();
self.load(meta['id'], function(data) {
self.callback(meta['id'], data);
});
e.preventDefault();
});
var method = $('<a href="javascript:" />')
.text(meta['method'])
.on('click', function(e) {
self.$table.empty();
self.find({method: meta['method']}, 0, self.handleFind.bind(self));
e.preventDefault();
});
var uri = $('<a href="javascript:" />')
.text(meta['uri'])
.on('click', function(e) {
self.$table.empty();
self.find({uri: meta['uri']}, 0, self.handleFind.bind(self));
e.preventDefault();
});
var ip = $('<a href="javascript:" />')
.text(meta['ip'])
.on('click', function(e) {
self.$table.empty();
self.find({ip: meta['ip']}, 0, self.handleFind.bind(self));
e.preventDefault();
});
$('<tr />')
.append($('<td />').append(a))
.append($('<td />').append(method))
.append($('<td />').append(uri))
.append('<td>' + meta['datetime'] + '</td>')
.append('<td>' + meta['ip'] + '</td>')
.appendTo(self.$table);
});
if (data.length < this.get('items_per_page')) {
this.$loadmorebtn.hide();
}
},
show: function(callback) {
this.callback = callback;
this.$el.show();
this.$overlay.show();
this.refresh();
},
hide: function() {
this.$el.hide();
this.$overlay.hide();
},
find: function(filters, offset, callback) {
var data = $.extend({}, filters, {max: this.get('items_per_page'), offset: offset || 0});
this.last_find_request = data;
this.ajax(data, callback);
},
load: function(id, callback) {
this.ajax({op: "get", id: id}, callback);
},
clear: function(callback) {
this.ajax({op: "clear"}, callback);
},
ajax: function(data, callback) {
$.ajax({
dataType: 'json',
url: this.get('url'),
data: data,
success: callback,
ignoreDebugBarAjaxHandler: true
});
}
});
})(PhpDebugBar.$);
|
JavaScript
| 0.000001 |
@@ -5691,37 +5691,30 @@
end(
+$(
'%3Ctd
-%3E' + meta%5B'ip'%5D + '%3C/td%3E'
+ /%3E').append(ip)
)%0A
|
4f2e22080a2f2f453ff03aafbbcacbcf0338c7e4
|
fix audio button toggle shifing position in the platformer example
|
examples/platformer/js/entities/HUD.js
|
examples/platformer/js/entities/HUD.js
|
/**
* HUD namespace
*/
game.HUD = game.HUD || {};
/**
* a HUD container and child items
*/
game.HUD.UIContainer = me.Container.extend({
init: function() {
// call the constructor
this._super(me.Container, "init");
// persistent across level change
this.isPersistent = true;
// Use screen coordinates
this.floating = true;
// make sure our object is always draw first
this.z = Infinity;
// give a name
this.name = "HUD";
// add our child score object at position
this.addChild(new game.HUD.ScoreItem(-10, -10));
// add our audio control object
this.addChild(new game.HUD.AudioControl(10, 10));
if (!me.device.isMobile) {
// add our fullscreen control object
this.addChild(new game.HUD.FSControl(10 + 48 + 10, 10));
}
}
});
/**
* a basic control to toggle fullscreen on/off
*/
game.HUD.FSControl = me.GUI_Object.extend({
/**
* constructor
*/
init: function(x, y) {
this._super(me.GUI_Object, "init", [ x, y, {
image: game.texture,
region : "shadedDark30.png"
} ]);
this.setOpacity(0.5);
this.anchorPoint.set(0, 0);
},
/**
* function called when the pointer is over the object
*/
onOver : function (/* event */) {
this.setOpacity(1.0);
},
/**
* function called when the pointer is leaving the object area
*/
onOut : function (/* event */) {
this.setOpacity(0.5);
},
/**
* function called when the object is clicked on
*/
onClick : function (/* event */) {
if (!me.device.isFullscreen) {
me.device.requestFullscreen();
} else {
me.device.exitFullscreen();
}
return false;
}
});
/**
* a basic control to toggle fullscreen on/off
*/
game.HUD.AudioControl = me.GUI_Object.extend({
/**
* constructor
*/
init: function(x, y) {
this._super(me.GUI_Object, "init", [ x, y, {
image: game.texture,
region : "shadedDark13.png" // ON by default
} ]);
this.anchorPoint.set(0, 0);
this.setOpacity(0.5);
this.isMute = false;
},
/**
* function called when the pointer is over the object
*/
onOver : function (/* event */) {
this.setOpacity(1.0);
},
/**
* function called when the pointer is leaving the object area
*/
onOut : function (/* event */) {
this.setOpacity(0.5);
},
/**
* function called when the object is clicked on
*/
onClick : function (/* event */) {
if (this.isMute) {
me.audio.unmuteAll();
this.setRegion(game.texture.getRegion("shadedDark13.png"));
this.isMute = false;
} else {
me.audio.muteAll();
this.setRegion(game.texture.getRegion("shadedDark15.png"));
this.isMute = true;
}
return false;
}
});
/**
* a basic HUD item to display score
*/
game.HUD.ScoreItem = me.Renderable.extend({
/**
* constructor
*/
init: function(x, y) {
this.relative = new me.Vector2d(x, y);
// call the super constructor
// (size does not matter here)
this._super(me.Renderable, "init", [
me.game.viewport.width + x,
me.game.viewport.height + y,
10,
10
]);
// create a font
this.font = new me.BitmapText(0, 0, {
font : "PressStart2P",
textAlign : "right",
textBaseline : "bottom"
});
// local copy of the global score
this.score = -1;
},
/**
* update function
*/
update : function (/*dt*/) {
this.pos.x = me.game.viewport.width + this.relative.x;
this.pos.y = me.game.viewport.height + this.relative.y;
// we don't draw anything fancy here, so just
// return true if the score has been updated
if (this.score !== game.data.score) {
this.score = game.data.score;
return true;
}
return false;
},
/**
* draw the score
*/
draw : function (renderer) {
this.font.draw(renderer, game.data.score, this.pos.x, this.pos.y);
}
});
|
JavaScript
| 0 |
@@ -704,22 +704,22 @@
Control(
-10, 10
+36, 56
));%0A%0A
@@ -852,24 +852,24 @@
rol(
+36 +
10 + 48
- + 10, 10
+, 56
));%0A
@@ -1224,44 +1224,8 @@
5);%0A
- this.anchorPoint.set(0, 0);%0A
@@ -2152,44 +2152,8 @@
%5D);%0A
- this.anchorPoint.set(0, 0);%0A
|
e494141a5894a87a41d6d9a35c7d251a17245d48
|
remove unnecessary $(...) wrapping of test forms
|
test/serialize-object-test.js
|
test/serialize-object-test.js
|
var assert = chai.assert;
describe("serializeObject", function() {
it("should convert checkboxes to boolean", function () {
var expected,
actual,
forms = {
single: $('<form>' +
'<input type="text" name="foo" value="on"/>' +
'<input type="checkbox" name="a" checked/>' +
'<input type="checkbox" name="x"/>' +
'</form>'),
multiple: $('<form>' +
'<input type="text" name="foo" value="on"/>' +
'<input type="checkbox" name="a" checked/>' +
'<input type="checkbox" name="b" checked/>' +
'<input type="checkbox" name="x"/>' +
'</form>'),
nested: $('<form>' +
'<input type="text" name="foo" value="on"/>' +
'<input type="checkbox" name="options[mu][a]" checked/>' +
'<input type="checkbox" name="options[mu][b]" checked/>' +
'<input type="checkbox" name="options[mu][x]"/>' +
'</form>')
};
expected = {foo: 'on', a: true};
actual = $(forms.single).serializeObject();
assert.deepEqual(actual, expected);
expected = {foo: 'on', a: true, b: true};
actual = $(forms.multiple).serializeObject();
assert.deepEqual(actual, expected);
expected = {foo: 'on', options: {mu: {a: true, b: true}}};
actual = $(forms.nested).serializeObject();
assert.deepEqual(actual, expected);
});
});
|
JavaScript
| 0 |
@@ -183,16 +183,17 @@
+$
single:
@@ -197,32 +197,32 @@
e: $('%3Cform%3E' +%0A
-
@@ -444,16 +444,17 @@
+$
multiple
@@ -785,16 +785,17 @@
+$
nested:
@@ -1208,23 +1208,21 @@
l =
-$(
forms.
+$
single
-)
.ser
@@ -1341,24 +1341,23 @@
l =
-$(
forms.
+$
multiple
).se
@@ -1352,17 +1352,16 @@
multiple
-)
.seriali
@@ -1493,23 +1493,21 @@
l =
-$(
forms.
+$
nested
-)
.ser
|
92977ec5960d7598612962ddd6cd5df6d4394088
|
Comment update
|
test/source/class/fix/Json.js
|
test/source/class/fix/Json.js
|
var suite = new core.testrunner.Suite("Fix/JSON");
suite.test("Parse", function()
{
// Primitives
this.isIdentical(JSON.parse('false'), false);
this.isIdentical(JSON.parse('0'), 0);
// Primitives in Objects
this.isIdentical(JSON.parse('{"d":3.14}').d, 3.14);
this.isIdentical(JSON.parse('{"d":"hello"}').d, "hello");
this.isIdentical(JSON.parse('{"d":false}').d, false);
// Array
this.isEqual(JSON.parse('{"d":[1,2,3]}').d.toString(), "1,2,3");
this.isEqual(JSON.parse('{"d":[1,2,3]}').d.length, 3);
// Object
this.isIdentical(JSON.parse('{"d":{"x":1}}').d.x, 1);
// Basic Parse Test
var serialized = '{"A":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
var value = JSON.parse(serialized);
this.isIdentical(value.A.length, 5);
this.isIdentical(value.A[0], 1);
// Prevent escaped
this.raisesException(function() {
JSON.parse('"\t"')
});
// Prevent octals
this.raisesException(function() {
JSON.parse("01")
});
});
suite.test("Stringify", function()
{
var undef, value;
var serialized = '{"A":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
var getClass = Object.prototype.toString;
// A test function object with a custom `toJSON` method.
(value = function () {
return 1;
}).toJSON = value;
// Firefox 3.1b1 and b2 serialize string, number, and boolean
// primitives as object literals.
this.isIdentical(JSON.stringify(0), "0");
// FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
// literals.
this.isIdentical(JSON.stringify(new Number()), "0");
this.isEqual(JSON.stringify(new String()), '""');
// FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
// does not define a canonical JSON representation (this applies to
// objects with `toJSON` properties as well, *unless* they are nested
// within an object or array).
this.isIdentical(JSON.stringify(getClass), undef);
// IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
// FF 3.1b3 pass this test.
this.isIdentical(JSON.stringify(undef), undef);
// Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
// respectively, if the value is omitted entirely.
this.isIdentical(JSON.stringify(), undef);
// FF 3.1b1, 2 throw an error if the given value is not a number,
// string, array, object, Boolean, or `null` literal. This applies to
// objects with custom `toJSON` methods as well, unless they are nested
// inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
// methods entirely.
this.isIdentical(JSON.stringify(value), "1");
this.isEqual(JSON.stringify([value]), "[1]");
// Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
// `"[null]"`.
this.isEqual(JSON.stringify([undef]), "[null]");
// YUI 3.0.0b1 fails to serialize `null` literals.
this.isEqual(JSON.stringify(null), "null");
// FF 3.1b1, 2 halts serialization if an array contains a function:
// `[1, true, getClass, 1]` serializes as "[1,true,],". These versions
// of Firefox also allow trailing commas in JSON objects and arrays.
// FF 3.1b3 elides non-JSON values from objects and arrays, unless they
// define custom `toJSON` methods.
this.isEqual(JSON.stringify([undef, getClass, null]), "[null,null,null]");
// Simple serialization test. FF 3.1b1 uses Unicode escape sequences
// where character escape codes are expected (e.g., `\b` => `\u0008`).
this.isEqual(JSON.stringify({ "A": [value, true, false, null, "\0\b\n\f\r\t"] }), serialized);
// FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
this.isIdentical(JSON.stringify(null, value), "1");
this.isEqual(JSON.stringify([1, 2], null, 1), "[\n 1,\n 2\n]");
// JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
// serialize extended years.
this.isEqual(JSON.stringify(new Date(-8.64e15)), '"-271821-04-20T00:00:00.000Z"');
// The milliseconds are optional in ES 5, but required in 5.1.
this.isEqual(JSON.stringify(new Date(8.64e15)), '"+275760-09-13T00:00:00.000Z"');
// Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
// four-digit years instead of six-digit years. Credits: @Yaffle.
this.isEqual(JSON.stringify(new Date(-621987552e5)), '"-000001-01-01T00:00:00.000Z"');
// Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
// values less than 1000. Credits: @Yaffle.
this.isEqual(JSON.stringify(new Date(-1)), '"1969-12-31T23:59:59.999Z"');
});
|
JavaScript
| 0 |
@@ -2068,31 +2068,27 @@
// Safari %3C
-= 5.1.7
+ 7?
and FF 3.1b
|
0a9976002aab3746b3f4ddd472abf9b2fd6871a3
|
Add test for December date parsing.
|
test/spec/TodoTxtItem-Date.js
|
test/spec/TodoTxtItem-Date.js
|
describe( "TodoTxtItem", function () {
var target = {
raw: "2011-07-31 This is a task.",
render: "2011-07-31 This is a task.",
text: "This is a task.",
priority: null,
complete: false,
completed: null,
date: "2011-07-31",
contexts: null,
projects: null
};
var invalid = [
// Date must immediately follow priority
{ raw: "(A) Task text 2011-07-31", text: "Task text 2011-07-31" },
// The first date on completed tasks belongs to the completion
{ raw: "x 2011-07-31 Task text", text: "Task text" }
];
describe( "when given a dated task", TodoTxtItemHelper( target ) );
describe( "when given an invalid date", function () {
it( "should not parse it", function () {
var item;
for( i in invalid ) {
item = new TodoTxtItem( invalid[i].raw );
expect( item.date ).toEqual( null );
expect( item.text ).toEqual( invalid[i].text );
}
} );
} );
} );
|
JavaScript
| 0.000001 |
@@ -271,16 +271,263 @@
ll%0A%09%7D;%0A%0A
+%09var december_target = %7B%0A%09%09raw: %222011-12-29 This is a task.%22,%0A%09%09render: %222011-12-29 This is a task.%22,%0A%09%09text: %22This is a task.%22,%0A%09%09priority: null,%0A%09%09complete: false,%0A%09%09completed: null,%0A%09%09date: %222011-12-29%22,%0A%09%09contexts: null,%0A%09%09projects: null%0A%09%7D;%0A%0A
%09var inv
@@ -842,16 +842,112 @@
get ) );
+%0A%09describe( %22when given a dated task in the 12th month%22, TodoTxtItemHelper( december_target ) );
%0A%0A%09descr
|
882e17f86c26d298f9e40a02b915a62718be87d1
|
read parameters from command line + infer deckjs directory from script directory
|
extensions/bundle-maker/make-packed.js
|
extensions/bundle-maker/make-packed.js
|
var FS = require('fs');
var writefile = function(where, what) {
FS.writeFile(where, what, function(err) {
if(err) {
console.log(err);
} else {
console.log("Saved: '"+where+"'");
}
});
};
var readfile = function(path) {
return FS.readFileSync(path).toString();
}
var includejs = function(js) {
eval(readfile(js));
return includedeck;
};
console.log = function (d) {
process.stdout.write(d + '\n');
};
ACTUALLY_EXPORT_A_LIST_OF_FILES = 'oh yeah!';
var includedeck = includejs('extensions/includedeck/load.js');
var files = includedeck("extensions/includedeck/load.js profile-3 theme:swiss", {PREFIX: '.'});
var header = ""
var alljs = ""
var allcss = ""
var gitversion = readfile('.git/refs/heads/master').replace(/\n/g, '')
var nl = '\n'
header += "/*" + nl
header += " This is a packed deck.js with some extensions and styles." + nl
header += " It has been generated from version " + gitversion + " ." + nl
header += " It includes:" + nl
for (f in files) {
if (files[f].match(/\.js$/)) {
alljs += '\n' + readfile(files[f]);
header += " " + files[f] + nl;
}
}
for (f in files) {
if (files[f].match(/\.css$/)) {
allcss += '\n' + readfile(files[f]);
header += " " + files[f] + nl;
}
}
header += "*/" + nl
allcss = allcss.replace(/(["\\])/g, '\\$1').replace(/\n/g, '\\n');
alljs = header + alljs;
alljs += 'function ACTUALLY_FILL_CSS(el) { $(el).text("'+allcss+'") }';
writefile('extensions/bundle-maker/deckjs-extended.js', alljs);
|
JavaScript
| 0 |
@@ -1,12 +1,128 @@
+%0Avar argv_modules = process.argv%5B2%5D %7C%7C %22profile-3 theme:swiss%22%0Avar argv_out = process.argv%5B3%5D %7C%7C %22deckjs-custom.js%22%0A
%0Avar FS = re
@@ -583,16 +583,91 @@
');%0A%7D;%0A%0A
+var deckjsdir = process.argv%5B1%5D.replace(/%5C/%5B%5E%5C/%5D*%5C/%5B%5E%5C/%5D*%5C/%5B%5E%5C/%5D*$/g, '/')%0A
%0AACTUALL
@@ -724,21 +724,30 @@
deck
- = includejs(
+_loadjs = deckjsdir +
'ext
@@ -774,16 +774,63 @@
load.js'
+%0Avar includedeck = includejs(includedeck_loadjs
);%0Avar f
@@ -852,20 +852,8 @@
eck(
-%22extensions/
incl
@@ -863,39 +863,36 @@
deck
-/
+_
load
-.
js
-profile-3 theme:swiss%22
++ %22 %22 + argv_modules
, %7BP
@@ -902,11 +902,17 @@
IX:
-'.'
+deckjsdir
%7D);%0A
@@ -986,16 +986,26 @@
eadfile(
+deckjsdir+
'.git/re
@@ -1759,52 +1759,16 @@
ile(
-'extensions/bundle-maker/deckjs-extended.js'
+argv_out
, al
|
d035fd1c3803a5e241264750aebd12383850c9f0
|
Update comment
|
extensions/tools/hooks/deathChecker.js
|
extensions/tools/hooks/deathChecker.js
|
'use strict';
// Required settings:
// deathChecker.ignore = ['FOO'] Roles in this array shouldn't be replaced
// deathChecker.copy = ['BAR'] Roles in this array should be replaced
//
// Notes:
// - If a role has been found death and has not been found in either arrays
// the chat might spam because the deathChecker doesn't know what to do
//
// - If you want to prevent a creep from being copied when it dies,
// set memory property 'copyOnDeath' to false
var removeQueue = [];
var deathChecker = function() {
for (var i in Memory.creeps) {
if (Game.creeps[i]) {
continue; // Ignore when creep is found alive
}
if (AI.settings.deathChecker.ignore.indexOf(Memory.creeps[i].role) !== -1 ||
("copyOnDeath" in Memory.creeps[i] && Memory.creeps[i].copyOnDeath === false)
) {
console.log('Hook deathChecker: Found dead creep ' + i + '. Deleting...');
removeQueue.push(i);
} else if (AI.settings.deathChecker.copy.indexOf(Memory.creeps[i].role) !== -1) {
console.log('Hook deathChecker: Found dead creep ' + i + '. Copying to queue...');
AI.exec('creepClone', {
/* Fake creep object*/
role: Memory.creeps[i].role,
memory: Memory.creeps[i]
}, false);
removeQueue.push(i);
} else if (AI.settings.deathChecker.copyPriority.indexOf(Memory.creeps[i].role) !== -1) {
console.log('Hook deathChecker: Found dead creep ' + i + '. Copying to priority queue...');
AI.exec('creepClone', {
/* Fake creep object*/
role: Memory.creeps[i].role,
memory: Memory.creeps[i]
}, true);
removeQueue.push(i);
} else {
console.log('Hook deathChecker: Found dead creep ' + i + '. Dunno what to do...');
}
}
};
var removeDeaths = function() {
for (var i = 0; i < removeQueue.length; i++) {
delete Memory.creeps[removeQueue[i]];
}
};
function preController() {
deathChecker();
}
function postController() {
removeDeaths();
}
module.exports = {
preController: preController,
postController: postController
};
|
JavaScript
| 0 |
@@ -175,16 +175,105 @@
eplaced%0A
+// deathChecker.copyPriority = %5B'FOOBAR'%5D Roles in this array should be replaced quickly%0A
//%0A// No
|
590adaff23b1c88cafd0749cbd39711566ed2a8c
|
test onSetImage
|
src/Image/__tests__/withImage.test.js
|
src/Image/__tests__/withImage.test.js
|
/* eslint-env jest */
import _ from 'lodash';
import { defaultState, handlers, createInitialState } from '../withImage';
const [{
openEditor,
onUploadFail,
onUploadStart,
onUploadSucceed,
reset,
}, {
onUpload,
}] = handlers;
test('openEditor({ setState, ...props }):handler', () => {
const setState = jest.fn();
openEditor({ setState })();
expect(setState).toHaveBeenCalled();
expect(setState).toHaveBeenCalledWith({ uploaded: false });
});
describe('createInitialState({ initialState, ...props }): handler', () => {
test('with empty initialState', () => {
const res = createInitialState({ initialState: {} });
expect(res).toEqual(defaultState);
});
test('when uploading is initialized in initialState', () => {
const res = createInitialState({
initialState: {
uploading: true,
},
});
expect(res).toEqual({
...defaultState,
uploading: true,
});
});
test('when uploading is controlled in props', () => {
const res = createInitialState({
initialState: {
uploading: true,
},
uploading: false,
});
expect(res).toEqual({
...defaultState,
uploading: false,
});
});
});
describe('reset({ resetState, ...props }):handler', () => {
let props;
let res;
const resetState = (fn) => {
res = fn(props);
return res;
};
const createNewState = jest.fn();
beforeEach(() => {
props = { foo: 1, bar: 2 };
res = null;
createNewState.mockClear();
});
test('when editor is set', () => {
const editor = { reset: jest.fn() };
props.editor = editor;
reset({ resetState, ...props })();
expect(res).toEqual({
...defaultState,
editor,
});
expect(editor.reset).toHaveBeenCalled();
});
test('when image is controlled in props', () => {
const editor = { reset: jest.fn() };
props.editor = editor;
props.image = _.stubObject();
reset({ resetState, ...props })();
expect(res).toEqual({
...defaultState,
editor,
});
expect(editor.reset).not.toHaveBeenCalled();
});
});
test('onUploadStart({ setState }):handler', () => {
const setState = jest.fn();
onUploadStart({ setState })();
expect(setState).toHaveBeenCalled();
expect(setState).toHaveBeenCalledWith({
uploaded: false,
uploading: true,
failed: false,
});
});
test('onUploadSucceed({ setState }):handler', () => {
const setState = jest.fn();
const url = 'http://url.com';
onUploadSucceed({ setState })({ url });
expect(setState).toHaveBeenCalled();
expect(setState).toHaveBeenCalledWith({
url,
uploaded: true,
uploading: false,
});
});
test('onUploadFail({ setState }):handler', () => {
const setState = jest.fn();
onUploadFail({ setState })();
expect(setState).toHaveBeenCalled();
expect(setState).toHaveBeenCalledWith({
uploading: false,
failed: true,
});
});
describe('onUpload({ uploadImage }):handler', () => {
const dataUrl = _.stubString();
let props;
beforeEach(() => {
props = {
editor: {
getDataUrl: jest.fn(() => dataUrl),
},
onUploadStart: jest.fn(),
onUploadSucceed: jest.fn(),
onUploadFail: jest.fn(),
};
});
test('when uploadImage will resolve', async () => {
const imageUploaded = _.stubObject();
const uploadImage = jest.fn(() => new Promise(resolve => resolve(imageUploaded)));
await onUpload({
...props,
uploadImage,
})();
expect(props.editor.getDataUrl).toHaveBeenCalled();
expect(props.onUploadStart).toHaveBeenCalled();
expect(props.onUploadSucceed).toHaveBeenCalled();
expect(props.onUploadFail).not.toHaveBeenCalled();
});
test('when uploadImage will reject', async () => {
const uploadImage = jest.fn(() => new Promise((resolve, reject) => reject()));
await onUpload({
...props,
uploadImage,
})();
expect(props.editor.getDataUrl).toHaveBeenCalled();
expect(props.onUploadStart).toHaveBeenCalled();
expect(props.onUploadSucceed).not.toHaveBeenCalled();
expect(props.onUploadFail).toHaveBeenCalled();
});
test('when no uploadImage', async () => {
await onUpload(props)();
expect(props.editor.getDataUrl).not.toHaveBeenCalled();
expect(props.onUploadStart).not.toHaveBeenCalled();
expect(props.onUploadSucceed).not.toHaveBeenCalled();
expect(props.onUploadFail).not.toHaveBeenCalled();
});
});
|
JavaScript
| 0.000006 |
@@ -216,16 +216,30 @@
Upload,%0A
+ onSetImage,%0A
%7D%5D = han
@@ -4432,28 +4432,388 @@
HaveBeenCalled();%0A %7D);%0A%7D);%0A
+%0Atest('onSetImage(%7B setImage, openEditor %7D):handler(image)%7B...%7D', () =%3E %7B%0A const props = %7B%0A setImage: jest.fn(),%0A openEditor: jest.fn(),%0A %7D;%0A%0A const image = _.stubObject();%0A onSetImage(props)(image);%0A expect(props.setImage).toHaveBeenCalled();%0A expect(props.setImage).toHaveBeenCalledWith(image);%0A expect(props.openEditor).toHaveBeenCalled();%0A%7D);%0A
|
94cbff7e600d2a6da9ed9e3a3c78621e43e92902
|
load from zlib compressed buffer is supported
|
nbt.js
|
nbt.js
|
/**
* XadillaX created at 2014-12-24 14:48:57
*
* Copyright (c) 2014 XadillaX' Gensokyo, all rights
* reserved
*/
var Tag = require("./tags/base");
var fs = require("fs");
var zlib = require("zlib");
/**
* NBT Class
* @constructor
* @refer http://minecraft.gamepedia.com/NBT_Format
*/
var NBT = function() {
this.root = {};
};
/**
* load NBT structure from buffer
* @param {Buffer} buff NBT buffer data
* @param {Function} callback callback function
*/
NBT.prototype.loadFromBuffer = function(buff, callback) {
try {
this._buff = buff;
var offset = 0;
while(offset < buff.length) {
var wrapper = Tag.getNextTag(buff, offset);
var tag = wrapper.tag;
var len = wrapper.length;
this.root[tag.id] = tag;
offset += len;
}
} catch(e) {
return callback(e);
}
callback();
};
/**
* write to compressed buffer
* @param {Function} callback callback function
* @param {String} [method] compress method (gzip|deflate)
*/
NBT.prototype.writeToCompressedBuffer = function(callback, method) {
method = method || "gzip";
try {
var _buff = this.writeToBuffer();
zlib[method](_buff, callback);
} catch(e) {
return callback(e);
}
};
/**
* write to buffer
* @return {Buffer} the result buffer data
*/
NBT.prototype.writeToBuffer = function() {
var buffLength = this.calcBufferLength();
var buff = new Buffer(buffLength);
var len = 0;
for(var key in this.root) {
if(!this.root.hasOwnProperty(key)) continue;
var object = this.root[key];
buff.writeUInt8(object.getTypeId(), len);
var nameBuff = new Buffer(object.id, "utf8");
nameBuff.copy(buff, len + 1 + 2);
buff.writeUInt16BE(nameBuff.length, len + 1);
len += object.writeBuffer(buff, len + 1 + 2 + nameBuff.length);
len += (1 + 2 + nameBuff.length);
}
return buff;
};
/**
* select a tag
* @param {String} tagName the tag name in root
* @return {Tag} the tag which matches `tagName`
*/
NBT.prototype.select = function(tagName) {
if(!this.root || !Object.keys(this.root).length) return null;
if(undefined === this.root[tagName]) return null;
return this.root[tagName];
};
NBT.prototype.get = NBT.prototype.select;
/**
* get root object's length
* @return {Number} root length
*/
NBT.prototype.count = function() {
if(!this.root) return null;
return Object.keys(this.root).length;
};
/**
* get root's keys
* @return {Number} root's keys
*/
NBT.prototype.keys = function() {
if(!this.root) return [];
return Object.keys(this.root);
};
/**
* inspect
* @return {String}
*/
NBT.prototype.inspect = function() {
return "<NBT " + JSON.stringify(this.keys()) + ">";
};
/**
* toString
* @return {String}
*/
NBT.prototype.toString = function() {
return JSON.stringify(this.toJSON(), true, 2);
};
/**
* load NBT structure from file
* @param {String} filename NBT filename
* @param {Function} callback callback function
*/
NBT.prototype.loadFromFile = function(filename, callback) {
var self = this;
fs.readFile(filename, function(err, buff) {
if(err) {
return callback(err);
}
self.loadFromBuffer(buff, callback);
});
};
/**
* load NBT structure from zlib compressed file
* @param {String} filename file's name
* @param {Function} callback callback function
*/
NBT.prototype.loadFromZlibCompressedFile = function(filename, callback) {
var self = this;
fs.readFile(filename, function(err, buff) {
if(err) {
return callback(err);
}
zlib.unzip(buff, function(err, buff) {
if(err) {
return callback(err);
}
self.loadFromBuffer(buff, callback);
});
});
};
/**
* write to file
* @param {String} filename file's name
* @param {Function} callback callback function
*/
NBT.prototype.writeToFile = function(filename, callback) {
try {
fs.writeFile(filename, this.writeToBuffer(), callback);
} catch(e) {
return callback(e);
}
};
/**
* write to compressed file
* @param {String} filename file's name
* @param {Function} callback callback function
* @param {String} [method] compress method (gzip|deflate)
*/
NBT.prototype.writeToCompressedFile = function(filename, callback, method) {
this.writeToCompressedBuffer(function(err, buff) {
if(err) return callback(err);
fs.writeFile(filename, buff, callback);
}, method);
};
/**
* calculate buffer length
* @return {Number} precalculated buffer length
*/
NBT.prototype.calcBufferLength = function() {
var len = 0;
for(var key in this.root) {
if(!this.root.hasOwnProperty(key)) continue;
// child type id for 1 byte, child name length for 2 bytes and child
// name for (child name length) byte(s).
len += 1;
len += 2;
len += Buffer.byteLength(this.root[key].id, "utf8");
// add the child body's length
len += this.root[key].calcBufferLength();
}
return len;
};
/**
* toJSON
* @return {Object} a JSON object
*/
NBT.prototype.toJSON = function() {
var res = {};
for(var key in this.root) {
if(!this.root.hasOwnProperty(key)) continue;
res[key] = this.root[key].toJSON();
}
return res;
};
module.exports = NBT;
|
JavaScript
| 0 |
@@ -894,24 +894,409 @@
back();%0A%7D;%0A%0A
+/**%0A * load from compressed buffer%0A * @param %7BBuffer%7D buff compressed buffer%0A * @param %7BFunction%7D callback callback function%0A */%0ANBT.prototype.loadFromZlibCompressedBuffer = function(buff, callback) %7B%0A var self = this;%0A zlib.unzip(buff, function(err, buff) %7B%0A if(err) %7B%0A return callback(err);%0A %7D%0A%0A self.loadFromBuffer(buff, callback);%0A %7D);%0A%7D;%0A%0A
/**%0A * write
@@ -4080,147 +4080,35 @@
-zlib.unzip(buff, function(err, buff) %7B%0A if(err) %7B%0A return callback(err);%0A %7D%0A%0A self.loadFrom
+self.loadFromZlibCompressed
Buff
@@ -4131,20 +4131,8 @@
k);%0A
- %7D);%0A
|
72ab9f448d7ee79b23f3891e1ba3e485ae8a97f0
|
Remove last data-effect=solid
|
src/Main/Report/FightNavigationBar.js
|
src/Main/Report/FightNavigationBar.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import SkullIcon from 'Interface/Icons/Skull';
import Icon from 'common/Icon';
import { getReport } from 'Interface/selectors/report';
import { getFightId, getPlayerId, getPlayerName, getResultTab } from 'Interface/selectors/url/report';
import makeAnalyzerUrl from 'Interface/common/makeAnalyzerUrl';
import { findByBossId } from 'Raids';
import DIFFICULTIES from 'common/DIFFICULTIES';
import getWipeCount from 'common/getWipeCount';
import './FightNavigationBar.css';
import SkullRaidMarker from './Results/Images/skull-raidmarker.png';
class FightNavigationBar extends React.PureComponent {
static propTypes = {
report: PropTypes.shape({
code: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
fights: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
difficulty: PropTypes.number,
boss: PropTypes.number.isRequired,
start_time: PropTypes.number.isRequired,
end_time: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
kill: PropTypes.bool,
})),
}),
fightId: PropTypes.number,
playerId: PropTypes.number,
playerName: PropTypes.string,
resultTab: PropTypes.string,
};
render() {
const { report, playerId, fightId, playerName, resultTab } = this.props;
if (!report) {
return null;
}
const player = playerId ? report.friendlies.find(friendly => friendly.id === playerId) : report.friendlies.find(friendly => friendly.name === playerName);
if (!player) {
return null;
}
return (
<nav className="fight">
<ul>
{player.fights
.map(f => report.fights[f.id - 1])
.filter(fight => fight.boss !== 0)
.map(fight => {
const boss = findByBossId(fight.boss);
return (
<li
key={fight.id}
className={`${fight.id === fightId ? 'selected' : ''} ${fight.kill ? 'kill' : 'wipe'}`}
data-tip={`${DIFFICULTIES[fight.difficulty]} ${fight.name} ${!fight.kill ? `(Wipe ${getWipeCount(report.fights, fight)})` : 'Kill'}`}
data-place="right"
data-effect="solid"
>
<Link to={makeAnalyzerUrl(report, fight.id, playerId, resultTab)}>
<figure>
{boss && boss.icon ? <Icon icon={boss.icon} alt={boss ? boss.name : fight.name} /> : (
<img
src={boss ? boss.headshot : SkullRaidMarker}
alt={boss ? boss.name : fight.name}
/>
)}
<div className="over-image">
{fight.kill ? <SkullIcon /> : `${Math.floor(fight.fightPercentage / 100)}%`}
</div>
</figure>
</Link>
</li>
);
})}
</ul>
</nav>
);
}
}
const mapStateToProps = state => ({
report: getReport(state),
fightId: getFightId(state),
playerId: getPlayerId(state),
playerName: getPlayerName(state),
resultTab: getResultTab(state),
});
export default connect(mapStateToProps)(FightNavigationBar);
|
JavaScript
| 0.00111 |
@@ -2338,46 +2338,8 @@
ht%22%0A
- data-effect=%22solid%22%0A
|
cd71bcdb15571efbf0f5821e2e7754a9e280b662
|
Change block color to number color
|
src/View/LevelSelectViewController.js
|
src/View/LevelSelectViewController.js
|
function LevelSelectViewController( canvas, storageManager, numberColor, blockColor, blockY, rows, columns, prng, monochromaticPaletteBuilder ) {
this.canvas = canvas;
this.brush = canvas.getContext('2d');
this.storageManager = storageManager;
this.numberColor = numberColor;
this.blockColor = blockColor;
var offset = canvas.height * .1;
this.blockSize = Math.min(this.canvas.width / columns, (this.canvas.height - offset) / rows);
this.blockY = blockY;
this.brush.textAlign = 'center';
this.brush.textBaseline = 'middle';
this.prng = prng;
this.monochromaticPaletteBuilder = monochromaticPaletteBuilder;
}
LevelSelectViewController.prototype.drawNumber = function(value, x, y, end) {
this.brush.font = 'bold ' + this.blockSize * .5 + 'px sans-serif';
this.brush.fillRect(x - this.blockSize / 2, this.blockY, this.blockSize, this.blockSize);
this.brush.fillStyle = this.numberColor;
if(value < 1) {
value = '?';
}
this.brush.fillText('' + value, x, this.blockY + this.blockSize / 2);
};
LevelSelectViewController.prototype.drawLevelResults = function(value) {
if(value < 1) {
this.drawDefaultView();
return;
}
var results = this.storageManager.getLevelResult(value);
if(!results) {
this.drawUnplayedLevelView(value);
return;
}
var number = results.endNumber;
if( number === 1 ) {
result = 'ACE!'
} else {
result = number < 10 ? 'LOW!' : 'High';
}
result += ' (' + number + ')';
this.brush.fillText('Level ' + value, canvas.width/2, canvas.height * .10);
this.brush.font = 'bold ' + Math.min(canvas.width * .25, 100) + 'px Arial';
this.brush.fillText(result, canvas.width/2, canvas.height * .30);
this.brush.font = Math.min(canvas.width * .1, 40) + 'px Arial';
};
LevelSelectViewController.prototype.drawDefaultView = function() {
this.brush.font = 'bold ' + this.blockSize * .5 + 'px Arial';
this.brush.fillText('Select a Level', canvas.width/2, canvas.height * .10);
};
LevelSelectViewController.prototype.drawUnplayedLevelView = function(value) {
this.brush.fillText('Level ' + value, canvas.width/2, canvas.height * .10);
};
LevelSelectViewController.prototype.draw = function(value, x, y, end) {
var blockColor = '#000000';
if(end) {
if( typeof this.prng.seed === 'function') {
this.prng.seed(value);
}
var hue = Math.floor(this.prng.random() * 360);
var saturation = Math.floor(this.prng.random() * 20) + 80;
this.monochromaticPaletteBuilder.hue = hue;
this.monochromaticPaletteBuilder.saturation = saturation;
blockColor = this.monochromaticPaletteBuilder.getColor(8, 16, 80).toString();
}
this.brush.clearRect(0, 0, canvas.width, canvas.height);
this.brush.fillStyle = blockColor;
this.brush.font = 'bold ' + this.blockSize * .5 + 'px Arial';
this.drawLevelResults(value);
this.drawNumber(value, x, y, end);
};
|
JavaScript
| 0.000002 |
@@ -2676,25 +2676,26 @@
b
-lock
+oard
Color
+s
= this.
@@ -2726,26 +2726,107 @@
der.
-getColor(8, 16, 80
+build(16, 70);%0A blockColor = HSL.complement(boardColors%5BMath.floor(this.prng.random() * 16)%5D
).to
|
ee8c36f63eb819b6c487aa5e4111634cebecaa04
|
add feedbackId to the progressed result
|
src/api/challenges/feedback/speech.js
|
src/api/challenges/feedback/speech.js
|
/**
* This file contains the functions that are needed to interact with the ITSLanguage Speech
* Feedback API.
*
* It's possible to get feedback while recording. After every sentence feedback is provided
* indicating whether or not the sentence was read well. This will be done through the
* ITSLanguage WebSocket Server.
*
* The general approach for getting real-time feedback is:
* - Prepare the speech feedback
* - Register audio procedure for streaming
* - Start listening for audio
*
* To read up on the Speech feedback:
* @see https://itslanguage.github.io/itslanguage-docs/websocket/feedback/index.html
*
* To read more on Speech Challenges:
* @see https://itslanguage.github.io/itslanguage-docs/api/speech_challenges/index.html
*
* @TODO: The feedback.pause and feedback.resume are not implemented yet.
*/
import {
registerStreamForRecorder,
waitForUserMediaApproval
} from '../../utils/audio-over-socket';
import {makeWebsocketCall} from '../../communication/websocket';
/**
* Prepare a new Speech Feedback.
* Should be called upon each new speech feedback.
* The backend will generate an unique ID for the feedback and prepare a speech challenge.
*
* @param {string} challengeId - The ID of the challenge to prepare.
* @returns {Promise} - The ID of the Speech Feedback.
*/
export function prepareFeedback(challengeId) {
return makeWebsocketCall('feedback.prepare', {args: [challengeId]});
}
/**
* In order to receive feedback the server needs to listen for audio on a registered audio rpc.
* While listening the server will reply using progressive results. The server will stop listening
* when the audio rpc returns.
*
* If you call this function the SDK will register an RPC method to the realm on which audio will be
* streamed to the backend.
*
* @param {string} feedbackId - The Id of the Feedback Challenge.
* @param {Function} progressCb - A callback which will be used to receive progress on.
* @param {Recorder} recorder - Audio recorder instance.
* @returns {Promise} - After each sentence there will be real-time feedback on that sentence. This
* feedback will be given through the progressiveResultsCb function. When the
* rpc is done, the promise will return an recording with the appropriate
* feedback per sentence.
*/
export function listenAndReply(feedbackId, progressCb, recorder) {
// Generate a somewhat unique RPC name
const rpcNameToRegister = `feedback.stream.${Math.floor(Date.now() / 1000)}`;
// Below we use registration.procedure instead of rpcNameToRegister. This is because the later
// lacks some namespacing information that we do need.
return registerStreamForRecorder(recorder, rpcNameToRegister)
.then(registration =>
makeWebsocketCall(
'feedback.listen_and_reply',
{
args: [feedbackId, registration.procedure],
progressCb
}
)
);
}
/**
* Feedback can be paused. This will stop the backend from processing the audio stream and returning
* feedback.
*
* Important note: pausing the feedback will not stop the feedback. Also make sure to stop sending
* data from the recorder to the backend.
*
* @param {string} feedbackId - The ID of the feedback to pause.
* @returns {Promise} - An error if something went wrong.
*/
export function pause(feedbackId) {
return makeWebsocketCall('feedback.pause', {args: [feedbackId]});
}
/**
* A paused feedback can be resumed at a sentence in the challenge. If not provided, it will resume
* at the first sentence.
*
* @param {string} feedbackId - The ID of the feedback to resume.
* @param {string} sentenceId - The ID of the sentence to resume feedback from.
* @returns {Promise} - An error if something went wrong.
*/
export function resume(feedbackId, sentenceId = 0) {
return makeWebsocketCall('feedback.resume', {args: [feedbackId, sentenceId]});
}
/**
* Function for convenience. Using this function calls the corresponding functions so that the
* required backend flow is backed up.
*
* It will call the following functions (and more important, in the correct order):
* - {@link prepareFeedback}.
* - {@link waitForUserMediaApproval}.
* - {@link listenAndReply}.
*
* @param {string} challengeId - The Id of the Challenge to get feedback on.
* @param {Function} progressiveResultsCb - A callback which will be used to receive progress on.
* @param {Recorder} recorder - Audio recorder instance.
* @returns {Promise} - After each sentence there will be real-time feedback on that sentence. This
* feedback will be given through the progressiveResultsCb function. When the
* rpc is done, the promise will return an recording with the appropriate
* feedback per sentence.
*/
export function feedback(challengeId, progressiveResultsCb, recorder) {
return prepareFeedback(challengeId)
.then(feedbackId => waitForUserMediaApproval(feedbackId, recorder))
.then(feedbackId => listenAndReply(feedbackId, progressiveResultsCb, recorder));
}
|
JavaScript
| 0.000001 |
@@ -2939,16 +2939,51 @@
ogressCb
+: progressCb.bind(null, feedbackId)
%0A
|
2307ddfdad6a60e05edd5e631c6f4af9b7cdd939
|
remove commented code
|
src/broker/saslAuthenticator/index.js
|
src/broker/saslAuthenticator/index.js
|
const { requests, lookup } = require('../../protocol/requests')
const apiKeys = require('../../protocol/requests/apiKeys')
const PlainAuthenticator = require('./plain')
const SCRAM256Authenticator = require('./scram256')
const SCRAM512Authenticator = require('./scram512')
const AWSIAMAuthenticator = require('./awsIam')
const OAuthBearerAuthenticator = require('./oauthBearer')
const { KafkaJSSASLAuthenticationError } = require('../../errors')
const AUTHENTICATORS = {
PLAIN: PlainAuthenticator,
'SCRAM-SHA-256': SCRAM256Authenticator,
'SCRAM-SHA-512': SCRAM512Authenticator,
AWS: AWSIAMAuthenticator,
OAUTHBEARER: OAuthBearerAuthenticator,
}
const SUPPORTED_MECHANISMS = Object.keys(AUTHENTICATORS)
const UNLIMITED_SESSION_LIFETIME = '0'
module.exports = class SASLAuthenticator {
constructor(connection, logger, versions, supportAuthenticationProtocol) {
this.connection = connection
this.logger = logger
this.sessionLifetime = UNLIMITED_SESSION_LIFETIME
const lookupRequest = lookup(versions)
this.saslHandshake = lookupRequest(apiKeys.SaslHandshake, requests.SaslHandshake)
this.protocolAuthentication = supportAuthenticationProtocol
? lookupRequest(apiKeys.SaslAuthenticate, requests.SaslAuthenticate)
: null
}
async authenticate() {
const mechanism = this.connection.sasl.mechanism.toUpperCase()
// if (!SUPPORTED_MECHANISMS.includes(mechanism)) {
// throw new KafkaJSSASLAuthenticationError(
// `SASL ${mechanism} mechanism is not supported by the client`
// )
// }
const handshake = await this.connection.send(this.saslHandshake({ mechanism }))
if (!handshake.enabledMechanisms.includes(mechanism)) {
throw new KafkaJSSASLAuthenticationError(
`SASL ${mechanism} mechanism is not supported by the server`
)
}
const saslAuthenticate = async ({ request, response, authExpectResponse }) => {
if (this.protocolAuthentication) {
const { buffer: requestAuthBytes } = await request.encode()
const authResponse = await this.connection.send(
this.protocolAuthentication({ authBytes: requestAuthBytes })
)
// `0` is a string because `sessionLifetimeMs` is an int64 encoded as string.
// This is not present in SaslAuthenticateV0, so we default to `"0"`
this.sessionLifetime = authResponse.sessionLifetimeMs || UNLIMITED_SESSION_LIFETIME
if (!authExpectResponse) {
return
}
const { authBytes: responseAuthBytes } = authResponse
const payloadDecoded = await response.decode(responseAuthBytes)
return response.parse(payloadDecoded)
}
return this.connection.sendAuthRequest({ request, response, authExpectResponse })
}
if (SUPPORTED_MECHANISMS.includes(mechanism)) {
const Authenticator = AUTHENTICATORS[mechanism]
await new Authenticator(this.connection, this.logger, saslAuthenticate).authenticate()
} else {
await this.connection.sasl
.authenticationProvider(
{
host: this.connection.host,
port: this.connection.port,
},
this.logger.namespace(`SaslAuthenticator-${mechanism}`),
saslAuthenticate
)
.authenticate()
}
}
}
|
JavaScript
| 0 |
@@ -1362,208 +1362,8 @@
e()%0A
- // if (!SUPPORTED_MECHANISMS.includes(mechanism)) %7B%0A // throw new KafkaJSSASLAuthenticationError(%0A // %60SASL $%7Bmechanism%7D mechanism is not supported by the client%60%0A // )%0A // %7D%0A%0A
|
fe86bdeaee1997d266a1a611283fd910e0e3710a
|
Update UnverifyCommand.js (#335)
|
src/commands/rover/UnverifyCommand.js
|
src/commands/rover/UnverifyCommand.js
|
const Command = require('../Command')
module.exports =
class UnverifyCommand extends Command {
constructor (client) {
super(client, {
name: 'unverify',
properName: 'Unverify',
aliases: ['unlink'],
userPermissions: []
})
}
async fn (msg) {
msg.author.send('To unverify, please contact a moderator or above at our support server: https://discord.gg/7yfwrat').then(() => {
msg.reply('Sent you a DM with information.')
}).catch(() => {
msg.reply('I can\'t seem to message you - please make sure your DMs are enabled!')
})
}
}
|
JavaScript
| 0 |
@@ -184,24 +184,87 @@
'Unverify',%0A
+ description: 'Displays instructions on how to unverify',%0A
aliase
@@ -360,59 +360,210 @@
nd('
-To unverify, please
+Before we get started, you do **not** need to be unverified to verify as a new ac
co
+u
nt
-act a moderator or above at
+, to reverify, head to https://verify.eryn.io/ and verify with the new account. %5Cn%5CnTo unverify, you need to head to
our
@@ -577,17 +577,19 @@
t server
-:
+ at
https:/
@@ -607,16 +607,77 @@
/7yfwrat
+ and ask one of the moderators to handle your unverification.
').then(
|
0623f8c893b10abf69e02f1c51a8bb69b1cecef4
|
fix select2 multi
|
src/components/fields/Select/index.js
|
src/components/fields/Select/index.js
|
import React from 'react'
import Select from 'react-select'
import autobind from 'autobind-decorator'
import PropTypes from 'prop-types'
export default class SelectField extends React.Component {
static propTypes = {
fieldName: PropTypes.string,
onChange: PropTypes.func,
value: PropTypes.any,
passProps: PropTypes.object,
errorMessage: PropTypes.node,
label: PropTypes.node,
description: PropTypes.node,
multi: PropTypes.bool,
options: PropTypes.array
}
static defaultProps = {
options: []
}
state = {}
@autobind
onChange(params) {
const {multi} = this.props
if (multi) {
this.props.onChange(params.map(item => item.value))
} else {
this.props.onChange(params.value)
}
}
getValue() {
const {value, options, multi} = this.props
if (multi) {
const selectedOptions = options.filter(option => value.includes(option.value))
return selectedOptions
} else {
const selectedOption = options.find(option => option.value === value)
if (!selectedOption) return
return selectedOption
}
}
render() {
return (
<div>
<div className="label">{this.props.label}</div>
<Select
classNamePrefix="orion-select"
isMulti={this.props.multi}
name={this.props.fieldName}
value={this.getValue()}
onChange={this.onChange}
options={this.props.options}
{...this.props.passProps}
/>
<div className="description">{this.props.description}</div>
<div className="os-input-error">{this.props.errorMessage}</div>
</div>
)
}
}
|
JavaScript
| 0 |
@@ -888,21 +888,29 @@
tion =%3E
+(
value
+ %7C%7C %5B%5D)
.include
|
c165209632477fdd29b12d1f56f95c66d11dbed9
|
default codec should use a better end marker. {okay: true}
|
codec.js
|
codec.js
|
var svarint = require('signed-varint')
var varstruct = require('varstruct')
var varmatch = require('varstruct-match')
var assert = require('assert')
var b2s = varstruct.buffer(32)
var signature = varstruct.buffer(64)
var type = varstruct.varbuf(varstruct.bound(varstruct.byte, 0, 32))
var content = varstruct.varbuf(varstruct.bound(varstruct.varint, 0, 1024))
//TODO, make a thing so that the total length of the
//message + the references is <= 1024
var References = varstruct.vararray(
varstruct.bound(varstruct.varint, 0, 1024),
varstruct.buffer(32))
var UnsignedMessage = varstruct({
previous : b2s,
author : b2s,
timestamp : varstruct.varint,
timezone : svarint,
sequence : varstruct.varint,
type : type,
message : content
})
var Message = varstruct({
previous : b2s,
author : b2s,
sequence : varstruct.varint,
timestamp : varstruct.varint,
timezone : svarint,
type : type,
message : content,
signature : signature
})
function fixed(codec, value) {
function encode (v,b,o) {
return codec.encode(value,b,o)
}
function decode (b,o) {
var v = codec.decode(b,o)
assert.deepEqual(v, value)
return v
}
var length = codec.length || codec.encodingLength(value)
encode.bytesWritten = decode.bytesRead = length
return {
encode: encode,
decode: decode,
length: length
}
}
function prefix (value) {
return fixed(varstruct.byte, value)
}
var Key = varstruct({
id: b2s,
sequence: varstruct.UInt64
})
var FeedKey = varstruct({
timestamp: varstruct.UInt64,
id: b2s
})
var LatestKey = b2s
var Broadcast = varstruct({
magic: fixed(varstruct.buffer(4), new Buffer('SCBT')),
id: b2s,
//don't use varints, so that the same buffer can be reused over and over.
port: varstruct.UInt32,
timestamp: varstruct.UInt64
})
function isInteger (n) {
return 'number' === typeof n && Math.round(n) === n
}
function isHash(b) {
return Buffer.isBuffer(b) && b.length == 32
}
var TypeIndex = varstruct({
type: varstruct.buffer(32),
id: b2s,
sequence: varstruct.UInt64
})
var ReferenceIndex = varstruct({
type: varstruct.buffer(32),
id: b2s,
reference: varstruct.buffer(32),
sequence: varstruct.UInt64
})
var ReferencedIndex = varstruct({
referenced: varstruct.buffer(32),
type: varstruct.buffer(32),
id: b2s,
sequence: varstruct.UInt64
})
exports = module.exports =
varmatch(varstruct.varint)
.type(0, Message, function (t) {
return isHash(t.previous) && isHash(t.author) && t.signature
})
.type(0, UnsignedMessage, function (t) {
return isHash(t.previous) && isHash(t.author) && !t.signature
})
.type(1, Key, function (t) {
return isHash(t.id) && isInteger(t.sequence) && !Buffer.isBuffer(t.type)
})
.type(2, FeedKey, function (t) {
return isHash(t.id) && isInteger(t.timestamp)
})
.type(3, LatestKey, isHash)
.type(4, varstruct.varint, isInteger)
// .type(5, TypeIndex, function (t) {
// return (
// Buffer.isBuffer(t.type)
// && isHash(t.id)
// && isInteger(t.sequence)
// && !t.reference && !t.referenced
// )
// })
// .type(6, ReferenceIndex, function (t) {
// return (
// Buffer.isBuffer(t.type)
// && isHash(t.id)
// && isInteger(t.sequence)
// && isHash(t.reference)
// )
// })
// .type(7, ReferencedIndex, function (t) {
// return (
// isHash(t.referenced)
// && Buffer.isBuffer(t.type)
// && isHash(t.id)
// && isInteger(t.sequence)
// )
// })
exports.UnsignedMessage = UnsignedMessage
exports.Message = Message
exports.Key = Key
exports.FeedKey = FeedKey
exports.Broadcast = Broadcast
exports.TypeIndex = TypeIndex
exports.ReferenceIndex = ReferenceIndex
exports.ReferencedIndex = ReferencedIndex
exports.buffer = true
|
JavaScript
| 0.999999 |
@@ -1055,21 +1055,34 @@
(codec,
-value
+encodeAs, decodeAs
) %7B%0A fu
@@ -1129,21 +1129,24 @@
.encode(
-value
+encodeAs
,b,o)%0A
@@ -1227,21 +1227,24 @@
qual(v,
-value
+encodeAs
)%0A re
@@ -1247,16 +1247,28 @@
return
+ decodeAs %7C%7C
v%0A %7D%0A
@@ -2451,16 +2451,90 @@
t64%0A%7D)%0A%0A
+var Okay =%0A fixed(varstruct.buffer(4), new Buffer('okay'), %7Bokay: true%7D)%0A
%0Aexports
@@ -3074,18 +3074,16 @@
nteger)%0A
-//
.type(
@@ -3089,225 +3089,12 @@
(5,
-TypeIndex, function (t) %7B%0A// return (%0A// Buffer.isBuffer(t.type)%0A// && isHash(t.id)%0A// && isInteger(t.sequence)%0A// && !t.reference && !t.referenced%0A// )%0A// %7D)%0A// .type(6, ReferenceIndex
+Okay
, fu
@@ -3105,345 +3105,36 @@
on (
-t
+b
) %7B%0A
-//
-
return
-(%0A// Buffer.isBuffer(t.type)%0A// && isHash(t.id)%0A// && isInteger(t.sequence)%0A// && isHash(t.reference)%0A// )%0A// %7D)%0A// .type(7, ReferencedIndex, function (t) %7B%0A// return (%0A// isHash(t.referenced)%0A// && Buffer.isBuffer(t.type)%0A// && isHash(t.id)%0A// && isInteger(t.sequence)%0A// )%0A//
+b && b.okay%0A
%7D)
|
30219918da7aeef89ca7fcd27d11281f2d5f4581
|
make sure waitForFocus actually waits.
|
testharness/test-functions.js
|
testharness/test-functions.js
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is WebApp Tabs.
*
* The Initial Developer of the Original Code is
* Dave Townsend <[email protected]>
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
const Cc = Components.classes;
const Ci = Components.interfaces;
function info(aMessage) {
_log("TEST-INFO " + aMessage);
}
function ok(aCondition, aMessage) {
if (aCondition)
_logPass(aMessage + ", " + aCondition + " == " + true);
else
_logFail(aMessage + ", " + aCondition + " == " + true);
}
function is(aFound, aExpected, aMessage) {
if (aFound == aExpected)
_logPass(aMessage + ", " + aFound + " == " + aExpected);
else
_logFail(aMessage + ", " + aFound + " == " + aExpected);
}
function isnot(aFound, aNotExpected, aMessage) {
if (aFound != aNotExpected)
_logPass(aMessage + ", " + aFound + " != " + aExpected);
else
_logFail(aMessage + ", " + aFound + " != " + aExpected);
}
function unexpected(aMessage, aException) {
_logFail(aMessage, aException);
}
function safeCall(aCallback) {
try {
aCallback();
}
catch (e) {
unexpected("Failed calling a callback", e);
}
}
function clickElement(aTarget) {
var utils = aTarget.ownerDocument.defaultView
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils);
var rect = aTarget.getBoundingClientRect();
var left = rect.left + rect.width / 2;
var top = rect.top + rect.height / 2;
utils.sendMouseEvent("mousedown", left, top, 0, 1, 0);
utils.sendMouseEvent("mouseup", left, top, 0, 1, 0);
}
function executeSoon(aCallback) {
waitForExplicitFinish();
let tm = Cc["@mozilla.org/thread-manager;1"].
getService(Ci.nsIThreadManager);
tm.currentThread.dispatch(function() {
safeCall(aCallback);
finish();
}, Ci.nsIEventTarget.DISPATCH_NORMAL);
}
function waitForFocus(aWindow, aCallback, aExpectBlankPage, aWaitVars) {
if (!aWindow)
aWindow = window;
aExpectBlankPage = !!aExpectBlankPage;
var waitVars = {
started: false
};
let focusManager = Cc["@mozilla.org/focus-manager;1"].
getService(Ci.nsIFocusManager);
let childTargetWindow = {};
focusManager.getFocusedElementForWindow(aWindow, true, childTargetWindow);
childTargetWindow = childTargetWindow.value;
function maybeRunTests() {
if (waitVars.loaded && waitVars.focused && !waitVars.started) {
waitVars.started = true;
executeSoon(aCallback);
}
}
function waitForEvent(aEvent) {
try {
// Check to make sure that this isn't a load event for a blank or
// non-blank page that wasn't desired.
if (aEvent.type == "load" && (aExpectBlankPage != (aEvent.target.location == "about:blank")))
return;
info("Got " + aEvent.type);
waitVars[aEvent.type + "ed"] = true;
var win = (aEvent.type == "load") ? aWindow : childTargetWindow;
win.removeEventListener(aEvent.type, waitForEvent, true);
maybeRunTests();
} catch (e) {
unexpected("Exception caught in waitForEvent", e);
}
}
// If the current document is about:blank and we are not expecting a blank
// page (or vice versa), and the document has not yet loaded, wait for the
// page to load. A common situation is to wait for a newly opened window
// to load its content, and we want to skip over any intermediate blank
// pages that load. This issue is described in bug 554873.
waitVars.loaded = (aExpectBlankPage == (aWindow.location.href == "about:blank")) &&
aWindow.document.readyState == "complete";
if (!waitVars.loaded) {
info("Must wait for load");
aWindow.addEventListener("load", waitForEvent, true);
}
// Check if the desired window is already focused.
var focusedChildWindow = { };
if (focusManager.activeWindow) {
focusManager.getFocusedElementForWindow(focusManager.activeWindow, true, focusedChildWindow);
focusedChildWindow = focusedChildWindow.value;
}
// If this is a child frame, ensure that the frame is focused.
waitVars.focused = (focusedChildWindow == childTargetWindow);
if (waitVars.focused) {
// If the frame is already focused and loaded, call the callback directly.
maybeRunTests();
}
else {
info("Must wait for focus");
childTargetWindow.addEventListener("focus", waitForEvent, true);
childTargetWindow.focus();
}
};
|
JavaScript
| 0 |
@@ -3423,24 +3423,52 @@
WaitVars) %7B%0A
+ waitForExplicitFinish();%0A%0A
if (!aWind
@@ -4000,24 +4000,40 @@
aCallback);%0A
+ finish();%0A
%7D%0A %7D%0A%0A
|
4c55d3e2835740f4f88683c734bc01eea373ed0a
|
return dialog object from frappe.prompt
|
frappe/public/js/frappe/ui/messages.js
|
frappe/public/js/frappe/ui/messages.js
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
frappe.provide("frappe.messages")
frappe.messages.waiting = function(parent, msg) {
return $(frappe.messages.get_waiting_message(msg))
.appendTo(parent);
};
frappe.messages.get_waiting_message = function(msg) {
return repl('<div class="msg-box" style="width: 63%; margin: 30px auto;">\
<p class="text-center">%(msg)s</p></div>', { msg: msg });
}
frappe.throw = function(msg) {
msgprint(msg);
throw new Error(msg);
}
frappe.confirm = function(message, ifyes, ifno) {
var d = new frappe.ui.Dialog({
title: __("Confirm"),
fields: [
{fieldtype:"HTML", options:"<p class='frappe-confirm-message'>" + message + "</p>"}
],
primary_action_label: __("Yes"),
primary_action: function() { d.hide(); ifyes(); }
});
d.show();
if(ifno) {
d.$wrapper.find(".modal-footer .btn-default").click(ifno);
}
return d;
}
frappe.prompt = function(fields, callback, title, primary_label) {
if(!$.isArray(fields)) fields = [fields];
var d = new frappe.ui.Dialog({
fields: fields,
title: title || __("Enter Value"),
})
d.set_primary_action(primary_label || __("Submit"), function() {
var values = d.get_values();
if(!values) {
return;
}
d.hide();
callback(values);
})
d.show();
}
var msg_dialog=null;
frappe.msgprint = function(msg, title) {
if(!msg) return;
if(msg instanceof Array) {
$.each(msg, function(i,v) {
if(v) {
msgprint(v);
}
})
return;
}
if(typeof(msg)!='string')
msg = JSON.stringify(msg);
// small message
if(msg.substr(0,8)=='__small:') {
show_alert(msg.substr(8)); return;
}
if(!msg_dialog) {
msg_dialog = new frappe.ui.Dialog({
title: __("Message"),
onhide: function() {
if(msg_dialog.custom_onhide) {
msg_dialog.custom_onhide();
}
msg_dialog.msg_area.empty();
}
});
msg_dialog.msg_area = $('<div class="msgprint">')
.appendTo(msg_dialog.body);
}
if(msg.search(/<br>|<p>|<li>/)==-1)
msg = replace_newlines(msg);
msg_dialog.set_title(title || __('Message'))
// append a <hr> if another msg already exists
if(msg_dialog.msg_area.html()) msg_dialog.msg_area.append("<hr>");
msg_dialog.msg_area.append(msg);
// make msgprint always appear on top
msg_dialog.$wrapper.css("z-index", 2000);
msg_dialog.show();
return msg_dialog;
}
var msgprint = frappe.msgprint;
// Floating Message
function show_alert(txt, seconds) {
if(!$('#dialog-container').length) {
$('<div id="dialog-container"><div id="alert-container"></div></div>').appendTo('body');
}
var div = $(repl('<div class="alert desk-alert" style="display: none;">'
+ '<a class="close">×</a><span class="alert-message">%(txt)s</span>'
+ '</div>', {txt: txt}))
.appendTo("#alert-container")
.fadeIn(300);
div.find('.close').click(function() {
$(this).parent().remove();
return false;
});
div.delay(seconds ? seconds * 1000 : 3000).fadeOut(300);
return div;
}
|
JavaScript
| 0.00001 |
@@ -1303,16 +1303,27 @@
show();%0A
+%09return d;%0A
%7D%0A%0Avar m
|
84676e36ca93615280dda16c032380afe037df0b
|
Fix the typo
|
models/installation.js
|
models/installation.js
|
/*!
* Module Dependencies
*/
var loopback = require('loopback');
/**
* Installation Model connects a mobile application to the device, the user and
* other information for the server side to locate devices using application
* id/version, user id, device type, and subscriptions.
*/
var Installation = loopback.createModel('Installation',
{
// The registration id
id: {
type: String,
id: true,
generated: true
},
appId: {type: String, required: true}, // The application id
appVersion: String, // The application version, optional
userId: String,
deviceType: {type: String, required: true},
deviceToken: {type: String, required: true},
badge: Number,
subscriptions: [String],
timeZone: String,
created: Date,
modified: Date,
status: String
}
);
Installation.beforeCreate = function (next) {
var reg = this;
reg.created = reg.modified = new Date();
next();
};
/**
* Find installations by application id/version
* @param {String} deviceType The device type
* @param {String} appId The application id
* @param {String} [appVersion] The application version
* @callback {Function} cb The callback function
* @param {Error|String} err The error object
* @param {Installation[]} installations The selected installations
*/
Installation.findByApp = function (deviceType, appId, appVersion, cb) {
if(!cb && typeof appVersion === 'function') {
cb = appVersion;
appVersion = undefined;
}
var filter = {where: {appId: appId, appVersion: appVersion, deviceType: deviceType}};
Installation.find(filter, cb);
};
/**
* Find installations by user id
* @param {String} userId The user id
* @param {String} deviceType The device type
* @param {Function} cb The callback function
*
* @callback {Function} cb The callback function
* @param {Error|String} err The error object
* @param {Installation[]} installations The selected installations
*/
Installation.findByUser = function (deviceType, userId, cb) {
var filter = {where: {userId: userId, deviceType: deviceType}};
Installation.find(filter, cb);
};
/**
* Find installations by subscriptions
* @param {String|String[]} subscriptions A list of subscriptions
* @param {String} deviceType The device type
*
* @callback {Function} cb The callback function
* @param {Error|String} err The error object
* @param {Installation[]} installations The selected installations
*/
Installation.findBySubscriptions = function (deviceType, subscriptions, cb) {
if(typeof subscriptions === 'string') {
subscriptions = subscriptions.split(/[\s,]+/);
}
var filter = {where: {subscriptions: {inq: subscriptions}, deviceType: deviceType}};
Installation.find(filter, cb);
};
/*!
* Configure the remoting attributes for a given function
* @param {Function} fn The function
* @param {Object} options The options
* @private
*/
function setRemoting(fn, options) {
options = options || {};
for(var opt in options) {
if(options.hasOwnProperty(opt)) {
fn[opt] = options[opt];
}
}
fn.shared = true;
}
setRemoting(Installation.findByApp, {
description: 'Find installations by application id',
accepts: [
{arg: 'deviceType', type: 'string', description: 'Device type', http: {source: 'query'}},
{arg: 'appId', type: 'string', description: 'Application id', http: {source: 'query'}},
{arg: 'appVersion', type: 'string', description: 'Application version', http: {source: 'query'}}
],
returns: {arg: 'data', type: 'object', root: true},
http: {verb: 'get', path: '/byApp'}
});
setRemoting(Installation.findByUser, {
description: 'Find installations by user id',
accepts: [
{arg: 'deviceType', type: 'string', description: 'Device type', http: {source: 'query'}},
{arg: 'userId', type: 'string', description: 'User id', http: {source: 'query'}}
],
returns: {arg: 'data', type: 'object', root: true},
http: {verb: 'get', path: '/byUser'}
});
setRemoting(Installation.findBySubscription, {
description: 'Find installations by subscriptions',
accepts: [
{arg: 'deviceType', type: 'string', description: 'Device type', http: {source: 'query'}},
{arg: 'subscriptions', type: 'string', description: 'Subscriptions', http: {source: 'query'}}
],
returns: {arg: 'data', type: 'object', root: true},
http: {verb: 'get', path: '/bySubscription'}
});
module.exports = Installation;
|
JavaScript
| 1 |
@@ -4177,16 +4177,17 @@
cription
+s
, %7B%0A
@@ -4562,16 +4562,17 @@
cription
+s
'%7D%0A%7D);%0A%0A
|
427a926ef8e1483566df43d57c32ac60d00bd19b
|
fix problems with this/self
|
models/opcua-client.js
|
models/opcua-client.js
|
/**
*
* Created by Dominik on 25.04.2016.
* Based on sample_client.js from https://github.com/node-opcua/node-opcua/blob/master/documentation/sample_client.js
*
*/
/*global require,console,setTimeout */
var opcua = require("node-opcua");
var async = require("async");
var Q = require("q");
var should = require("should");
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var debug = require('debug')('mi5-simple-opcua:client');
//debug.log = console.log.bind(console); // --> debug goes to stdout
//var the_session, the_subscription, eventEmitter;
util.inherits(OpcuaClient, EventEmitter);
function OpcuaClient(endpointUrl, callback){
self = this;
EventEmitter.call(this);
client = new opcua.OPCUAClient();
connect(client, endpointUrl)
.then(createSession)
.then(subscribe)
.then(function(){
self.emit('connect');
callback();
})
.catch(function(err){
console.error(err);
self.emit('error', err);
callback(err);
});
}
function connect(client, endpointUrl){
var deferred = Q.defer();
client.connect(endpointUrl,function (err) {
if(err) {
deferred.reject(err);
} else {
debug("connected to opcua server at " + endpointUrl);
deferred.resolve();
}
});
return deferred.promise;
}
function createSession(){
var deferred = Q.defer();
client.createSession(function(err,session) {
if(!err) {
the_session = session;
deferred.resolve();
} else {
deferred.reject(err);
}
});
return deferred.promise;
}
function subscribe(){
var deferred = Q.defer();
the_subscription = new opcua.ClientSubscription(the_session,{
requestedPublishingInterval: 1000,
requestedLifetimeCount: 10,
requestedMaxKeepAliveCount: 2,
maxNotificationsPerPublish: 10,
publishingEnabled: true,
priority: 10
});
the_subscription.on("started",function(){
debug("subscription started - subscriptionId = ",the_subscription.subscriptionId);
deferred.resolve();
}).on("keepalive",function(){
//debug("keepalive");
}).on("terminated",function(){
debug("terminated");
});
return deferred.promise;
}
OpcuaClient.prototype.readVariable = function(nodeId, callback){
//debug('nodeId: '+nodeId);
the_session.readVariableValue(nodeId, function(err,dataValue) {
dataValue.statusCode.should.eql(opcua.StatusCodes.Good);
if(!err) callback(err, dataValue.value.value);
else callback(err);
});
};
OpcuaClient.prototype.readDatatype = function(nodeId, callback){
the_session.readVariableValue(nodeId, function(err,dataValue) {
if(!err) {
dataValue.statusCode.should.eql(opcua.StatusCodes.Good);
callback(err, dataValue.value.dataType.key);
} else {callback(err);}
});
};
OpcuaClient.prototype.monitorItem = function(nodeId){
var monitoredItem = the_subscription.monitor({
nodeId: opcua.resolveNodeId(nodeId),
attributeId: opcua.AttributeIds.Value
},
{
samplingInterval: 100,
discardOldest: true,
queueSize: 10
},
opcua.read_service.TimestampsToReturn.Both
);
return monitoredItem;
};
OpcuaClient.prototype.onChange = function(nodeId, callback){
var monitoredItem = this.monitorItem(nodeId);
setTimeout(function(){monitoredItem.on("changed",function(dataValue){
var value = dataValue.value.value;
//debug(new Date().toString(), nodeId, value);
callback(value);
});},10000);
};
OpcuaClient.prototype.writeNodeValue = function(nodeId, value, dataType, callback) {
var nodesToWrite = [
{
nodeId: nodeId,
attributeId: opcua.AttributeIds.Value,
indexRange: null,
value: { /* dataValue*/
// note: most servers reject timestamps written manually here
value: { /* Variant */
dataType: opcua.DataType[dataType],
value: value
}
}
}
];
the_session.write(nodesToWrite, function (err, statusCodes) {
if (!err) {
// debug('statusCodes:'+statusCodes);
statusCodes.length.should.equal(nodesToWrite.length);
statusCodes.forEach(function(item){
item.should.eql(opcua.StatusCodes.Good);
});
}
callback(err);
});
};
module.exports = OpcuaClient;
|
JavaScript
| 0.000027 |
@@ -708,16 +708,21 @@
this);%0A%09
+this.
client =
@@ -751,32 +751,37 @@
();%0A%0A%09%0A%09connect(
+self.
client, endpoint
@@ -1331,18 +1331,41 @@
fer();%0A%09
-%0A%09
+var self = this;%0A%09%0A%09self.
client.c
@@ -1417,16 +1417,21 @@
r) %7B%0A%09%09%09
+self.
the_sess
@@ -1594,18 +1594,41 @@
fer();%0A%09
-%0A%09
+var self = this;%0A%09%0A%09self.
the_subs
@@ -1667,16 +1667,21 @@
ription(
+self.
the_sess
@@ -1886,24 +1886,29 @@
%7D);%0A %0A
+self.
the_subscrip
@@ -2302,16 +2302,21 @@
deId);%0A%09
+this.
the_sess
@@ -2577,16 +2577,21 @@
back)%7B%0A%09
+this.
the_sess
@@ -2881,16 +2881,21 @@
Item =
+this.
the_subs
@@ -4005,16 +4005,21 @@
%5D;%0A%0A
+this.
the_sess
|
d285bea9fb6e80bba8a933c9d6450eee002ccd7d
|
Move flagchunk transparency handling back into conditional
|
src/core/display/chunks/flagsChunk.js
|
src/core/display/chunks/flagsChunk.js
|
/**
* Create display state chunk type for draw and pick render of flags
*/
SceneJS_ChunkFactory.createChunkType({
type: "flags",
build: function () {
var draw = this.program.draw;
this._uClippingDraw = draw.getUniform("SCENEJS_uClipping");
this._uSolidDraw = draw.getUniform("SCENEJS_uSolid");
this._uSolidColorDraw = draw.getUniform("SCENEJS_uSolidColor");
var pick = this.program.pick;
this._uClippingPick = pick.getUniform("SCENEJS_uClipping");
},
drawAndPick: function (frameCtx) {
var gl = this.program.gl;
var backfaces = this.core.backfaces;
if (frameCtx.backfaces != backfaces) {
if (backfaces) {
gl.disable(gl.CULL_FACE);
} else {
gl.enable(gl.CULL_FACE);
}
frameCtx.backfaces = backfaces;
}
var frontface = this.core.frontface;
if (frameCtx.frontface != frontface) {
if (frontface == "ccw") {
gl.frontFace(gl.CCW);
} else {
gl.frontFace(gl.CW);
}
frameCtx.frontface = frontface;
}
var transparent = this.core.transparent;
if (frameCtx.transparent != transparent) {
if (transparent) {
// Entering a transparency bin
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
frameCtx.blendEnabled = true;
} else {
// Leaving a transparency bin
gl.disable(gl.BLEND);
frameCtx.blendEnabled = false;
}
frameCtx.transparent = transparent;
}
var picking = frameCtx.picking;
if (picking) {
if (this._uClippingPick) {
this._uClippingPick.setValue(this.core.clipping);
}
} else {
if (this._uClippingDraw) {
this._uClippingDraw.setValue(this.core.clipping);
}
if (this._uSolidDraw) {
this._uSolidDraw.setValue(this.core.solid);
}
if (this._uSolidColorDraw) {
this._uSolidColorDraw.setValue(this.core.solidColor);
}
}
}
});
|
JavaScript
| 0.000001 |
@@ -1172,32 +1172,239 @@
ace;%0A %7D%0A%0A
+ var picking = frameCtx.picking;%0A%0A if (picking) %7B%0A%0A if (this._uClippingPick) %7B%0A this._uClippingPick.setValue(this.core.clipping);%0A %7D%0A%0A %7D else %7B%0A%0A
var tran
@@ -1437,16 +1437,20 @@
arent;%0A%0A
+
@@ -1501,24 +1501,28 @@
+
+
if (transpar
@@ -1521,32 +1521,36 @@
transparent) %7B%0A%0A
+
@@ -1589,32 +1589,36 @@
+
+
gl.enable(gl.BLE
@@ -1614,32 +1614,36 @@
able(gl.BLEND);%0A
+
@@ -1702,32 +1702,36 @@
+
+
frameCtx.blendEn
@@ -1749,32 +1749,36 @@
e;%0A%0A
+
%7D else %7B%0A%0A
@@ -1787,16 +1787,20 @@
+
+
// Leavi
@@ -1814,32 +1814,36 @@
ansparency bin%0A%0A
+
@@ -1872,32 +1872,36 @@
+
frameCtx.blendEn
@@ -1919,35 +1919,43 @@
se;%0A
+
+
%7D%0A%0A
+
fram
@@ -1998,213 +1998,13 @@
-%7D%0A%0A%0A var picking = frameCtx.picking;%0A%0A if (picking) %7B%0A%0A if (this._uClippingPick) %7B%0A this._uClippingPick.setValue(this.core.clipping);%0A %7D%0A%0A %7D else %7B
+ %7D
%0A%0A
|
6939e4964310b2626e29740dbe374bcc9133480d
|
Enable async long traces.
|
packages/xo-cli/src/cli.js
|
packages/xo-cli/src/cli.js
|
'use strict';
//====================================================================
var _ = require('lodash');
var Promise = require('bluebird');
var multiline = require('multiline');
var chalk = require('chalk');
var Xo = require('xo-lib');
//--------------------------------------------------------------------
var config = require('./config');
var prompt = require('./prompt');
//====================================================================
var connect = function () {
return config.load().bind({}).then(function (config) {
if (!config.server)
{
throw 'no server to connect to!';
}
if (!config.token)
{
throw 'no token available';
}
var xo = new Xo(config.server);
return xo.call('session.signInWithToken', {
token: config.token,
}).return(xo);
});
};
var wrap = function (val) {
return function () {
return val;
};
};
//====================================================================
exports = module.exports = function (args) {
if (!args || !args.length) {
return help();
}
var fnName = args[0].replace(/^--|-\w/g, function (match) {
if (match === '--')
{
return '';
}
return match[1].toUpperCase();
});
if (fnName in exports) {
return exports[fnName](args.slice(1));
}
return exports.call(args);
};
//--------------------------------------------------------------------
var help = exports.help = wrap(multiline.stripIndent(function () {/*
Usage:
xo-cli --register [<XO-Server URL>] [<username>] [<password>]
Registers the XO instance to use.
xo-cli --list-commands [--json]
Returns the list of available commands on the current XO instance.
xo-cli <command> [<name>=<value>]...
Executes a command on the current XO instance.
*/}));
exports.version = wrap('xo-cli v'+ require('../package').version);
exports.register = function (args) {
var xo;
return Promise.try(function () {
xo = new Xo(args[0]);
return xo.call('session.signInWithPassword', {
email: args[1],
password: args[2],
});
}).then(function (user) {
console.log('Successfully logged with', user.email);
return xo.call('token.create');
}).then(function (token) {
return config.set({
server: args[0],
token: token,
});
});
};
exports.unregister = function () {
return config.unset([
'server',
'token',
]);
};
exports.listCommands = function (args) {
return connect().then(function (xo) {
return xo.call('system.getMethodsInfo');
}).then(function (methods) {
if (args.indexOf('--json') !== -1)
{
return methods;
}
methods = _.pairs(methods);
methods.sort(function (a, b) {
a = a[0];
b = b[0];
if (a < b) {
return -1;
}
return +(a > b);
});
var str = [];
methods.forEach(function (method) {
var name = method[0];
var info = method[1];
str.push(chalk.bold.blue(name));
_.each(info.params || [], function (info, name) {
str.push(' ');
if (info.optional) {
str.push('[');
}
str.push(name, '=<', info.type || 'unknown', '>');
if (info.optional) {
str.push(']');
}
});
str.push('\n');
if (info.description) {
str.push(' ', info.description, '\n');
}
});
return str.join('');
});
};
var PARAM_RE = /^([^=]+)=(.*)$/;
exports.call = function (args) {
if (!args.length) {
throw 'missing command name';
}
var method = args.shift();
var params = {};
args.forEach(function (arg) {
var matches;
if (!(matches = arg.match(PARAM_RE))) {
throw 'invalid arg: '+arg;
}
params[matches[1]] = matches[2];
});
return connect().then(function (xo) {
return xo.call(method, params);
});
};
|
JavaScript
| 0 |
@@ -138,24 +138,51 @@
bluebird');%0A
+Promise.longStackTraces();%0A
var multilin
|
728e2b8190192c7235bfbd819de6fcfd08b0cebc
|
Fix test descriptions
|
src/directives/conversationControl.js
|
src/directives/conversationControl.js
|
;(function() {
'use strict';
angular.module('gebo-client-performatives.conversationControl',
['gebo-client-performatives.request',
'templates/server-reply-request.html',
'templates/client-reply-request.html',
'templates/server-propose-discharge-perform.html',
'templates/client-propose-discharge-perform.html',
'templates/server-reply-propose-discharge-perform.html',
'templates/client-reply-propose-discharge-perform.html',
'templates/server-perform.html']).
directive('conversationControl', function ($templateCache, Request, $compile) {
var _link = function(scope, element, attributes) {
if (scope.sc && scope.email && scope.conversationId) {
var directive = Request.getDirectiveName(scope.sc, scope.email);
element.html($templateCache.get('templates/' + directive + '.html'));
$compile(element.contents())(scope);
}
};
/**
* Controller
*/
var _controller = function($scope, $element, $attrs, $transclude) {
$attrs.$observe('sc', function(newValue) {
$scope.sc = newValue;
});
$attrs.$observe('email', function(newValue) {
$scope.email = newValue;
});
$attrs.$observe('conversationId', function(newValue) {
$scope.conversationId = newValue;
});
/**
* agree
*/
$scope.agree = function() {
Request.agree(JSON.parse($scope.sc), $scope.email, $scope.conversationId);
};
/**
* notUnderstood
*/
$scope.notUnderstood = function() {
Request.notUnderstood(JSON.parse($scope.sc), $scope.email, $scope.conversationId);
};
/**
* refuse
*/
$scope.refuse = function() {
Request.refuse(JSON.parse($scope.sc), $scope.email, $scope.conversationId);
};
/**
* timeout
*/
$scope.timeout = function() {
Request.timeout(JSON.parse($scope.sc), $scope.email, $scope.conversationId);
};
/**
* failure
*/
$scope.failure = function() {
Request.failure(JSON.parse($scope.sc), $scope.email, $scope.conversationId);
};
/**
* proposeDischarge
*/
$scope.proposeDischarge = function() {
Request.proposeDischarge(JSON.parse($scope.sc), $scope.email, $scope.conversationId);
};
/**
* cancel
*/
$scope.cancel = function() {
Request.cancel(JSON.parse($scope.sc), $scope.email, $scope.conversationId);
};
};
return {
restrict: 'E',
scope: true,
link: _link,
controller: _controller,
};
});
}());
|
JavaScript
| 0.002423 |
@@ -87,33 +87,34 @@
ves.conversation
-C
+-c
ontrol',%0A
|
dccdb1accb9598563464c5fa31bcb6332fcc1323
|
Fix Weak Armor in past gens
|
mods/gen6/abilities.js
|
mods/gen6/abilities.js
|
'use strict';
exports.BattleAbilities = {
"aerilate": {
inherit: true,
desc: "This Pokemon's Normal-type moves become Flying-type moves and have their power multiplied by 1.3. This effect comes after other effects that change a move's type, but before Ion Deluge and Electrify's effects.",
shortDesc: "This Pokemon's Normal-type moves become Flying type and have 1.3x power.",
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, pokemon, target, move) {
return this.chainModify([0x14CD, 0x1000]);
},
},
},
"aftermath": {
inherit: true,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.flags['contact'] && !target.hp) {
this.damage(source.maxhp / 4, source, target, null, true);
}
},
},
"galewings": {
inherit: true,
shortDesc: "This Pokemon's Flying-type moves have their priority increased by 1.",
onModifyPriority: function (priority, pokemon, target, move) {
if (move && move.type === 'Flying') return priority + 1;
},
rating: 4.5,
},
"ironbarbs": {
inherit: true,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.flags['contact']) {
this.damage(source.maxhp / 8, source, target, null, true);
}
},
},
"liquidooze": {
inherit: true,
onSourceTryHeal: function (damage, target, source, effect) {
this.debug("Heal is occurring: " + target + " <- " + source + " :: " + effect.id);
let canOoze = {drain: 1, leechseed: 1};
if (canOoze[effect.id]) {
this.damage(damage, null, null, null, true);
return 0;
}
},
},
"multitype": {
inherit: true,
shortDesc: "If this Pokemon is an Arceus, its type changes to match its held Plate.",
},
"normalize": {
inherit: true,
desc: "This Pokemon's moves are changed to be Normal type. This effect comes before other effects that change a move's type.",
shortDesc: "This Pokemon's moves are changed to be Normal type.",
onModifyMovePriority: 1,
onModifyMove: function (move) {
if (move.id !== 'struggle' && this.getMove(move.id).type !== 'Normal') {
move.type = 'Normal';
}
},
rating: -1,
},
"parentalbond": {
inherit: true,
desc: "This Pokemon's damaging moves become multi-hit moves that hit twice. The second hit has its damage halved. Does not affect multi-hit moves or moves that have multiple targets.",
shortDesc: "This Pokemon's damaging moves hit twice. The second hit has its damage halved.",
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower) {
if (this.effectData.hit) {
this.effectData.hit++;
return this.chainModify(0.5);
} else {
this.effectData.hit = 1;
}
},
onSourceModifySecondaries: function (secondaries, target, source, move) {
if (move.id === 'secretpower' && this.effectData.hit < 2) {
// hack to prevent accidentally suppressing King's Rock/Razor Fang
return secondaries.filter(effect => effect.volatileStatus === 'flinch');
}
},
},
},
"pixilate": {
inherit: true,
desc: "This Pokemon's Normal-type moves become Fairy-type moves and have their power multiplied by 1.3. This effect comes after other effects that change a move's type, but before Ion Deluge and Electrify's effects.",
shortDesc: "This Pokemon's Normal-type moves become Fairy type and have 1.3x power.",
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, pokemon, target, move) {
return this.chainModify([0x14CD, 0x1000]);
},
},
},
"prankster": {
inherit: true,
shortDesc: "This Pokemon's non-damaging moves have their priority increased by 1.",
rating: 4.5,
},
"refrigerate": {
inherit: true,
desc: "This Pokemon's Normal-type moves become Ice-type moves and have their power multiplied by 1.3. This effect comes after other effects that change a move's type, but before Ion Deluge and Electrify's effects.",
shortDesc: "This Pokemon's Normal-type moves become Ice type and have 1.3x power.",
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, pokemon, target, move) {
return this.chainModify([0x1333, 0x1000]);
},
},
},
"roughskin": {
inherit: true,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.flags['contact']) {
this.damage(source.maxhp / 8, source, target, null, true);
}
},
},
"stancechange": {
inherit: true,
onBeforeMovePriority: 11,
},
"weakarmor": {
desc: "If a physical attack hits this Pokemon, its Defense is lowered by 1 stage and its Speed is raised by 1 stage.",
shortDesc: "If a physical attack hits this Pokemon, Defense is lowered by 1, Speed is raised by 1.",
onAfterDamage: function (damage, target, source, move) {
if (move.category === 'Physical') {
this.boost({def:-1, spe:1});
}
},
rating: 0.5,
},
};
|
JavaScript
| 0 |
@@ -4568,16 +4568,33 @@
mor%22: %7B%0A
+%09%09inherit: true,%0A
%09%09desc:
|
953ad87433c819a832c3cb9c9742cf3963f0d5d6
|
change timeout
|
mocha_test/test.js
|
mocha_test/test.js
|
/**
* @author: Jerry Zou
* @email: [email protected]
*/
var chai = require('chai')
, expect = chai.expect
, Data = require('../data.js')
, D = Data;
function testcase(test) {
return 'testcase: ' + JSON.stringify(test);
}
describe('Data.js', function() {
// set timeout for asynchronous code
this.timeout(100);
var x;
describe('get & set', function() {
it('simple get & set', function() {
expect(D.get('a')).to.equal(undefined);
D.set('a', 1);
expect(D.get('a')).to.equal(1);
D.clear();
});
it('some edge cases', function() {
D.set('1.+-*/!@#$%^&()', 1);
expect(D.get('1.+-*/!@#$%^&()')).to.equal(1);
D.set('a');
expect(D.get('a')).to.equal(undefined);
expect(D.get('a.b.c.d.e.f')).to.equal(undefined);
expect(D.get('')).to.equal(undefined);
expect(D.get('a-b-c-d')).to.equal(undefined);
});
var tests = [
{
'set': { 'a.b.c': 1 },
'get': { 'a.b': { c: 1 } }
},
{
'set': { 'a.b.c': [1, 2, 3] },
'get': {
'a.b.c.1': 2,
'a': { b:{c:[1,2,3]} }
}
},
{
'set': { 'a': { b:{c:[1,2,3]} } },
'get': { 'a.b.c.2': 3 }
},
{
'set': { 'a.b.c.d.e.f': 1 },
'get': { 'a.b.c.d.e': { f: 1 } }
},
{
'set': { 'a': [ {b:1} ] },
'get': {
'a.0.b': 1,
'a': [ {b:1} ]
}
}
];
tests.forEach(function(test, index) {
it('complex get & set - ' + index, function() {
for (var key in test.set) {
if (test.set.hasOwnProperty(key)) {
D.set(key, test.set[key]);
}
}
for (key in test.get) {
if (test.get.hasOwnProperty(key)) {
expect(D.get(key), testcase(test)).to.deep.equal(test.get[key]);
}
}
D.clear();
});
});
});
describe('has', function() {
it('simple has', function() {
expect(D.has('a')).to.equal(false);
D.set('a', 1);
expect(D.has('a')).to.equal(true);
D.clear();
});
});
describe('sub', function() {
it('several steps', function(done) {
var target
, events = ['add', 'delete', 'set', 'set', 'set', 'update']
, eventStack = []
, tryDone = function() {
if (eventStack.length >= events.length) {
eventStack.sort(function(a, b) { return a > b; });
expect(eventStack).to.deep.equal(events);
D.clear();
done();
}
};
['set', 'add', 'delete', 'update'].forEach(function(eventName) {
D.sub(eventName, 'a', function (e) {
expect(e).to.deep.equal({ type: eventName, key: 'a', data: target });
eventStack.push(eventName);
tryDone();
});
});
target = 1;
D.set('a', 1);
target = 2;
D.set('a', 2);
target = undefined;
D.set('a', undefined);
});
/***
* 测试用例 tests
* 注意:`events`指的是这一个测试用例中,会被触发的事件名序列
*/
var tests = [
{
'set': { 'a.b.c': [1, 2, 3] },
'sub': {
'a.b.c.1': 2,
'a.b.c.2': 3
},
'events': [ 'add', 'add', 'set', 'set' ]
},
{
'set': { 'a': { b:{c:[1,2,3]} } },
'sub': {
'a': { b:{c:[1,2,3]} },
'a.b': {c:[1,2,3]},
'a.b.c': [1,2,3],
'a.b.c.2': 3
},
'events': [ 'add', 'add', 'add', 'add', 'set', 'set', 'set', 'set' ]
}
];
tests.forEach(function(test, index) {
it('complex sub - ' + index, function(done) {
D.clear();
var events = test.events
, eventStack = []
, tryDone = function(force) {
if (force || eventStack.length >= events.length) {
eventStack.sort(function(a, b) { return a > b; });
events.sort(function(a, b) { return a > b; });
expect(eventStack, testcase(test)).to.deep.equal(events);
// wait to check if number of triggered events is more than expectation
setTimeout(function() { done(); }, 5);
}
};
for (key in test.sub) {
if (test.sub.hasOwnProperty(key)) {
(function(key) {
['set', 'update', 'delete', 'add'].forEach(function(eventName) {
D.sub(eventName, key, function (e) {
expect(e).to.deep.equal({ type: eventName, key: key, data: test.sub[key] });
eventStack.push(eventName);
tryDone();
});
});
}(key));
}
}
for (var key in test.set) {
if (test.set.hasOwnProperty(key)) {
D.set(key, test.set[key]);
}
}
// done by force if number of triggered events is less than expectation
setTimeout(function() { tryDone(true); }, 80);
});
});
});
describe('unsub', function() {
it('simple test', function(){
var triggerTimes = 0
, eid = D.sub('set', 'm', function (e) { triggerTimes++; });
D.set('m', 1);
D.set('m', 2);
D.unsub('set', 'm', eid);
D.set('m', 3);
D.set('m', 4);
D.clear();
expect(triggerTimes).to.equal(2);
});
});
describe('multiple Data', function() {
it('simple test', function() {
var A = new Data();
var B = new Data();
A.set('a', 123);
B.set('a', 456);
expect(A.get('a')).to.equal(123);
expect(B.get('a')).to.equal(456);
});
});
});
|
JavaScript
| 0.000003 |
@@ -326,18 +326,10 @@
(100
+0
)
-;%0A var x
;%0A%0A
|
0dae2a5011a1ededa5b24ae6c37c22546bd3781e
|
make getTitle of an html page more error resistant.
|
model/htmltitle.js
|
model/htmltitle.js
|
"use strict";
const cheerio = require("cheerio");
const request = require("request");
const iconv = require("iconv-lite");
const debug = require("debug")("OSMBC:model:htmltitle");
function linkFrom(url, page) {
if (url.substring(0, page.length + 7) === ("http://" + page)) return true;
if (url.substring(0, page.length + 8) === ("https://" + page)) return true;
return false;
}
function retrieveForum(body, url) {
if (linkFrom(url, "forum.openstreetmap.org")) {
const c = cheerio.load(body);
const title = c("title").text().replace(" / OpenStreetMap Forum", "");
return title;
}
return null;
}
function retrieveOsmBlog(body, url) {
if (linkFrom(url, "www.openstreetmap.org")) {
const c = cheerio.load(body);
const title = c("title").text().replace("OpenStreetMap | ", "");
return title;
}
return null;
}
function retrieveTwitter(body, url) {
if (linkFrom(url, "twitter.com")) {
const c = cheerio.load(body);
let title = c('meta[property="og:description"]').attr("content");
// Only replace Twitter Url, if it exists.
if (title) title = title.replace(/(https?:\/\/[^[\] \n\r"”“]*)/gi, "<..>");
return title;
}
return null;
}
function retrieveTitle(body) {
const c = cheerio.load(body);
const title = c("title").text();
return title;
}
// Team wished only to grap title, not description.
/*
function retrieveDescription(body) {
let c = cheerio.load(body);
let title = c('meta[property="og:description"]').attr("content");
if (typeof(title)=="undefined") title = null;
return title;
} */
const converterList = [retrieveForum, retrieveTwitter, retrieveOsmBlog, retrieveTitle];
function getTitle(url, callback) {
debug("getTitle");
request({ method: "GET", url: url, followAllRedirects: true, encoding: null, timeout: 2000 },
function (error, response, body) {
if (error && error.code === "ESOCKETTIMEDOUT") return callback(null, url + " TIMEOUT");
if (error) return callback(null, "Page not Found");
// try to get charset from Headers (version 1)
let fromcharset = response.headers["content-encoding"];
// if not exist, try to get charset from Headers (version 2)
if (!fromcharset) {
const ct = response.headers["content-type"];
if (ct) {
const r = ct.match(/.*?charset=([^"']+)/);
if (r)fromcharset = r[1];
}
}
// if not exist, try to parse html page for charset in text
if (!fromcharset) {
const r = body.toString("utf-8").match((/<meta.*?charset=([^"']+)/));
if (r) fromcharset = r[1];
}
// nothing given, to use parser set incoming & outcoming charset equal
if (!fromcharset) fromcharset = "UTF-8";
let utf8body = null;
utf8body = iconv.decode(body, fromcharset);
/*
try {
var iconv = new Iconv(fromcharset, "UTF-8");
utf8body = iconv.convert(body).toString("UTF-8");
} catch (err) {
// There is a convert error, ognore it and convert with UTF-8
utf8body = body.toString("UTF-8");
} */
let r = null;
for (let i = 0; i < converterList.length; i++) {
r = converterList[i](utf8body, url);
if (r) break;
}
// remove all linebreaks
r = r.replace(/(\r\n|\n|\r)/gm, " ");
if (r === null) r = "Not Found";
return callback(null, r);
}
);
}
module.exports.getTitle = getTitle;
module.exports.fortestonly = {};
module.exports.fortestonly.linkFrom = linkFrom;
|
JavaScript
| 0 |
@@ -2685,32 +2685,53 @@
qual%0A if (!
+iconv.encodingExists(
fromcharset) fro
@@ -2726,16 +2726,17 @@
charset)
+)
fromcha
@@ -2751,16 +2751,17 @@
UTF-8%22;%0A
+%0A
le
|
c557562ebb0ec25d810853d27485c4ccf4c8c376
|
remove now unused local eval instance ID
|
ui/analyse/src/ceval/cevalCtrl.js
|
ui/analyse/src/ceval/cevalCtrl.js
|
var m = require('mithril');
var makePool = require('./cevalPool');
var dict = require('./cevalDict');
var util = require('../util');
var stockfishProtocol = require('./stockfishProtocol');
var sunsetterProtocol = require('./sunsetterProtocol');
module.exports = function(root, possible, variant, emit) {
var instanceId = Math.random().toString(36).substring(2).slice(0, 4);
var pnaclSupported = navigator.mimeTypes['application/x-pnacl'];
var minDepth = 7;
var maxDepth = util.storedProp('ceval.max-depth', 18);
var multiPv = util.storedProp('ceval.multipv', 1);
var threads = util.storedProp('ceval.threads', Math.ceil((navigator.hardwareConcurrency || 1) / 2));
var hashSize = util.storedProp('ceval.hash-size', 128);
var showPvs = util.storedProp('ceval.show-pvs', false);
var curDepth = 0;
var enableStorage = lichess.storage.make('client-eval-enabled');
var allowed = m.prop(true);
var enabled = m.prop(possible() && allowed() && enableStorage.get() == '1');
var started = false;
var hoveringUci = m.prop(null);
var pool;
if (variant.key !== 'crazyhouse') {
pool = makePool(stockfishProtocol, {
asmjs: '/assets/vendor/stockfish.js/stockfish.js',
pnacl: pnaclSupported && '/assets/vendor/stockfish.pexe/nacl/stockfish.nmf'
}, {
minDepth: minDepth,
maxDepth: maxDepth,
variant: variant,
multiPv: multiPv,
threads: pnaclSupported && threads,
hashSize: pnaclSupported && hashSize
});
} else {
pool = makePool(sunsetterProtocol, {
asmjs: '/assets/vendor/Sunsetter/sunsetter.js'
});
}
// adjusts maxDepth based on nodes per second
var npsRecorder = (function() {
var values = [];
var applies = function(res) {
return res.eval.nps && res.eval.depth >= 16 &&
!res.eval.mate && Math.abs(res.eval.cp) < 500 &&
(res.work.currentFen.split(/\s/)[0].split(/[nbrqkp]/i).length - 1) >= 10;
}
return function(res) {
if (!applies(res)) return;
values.push(res.eval.nps);
if (values.length >= 5) {
var depth = 18,
knps = util.median(values) / 1000;
if (knps > 100) depth = 19;
if (knps > 150) depth = 20;
if (knps > 250) depth = 21;
if (knps > 500) depth = 22;
if (knps > 1000) depth = 23;
if (knps > 2000) depth = 24;
if (knps > 3500) depth = 25;
maxDepth(depth);
if (values.length > 20) values.shift();
}
};
})();
var onEmit = function(res) {
res.instanceId = instanceId;
res.eval.maxDepth = res.work.maxDepth;
npsRecorder(res);
curDepth = res.eval.depth;
emit(res);
}
var start = function(path, steps, threatMode) {
if (!enabled() || !possible()) return;
var step = steps[steps.length - 1];
var existing = step[threatMode ? 'threat' : 'ceval'];
if (existing && existing.depth >= maxDepth()) return;
var work = {
initialFen: steps[0].fen,
moves: [],
currentFen: step.fen,
path: path,
ply: step.ply,
maxDepth: maxDepth(),
threatMode: threatMode,
emit: function(res) {
if (enabled()) onEmit(res);
}
};
if (threatMode) {
var c = step.ply % 2 === 1 ? 'w' : 'b';
var fen = step.fen.replace(/ (w|b) /, ' ' + c + ' ');
work.currentFen = fen;
work.initialFen = fen;
} else {
// send fen after latest castling move and the following moves
for (var i = 1; i < steps.length; i++) {
var step = steps[i];
if (step.san.indexOf('O-O') === 0) {
work.moves = [];
work.initialFen = step.fen;
} else work.moves.push(step.uci);
}
}
var dictRes = dict(work, variant, multiPv());
if (dictRes) {
setTimeout(function() {
// this has to be delayed, or it slows down analysis first render.
work.emit({
work: work,
eval: {
depth: maxDepth(),
cp: dictRes.cp,
best: dictRes.best,
pvs: dictRes.pvs,
dict: true
}
});
}, 500);
pool.warmup();
} else pool.start(work);
started = true;
};
var stop = function() {
if (!enabled() || !started) return;
pool.stop();
started = false;
};
return {
instanceId: instanceId,
pnaclSupported: pnaclSupported,
start: start,
stop: stop,
allowed: allowed,
possible: possible,
enabled: enabled,
multiPv: multiPv,
threads: threads,
hashSize: hashSize,
showPvs: showPvs,
hoveringUci: hoveringUci,
setHoveringUci: function(uci) {
hoveringUci(uci);
root.setAutoShapes();
},
toggle: function() {
if (!possible() || !allowed()) return;
stop();
enabled(!enabled());
enableStorage.set(enabled() ? '1' : '0');
},
curDepth: function() {
return curDepth;
},
maxDepth: maxDepth,
destroy: pool.destroy
};
};
|
JavaScript
| 0 |
@@ -303,80 +303,8 @@
%7B%0A%0A
- var instanceId = Math.random().toString(36).substring(2).slice(0, 4);%0A
va
@@ -2435,41 +2435,8 @@
) %7B%0A
- res.instanceId = instanceId;%0A
@@ -4199,36 +4199,8 @@
n %7B%0A
- instanceId: instanceId,%0A
|
495818ef3041837f167f9a9a4a6147ff99f6cd84
|
Remove stuff
|
models/customer.js
|
models/customer.js
|
var _ = require('lodash');
var assert = require('assert');
var moment = require('moment');
var Request = require('../lib/external-request');
var Customer = module.exports = function(name, opts) {
assert(!_.isObject(name), "Must pass a name to Customer model");
assert(_.isString(name), "Must pass a name to Customer model");
if (!(this instanceof Customer)) {
return new Customer(name, opts);
}
_.extend(this, {
host: process.env.LICENSE_API || "https://license-api-example.com",
name: name,
}, opts);
};
Customer.prototype.get = function(callback) {
var self = this;
var stripeUrl = this.host + '/customer/' + self.name + '/stripe';
Request.get({
url: stripeUrl,
json: true
}, function(err, resp, stripeData) {
if (err) {
return callback(err);
}
if (resp.statusCode === 404) {
err = Error('customer not found: ' + self.name);
err.statusCode = resp.statusCode;
return callback(err);
}
return callback(null, stripeData);
});
};
Customer.prototype.getSubscriptions = function(callback) {
var url = this.host + '/customer/' + this.name + '/stripe/subscription';
Request.get({
url: url,
json: true
}, function(err, resp, body) {
if (err) {
return callback(err);
}
if (resp.statusCode === 404) {
return callback(null, []);
}
body.forEach(function(subscription) {
// does this seem right?
subscription.next_billing_date = moment.unix(subscription.current_period_end);
subscription.privateModules = !!subscription.npm_org.match(/_private-modules/);
});
return callback(null, body);
});
};
Customer.prototype.updateBilling = function(body, callback) {
var _this = this;
var url;
var props = ['name', 'email', 'card'];
for (var i in props) {
var prop = props[i];
if (!body[prop]) {
return callback(Error(prop + " is a required property"));
}
}
this.get(function(err, customer) {
var cb = function(err, resp, body) {
if (typeof body === 'string') {
// not an "error", per se, according to stripe
// but should still be bubbled up to the user
err = new Error(body);
}
return err ? callback(err) : callback(null, body);
};
// Create new customer
if (err && err.statusCode === 404) {
url = _this.host + '/customer/stripe';
return Request.put({
url: url,
json: true,
body: body
}, cb);
}
// Some other kind of error
if (err) {
return callback(err);
}
// Update existing customer
url = _this.host + '/customer/' + body.name + '/stripe';
return Request.post({
url: url,
json: true,
body: body
}, cb);
});
};
Customer.prototype.createSubscription = function(planInfo, callback) {
var url = this.host + '/customer/' + this.name + '/stripe/subscription';
Request.put({
url: url,
json: true,
body: planInfo
}, function(err, resp, body) {
callback(err, body);
});
};
Customer.prototype.del = function(callback) {
var url = this.host + '/customer/' + this.name + '/stripe';
Request.del({
url: url,
json: true
}, function(err, resp, body) {
return err ? callback(err) : callback(null, body);
});
};
Customer.prototype.getLicense = function (name, callback) {
var url = this.host + '/customer/' + name + '/license';
Request.get({
url: url,
json: true
}, function (err, resp, body) {
if (err) { return callback(err); }
return callback(null, body);
});
};
Customer.prototype.extendSponsorship = function (licenseId, name, callback) {
var url = this.host + '/sponsorship/' + licenseId;
Request.put({
url: url,
json: true,
body: {
npm_user: name
}
}, function (err, resp, body) {
if (err) { return callback(err); }
return callback(null, body);
});
};
Customer.prototype.acceptSponsorship = function (verificationKey, callback) {
var url = this.host + '/sponsorship/' + verificationKey + '/accept';
Request.post({
url: url,
json: true
}, function (err, resp, body) {
if (err) { return callback(err); }
return callback(null, body);
});
};
Customer.prototype.getAllSponsorships = function (licenseId, callback) {
var url = this.host + '/sponsorship/' + licenseId;
Request.get({
url: url,
json: true
}, function (err, resp, body) {
if (err) { callback(err); }
return callback(null, body);
});
};
Customer.prototype.getLicenseIdForOrg = function (orgName, callback) {
this.getSubscriptions(function (err, subscriptions) {
if (err) { return callback(err); }
var org = _.find(subscriptions, function (subscription) {
return orgName === subscription.npm_org;
});
if (!org) {
err = new Error('No org with that name exists');
return callback(err);
}
if (!org.license_id) {
err = new Error('That org does not have a license_id');
return callback(err);
}
return callback(null, org.license_id);
});
};
|
JavaScript
| 0 |
@@ -4494,16 +4494,368 @@
%7D);%0A%7D;%0A%0A
+var removeSponsorship = function (npmUser, licenseId, callback) %7B%0A var url = this.host + '/sponsorship/' + licenseId + '/decline/' + npmUser;%0A%0A Request.del(%7B%0A url: url,%0A json: true%0A %7D, function (err, resp, body) %7B%0A %7D);%0A%7D;%0A%0ACustomer.prototype.declineSponsorship =%0A Customer.prototype.revokeSponsorship =%0A removeSponsorship.bind(Customer);%0A
%0ACustome
|
3a9dae68add635d8800058c0b6d2408ce07ed785
|
Fix admin location view
|
models/location.js
|
models/location.js
|
'use strict';
const sequelize = require('sequelize');
const Remarkable = require('remarkable');
const markdown = new Remarkable();
module.exports = function(db) {
return db.define('location', {
id: { type: sequelize.INTEGER, primaryKey: true, autoIncrement: true },
name: {
type: sequelize.TEXT,
allowNull: false,
validate: {
notEmpty: true
},
},
address: {
type: sequelize.TEXT,
allowNull: false,
validate: {
notEmpty: true
},
},
description: { type: sequelize.TEXT },
longitude: {
type: sequelize.FLOAT,
allowNull: false,
validate: {
notEmpty: true
},
},
latitude: {
type: sequelize.FLOAT,
allowNull: false,
validate: {
notEmpty: true
},
},
}, {
timestamps: false,
createdAt: false,
underscored: true,
instanceMethods: {
addressAsHTML: function() {
return this.getDataValue('address').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>');
},
descriptionAsHTML: function() {
var d = this.getDataValue('description');
return d ? markdown(d) : null;
},
},
getterMethods: {
singleLine: function() {
return this.name + ', ' + this.address.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1, ');
},
},
});
};
|
JavaScript
| 0 |
@@ -1051,16 +1051,23 @@
markdown
+.render
(d) : nu
|
f353e51a40393e47e7b7e9f70d3440284ecd820b
|
Improve icon Url resolution
|
models/manifest.js
|
models/manifest.js
|
/**
* Copyright 2015-2016, Google, Inc.
* 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';
const DOMAIN_PATH_REGEXP = /(http[s]*:\/\/[a-z0-9A-Z-\.]+)(\/(.*?\/)*)*/;
/**
* Class representing a Web App Manifest
*/
class Manifest {
constructor(manifestUrl, jsonManifest) {
this.url = manifestUrl;
this.raw = JSON.stringify(jsonManifest);
this.name = jsonManifest.name;
this.description = jsonManifest.description;
this.startUrl = jsonManifest.start_url;
this.backgroundColor = jsonManifest.background_color;
this.icons = jsonManifest.icons;
}
getBestIcon() {
function getIconSize(icon) {
if (!icon.sizes) {
return 0;
}
return parseInt(icon.sizes.substring(0, icon.sizes.indexOf('x')), 10);
}
if (!this.icons) {
return null;
}
let bestIcon;
let bestIconSize;
this.icons.forEach(icon => {
if (!bestIcon) {
bestIcon = icon;
bestIconSize = getIconSize(icon);
return;
}
const iconSize = getIconSize(icon);
if (iconSize > bestIconSize) {
bestIcon = icon;
bestIconSize = iconSize;
}
});
return bestIcon;
}
/** Gets the Url for the largest icon in the Manifest */
getBestIconUrl() {
const bestIcon = this.getBestIcon();
if (!bestIcon) {
return '';
}
const iconUrl = bestIcon.src;
if (iconUrl.match(DOMAIN_PATH_REGEXP)) {
return iconUrl;
}
const match = DOMAIN_PATH_REGEXP.exec(this.url);
const domain = match[1];
const path = match[2] || '';
if (iconUrl[0] === '/') {
return domain + iconUrl;
}
return domain + path + iconUrl;
}
}
module.exports = Manifest;
|
JavaScript
| 0 |
@@ -611,81 +611,34 @@
t';%0A
-%0A
const
-DOMAIN_PATH_REGEXP = /(http%5Bs%5D*:%5C/%5C/%5Ba-z0-9A-Z-%5C.%5D+)(%5C/(.*?%5C/)*)*/
+url = require('url')
;%0A%0A/
@@ -1734,20 +1734,18 @@
) %7B%0A
-cons
+le
t bestIc
@@ -1769,17 +1769,16 @@
Icon();%0A
-%0A
if (
@@ -1790,111 +1790,25 @@
Icon
-) %7B%0A return '';%0A %7D%0A%0A const iconUrl = bestIcon.src;%0A if (iconUrl.match(DOMAIN_PATH_REGEXP)
+ %7C%7C !bestIcon.src
) %7B%0A
@@ -1820,31 +1820,26 @@
return
-iconUrl
+''
;%0A %7D%0A
%0A con
@@ -1834,226 +1834,54 @@
%7D%0A
-%0A
-const match = DOMAIN_PATH_REGEXP.exec(this.url);%0A const domain = match%5B1%5D;%0A const path = match%5B2%5D %7C%7C '';%0A%0A if (iconUrl%5B0%5D === '/') %7B%0A return domain + iconUrl;%0A %7D%0A return domain + path + iconUrl
+return url.resolve(this.url, bestIcon.src)
;%0A
|
d35d04f0a862ad5cb99a1f719fa1f626f933e89b
|
Update dronebl.js
|
modules/dronebl.js
|
modules/dronebl.js
|
"use strict"
var settings = require('../config').settings;
var DroneBL = require('dronebl');
exports.module = function() {
this.onCommand_dronebl = function(user, args) {
if(args.trim() != "") {
var chan = this.channel;
DroneBL.lookup(args.split(" ")[0], function(res) {
chan.say(res);
});
} else {
this.channel.say("You're doing it wrong.\nUsage: " + settings.defaultCommandTrigger + "dronebl <IP Address>");
}
}
}
|
JavaScript
| 0 |
@@ -289,29 +289,328 @@
-chan.say(res);%0A
+%09%09%09if (res == 'true') %7B%0A %09%09%09%09chan.say(args.split(%22 %22)%5B0%5D + %22 is listed in DroneBL%22);%0A %09%09%09%7D else if (res == 'false') %7B%0A %09%09%09%09chan.say(args.split(%22 %22)%5B0%5D + %22 is not listed in DroneBL%22);%0A %09%09%09%7D else %7B%0A %09%09%09%09chan.say(%22An error occured when looking up that IP address%22);%0A %09%09%09%7D%0A %09%09%09
%7D);%0A
|
62105b3c0fc2d3163e6383ea36060178758f407c
|
use redis' setex for status prop
|
modules/monitor.js
|
modules/monitor.js
|
import _ from 'lodash'
import Promise from 'bluebird'
import Debug from '../lib/util'
import YodelModule from '../lib/module'
let debug = new Debug('yodel:monitor')
export default class Monitor extends YodelModule {
/**
* Statics
*/
static HASH_FIELDS = ['nickname', 'channelId', 'channelName', 'connectedAt']
static sanitizeChannelName (name) {
name = '' + name
return name.replace(/\[spacer\s*[0-9]*\]/, '')
}
static getKeysByPattern (redis, pattern) {
return new Promise((resolve, reject) => {
let stream = redis.scanStream({ match: `${ redis.options.keyPrefix }${ pattern }` })
let keys = []
stream.on('data', resultKeys => {
for (let key of resultKeys) {
keys.push(key.substr(redis.options.keyPrefix.length))
}
})
stream.on('end', () => {
resolve(keys)
})
})
}
/**
* Constructor
*/
constructor (teamspeak, redis) {
debug.log('initializing monitor')
super(teamspeak, redis)
this.interval = 0
this.teamspeak
.on('connect', ::this.onConnect)
.on('error', ::this.onError)
.on('client.enter', ::this.onClientEnter)
.on('client.leave', ::this.onClientLeave)
.on('client.move', ::this.onClientMove)
.on('channeledited', ::this.onChannelEdit)
}
/**
* Methods
*/
updateMeta (clid = null, initial = false) {
debug.log(`updating meta${ clid ? ` for ${ clid }` : ''}`)
if (clid) {
this.teamspeak.findByClid(clid).then(
client => this.redis.hset(`connections:${ client.client_unique_identifier }`, `nickname${ clid }`, client.client_nickname)
)
} else {
this.teamspeak.getOnlineClients().then(clients => {
let commands = []
_.each(
clients,
client => {
let cluid = client.client_unique_identifier
commands.push(
['hset', `data:${ cluid }`, 'ranks', `${ client.client_servergroups }`],
['hset', `connections:${ cluid }`, `nickname${ client.clid }`, client.client_nickname]
)
}
)
if (!initial) {
let activeTimes = []
let onlineTimes = _(clients)
.uniq('client_unique_identifier')
.map(client => [
'hincrby',
`data:${ client.client_unique_identifier }`,
'onlineTime', 5000
])
.value()
_(clients)
.groupBy('client_unique_identifier')
.each(function (connections, id, clients) {
let client = connections[0]
if (connections.length > 1) {
client = _.sortBy(connections, 'client_idle_time')[0]
}
if (client.client_idle_time > 1 * 60 * 1000) return
activeTimes.push([
'hincrby',
`data:${ client.client_unique_identifier }`,
'activeTime', 5000
])
})
commands = commands.concat(onlineTimes, activeTimes)
}
this.redis.pipeline(commands).exec()
})
}
}
updateCurrentChannel (clid, cid) {
this.teamspeak.getChannelInfo(cid).then(
channel => this.redis.hmset(
`connections:${ this.cluidCache.get(clid) }`,
`channelId${ clid }`, cid,
`channelName${ clid }`, Monitor.sanitizeChannelName(channel.channel_name)
)
)
}
updateConnectedAt (clid) {
this.teamspeak.findByClid(clid).then(
info => this.redis.hset(
`connections:${ this.cluidCache.get(clid) }`,
`connectedAt${ clid }`, Date.now() - info.connection_connected_time
)
)
}
clientEnter (clid, cluid, cid) {
Promise.join(
this.teamspeak.getChannelInfo(cid),
this.teamspeak.findByClid(clid),
(channel, client) => {
let data = {
[`channelId${ clid }`]: cid,
[`channelName${ clid }`]: Monitor.sanitizeChannelName(channel.channel_name),
[`connectedAt${ clid }`]: Date.now() - client.connection_connected_time,
[`nickname${ clid }`]: client.client_nickname
}
this.redis.pipeline()
.sadd('online', cluid)
.hmset(`connections:${ cluid }`, data)
.exec()
}
)
}
/**
* Events
*/
onConnect (onlineClients) {
debug.log('onConnect')
Monitor.getKeysByPattern(this.redis, 'connections:*')
.then(
keys => keys.length ? this.redis.del(keys) : Promise.resolve()
)
.then(
() => {
let commands = [
['set', 'status', 'OK'],
['del', 'online']
]
for (let client of onlineClients) {
let cluid = client.client_unique_identifier
this.updateCurrentChannel(client.clid, client.cid)
this.updateConnectedAt(client.clid)
commands.push(['sadd', 'online', cluid])
}
this.redis.pipeline(commands).exec()
}
)
if (this.interval)
clearInterval(this.interval)
this.interval = setInterval(::this.updateMeta, 5000)
this.updateMeta(null, true)
}
onError () {
if (this.interval)
this.interval = clearInterval(this.interval)
this.redis.pipeline()
.set('status', 'ERR')
.del('online')
.exec()
}
onClientEnter (client) {
debug.log('"%s" (clid %s) entered, type %s', client.client_unique_identifier, client.clid, client.client_type ? 'query' : 'voice')
if (client.client_type !== 0) return
this.clientEnter(client.clid, client.client_unique_identifier, client.ctid)
}
onClientLeave (client) {
let cluid = this.cluidCache.get(client.clid)
if (!cluid) {
debug.log('unknown client left')
debug.log(client)
return
}
let fields = _.map(Monitor.HASH_FIELDS, field => field + client.clid)
debug.log(`${ cluid } left`)
this.redis.hdel(
`connections:${ cluid }`,
...fields,
err => {
if (err) console.error(err)
}
)
this.teamspeak.isConnected(cluid).then((clientIsConnected) => {
if (!clientIsConnected) {
this.redis.srem('online', cluid)
}
})
}
onClientMove (data) {
debug.log(`client (clid ${ data.clid }) moved out of channel (ctid ${ data.ctid })`)
this.updateCurrentChannel(data.clid, data.ctid)
}
onChannelEdit (data) {
this.teamspeak.getOnlineClients().then(clients => {
let commands = _(clients)
.filter({ cid: data.cid })
.map(client => [
'hmset',
`connections:${ client.client_unique_identifier }`,
`channelId${ client.clid }`, data.cid,
`channelName${ client.clid }`, data.channel_name
])
.value()
this.redis.pipeline(commands).exec()
})
}
}
|
JavaScript
| 0 |
@@ -1742,24 +1742,73 @@
commands = %5B
+%0A %5B'setex', 'status', 10, 'OK'%5D%0A
%5D%0A%0A _
@@ -4641,16 +4641,18 @@
%5B'set
+ex
', 'stat
@@ -4655,16 +4655,20 @@
status',
+ 10,
'OK'%5D,%0A
|
14d9858d3b6f07fd181d8776a74d4fd84ffa1b6a
|
remove print statements + added error handling
|
modules/twitter.js
|
modules/twitter.js
|
var config = require('config');
var Twit = require('twit');
var T = new Twit({
consumer_key: config.get('twitter.consumerKey'),
consumer_secret: config.get('twitter.consumerSecret'),
access_token: config.get('twitter.accessToken'),
access_token_secret: config.get('twitter.accessTokenSecret'),
timeout_ms: 60*1000, // optional HTTP request timeout to apply to all requests.
})
function trigger(tweetURL, api, message) {
var threadID = message.threadID;
var tweetID = splitAtStatus(tweetURL);
var response = "";
T.get('statuses/show/:id', {'id': tweetID, 'include_entities': true}, function (err, data, response) {
//console.log(data.entities);
var picURL = "";
var x = data.entities.hasOwnProperty('media');
//handle with image
if (x === true) {
console.log("attaching image");
picURL = data.entities.media[0].media_url;
response = {
body: '@' + data.user.screen_name + ' tweeted: ' + data.text,
url: picURL
}
}
else {
console.log("no image");
response = '@' + data.user.screen_name + ' tweeted: ' + data.text;
}
//send message
api.sendMessage(response, threadID);
});
}
function splitAtStatus(url) {
var id = url.split("/status/");
return id[1];
}
module.exports = {
trigger: trigger
}
|
JavaScript
| 0 |
@@ -520,16 +520,149 @@
se = %22%22;
+%0A%0A%09//could not parse a number %0A%09if (tweetID === undefined %7C%7C tweetID === null) %7B%0A %09return console.error(%22Not a proper tweet!%22);%0A%09%7D
%0A%09%0A%09T.ge
@@ -766,40 +766,84 @@
%7B%0A%09%09
-//console.log(data.entities);
+if (err) %7B%0A%09%09%09return console.error(%22Impromper tweet URL!%22);%0A%09%09%7D%0A%09%09else %7B
%0A%09%09
+%09
var
@@ -855,16 +855,17 @@
L = %22%22;%0A
+%09
%09%09var x
@@ -908,16 +908,17 @@
a');%0A%0A%09%09
+%09
//handle
@@ -929,16 +929,17 @@
h image%0A
+%09
%09%09if (x
@@ -955,42 +955,8 @@
%7B%0A%09
-%09%09console.log(%22attaching image%22);%0A
%09%09%09p
@@ -997,16 +997,17 @@
ia_url;%0A
+%09
%09%09%09respo
@@ -1018,16 +1018,17 @@
= %7B%0A%09%09%09%09
+%09
body: '@
@@ -1085,16 +1085,17 @@
xt,%0A%09%09%09%09
+%09
url: pic
@@ -1105,24 +1105,27 @@
%0A%09%09%09
+%09
%7D%0A
+%09
%09%09%7D%0A%09%09
+%09
else %7B%0A%09
%09%09co
@@ -1124,35 +1124,8 @@
%7B%0A%09
-%09%09console.log(%22no image%22);%0A
%09%09%09r
@@ -1192,19 +1192,21 @@
text;%0A%09%09
+%09
%7D%0A%0A
+%09
%09%09//send
@@ -1216,16 +1216,17 @@
ssage %09%0A
+%09
%09%09api.se
@@ -1256,16 +1256,20 @@
eadID);%0A
+%09%09%7D%0A
%09%7D);%0A%7D%0A%0A
|
5b4d50bf0958c66dd7bb375118e83118aed6da1a
|
add stopSeedCreating option to vm
|
Mold/Core/VM.js
|
Mold/Core/VM.js
|
"use strict";
//!info transpiled
/**
* @module Mold.Core.VM
* @description runs a new Mold instance in a sandbox
*/
Seed({
type : "module",
},
function(modul){
var instanceCount = 1;
var MoldVM = function(conf){
conf = conf || {};
this.sandbox = {
global : {
global : {},
vmInstance : instanceCount
},
console : console
}
if(conf.policy){
this.sandbox = {};
if(conf.policy.allowedModuls && conf.policy.allowedModuls.length){
this.sandbox.require = function(module){
if(!~conf.policy.allowedModules.indexOf(module)){
throw new Mold.Errors.PolicyError("Modul access for modul '" + module + "' denied! [Mold.Core.VM]");
}
return require.apply(this, arguments);
}
}
}
instanceCount++;
Mold.copyGlobalProperties(this.sandbox);
this.moldPath = conf.moldPath || 'Mold.js',
this.confPath = conf.configPath || '',
this.confName = conf.configName || 'mold.json'
this.disableDependencyErrors = conf.disableDependencyErrors || false
this.sandbox.process.argv = [
'config-path', this.confPath,
'config-name', this.confName,
'use-one-config', true,
'disable-dependency-errors', this.disableDependencyErrors,
'stop-seed-creating', stopSeedCreating
];
this.vm = require('vm');
this.fs = require('fs');
this.context = new this.vm.createContext(this.sandbox);
//load core
var moldJsPath = (Mold.Core.Config.search('config-path')) ? Mold.Core.Config.search('config-path') + this.moldPath : this.moldPath;
var data = this.fs.readFileSync(moldJsPath);
var moldScript = new this.vm.Script(data);
moldScript.runInContext(this.context, { filename : "Mold.Core.VM" });
this.Mold = this.sandbox.global.Mold;
}
MoldVM.prototype = {
setConf : function(conf){
this.Mold.Core.Config.overwrite(conf);
}
}
modul.exports = MoldVM;
}
)
|
JavaScript
| 0 |
@@ -1039,16 +1039,74 @@
%7C%7C false
+%0A%09%09%09this.stopSeedCreating = conf.stopSeedCreating %7C%7C false
%0A%0A%09%09%09thi
@@ -1318,16 +1318,21 @@
ating',
+this.
stopSeed
|
6dd40df318a6e24537002cf95010669cea41945d
|
Update LayerCreator.js
|
src/gameobjects/layer/LayerCreator.js
|
src/gameobjects/layer/LayerCreator.js
|
/**
* @author Richard Davey <[email protected]>
* @author Felipe Alfonso <@bitnenfer>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var BuildGameObject = require('../BuildGameObject');
var Layer = require('./Layer');
var GameObjectCreator = require('../GameObjectCreator');
var GetAdvancedValue = require('../../utils/object/GetAdvancedValue');
/**
* Creates a new Layer Game Object and returns it.
*
* Note: This method will only be available if the Layer Game Object has been built into Phaser.
*
* @method Phaser.GameObjects.GameObjectCreator#layer
* @since 3.50.0
*
* @param {object} config - The configuration object this Game Object will use to create itself.
* @param {boolean} [addToScene] - Add this Game Object to the Scene after creating it? If set this argument overrides the `add` property in the config object.
*
* @return {Phaser.GameObjects.Layer} The Game Object that was created.
*/
GameObjectCreator.register('layer', function (config, addToScene)
{
if (config === undefined) { config = {}; }
var children = GetAdvancedValue(config, 'children', null);
var layer = new Layer(this.scene, children);
if (addToScene !== undefined)
{
config.add = addToScene;
}
BuildGameObject(this.scene, layer, config);
return layer;
});
|
JavaScript
| 0 |
@@ -55,53 +55,8 @@
om%3E%0A
- * @author Felipe Alfonso %3C@bitnenfer%3E%0A
* @
|
8a7279fd726dbf8e921f238b62a03e08c8050407
|
Remove superflous default and whitespace
|
set.js
|
set.js
|
var value = true
, unique = function(iset){
var set = {}
, i = 0
, l = iset.length
for(; i < l; i++) {
set[iset[i]] = value
}
return set
}
var Set = function(input){
var set
this.contains = function(prop){
return !!set[prop]
}
this.empty = function(){
return Object.keys(set).length == 0
}
this.size = function(){
return Object.keys(set).length
}
this.get = function(){
return Object.keys(set)
}
this.add = function(prop){
set[prop] = value
}
this.remove = function(prop){
delete set[prop]
}
this.union = function(iset){
return new Set(this.get().concat(iset.get()))
}
this.intersect = function(iset){
var items = iset.get()
, i = 0
, l = items.length
, oset = new Set()
, prop
for(; i < l; i++){
prop = items[i]
if(this.contains(prop)){
oset.add(prop)
}
}
items = this.get()
for(i = 0, l = items.length; i < l; i++){
prop = items[i]
if(iset.contains(prop)){
oset.add(prop)
}
}
return oset
}
this.difference = function(iset){
var items = iset.get()
, i = 0
, l = items.length
, oset = this.union(iset)
, prop
for(; i < l; i++){
prop = items[i]
if(this.contains(prop)){
oset.remove(prop)
}
}
return oset
}
this.subset = function(iset){
var items = iset.get()
, subset = false
, i = 0
, l = items.length
for(; i < l; i++){
prop = items[i]
if(this.contains(prop)){
subset = true
}
else{
subset = false
break
}
}
return subset
}
this.find = function(pred){
return this.get().filter(pred)
}
this.clear = function(){
set = {}
}
set = unique(input || []) || {}
}
Set.unique = function(iset){
return Object.keys(unique(iset))
}
module.exports = Set;
|
JavaScript
| 0.000001 |
@@ -1867,14 +1867,8 @@
%5B%5D)
- %7C%7C %7B%7D
%0A%7D%0A%0A
@@ -1934,18 +1934,16 @@
et))%0A%7D%0A%0A
-%0A%0A
module.e
|
fbc3fdcbec27bb68c8ad0bce016db8a9cf89887d
|
Fix network connection bug by directly listening to online and offline events
|
src/js/components/Onboarding/index.js
|
src/js/components/Onboarding/index.js
|
var Container = require('react-container');
var Sentry = require('react-sentry');
var OnboardingHeader = require('../OnboardingHeader');
var React = require('react/addons');
var Scanner = require('../Scanner');
var Tappable = require('react-tappable');
var Transition = React.addons.CSSTransitionGroup;
var { Link, Transitions } = require('../../touchstone');
var classnames = require('classnames');
var icons = require('../../icons');
var OnboardingView = React.createClass({
mixins: [Sentry(), Transitions],
contextTypes: { dataStore: React.PropTypes.object.isRequired },
propTypes: {
title: React.PropTypes.string,
id: React.PropTypes.string.isRequired,
nextScreen: React.PropTypes.string.isRequired,
onCodeEnter: React.PropTypes.func.isRequired,
},
getInitialState () {
var showResendEmail = this.context.dataStore.getSettings().showResendEmail;
return {
online: window.navigator.onLine,
scanning: false,
showResendEmail: showResendEmail,
valid: false
};
},
componentDidMount () {
this.watch(window, 'online', this.updateOnlineStatus);
this.watch(window, 'offline', this.updateOnlineStatus);
},
updateOnlineStatus (event) {
this.setState({
online: window.navigator.onLine
});
},
enableScanner () {
if (!window.cordova) return window.alert('Sorry, this is only available on mobile devices');
this.setState({ scanning: true });
},
handleScanner (err, ticketCode) {
var dataStore = this.context.dataStore;
var self = this;
this.setState({ scanning: false });
if (!ticketCode || err) {
return console.error('Scanner Failed:', err);
}
// success
this.setState({
loading: true
}, function () {
self.props.onCodeEnter(ticketCode, (err) => {
self.setState({
loading: false,
valid: !err
}, function () {
// success: show the success icon for 1 second then fade to the app
if (self.state.valid === true) {
setTimeout(function () {
self.transitionTo(self.props.nextScreen, {
transition: 'fade'
});
}, 1000);
// fail: return validity to neutral
} else {
setTimeout(function () {
self.setState({ valid: null });
}, 2000);
}
});
});
});
},
renderIcon (icon) {
var iconClassname = classnames('onboarding-scan__icon', {
'ion-load-b': this.state.scanning,
'is-loading': this.state.scanning || this.state.loading,
'ion-ios-checkmark': this.state.valid,
'is-valid': this.state.valid
});
var element = (this.state.scanning || this.state.valid) ? (
<span className={iconClassname} />
) : (
<span dangerouslySetInnerHTML={{__html: icon}} className="onboarding-scan__image" />
);
return element;
},
renderScanButton () {
var content = this.state.online ? (
<div key="online" className="onboarding-scan">
<Tappable loading={this.state.scanning} onTap={this.enableScanner} className="onboarding-scan__button">
{this.renderIcon(icons.qr)}
</Tappable>
<div className="onboarding-scan__text">Scan the QR code in your email</div>
</div>
) : (
<div key="offline" className="onboarding-scan">
<div className="onboarding-scan__button">
<div className="onboarding-scan__icon ion-wifi" />
</div>
<div className="onboarding-scan__text">Please find a data connection to register</div>
</div>
);
return (
<Transition transitionName="animation-fade" className="onboarding-scan-wrapper">
{content}
</Transition>
);
},
renderEnterCode () {
return this.state.online ? <Link to={"app:onboarding-" + this.props.id + "-enter-code"} transition="fade" className="onboarding-footer__button onboarding-footer__button--primary">Enter Code</Link> : null;
},
renderResendEmail () {
return (this.state.online && this.state.showResendEmail) ? <Link to={"app:onboarding-" + this.props.id + "-resend-email"} transition="fade" className="onboarding-footer__button">Resend Code</Link> : null;
},
renderScanner () {
return this.state.scanning ? <Scanner action={this.handleScanner} /> : null;
},
render () {
return (
<Container direction="column" className="onboarding-container">
<OnboardingHeader />
<h2 className="onboarding-heading-1">{this.props.title}</h2>
<Container justify align="center" direction="column" className="onboarding-body">
{this.renderScanButton()}
</Container>
<Container justify align="center" direction="row" className="onboarding-footer">
{this.renderResendEmail()}
<Link to={this.props.nextScreen} transition={this.props.transition || "fade"} className="onboarding-footer__button">Skip</Link>
{this.renderEnterCode()}
</Container>
{this.renderScanner()}
</Container>
);
}
});
export default OnboardingView;
|
JavaScript
| 0 |
@@ -1141,18 +1141,264 @@
atus);%0A%09
+%09document.addEventListener('online', this.onOnline, false);%0A%09%09document.addEventListener('offline', this.onOffline, false);%0A%09%7D,%0A%0A%09onOnline () %7B%0A%09%09this.setState(%7B%0A%09%09%09online: true,%0A%09%09%7D);%0A%09%7D%0A%0A%09onOffline () %7B%0A%09%09this.setState(%7B%0A%09%09%09online: false,%0A%09%09%7D);%0A%09
%7D
-,
%0A%0A%09updat
|
91d0a723e90fdc81fd6250a5b480c58eadadcdb2
|
add hand-written iterator benchmark [ci skip]
|
benchmark/iterator-compute.js
|
benchmark/iterator-compute.js
|
/* eslint-disable */
'use strict';
class Standard {
constructor(x, y) {
this.x = x;
this.y = y;
}
computeSum() {
let sum = 0;
for (let x = 0; x < this.x; x++) {
for (let y = 0; y < this.y; y++) {
sum += x * y;
}
}
return sum;
}
}
class Iterator {
constructor(x, y) {
this.x = x;
this.y = y;
}
computeSum() {
let sum = 0;
for (const {x, y} of this.keys()) {
sum += x * y;
}
return sum;
}
*keys() {
for (let x = 0; x < this.x; x++) {
for (let y = 0; y < this.y; y++) {
yield {x, y};
}
}
}
}
const standard = new Standard(10, 15);
const iterator = new Iterator(10, 15);
// warm up
for (let i = 0; i < 1000; i++) {
standard.computeSum();
iterator.computeSum();
}
// check result
if (standard.computeSum() !== 4725) throw new Error('wrong value: ' + standard.computeSum());
if (iterator.computeSum() !== 4725) throw new Error('wrong value: ' + iterator.computeSum());
test('standard', standard);
test('iterator', iterator);
function test(name, fun) {
console.time(name);
for (let i = 0; i < 1e6; i++) {
fun.computeSum();
}
console.timeEnd(name);
}
|
JavaScript
| 0 |
@@ -732,16 +732,755 @@
%7D%0A%7D%0A%0A
+class Iterator2 %7B%0A constructor(x, y) %7B%0A this.x = x;%0A this.y = y;%0A %7D%0A%0A computeSum() %7B%0A let sum = 0;%0A for (const %7Bx, y%7D of this.keys()) %7B%0A sum += x * y;%0A %7D%0A return sum;%0A %7D%0A%0A keys() %7B%0A return %7B%0A %5BSymbol.iterator%5D: () =%3E %7B%0A let x = 0, y = 0;%0A return %7B%0A next: () =%3E %7B%0A if (y === this.y) %7B%0A y = 0;%0A x++;%0A %7D%0A if (x === this.x) return %7Bdone: true%7D;%0A return %7Bdone: false, value: %7Bx, y: y++%7D%7D;%0A %7D%0A %7D;%0A %7D%0A %7D;%0A %7D%0A%7D%0A
%0Aconst s
@@ -1549,16 +1549,57 @@
10, 15);
+%0Aconst iterator2 = new Iterator2(10, 15);
%0A%0A// war
@@ -1690,16 +1690,44 @@
eSum();%0A
+ iterator2.computeSum();%0A
%7D%0A%0A// ch
@@ -1924,16 +1924,112 @@
eSum());
+%0Aif (iterator2.computeSum() !== 4725) throw new Error('wrong value: ' + iterator2.computeSum());
%0A%0Atest('
@@ -2077,16 +2077,46 @@
erator);
+%0Atest('iterator2', iterator2);
%0A%0Afuncti
|
daea9aafecce28373074da5ed874c935e29d1851
|
add props to manage user state
|
bitcoin-show/src/BCShowApp.js
|
bitcoin-show/src/BCShowApp.js
|
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { fetchQuestion } from './actions/questionActions';
import fetchAwards, { updateAward } from './actions/awardActions';
import Options from './containers/OptionsPanel';
import Question from './containers/QuestionPanel';
class App extends Component {
componentWillReceiveProps(nextProps) {
if (nextProps.shouldUpdateQuestion) {
if (nextProps.award.number === this.props.award.number) {
this.props.updateAward();
} else {
this.props.fetchQuestion(this.props.award.level);
}
}
}
render() {
return (
<div>
<button onClick={() => {
this.props.fetchQuestion(this.props.award.level);
this.props.fetchAwards();
}}>Carregar</button>
<div>
{this.props.questionData.questionLoadCompleted && <Question />}
{this.props.questionData.questionLoadCompleted && <Options />}
</div>
<div>
<table>
<thead>
<tr>
<th>Right</th>
<th>Stop</th>
<th>Error</th>
</tr>
</thead>
<tbody>
<tr>
<td>{this.props.award.right}</td>
<td>{this.props.award.stop}</td>
<td>{this.props.award.wrong}</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
questionData: state.questionData,
award: state.awardData.value,
shouldUpdateQuestion: state.questionData.shouldUpdateQuestion,
};
}
const mapDispatchToProps = dispatch =>
bindActionCreators({
fetchQuestion,
fetchAwards,
updateAward,
}, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps,
)(App);
App.propTypes = {
fetchQuestion: PropTypes.func.isRequired,
fetchAwards: PropTypes.func.isRequired,
updateAward: PropTypes.func.isRequired,
shouldUpdateQuestion: PropTypes.bool.isRequired,
award: PropTypes.shape({
number: PropTypes.number.isRequired,
right: PropTypes.number.isRequired,
stop: PropTypes.number.isRequired,
wrong: PropTypes.number.isRequired,
level: PropTypes.number.isRequired,
}).isRequired,
};
|
JavaScript
| 0.000001 |
@@ -448,24 +448,247 @@
extProps) %7B%0A
+ if (nextProps.willUserStop) %7B%0A console.log('voce parou');%0A %7D%0A if (nextProps.shouldSkipQuestion) %7B%0A console.log('voce pulou');%0A %7D%0A if (nextProps.userFailed) %7B%0A console.log('voce errou');%0A %7D%0A
if (next
@@ -713,24 +713,24 @@
Question) %7B%0A
-
if (ne
@@ -1083,16 +1083,25 @@
%7D%7D
+%0A
%3ECarrega
@@ -1780,16 +1780,17 @@
;%0A %7D%0A%7D%0A
+%0A
function
@@ -2179,16 +2179,17 @@
(App);%0A%0A
+%0A
App.prop
@@ -2604,16 +2604,16 @@
quired,%0A
-
%7D).isR
@@ -2621,11 +2621,209 @@
quired,%0A
+ willUserStop: PropTypes.bool,%0A shouldSkipQuestion: PropTypes.bool,%0A userFailed: PropTypes.bool,%0A%7D;%0A%0AApp.defaultProps = %7B%0A willUserStop: false,%0A shouldSkipQuestion: false,%0A userFailed: false,%0A
%7D;%0A
|
dff96f88897d4fb91feed7e2466ca02ba8d2da82
|
Fix localstorage fs
|
lib/drivers/localstorage.js
|
lib/drivers/localstorage.js
|
var util = require('util');
var _ = require('lodash');
var DriverMemory = require('./memory');
function Driver(options, fs) {
var that = this;
options = _.defaults({}, options || {}, {
key: "repofs"
});
DriverMemory.apply(this, arguments);
if (window.localStorage[this.options.key]) {
this.branches = JSON.parse(window.localStorage[this.options.key]);
}
fs.on('watcher', function() {
window.localStorage[this.options.key] = JSON.stringify(that.branches);
});
}
util.inherits(Driver, DriverMemory);
Driver.id = "localstorage";
module.exports = Driver;
|
JavaScript
| 0.000003 |
@@ -283,34 +283,34 @@
.localStorage%5Bth
-is
+at
.options.key%5D) %7B
@@ -359,34 +359,34 @@
.localStorage%5Bth
-is
+at
.options.key%5D);%0A
@@ -456,18 +456,18 @@
orage%5Bth
-is
+at
.options
|
a2425b1d5fbce939203626b11b1dc31ee001b6e5
|
Make InvalidArgument error ctor to be available to outside
|
lib/game_of_life.support.js
|
lib/game_of_life.support.js
|
(function (GoL, _) {
var CT = { Alive: '*', Dead: '.' }
, ctParser = _(CT).chain()
.map(function (val, key) { return [val, key]; })
.reduce(function (memo, valKey) { memo[valKey[0]] = valKey[1]; return memo; }, {})
.value();
function InvalidArgument(message) {
this.prototype = Error.prototype;
this.name = 'InvalidArgument';
this.message = message;
this.toString = function () {
return this.name + ': ' + this.message;
};
};
function cellSymbolToObject(symbol) {
var obj = ctParser[symbol];
if (obj === undefined) {
throw new InvalidArgument('Unknown cell symbol in zero generation: ' + symbol);
}
return CT[obj];
}
GoL.Support = {
CellTypes: CT
, parseCanvas: function (canvas) {
if (!canvas || !canvas[0] || !canvas[0].getContext) {
throw new InvalidArgument('Not a canvas element');
}
return canvas[0];
}
, parseCellGrid: function (layout) {
var rows = layout.trim().split("\n")
, grid
, gridWidth
, gridIsSquare;
if (rows.length < 1) {
throw new InvalidArgument('Cell grid is too small');
}
grid = _.map(rows, function (row) { return _.map(row.split(''), cellSymbolToObject) });
gridWidth = grid.length;
gridIsSquare = _.all(grid, function (row) { return row.length === gridWidth });
if (!gridIsSquare) {
throw new InvalidArgument('Cell grid is not a square');
}
return grid;
}
};
})(GameOfLife, _);
|
JavaScript
| 0 |
@@ -742,16 +742,55 @@
%7B%0A
+ InvalidArgument: InvalidArgument%0A ,
CellTyp
|
d0be8898263d2fae30aeac0d21e89d5a7961f5be
|
Update express.js
|
madness/express.js
|
madness/express.js
|
//Request client port, 4004 if none.
var gameport = process.env.PORT || 4004,
io = require('socket.io'),
|
JavaScript
| 0.000002 |
@@ -103,8 +103,330 @@
t.io'),%0A
+ express = require('express'),%0A UUID = require('node-uuid'),%0A verbose = false,%0A app = express.createServer();%0A %0A app.listen(gameport);%0A %0A alert('%5Ct :: Express :: Listening on port '+gameport);%0A %0A app.get('/', function(req, res))%7B%0A //res.sendfile(__dirname + '/simplest.html');%0A %7D);%0A
|
f997b2835eb4b52983d5437eb84a4dd03771b28e
|
Add missing ajax promise APIs
|
lib/javascripts/base_app.js
|
lib/javascripts/base_app.js
|
import $ from 'jquery';
import Handlebars from 'handlebars';
import I18n from './i18n';
let maxHeight = 375;
function noop() {}
function resolveHandler(app, name) {
let handler = app.events[name];
if (!handler) { return noop; }
return _.isFunction(handler) ? handler.bind(app) : app[handler].bind(app);
}
function bindEvents(app) {
_.each(app.events, function(fn, key) {
let splittedKey = key.split(' '),
event = splittedKey[0],
element = splittedKey[1],
isDomEvent = !!element,
func = resolveHandler(app, key);
if (isDomEvent) {
$(document).on(event, element, func);
} else {
app.zafClient.on(event, func);
}
}.bind(app));
}
function registerHelpers(app) {
['setting', 'store'].forEach(function(api) {
Handlebars.registerHelper(api, function(key) {
return app[api](key);
});
});
Handlebars.registerHelper('t', function(key, context) {
try {
return app.I18n.t(key, context.hash);
} catch(e) {
console.error(e);
return e.message;
}
});
Handlebars.registerHelper('spinner', function() {
return new Handlebars.SafeString(`<div class="spinner dotted"></div>`);
});
}
function BaseApp(zafClient, data) {
this.zafClient = zafClient;
this.I18n = { t: I18n.t };
registerHelpers(this);
bindEvents(this);
let evt = { firstLoad: true };
this._metadata = data.metadata;
this._context = data.context;
zafClient.get('currentUser.locale').then(function(data) {
I18n.loadTranslations(data['currentUser.locale']);
if (this.defaultState) {
this.switchTo(this.defaultState);
}
resolveHandler(this, 'app.created')();
resolveHandler(this, 'app.activated')(evt, evt);
}.bind(this));
}
BaseApp.prototype = {
// These are public APIs of the framework that we are shimming to make it
// easier to migrate existing apps
events: {},
requests: {},
id: function() {
return this._metadata.appId;
},
installationId: function() {
return this._metadata.installationId;
},
guid: function() {
return this._context.instanceGuid;
},
currentLocation: function() {
return this._context.location;
},
ajax: function(name) {
let req = this.requests[name],
doneCallback = resolveHandler(this, name + '.done'),
failCallback = resolveHandler(this, name + '.fail'),
alwaysCallback = resolveHandler(this, name + '.always'),
options = _.isFunction(req) ? req.apply(this, Array.prototype.slice.call(arguments, 1)) : req;
return this.zafClient.request(options)
.then(doneCallback, failCallback)
.then(alwaysCallback, alwaysCallback);
},
renderTemplate: function(name, data) {
let template = require(`../../src/templates/${name}.hdbs`);
return template(data);
},
switchTo: function(name, data) {
this.$('[data-main]').html(this.renderTemplate(name, data));
let newHeight = Math.min($('html').height(), maxHeight);
this.zafClient.invoke('resize', { height: newHeight, width: '100%' });
},
$: function() {
let args = Array.prototype.slice.call(arguments, 0);
if (!args.length) return $('body');
return $.apply($, arguments);
},
setting: function(name) {
return this._metadata.settings[name];
},
store: function(keyOrObject, value) {
let installationId = this._metadata.installationId;
if (typeof keyOrObject === 'string') {
let key = `${installationId}:${keyOrObject}`;
if (arguments.length === 1) {
return JSON.parse(localStorage.getItem(key));
}
localStorage.setItem(key, JSON.stringify(value));
} else if (typeof keyOrObject === 'object') {
Object.keys(keyOrObject).forEach(function(key) {
localStorage.setItem(`${installationId}:${key}`, JSON.stringify(keyOrObject[key]));
});
}
}
}
BaseApp.extend = function(appPrototype) {
let App = function(client, data) {
BaseApp.call(this, client, data);
};
App.prototype = _.extend({}, BaseApp.prototype, appPrototype);
return App;
};
export default BaseApp;
|
JavaScript
| 0.000002 |
@@ -2254,146 +2254,298 @@
-doneCallback = resolveHandler(this, name + '.done'),%0A failCallback = resolveHandler(this, name + '.fail'),%0A alwaysCallback =
+options = _.isFunction(req) ? req.apply(this, Array.prototype.slice.call(arguments, 1)) : req,%0A dfd = $.Deferred(),%0A app = this;%0A%0A let alwaysCallback = resolveHandler(this, name + '.always');%0A%0A let doneCallback = function() %7B%0A dfd.resolveWith(app, arguments);%0A
res
@@ -2548,36 +2548,35 @@
resolveHandler(
-this
+app
, name + '.alway
@@ -2574,132 +2574,240 @@
+ '.
-always'),%0A options = _.isFunction(req) ? req.apply(this, Array.prototype.slice.call(arguments, 1)) : req;%0A%0A return
+done');%0A alwaysCallback.apply(app, arguments);%0A %7D;%0A%0A let failCallback = function() %7B%0A dfd.rejectWith(app, arguments);%0A resolveHandler(app, name + '.fail');%0A alwaysCallback.apply(app, arguments);%0A %7D;%0A%0A
thi
@@ -2838,34 +2838,8 @@
ons)
-%0A
.the
@@ -2871,70 +2871,34 @@
ack)
-%0A .then(alwaysCallback, alwaysCallback
+;%0A%0A return dfd.promise(
);%0A
|
a6308381b9230bb4fc82a4c6e47d7ee049ca752a
|
Fix #221 add option to disable refresh button
|
src/mw-layout/directives/mw_header.js
|
src/mw-layout/directives/mw_header.js
|
angular.module('mwUI.Layout')
.directive('mwHeader', function ($rootScope, $route, $location, BrowserTitleHandler) {
return {
transclude: true,
scope: {
title: '@',
url: '@?',
mwTitleIcon: '@?',
showBackButton: '=?',
mwBreadCrumbs: '=?',
description: '@?',
},
require: '^?mwUi',
templateUrl: 'uikit/mw-layout/directives/templates/mw_header.html',
link: function (scope, el, attrs, mwUiCtrl, $transclude) {
$rootScope.siteTitleDetails = scope.title;
BrowserTitleHandler.setTitle(scope.title);
scope.showRefreshButton = true;
if (scope.mwTitleIcon) {
el.find('.description').addClass('has-title-icon');
}
$transclude(function (clone) {
if ((!clone || clone.length === 0) && !scope.showBackButton) {
el.find('.mw-header').addClass('no-buttons');
}
if (el.find('[mw-form-actions]') && el.find('[mw-form-actions]').length > 0) {
scope.showRefreshButton = false;
}
});
scope.refresh = function () {
$route.reload();
};
scope.toggleDescription = function () {
scope.showDescription = !scope.showDescription;
};
scope.back = function () {
var path = scope.url.replace('#', '');
$location.path(path);
};
scope.canShowDescriptionButton = function () {
return angular.isDefined(scope.description);
};
scope.canShowBackButton = function () {
return (angular.isUndefined(scope.showBackButton) || scope.showBackButton) && angular.isDefined(scope.url);
};
if (!scope.url && scope.mwBreadCrumbs && scope.mwBreadCrumbs.length > 0) {
scope.url = scope.mwBreadCrumbs[scope.mwBreadCrumbs.length - 1].url;
} else if (!scope.url && scope.showBackButton) {
throw new Error('[mwHeader] Can not show back button when the attribute url is not defined');
}
if (mwUiCtrl) {
mwUiCtrl.addClass('has-mw-header');
scope.$on('$destroy', function () {
mwUiCtrl.removeClass('has-mw-header');
});
}
}
};
});
|
JavaScript
| 0 |
@@ -313,24 +313,52 @@
tion: '@?',%0A
+ disableReload: '=?'%0A
%7D,%0A
@@ -2249,24 +2249,113 @@
);%0A %7D
+%0A%0A if (scope.disableReload) %7B%0A scope.showRefreshButton = false;%0A %7D
%0A %7D%0A
|
9a3cf4eab1f9f4954595cddd2916eb0f80437547
|
Refactor component generator.
|
generator-lateralus/component/index.js
|
generator-lateralus/component/index.js
|
'use strict';
var yeoman = require('yeoman-generator');
var Mustache = require('mustache');
var _s = require('underscore.string');
var LateralusComponentGenerator = yeoman.generators.Base.extend({
initializing: function () {
this.pkg = require('../package.json');
this.isLateralus = this.appname === 'lateralus';
var options = this.options || {};
this.componentName = options.componentName || this.arguments[0];
},
writing: {
app: function () {
if (!this.componentName) {
return;
}
var renderData = {
componentName: this.componentName
,componentClassName: _s.classify(this.componentName)
};
var destRoot = this.isLateralus ?
'scripts/components/' :
'app/scripts/components/';
this.destinationRoot(destRoot + this.componentName);
var mainTemplate = Mustache.render(
this.src.read('main.js'), renderData);
this.dest.write('main.js', mainTemplate);
var modelTemplate = Mustache.render(
this.src.read('model.js'), renderData);
this.dest.write('model.js', modelTemplate);
var viewTemplate = Mustache.render(
this.src.read('view.js'), renderData);
this.dest.write('view.js', viewTemplate);
var templateTemplate = Mustache.render(
this.src.read('template.mustache'), renderData);
this.dest.write('template.mustache', templateTemplate);
var sassTemplate = Mustache.render(
this.src.read('styles/main.sass'), renderData);
this.dest.write('styles/main.sass', sassTemplate);
}
}
});
module.exports = LateralusComponentGenerator;
|
JavaScript
| 0 |
@@ -846,323 +846,95 @@
-var mainTemplate = Mustache.render(%0A this.src.read('main.js'), renderData);%0A this.dest.write('main.js', mainTemplate);%0A%0A var modelTemplate = Mustache.render(%0A this.src.read('model.js'), renderData);%0A this.dest.write('model.js', modelTemplate);%0A%0A var viewT
+%5B%0A 'main.js'%0A ,'model.js'%0A ,'view.js'%0A ,'t
emplate
- = M
+.m
ustache
-.render(
+'
%0A
@@ -942,96 +942,68 @@
-this.src.read('view.js'), renderData);%0A this.dest.write('view.js', viewTemplate);%0A%0A
+,'styles/main.sass'%0A %5D.forEach(function (fileName) %7B%0A
@@ -1008,24 +1008,24 @@
var
-template
+rendered
Template
@@ -1044,32 +1044,34 @@
render(%0A
+
this.src.read('t
@@ -1068,35 +1068,24 @@
rc.read(
-'template.mustache'
+fileName
), rende
@@ -1084,32 +1084,34 @@
), renderData);%0A
+
this.dest.
@@ -1120,37 +1120,26 @@
ite(
-'template.mustache', template
+fileName, rendered
Temp
@@ -1149,161 +1149,26 @@
e);%0A
-%0A
-var sassTemplate = Mustache.render(%0A this.src.read('styles/main.sass'), renderData);%0A this.dest.write('styles/main.sass', sassTemplate
+%7D.bind(this)
);%0A
|
da44268f0d748c2372715337f63c4bde1d90fa76
|
remove unnecessary logs.
|
src/node_modules/react-novnc/index.js
|
src/node_modules/react-novnc/index.js
|
import React, { Component } from 'react'
import { propTypes } from 'utils'
import { RFB } from 'novnc-node'
import {
format as formatUrl,
parse as parseUrl,
resolve as resolveUrl
} from 'url'
const parseRelativeUrl = (url) => parseUrl(resolveUrl(String(window.location), url))
const PROTOCOL_ALIASES = {
'http:': 'ws:',
'https:': 'wss:'
}
const fixProtocol = (url) => {
const protocol = PROTOCOL_ALIASES[url.protocol]
if (protocol) {
url.protocol = protocol
}
}
@propTypes({
onClipboardChange: propTypes.func,
url: propTypes.string.isRequired
})
export default class NoVnc extends Component {
constructor (props) {
super(props)
this._rfb = null
}
_clean () {
const rfb = this._rfb
if (rfb) {
this._rfb = null
rfb.disconnect()
}
}
_focus () {
const rfb = this._rfb
if (rfb) {
const { activeElement } = document
if (activeElement) {
activeElement.blur()
}
rfb.get_keyboard().grab()
rfb.get_mouse().grab()
}
}
_unfocus () {
const rfb = this._rfb
if (rfb) {
rfb.get_keyboard().grab()
rfb.get_mouse().grab()
}
}
componentDidMount () {
this._clean()
const url = parseRelativeUrl(this.props.url)
fixProtocol(url)
const isSecure = url.protocol === 'wss:'
const { onClipboardChange } = this.props
const rfb = this._rfb = new RFB({
encrypt: isSecure,
target: this.refs.canvas,
wsProtocols: [ 'chat' ],
onClipboardChange: onClipboardChange && ((_, text) => {
onClipboardChange(text)
}),
onUpdateState: (_, state) => console.log(state)
})
console.log(formatUrl(url))
rfb.connect(formatUrl(url))
}
componentWillUnmount () {
this._clean()
}
render () {
return <canvas
className='center-block'
height='480'
onMouseEnter={() => this._focus()}
onMouseLeave={() => this._unfocus()}
ref='canvas'
width='640'
/>
}
}
|
JavaScript
| 0 |
@@ -1593,101 +1593,14 @@
%7D)
-,%0A onUpdateState: (_, state) =%3E console.log(state)%0A %7D)%0A console.log(formatUrl(url)
+%0A %7D
)%0A
|
d301953feff98819c40b0cb7c5ba4f9b2061cc43
|
Update part2.js
|
3/part2.js
|
3/part2.js
|
/**
* Created by chrisjohnson on 03/12/2016.
*/
var fs = require('fs');
var input = fs.readFileSync('./input.txt', 'utf8'),
lines = input.split('\n').map(function (l) {
return l.trim().replace(/\s+/g, ' ').split(' ').map(function (num) {
return Number(num);
});
}),
triangles = [];
function sort(arr) {
return arr.sort(function (a, b) {
return a - b
});
}
function transpose(lines) {
const newLines = [];
for (var i = 0; i < lines.length - 2; i += 3) {
newLines.push(sort([lines[i][0], lines[i + 1][0], lines[i + 2][0]]));
newLines.push(sort([lines[i][1], lines[i + 1][1], lines[i + 2][1]]));
newLines.push(sort([lines[i][2], lines[i + 1][2], lines[i + 2][2]]));
}
return newLines;
}
transpose(lines).map(function (line) {
if (line[0] + line[1] > line[2]) {
triangles.push(line);
}
});
console.log(triangles.length);
|
JavaScript
| 0 |
@@ -332,16 +332,18 @@
(arr) %7B%0A
+
return a
@@ -854,18 +854,16 @@
%7D%0A%7D);%0A%0A
-%0A%0A
console.
@@ -884,8 +884,9 @@
length);
+%0A
|
fb9717734c3a90556ba6f66a245d36130188956c
|
Fix broken config test
|
src/reducers/__tests__/config-test.js
|
src/reducers/__tests__/config-test.js
|
/**
*
* @license
* Copyright (C) 2016 Joseph Roque
*
* 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.
*
* @author Joseph Roque
* @created 2016-10-08
* @file config-test.js
* @description Tests config reducers
*
*/
'use strict';
// Imports
import reducer from '../config';
// Expected initial state
const initialState = {
alwaysSearchAll: false,
busInfo: null,
currentSemester: 0,
firstTime: false,
language: null,
preferredTimeFormat: '12h',
prefersWheelchair: false,
semesters: [],
};
// Test configuration update
const configurationUpdate = {
alwaysSearchAll: true,
language: 'en',
};
// Expected state when configuration updated
const updatedState = {
alwaysSearchAll: true,
busInfo: {name: 'Buses', link: 'http://example.com'},
currentSemester: 0,
firstTime: false,
language: 'en',
preferredTimeFormat: '12h',
prefersWheelchair: false,
semesters: [],
};
describe('config reducer', () => {
it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(initialState);
});
it('should update the state', () => {
expect(
reducer(
initialState,
{
type: 'UPDATE_CONFIGURATION',
options: configurationUpdate,
}
)
).toEqual(updatedState);
});
});
|
JavaScript
| 0.000023 |
@@ -1095,16 +1095,72 @@
: true,%0A
+ busInfo: %7Bname: 'Buses', link: 'http://example.com'%7D,%0A
langua
|
0b2736f3efc2c77b7b6adcb53666bf9ef16bc434
|
rename Cygnus to DvaGUI
|
src/renderer/components/UI/Welcome.js
|
src/renderer/components/UI/Welcome.js
|
import React, { PropTypes } from 'react';
import { Button } from 'antd';
import './Welcome.less';
const Welcome = props =>
<div className="welcome">
<div className="welcome-title">
Welcome to Cygnus.
</div>
<Button type="ghost" onClick={props.onOpen}>
Open a Dva Project
</Button>
</div>;
Welcome.propTypes = {
onOpen: PropTypes.func,
};
export default Welcome;
|
JavaScript
| 0.999973 |
@@ -202,14 +202,14 @@
to
-Cygnus
+DvaGUI
.%0A
|
18c73efa62c0d4bd74a67f2a1b15eb73aab7ac70
|
Make missing assets 404 correctly
|
src/services/server/handlers/pages.js
|
src/services/server/handlers/pages.js
|
/**
* Module dependencies.
*/
var Promise = require('bluebird');
var path = require('path');
var _ = require('lodash');
var utils = require('../../../utils');
/*
* Export the pages route handlers.
*/
var handlers = exports = module.exports = {};
handlers.params = {};
/*
* Resolve a page from a path parameter
*/
handlers.params.page = function(req, res, next, pagePath) {
var page = req._pages.resolve(pagePath);
page.renderContent().then(function(){
res.locals.page = page.toJSON();
next();
});
};
/*
* Render a generic page.
*/
handlers.page = function(req, res){
var section = res.locals.section || {
handle: 'pages',
baseUrl: '/',
};
res.render('pages/page', {
section: section
});
};
|
JavaScript
| 0.000276 |
@@ -150,16 +150,71 @@
ash');%0A%0A
+var highlighter = require('../../../highlighter');%0A
var util
@@ -254,16 +254,16 @@
tils');%0A
-
%0A/*%0A * E
@@ -476,16 +476,30 @@
Path) %7B%0A
+ try %7B%0A
var
@@ -539,16 +539,20 @@
h);%0A
+
+
page.ren
@@ -585,24 +585,28 @@
()%7B%0A
+
+
res.locals.p
@@ -634,16 +634,20 @@
+
next();%0A
@@ -646,27 +646,154 @@
next();%0A
-%7D);
+ %7D);%0A %7D catch(err) %7B%0A return res.status(404).render('pages/404', %7B%0A message: err.message%0A %7D);%0A %7D
%0A%7D;%0A%0A/*%0A * R
|
f3fb66c51a20e2f495cce5ac0b33f7aee809f0c9
|
Prepare loaders for Webpack2
|
webpack/loaders.js
|
webpack/loaders.js
|
const { isTest } = require('../configuration');
const preJsx = {
test: /\.jsx?$/,
loaders: ['source-map', 'eslint'],
exclude: /node_modules/
};
const preTestJsx = {
test: /\.jsx?$/,
loader: 'isparta',
exclude: /(node_modules|__tests__|webpack\.tests\.js)/
};
const jsx = {
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/
};
const css = {
test: /\.css$/,
loaders: ['style', 'css']
};
const json = {
test: /\.json$/,
loader: 'json'
};
const md = {
test: /\.md$/,
loader: 'raw'
};
const images = {
test: /\.(jpe?g|png)$/,
loaders: ['file?name=assets/[name].[ext]', 'image-webpack'],
include: /assets/
};
const fonts = [
{
test: /\.woff2?(\?.*)?$/,
loader: 'url?limit=10000&mimetype=application/font-woff'
}, {
test: /\.ttf(\?.*)?$/,
loader: 'url?limit=10000&mimetype=application/octet-stream'
}, {
test: /\.eot(\?.*)?$/,
loader: 'file'
}, {
test: /\.svg(\?.*)?$/,
loader: 'url?limit=10000&mimetype=image/svg+xml'
}
];
module.exports = {
preLoaders: isTest ? [preTestJsx] : [preJsx],
loaders: [jsx, css, json, md, images, ...fonts]
};
|
JavaScript
| 0 |
@@ -611,19 +611,58 @@
s: %5B
-'file?
+%7B%0A loader: 'file',%0A query: %7B
name
-=
+: '
asse
@@ -677,16 +677,24 @@
%5D.%5Bext%5D'
+ %7D%0A %7D
, 'image
@@ -807,37 +807,82 @@
er: 'url
-?
+',%0A query: %7B%0A
limit
-=
+:
10000
-&
+,%0A
mimetype
=applica
@@ -865,33 +865,35 @@
mimetype
-=
+: '
application/font
@@ -899,16 +899,26 @@
t-woff'%0A
+ %7D%0A
%7D, %7B
@@ -969,37 +969,82 @@
er: 'url
-?
+',%0A query: %7B%0A
limit
-=
+:
10000
-&
+,%0A
mimetype
=applica
@@ -1035,17 +1035,19 @@
mimetype
-=
+: '
applicat
@@ -1064,16 +1064,26 @@
stream'%0A
+ %7D%0A
%7D, %7B
@@ -1201,29 +1201,74 @@
'url
-?
+',%0A query: %7B%0A
limit
-=
+:
10000
-&
+,%0A
mimetype
=ima
@@ -1263,17 +1263,19 @@
mimetype
-=
+: '
image/sv
@@ -1281,16 +1281,26 @@
vg+xml'%0A
+ %7D%0A
%7D%0A%5D;
|
e5caac932963b3eed9046886f4fb542fda45e752
|
Fix Hot Loading with Eslintgit st (#9) (#27)
|
webpack/plugins.js
|
webpack/plugins.js
|
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const SplitByPathPlugin = require('webpack-split-by-path');
const path = require('path');
const basePlugins = [
new webpack.DefinePlugin({
__DEV__: process.env.NODE_ENV !== 'production',
__TEST__: JSON.stringify(process.env.TEST),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new HtmlWebpackPlugin({
chunksSortMode: 'dependency',
template: './src/index.html',
inject: 'body'
}),
new webpack.NoErrorsPlugin()
];
const devPlugins = [
new StyleLintPlugin({
configFile: './.stylelintrc',
files: ['src/**/*.css'],
failOnError: false
})
];
const prodPlugins = [
new SplitByPathPlugin([
{ name: 'vendor', path: [path.join(__dirname, '..', 'node_modules/')] }
]),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
})
];
module.exports = basePlugins
.concat(process.env.NODE_ENV === 'production' ? prodPlugins : [])
.concat(process.env.NODE_ENV === 'development' ? devPlugins : []);
|
JavaScript
| 0 |
@@ -582,40 +582,8 @@
%7D)
-,%0A new webpack.NoErrorsPlugin()
%0A%5D;%0A
@@ -958,24 +958,56 @@
e%0A %7D%0A %7D)
+,%0A new webpack.NoErrorsPlugin()
%0A%5D;%0A%0Amodule.
|
169c002f26c4bfe0c7fc022e237fdb9af4f5a290
|
remove external script injection, use plain
|
pagelets/loader.js
|
pagelets/loader.js
|
'use strict';
//
// Current environment the application is running in.
//
var env = process.env.NODE_ENV || 'development';
//
// Expose the asynchronous client-side JS loader Pagelet.
//
require('./pagelet').extend({
name: 'loader',
view: '{{brand}}/loader/view.hbs',
//
// Provide some defaults for loading client-side Cortex applications.
//
// - apps: identifiers of the client-side applications that need to be loaded
// - load: internal JS for which the proper environment version will be loaded.
// - plain: external JS which will not be mapped by env/versions.
//
defaults: {
development: env === 'development',
apps: [],
load: [],
plain: [ '//webops.nodejitsu.com/js/ui.js' ]
},
/**
* Merge the data of custom and external to load and plain.
*
* @returns {Pagelet}
* @api private
*/
define: function define() {
var data = this.data
, load = data.load || this.defaults.load
, plain = data.plain || this.defaults.plain;
if ('custom' in data) data.load = load.concat(data.custom);
if ('external' in data) data.plain = plain.concat(data.external);
return this;
}
}).on(module);
|
JavaScript
| 0 |
@@ -1065,79 +1065,8 @@
m);%0A
- if ('external' in data) data.plain = plain.concat(data.external);%0A%0A
|
445b4af784dcf31ce2f87eb34091c8f05fac534d
|
add underline to originally linked words
|
plugins/urbandictionary.js
|
plugins/urbandictionary.js
|
var request = require("request");
function UrbanDictionaryPlugin(bot) {
var self = this;
self.name = "urbandictionary";
self.help = "Urban Dictionary plugin";
self.depend = ["cmd", "util"];
self.strip = function(str) {
return str.replace(/\[([^\]]+)\]/g, "$1").replace(/\r?\n/g, " ");
};
self.formatDefinition = function(str) {
return bot.plugins.util.ellipsize(self.strip(str), 350);
};
self.events = {
"cmd#ud": function(nick, to, args) {
if (args[1] == "random") {
request("https://api.urbandictionary.com/v0/random", function(err, res, body) {
if (!err && res.statusCode == 200) {
var j = JSON.parse(body);
if (j.list !== undefined && j.list.length !== 0) {
var item = j.list[0];
bot.say(to, "\x02" + item.word + "\x02 [random]: " + self.formatDefinition(item.definition));
}
}
});
}
else {
var match = args[0].match(/^(.*)\s+(\d+)\s*$/);
var str;
var i;
if (match) {
str = match[1];
i = parseInt(match[2]);
}
else {
str = args[0];
i = 1;
}
str = str.trim();
request({
uri: "https://api.urbandictionary.com/v0/define",
qs: {
term: str
}
}, function(err, res, body) {
if (!err && res.statusCode == 200) {
var j = JSON.parse(body);
if (j.list !== undefined && j.list.length !== 0) {
if (i - 1 >= 0 && i - 1 < j.list.length) {
var item = j.list[i - 1];
bot.say(to, "\x02" + item.word + "\x02 [" + i + "/" + j.list.length + "]: " + self.formatDefinition(item.definition));
}
else
bot.say(to, nick + ": \x02" + str + "\x02 [" + i + "/" + j.list.length + "] invalid result index");
}
else
bot.say(to, nick + ": couldn't find \x02" + str + "\x02");
}
});
}
}
};
}
module.exports = UrbanDictionaryPlugin;
|
JavaScript
| 0.000001 |
@@ -262,10 +262,18 @@
g, %22
-$1
+%5Cx1F$1%5Cx1F
%22).r
|
c83fec900f70ecae50cd4bb068b24d685ae5e49d
|
Use 'that' consistently.
|
lib/memoizeAsyncAccessor.js
|
lib/memoizeAsyncAccessor.js
|
/*global require, module, process*/
module.exports = function memoizeAsyncAccessor(name, computer) {
return function (cb) {
var that = this;
if (name in that) {
process.nextTick(function () {
cb(null, that[name]);
});
} else {
var waitingQueuePropertyName = '_' + name + '_queue';
if (waitingQueuePropertyName in this) {
that[waitingQueuePropertyName].push(cb);
} else {
that[waitingQueuePropertyName] = [cb];
computer.call(that, function (err, result) {
that[name] = result;
that[waitingQueuePropertyName].forEach(function (waitingCallback) {
waitingCallback(err, result);
});
delete that[waitingQueuePropertyName];
});
}
}
};
};
|
JavaScript
| 0 |
@@ -400,18 +400,18 @@
me in th
-is
+at
) %7B%0A
|
6ddbda14cd3c8758b223d239c7433e3bccdf0c53
|
remove unuse codes (#26)
|
test/fixtures/apps/env-app/config/config.default.js
|
test/fixtures/apps/env-app/config/config.default.js
|
'use strict';
exports.fakeplugin = {
foo: 'bar-default',
};
// exports.alipayuserservice = {
// authcenterUrl: 'http://authcenter.stable.alipay.net',
// };
exports.logger = {
consoleLevel: 'NONE',
};
|
JavaScript
| 0.000233 |
@@ -61,107 +61,8 @@
%7D;%0A%0A
-// exports.alipayuserservice = %7B%0A// authcenterUrl: 'http://authcenter.stable.alipay.net',%0A// %7D;%0A%0A
expo
|
1b14a18abf4fd1368a19dbc7ebe07f4ee71320f7
|
fix travis (#156)
|
test/fixtures/destructuring-with-arrows/expected.js
|
test/fixtures/destructuring-with-arrows/expected.js
|
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
const f = ({ a }) => {
_assert({
a
}, T, "{ a }");
};
const g = ({ a, ...b }) => {
_assert(_extends({
a
}, b), T, "{ a, ...b }");
};
|
JavaScript
| 0 |
@@ -248,24 +248,246 @@
target; %7D;%0A%0A
+function _objectWithoutProperties(obj, keys) %7B var target = %7B%7D; for (var i in obj) %7B if (keys.indexOf(i) %3E= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target%5Bi%5D = obj%5Bi%5D; %7D return target; %7D%0A%0A
const f = (%7B
@@ -552,25 +552,89 @@
= (
-%7B a, ...b
+_ref) =%3E %7B%0A let %7B a
%7D
-)
=
-%3E %7B
+ _ref;%0A%0A let b = _objectWithoutProperties(_ref, %5B%22a%22%5D);%0A
%0A _
|
0f181a34ee9b00bc14c04a0730cd91b071ff46a6
|
Fix typo in meteor setup
|
lib/modules/meteor/index.js
|
lib/modules/meteor/index.js
|
import path from 'path';
import debug from 'debug';
import nodemiral from 'nodemiral';
import {runTaskList} from '../utils';
import * as docker from '../docker/';
const log = debug('mup:module:meteor');
export function help(/* api */) {
log('exec => mup meteor help');
}
export function logs(/* api */) {
log('exec => mup meteor logs');
}
export function setup(api) {
log('exec => mup meteor setup');
const config = api.getConfig().meteor;
if (!config) {
console.error('error: no configs found for meteor');
process.exit(1);
}
const list = nodemiral.taskList('Setup Meteor');
list.executeScript('setup environment', {
script: path.resolve(__dirname, 'assets/meteor-setup.sh'),
vars: {
name: config.name,
},
});
if (config.ssl) {
taskList.copy('copying ssl certificate bundle', {
src: config.ssl.crt,
dest: '/opt/' + config.name + '/config/bundle.crt'
});
taskList.copy('copying ssl private key', {
src: config.ssl.key,
dest: '/opt/' + config.name + '/config/private.key'
});
taskList.executeScript('verifying ssl configurations', {
script: path.resolve(__dirname, 'assets/verify-ssl-config.sh'),
vars: {
name: config.name
},
});
}
const sessions = api.getSessions([ 'meteor' ]);
const apiForMeteor = api.withSessions([ 'meteor' ]);
return docker.setup(apiForMeteor)
.then(() => runTaskList(list, sessions));
}
export function start(api) {
log('exec => mup meteor start');
const list = nodemiral.taskList('Start Meteor');
list.executeScript('start meteor', {
script: path.resolve(__dirname, 'assets/meteor-start.sh')
});
const sessions = api.getSessions([ 'meteor' ]);
return runTaskList(list, sessions);
}
export function stop(api) {
log('exec => mup meteor stop');
const list = nodemiral.taskList('Stop Meteor');
list.executeScript('stop meteor', {
script: path.resolve(__dirname, 'assets/meteor-stop.sh')
});
const sessions = api.getSessions([ 'meteor' ]);
return runTaskList(list, sessions);
}
|
JavaScript
| 0.000162 |
@@ -774,29 +774,25 @@
.ssl) %7B%0A
-taskL
+l
ist.copy('co
@@ -917,29 +917,25 @@
%7D);%0A%0A
-taskL
+l
ist.copy('co
@@ -1058,21 +1058,17 @@
);%0A%0A
-taskL
+l
ist.exec
|
ac390ba126fdd7465c72a48a2246874558f75cfb
|
fix hidden files in model directory from breaking seed
|
core/required/model_factory.js
|
core/required/model_factory.js
|
'use strict';
const ModelArray = require('./model_array.js');
const fs = require('fs');
const async = require('async');
/**
* Factory for creating models
* @class
*/
class ModelFactory {
/**
* Create the ModelFactory with a provided Model to use as a reference.
* @param {Nodal.Model} modelConstructor Must pass the constructor for the type of ModelFactory you wish to create.
*/
constructor(modelConstructor) {
this.Model = modelConstructor;
}
/**
* Loads all model constructors in your ./app/models directory into an array
* @return {Array} Array of model Constructors
*/
static loadModels() {
let dir = './app/models';
if (!fs.existsSync(dir)) {
return [];
}
return fs
.readdirSync(dir)
.map(filename => require(`${process.cwd()}/app/models/${filename}`))
}
/**
* Creates new factories from a supplied array of Models, loading in data keyed by Model name
* @param {Array} Models Array of model constructors you wish to reference
* @param {Object} objModelData Keys are model names, values are arrays of model data you wish to create
* @param {Function} callback What to execute upon completion
*/
static createFromModels(Models, objModelData, callback) {
if (objModelData instanceof Array) {
async.series(
objModelData.map(objModelData => callback => this.createFromModels(Models, objModelData, callback)),
(err, results) => {
results = (results || []).reduce((results, res) => {
return results.concat(res);
}, []);
callback(err || null, results);
}
);
return;
}
async.parallel(
Models
.filter(Model => objModelData[Model.name] && objModelData[Model.name].length)
.map(Model => callback => new this(Model).create(objModelData[Model.name], callback)),
(err, results) => callback(err || null, results)
);
}
/**
* Populates a large amount of model data from an Object.
* @param {Array} Models Array of Model constructors
*/
static populate(objModelData, callback) {
return this.createFromModels(this.loadModels(), objModelData, callback);
}
/**
* Creates models from an array of Objects containing the model data
* @param {Array} arrModelData Array of objects to create model data from
*/
create(arrModelData, callback) {
// new this.Model(data, false, true) is telling the Model that this is from a seed
ModelArray
.from(arrModelData.map(data => new this.Model(data, false, true)))
.saveAll(callback);
}
}
module.exports = ModelFactory;
|
JavaScript
| 0 |
@@ -745,16 +745,71 @@
nc(dir)%0A
+ .filter(filename =%3E filename.indexOf('.') !== 0)%0A
.m
|
b01e46b02c107a113fcf37843fe2bef5ac526b5b
|
Update integration/sanity/request-name-script tests to chai
|
test/integration/sanity/request-name-script.test.js
|
test/integration/sanity/request-name-script.test.js
|
describe('request name scripts', function() {
var testrun;
before(function(done) {
this.run({
collection: {
item: [{
name: 'r1',
event: [{
listen: 'test',
script: {
exec: [
'var failed = postman.getEnvironmentVariable(\'fail\');',
// eslint-disable-next-line max-len
'tests[\'working\'] = !failed && (request.name===\'r1\' && request.description===\'testDesc\')'
]
}
}, {
listen: 'prerequest',
script: {
exec: [
'if(request.name!==\'r1\' || request.description!==\'testDesc\') {',
' postman.setEnvironmentVariable(\'fail\', \'true\')',
'}'
]
}
}],
request: {
url: 'postman-echo.com/get',
method: 'GET',
body: {
mode: 'formdata',
formdata: []
},
description: 'testDesc'
}
}]
}
}, function(err, results) {
testrun = results;
done(err);
});
});
it('must have run the test script successfully', function() {
var assertions = testrun.assertion.getCall(0).args[1];
expect(testrun).be.ok();
expect(testrun.test.calledOnce).be.ok();
expect(testrun.prerequest.calledOnce).be.ok();
expect(testrun.test.getCall(0).args[0]).to.be(null);
expect(assertions[0]).to.have.property('name', 'working');
expect(assertions[0]).to.have.property('passed', true);
});
it('must have completed the run', function() {
expect(testrun).be.ok();
expect(testrun.done.calledOnce).be.ok();
expect(testrun.done.getCall(0).args[0]).to.be(null);
expect(testrun.start.calledOnce).be.ok();
});
});
|
JavaScript
| 0 |
@@ -1,12 +1,50 @@
+var expect = require('chai').expect;%0A%0A
describe('re
@@ -1642,28 +1642,30 @@
);%0A%0A it('
-must
+should
have run th
@@ -1785,39 +1785,40 @@
expect(testrun).
+to.
be.ok
-()
;%0A expect
@@ -1829,58 +1829,80 @@
trun
+)
.t
-est.calledOnce).be.ok();%0A expect(testrun.
+o.nested.include(%7B%0A 'test.calledOnce': true,%0A '
prer
@@ -1918,24 +1918,33 @@
lledOnce
-).be.ok(
+': true%0A %7D
);%0A%0A
@@ -1984,38 +1984,37 @@
).args%5B0%5D).to.be
-(
+.
null
-)
;%0A expect
@@ -2036,29 +2036,42 @@
.to.
-have.property('
+nested.include(%7B%0A
name
-',
+:
'wo
@@ -2076,18 +2076,17 @@
working'
-);
+,
%0A
@@ -2090,61 +2090,34 @@
-expect(assertions%5B0%5D).to.have.property('
+
passed
-',
+:
true
+%0A %7D
);%0A
@@ -2136,12 +2136,14 @@
it('
-must
+should
hav
@@ -2201,23 +2201,24 @@
estrun).
+to.
be.ok
-()
;%0A
@@ -2243,137 +2243,167 @@
one.
-calledOnce).be.ok();%0A expect(testrun.done.getCall(0).args%5B0%5D).to.be(null);%0A expect(testrun.start.calledOnce).be.ok(
+getCall(0).args%5B0%5D).to.be.null;%0A expect(testrun).to.nested.include(%7B%0A 'done.calledOnce': true,%0A 'start.calledOnce': true%0A %7D
);%0A
|
7682c04b558f5077e3876ab691367ff5eb095daa
|
Add js tests for schedules with multiple class and slot items
|
server/static/js/js_tests/schedule/basic_test.js
|
server/static/js/js_tests/schedule/basic_test.js
|
define(function(require) {
var expect = require('ext/chai').expect;
var $ = require('ext/jquery');
var schedule_parser = require('schedule_parser');
describe('Schedule parsing', function() {
var parsedSchedulePromise = $.get(
'/static/js/js_tests/schedule/data/basic.txt').then(function(r) {
return schedule_parser.parseSchedule(r);
});
var testParsedScheduleAsync = function(testName, testCallback) {
it(testName, function(done) {
parsedSchedulePromise.then(function(scheduleData) {
try {
testCallback(scheduleData);
done();
} catch (e) {
return done(e);
}
});
});
};
testParsedScheduleAsync('extracts the term name',
function(scheduleData) {
expect(scheduleData.term_name).to.equal('Winter 2014');
});
testParsedScheduleAsync('produces correct number of courses',
function(scheduleData) {
expect(scheduleData.courses.length).to.equal(7);
});
testParsedScheduleAsync('produces no failed courses',
function(scheduleData) {
expect(scheduleData.failed_courses.length).to.equal(0);
});
testParsedScheduleAsync(
'extracts the correct number of items for course multiple time entries',
function(scheduleData) {
expect(scheduleData.courses[1].course_id).to.equal('ece106');
expect(scheduleData.courses[1].items.length).to.equal(63);
});
testParsedScheduleAsync('extracts the first course\'s course ID',
function(scheduleData) {
expect(scheduleData.courses[0].course_id).to.equal('cs138');
});
testParsedScheduleAsync(
'extracts the correct number of items for course with one time entry',
function(scheduleData) {
expect(scheduleData.courses[0].items.length).to.equal(39);
});
testParsedScheduleAsync('extracts the first item\'s building',
function(scheduleData) {
expect(scheduleData.courses[0].items[0].building).to.equal('OPT');
});
testParsedScheduleAsync('extracts the first item\'s prof name',
function(scheduleData) {
expect(scheduleData.courses[0].items[0].prof_name).to
.equal('Michael Godfrey');
});
testParsedScheduleAsync('extracts the first item\'s start date',
function(scheduleData) {
expect(scheduleData.courses[0].items[0].start_date).to.equal(1389106800);
});
testParsedScheduleAsync('extracts the first item\'s end date',
function(scheduleData) {
expect(scheduleData.courses[0].items[0].end_date).to.equal(1389111600);
});
testParsedScheduleAsync('extracts the first item\'s class number',
function(scheduleData) {
expect(scheduleData.courses[0].items[0].class_num).to.equal('5819');
});
testParsedScheduleAsync('extracts the first item\'s room',
function(scheduleData) {
expect(scheduleData.courses[0].items[0].room).to.equal('347');
});
testParsedScheduleAsync('extracts the first item\'s section number',
function(scheduleData) {
expect(scheduleData.courses[0].items[0].section_num).to.equal('001');
});
testParsedScheduleAsync('extracts the first item\'s section type',
function(scheduleData) {
expect(scheduleData.courses[0].items[0].section_type).to.equal('LEC');
});
testParsedScheduleAsync('extracts the last item\'s course ID',
function(scheduleData) {
expect(scheduleData.courses[6].course_id).to.equal('stat230');
});
testParsedScheduleAsync(
'extracts the correct number of items for last course',
function(scheduleData) {
expect(scheduleData.courses[6].items.length).to.equal(54);
});
testParsedScheduleAsync('extracts the last item\'s building',
function(scheduleData) {
expect(scheduleData.courses[6].items[53].building).to.equal('DC');
});
testParsedScheduleAsync('extracts the last item\'s prof name',
function(scheduleData) {
expect(scheduleData.courses[6].items[53].prof_name).to
.equal('Christian Boudreau');
});
testParsedScheduleAsync('extracts the last item\'s start date',
function(scheduleData) {
expect(scheduleData.courses[6].items[53].start_date).to.equal(1396629000);
});
testParsedScheduleAsync('extracts the last item\'s end date',
function(scheduleData) {
expect(scheduleData.courses[6].items[53].end_date).to.equal(1396632000);
});
testParsedScheduleAsync('extracts the last item\'s class number',
function(scheduleData) {
expect(scheduleData.courses[6].items[53].class_num).to.equal('7208');
});
testParsedScheduleAsync('extracts the last item\'s room',
function(scheduleData) {
expect(scheduleData.courses[6].items[53].room).to.equal('1350');
});
testParsedScheduleAsync('extracts the last item\'s section number',
function(scheduleData) {
expect(scheduleData.courses[6].items[53].section_num).to.equal('002');
});
testParsedScheduleAsync('extracts the last item\'s section type',
function(scheduleData) {
expect(scheduleData.courses[6].items[53].section_type).to.equal('LEC');
});
});
});
|
JavaScript
| 0 |
@@ -1222,76 +1222,61 @@
'
-extracts the correct number of items for course multiple time entrie
+validate course that has multiple class and slot item
s',%0A
@@ -1372,24 +1372,24 @@
('ece106');%0A
-
expect
@@ -1441,16 +1441,483 @@
al(63);%0A
+ expect(scheduleData.courses%5B1%5D.items%5B0%5D.section_type).to.equal('LEC');%0A expect(scheduleData.courses%5B1%5D.items%5B43%5D.section_type).to.equal('LEC');%0A expect(scheduleData.courses%5B1%5D.items%5B44%5D.section_type).to.equal('TUT');%0A expect(scheduleData.courses%5B1%5D.items%5B56%5D.section_type).to.equal('TUT');%0A expect(scheduleData.courses%5B1%5D.items%5B57%5D.section_type).to.equal('LAB');%0A expect(scheduleData.courses%5B1%5D.items%5B62%5D.section_type).to.equal('LAB');%0A
%7D);%0A
|
720ae0541539a3d0690a6a496f5aa11df92452ef
|
Include DOMSprite in 'include openfl/display'
|
lib/openfl/display/index.js
|
lib/openfl/display/index.js
|
module.exports = {
// Application: require("./Application").default,
Bitmap: require("./Bitmap").default,
BitmapData: require("./BitmapData").default,
BitmapDataChannel: require("./BitmapDataChannel").default,
BlendMode: require("./BlendMode").default,
CapsStyle: require("./CapsStyle").default,
DisplayObject: require("./DisplayObject").default,
DisplayObjectContainer: require("./DisplayObjectContainer").default,
// DOMSprite: require("./DOMSprite").default,
FPS: require("./FPS").default,
FrameLabel: require("./FrameLabel").default,
GradientType: require("./GradientType").default,
Graphics: require("./Graphics").default,
GraphicsBitmapFill: require("./GraphicsBitmapFill").default,
GraphicsEndFill: require("./GraphicsEndFill").default,
GraphicsGradientFill: require("./GraphicsGradientFill").default,
GraphicsPath: require("./GraphicsPath").default,
GraphicsPathCommand: require("./GraphicsPathCommand").default,
GraphicsPathWinding: require("./GraphicsPathWinding").default,
GraphicsSolidFill: require("./GraphicsSolidFill").default,
GraphicsStroke: require("./GraphicsStroke").default,
IBitmapDrawable: require("./IBitmapDrawable").default,
IGraphicsData: require("./IGraphicsData").default,
IGraphicsFill: require("./IGraphicsFill").default,
IGraphicsPath: require("./IGraphicsPath").default,
IGraphicsStroke: require("./IGraphicsStroke").default,
InteractiveObject: require("./InteractiveObject").default,
InterpolationMethod: require("./InterpolationMethod").default,
JointStyle: require("./JointStyle").default,
JPEGEncoderOptions: require("./JPEGEncoderOptions").default,
LineScaleMode: require("./LineScaleMode").default,
Loader: require("./Loader").default,
LoaderInfo: require("./LoaderInfo").default,
MovieClip: require("./MovieClip").default,
PixelSnapping: require("./PixelSnapping").default,
PNGEncoderOptions: require("./PNGEncoderOptions").default,
Preloader: require("./Preloader").default,
Shader: require("./Shader").default,
ShaderData: require("./ShaderData").default,
ShaderInput: require("./ShaderInput").default,
ShaderJob: require("./ShaderJob").default,
ShaderParameter: require("./ShaderParameter").default,
ShaderParameterType: require("./ShaderParameterType").default,
ShaderPrecision: require("./ShaderPrecision").default,
Shape: require("./Shape").default,
SimpleButton: require("./SimpleButton").default,
SpreadMethod: require("./SpreadMethod").default,
Sprite: require("./Sprite").default,
Stage: require("./Stage").default,
Stage3D: require("./Stage3D").default,
StageAlign: require("./StageAlign").default,
StageDisplayState: require("./StageDisplayState").default,
StageQuality: require("./StageQuality").default,
StageScaleMode: require("./StageScaleMode").default,
Tile: require("./Tile").default,
TileArray: require("./TileArray").default,
Tilemap: require("./Tilemap").default,
Tileset: require("./Tileset").default,
TriangleCulling: require("./TriangleCulling").default,
// Window: require("./Window").default
}
|
JavaScript
| 0 |
@@ -418,19 +418,16 @@
fault,%0A%09
-//
DOMSprit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.