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
bf6ee533be01193700b7435ccfc7235b783a1433
Update controller
assets/js/controller.js
assets/js/controller.js
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ var app = angular.module('application', ['ngRoute']) app.controller('HomeCtrl', ['$scope', 'RegisterServices', function ($scope, RegisterServices) { $scope.userName = null; var data = { userName : 'pudthai' }; var callServiceProfile = RegisterServices.getPofile(data); callServiceProfile.success(function(data) { if(data.status === 'success'){ data = data.data; $scope.userName = data.cusFullname; } }).error(function() { console.log('API Timeout'); }); }]);
JavaScript
0.000001
@@ -233,19 +233,16 @@ oute'%5D)%0A -app .control @@ -250,12 +250,12 @@ er(' -Home +Menu Ctrl @@ -678,9 +678,156 @@ %7D);%0A%7D%5D) -; +%0A.controller('SliderCtrl', %5B'$scope', 'RegisterServices', function ($scope) %7B%0A $scope.data = %7B%0A title : '%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%80%E0%B8%AD%E0%B8%87%E0%B8%A1%E0%B8%B2%E0%B9%80%E0%B8%9B%E0%B9%87%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%9B%E0%B8%A3%E0%B8%B6%E0%B8%81%E0%B8%A9%E0%B8%B2'%0A %7D;%0A%7D%5D)
008b63e1f20c267721d0979c7c946aa62a24aa52
Update grayscale.min.js
js/grayscale.min.js
js/grayscale.min.js
/*! * Start Bootstrap - Grayscale v3.3.7+1 (http://startbootstrap.com/template-overviews/grayscale) * Copyright 2013-2016 Start Bootstrap * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE) */ function collapseNavbar() { if ($(".navbar").offset().top > 50) { $(".navbar-fixed-top").addClass("top-nav-collapse"); } else { $(".navbar-fixed-top").removeClass("top-nav-collapse"); } } $(window).scroll(collapseNavbar); $(document).ready(collapseNavbar); $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); $('.navbar-collapse ul li a').click(function() { $(".navbar-collapse").collapse('hide'); }); var map = null; google.maps.event.addDomListener(window, 'load', init); google.maps.event.addDomListener(window, 'resize', function() { map.setCenter(new google.maps.LatLng(40.5853, -105.0844)); }); function init() { var mapOptions = { zoom: 15, center: new google.maps.LatLng(40.5853, -105.0844), disableDefaultUI: true, scrollwheel: false, draggable: false, styles: [{ "featureType": "water", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 29 }, { "weight": 0.2 }] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 18 }] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 16 }] }, { "featureType": "poi", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 21 }] }, { "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#000000" }, { "lightness": 16 }] }, { "elementType": "labels.text.fill", "stylers": [{ "saturation": 36 }, { "color": "#000000" }, { "lightness": 40 }] }, { "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 19 }] }, { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "administrative", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 17 }, { "weight": 1.2 }] }] }; var mapElement = document.getElementById('map'); map = new google.maps.Map(mapElement, mapOptions); var image = 'img/map-marker.png'; var myLatLng = new google.maps.LatLng(35.2271, 80.8431); var beachMarker = new google.maps.Marker({ position: myLatLng, map: map, icon: image }); }
JavaScript
0.000001
@@ -1030,34 +1030,32 @@ .LatLng( -40.5853, -105.0844 +35.2271, 80.8431 ));%0A%7D);%0A @@ -1147,28 +1147,31 @@ Lng( -40.5853, -105.0844), +35.2271, 80.8431),%0A %0A
8521efb64c59fdaca7e0ebde61244a8854363e3d
Create profile on user registration
src/actions/profile.js
src/actions/profile.js
import {PROFILE_API} from '../config'; import {push} from 'react-router-redux'; import {checkStatus, parseJSON, camelizeProps} from '../util/http'; import * as types from '../constants'; require('isomorphic-fetch'); export function getProfileDataRequest() { return { type: types.PROFILE_DATA_REQUEST }; } export function getProfileDataSuccess(payload) { return { type: types.PROFILE_DATA_SUCCESS, payload: payload }; } export function getProfileDataFailure(error) { return { type: types.PROFILE_DATA_FAILURE, payload: { status: error.response.status, statusText: error.response.statusText } }; } export function getProfile(userid, token) { return dispatch => { dispatch(getProfileDataRequest()); return fetch(PROFILE_API + '/profiles/' + userid + '/', { method: 'get', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'auth-token': token } }).then(checkStatus) .then(parseJSON) .then(camelizeProps) .then(json => { if (json.firstName) { dispatch(getProfileDataSuccess(json)); } else { dispatch(getProfileDataFailure(new Error('Something went wrong.'))); } }) .catch(error => { dispatch(getProfileDataFailure(error)); }); }; } export function createProfileRequest() { return { type: types.CREATE_PROFILE_REQUEST }; } export function createProfileSuccess() { return { type: types.CREATE_PROFILE_SUCCESS }; } export function createProfile(userid, firstName, lastName) { return dispatch => { dispatch(createProfileRequest()); return fetch(PROFILE_API + '/profiles/', { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({userid, firstName, lastName}) }).then(checkStatus) .then(parseJSON) .then(camelizeProps) .then(json => { // TODO: Do some validation console.log(json); dispatch(createProfileSuccess()); dispatch(push('/confirm-email')); }); }; }
JavaScript
0
@@ -1537,32 +1537,239 @@ SUCCESS%0A %7D;%0A%7D%0A%0A +export function createProfileFailure(error) %7B%0A return %7B%0A type: types.CREATE_PROFILE_FAILURE,%0A payload: %7B%0A status: error.response.status,%0A statusText: error.response.statusText%0A %7D%0A %7D;%0A%7D%0A%0A export function @@ -2078,34 +2078,91 @@ ingify(%7B -userid, firstName, +%0A auth_id: userid,%0A first_name: firstName,%0A last_name: lastNam @@ -2162,16 +2162,23 @@ lastName +%0A %7D)%0A %7D @@ -2281,63 +2281,68 @@ -// TODO: Do some validation%0A console.log(json);%0A +console.log(json);%0A if (json.auth_id === userid) %7B%0A @@ -2379,32 +2379,34 @@ ess());%0A + dispatch(push('/ @@ -2419,24 +2419,219 @@ m-email'));%0A + %7D else %7B%0A dispatch(createProfileFailure(new Error('Wrong response from jrc-profile')));%0A %7D%0A %7D)%0A .catch(error =%3E %7B%0A dispatch(createProfileFailure(error));%0A %7D);%0A
94fcbb86b500dd501127e69c86d425bdade08175
Fix rule name
lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-maximum-line-length/test/test.js
lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-maximum-line-length/test/test.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var RuleTester = require( 'eslint' ).RuleTester; var rule = require( './../lib' ); // FIXTURES // var valid = require( './fixtures/valid.js' ); var invalid = require( './fixtures/invalid.js' ); var unvalidated = require( './fixtures/unvalidated.js' ); // TESTS // tape( 'main export is an object', function test( t ) { t.ok( true, __filename ); t.equal( typeof rule, 'object', 'main export is an object' ); t.end(); }); tape( 'the function positively validates code with JSDoc descriptions that do not contain Markdown lint errors', function test( t ) { var tester = new RuleTester(); try { tester.run( 'jsdoc-list-maximum-line-length', rule, { 'valid': valid, 'invalid': [] }); t.pass( 'passed without errors' ); } catch ( err ) { t.fail( 'encountered an error: ' + err.message ); } t.end(); }); tape( 'the function negatively validates code with JSDoc descriptions that contain Markdown lint errors', function test( t ) { var tester = new RuleTester(); try { tester.run( 'jsdoc-list-maximum-line-length', rule, { 'valid': [], 'invalid': invalid }); t.pass( 'passed without errors' ); } catch ( err ) { t.fail( 'encountered an error: ' + err.message ); } t.end(); }); tape( 'the function does not validate non-JSDoc comments', function test( t ) { var tester = new RuleTester(); try { tester.run( 'jsdoc-list-maximum-line-length', rule, { 'valid': unvalidated, 'invalid': [] }); t.pass( 'passed without errors' ); } catch ( err ) { t.fail( 'encountered an error: ' + err.message ); } t.end(); });
JavaScript
0.001229
@@ -1288,37 +1288,32 @@ ter.run( 'jsdoc- -list- maximum-line-len @@ -1674,37 +1674,32 @@ ter.run( 'jsdoc- -list- maximum-line-len @@ -2027,13 +2027,8 @@ doc- -list- maxi
aa67dc21b301583a4d4e53990c6bb288a7871da7
Use new gmodstore endpoint
src/lib/scriptfodder.js
src/lib/scriptfodder.js
const request = require('request-promise').defaults({ headers: { 'user-agent': 'scriptfodder-publish' }, baseUrl: 'https://scriptfodder.com', json: true }) class ScriptFodder { constructor (apiKey) { this.apiKey = apiKey } uploadVersion ({ scriptId, changes, versionName, file }) { const opts = { method: 'POST', url: `/api/scripts/version/add/${scriptId}?api_key=${this.apiKey}`, formData: { file: { value: file, options: { filename: versionName + '.zip', contentType: 'application/zip' } }, name: versionName, changes } } return request(opts).then(response => { if (response.status === 'error') { throw new Error('API Response: ' + response.description) } return response }) } } module.exports = ScriptFodder
JavaScript
0
@@ -126,28 +126,25 @@ https:// -scriptfodder +gmodstore .com',%0A
7906ac66bbbda870f0e36a780db92ecc8c8f6287
add sf-array deletion failing tests
src/directives/sf-array.directive.spec.js
src/directives/sf-array.directive.spec.js
chai.should(); var runSync = function (scope, tmpl) { var directiveScope = tmpl.isolateScope(); var stub = sinon.stub(directiveScope, 'resolveReferences', function(schema, form) { directiveScope.render(schema, form); }); scope.$apply(); } describe('sf-array.directive.js', function() { var exampleSchema; beforeEach(module('schemaForm')); beforeEach( module(function($sceProvider) { $sceProvider.enabled(false); exampleSchema = { "type": "object", "properties": { "names": { "type": "array", "description": "foobar", "items": { "title": "Name", "type": "string", "default": 6 } } } }; }) ); it('should not throw needless errors on validate [ノಠ益ಠ]ノ彡┻━┻', function(done) { tmpl = angular.element('<form name="testform" sf-schema="schema" sf-form="form" sf-model="model" json="{{model | json}}"></form>'); inject(function($compile, $rootScope) { var scope = $rootScope.$new(); scope.model = {}; scope.schema = exampleSchema; scope.form = ["*"]; $compile(tmpl)(scope); runSync(scope, tmpl); tmpl.find('div.help-block').text().should.equal('foobar'); var add = tmpl.find('button').eq(1); add.click(); $rootScope.$apply(); setTimeout(function() { var errors = tmpl.find('.help-block'); errors.text().should.equal('foobar'); done(); }, 0) //tmpl.$valid.should.be.true; }); }); });
JavaScript
0.000002
@@ -616,24 +616,116 @@ %22items%22: %7B%0A + %22type%22: %22object%22,%0A %22properties%22: %7B%0A %22name%22: %7B%0A @@ -743,16 +743,20 @@ %22Name%22,%0A + @@ -793,16 +793,20 @@ + %22default @@ -810,16 +810,50 @@ ult%22: 6%0A + %7D%0A %7D%0A @@ -1708,13 +1708,905 @@ );%0A %7D); +%0A%0A it('should not delete innocent items on delete', function(done) %7B%0A%0A tmpl = angular.element('%3Cform name=%22testform%22 sf-schema=%22schema%22 sf-form=%22form%22 sf-model=%22model%22 json=%22%7B%7Bmodel %7C json%7D%7D%22%3E%3C/form%3E');%0A%0A inject(function($compile, $rootScope) %7B%0A var scope = $rootScope.$new();%0A scope.model = %7Bnames: %5B%7Bname: %220%22%7D, %7Bname: %221%22%7D, %7Bname: %222%22%7D, %7Bname: %223%22%7D%5D%7D;%0A%0A scope.schema = exampleSchema;%0A%0A scope.form = %5B%22*%22%5D;%0A%0A $compile(tmpl)(scope);%0A runSync(scope, tmpl);%0A%0A tmpl.find('div.help-block').text().should.equal('foobar');%0A%0A var close = tmpl.find('button.close');%0A close.eq(1).click();%0A%0A $rootScope.$apply();%0A%0A setTimeout(function() %7B%0A scope.model.names%5B0%5D.name.should.equal(%220%22);%0A scope.model.names%5B1%5D.name.should.equal(%222%22);%0A scope.model.names%5B2%5D.name.should.equal(%223%22);%0A done();%0A %7D, 0)%0A %7D);%0A %7D); %0A%7D);%0A
60f701d02c23554a5ed6d2e3ff6d071fa4a8bb77
no arrow
js/index.js
js/index.js
window.onload = function(){ //initialize // console.log('screen.height', window.innerHeight); var tc = document.getElementsByClassName('teaser-container')[0]; tc.style.opacity = 1.0; tc.style.height = window.innerHeight + 'px'; var invitee = document.getElementById('invitee'); invitee.innerHTML = gup('invitee'); invitee.classList.add('animated', 'tada', 'infinite'); // add animations var ti = document.getElementsByClassName('teaser-image')[0]; ti.classList.add('animated', 'fadeIn'); var list = document.getElementsByClassName('teaser-text'); for (var i=0; i<list.length; i++){ list[i].classList.add('animated', 'fadeInUp'); } $('#image-detail').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: false, fade: true, adaptiveHeight: true, asNavFor: '#image-list' }); $('#image-list').slick({ lazyLoad: 'ondemand', dots: true, infinite: true, speed: 300, slidesToShow: 3, slidesToScroll: 1, asNavFor: '#image-detail', centerMode: true, focusOnSelect: true }); } function gup(name) { name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.href); if(results == null) return ""; else return decodeURIComponent(results[1]); } function showImage(image){ document.getElementById('image-detail').src = image; // console.log('show image', image); // document.getElementById('popup').style.display = 'block'; // document.getElementById('popup').style.pointerEvents = 'auto'; document.getElementById('image-detail').classList.remove('animated', 'fadeIn'); document.getElementById('image-detail').classList.add('animated', 'fadeIn'); // // document.getElementById('popup-content').classList.add('animated', 'flipInX'); // document.getElementById('popup-image').src = image; // document.body.style.overflow = 'hidden'; }
JavaScript
0.99934
@@ -972,16 +972,35 @@ oll: 1,%0A + arrows: false,%0A asNa
4c4ba2df3d7630fd16f0c49c4b7c923109338807
Fix template literal test
test/template-literal.js
test/template-literal.js
import test from 'ava'; // Spoof supports-color require('./_supports-color')(__dirname); const m = require('..'); test('return an empty string for an empty literal', t => { const ctx = m.constructor(); t.is(ctx``, ''); }); test('return a regular string for a literal with no templates', t => { const ctx = m.constructor({level: 0}); t.is(ctx`hello`, 'hello'); }); test('correctly perform template parsing', t => { const ctx = m.constructor({level: 0}); t.is(ctx`{bold Hello, {cyan World!} This is a} test. {green Woo!}`, ctx.bold('Hello,', ctx.cyan('World!'), 'This is a') + ' test. ' + ctx.green('Woo!')); }); test('correctly perform template substitutions', t => { const ctx = m.constructor({level: 0}); const name = 'Sindre'; const exclamation = 'Neat'; t.is(ctx`{bold Hello, {cyan.inverse ${name}!} This is a} test. {green ${exclamation}!}`, ctx.bold('Hello,', ctx.cyan.inverse(name + '!'), 'This is a') + ' test. ' + ctx.green(exclamation + '!')); }); test('correctly parse and evaluate color-convert functions', t => { const ctx = m.constructor({level: 3}); t.is(ctx`{bold.rgb(144,10,178).inverse Hello, {~inverse there!}}`, '\u001B[0m\u001B[1m\u001B[38;2;144;10;178m\u001B[7mHello, ' + '\u001B[27m\u001B[39m\u001B[22m\u001B[0m\u001B[0m\u001B[1m' + '\u001B[38;2;144;10;178mthere!\u001B[39m\u001B[22m\u001B[0m'); t.is(ctx`{bold.bgRgb(144,10,178).inverse Hello, {~inverse there!}}`, '\u001B[0m\u001B[1m\u001B[48;2;144;10;178m\u001B[7mHello, ' + '\u001B[27m\u001B[49m\u001B[22m\u001B[0m\u001B[0m\u001B[1m' + '\u001B[48;2;144;10;178mthere!\u001B[49m\u001B[22m\u001B[0m'); }); test('properly handle escapes', t => { const ctx = m.constructor({level: 3}); t.is(ctx`{bold hello \{in brackets\}}`, '\u001B[0m\u001B[1mhello {in brackets}\u001B[22m\u001B[0m'); }); test('throw if there is an unclosed block', t => { const ctx = m.constructor({level: 3}); try { console.log(ctx`{bold this shouldn't appear ever\}`); t.fail(); } catch (err) { t.is(err.message, 'Template literal has an unclosed block'); } }); test('throw if there is an invalid style', t => { const ctx = m.constructor({level: 3}); try { console.log(ctx`{abadstylethatdoesntexist this shouldn't appear ever}`); t.fail(); } catch (err) { t.is(err.message, 'Invalid Chalk style: abadstylethatdoesntexist'); } }); test('properly style multiline color blocks', t => { const ctx = m.constructor({level: 3}); t.is( ctx`{bold Hello! This is a ${'multiline'} block! :) } {underline I hope you enjoy }`, '\u001B[0m\u001B[1m\u001B[22m\u001B[0m\n' + '\u001B[0m\u001B[1m\t\t\t\tHello! This is a\u001B[22m\u001B[0m\n' + '\u001B[0m\u001B[1m\t\t\t\tmultiline block!\u001B[22m\u001B[0m\n' + '\u001B[0m\u001B[1m\t\t\t\t:)\u001B[22m\u001B[0m\n' + '\u001B[0m\u001B[1m\t\t\t\u001B[22m\u001B[0m\u001B[0m \u001B[0m\u001B[0m\u001B[4m\u001B[24m\u001B[0m\n' + '\u001B[0m\u001B[4m\t\t\t\tI hope you enjoy\u001B[24m\u001B[0m\n' + '\u001B[0m\u001B[4m\t\t\t\u001B[24m\u001B[0m' ); }); test('escape interpolated values', t => { const ctx = m.constructor({level: 0}); t.is(ctx`Hello {bold hi}`, 'Hello hi'); t.is(ctx`Hello ${'{bold hi}'}`, 'Hello {bold hi}'); });
JavaScript
0.000002
@@ -2606,18 +2606,16 @@ %5B1m%5Ct%5Ct%5C -t%5C tHello! @@ -2674,18 +2674,16 @@ %5B1m%5Ct%5Ct%5C -t%5C tmultili @@ -2743,18 +2743,16 @@ 1m%5Ct%5Ct%5Ct -%5Ct :)%5Cu001B @@ -2792,26 +2792,24 @@ 001B%5B1m%5Ct%5Ct%5C -t%5C u001B%5B22m%5Cu0 @@ -2902,18 +2902,16 @@ %5B4m%5Ct%5Ct%5C -t%5C tI hope @@ -2970,18 +2970,16 @@ %5B4m%5Ct%5Ct%5C -t%5C u001B%5B24
62f80d4954ee751d278cb294579dcf074d178188
Use const instead of var
bin/kaba.js
bin/kaba.js
#!/usr/bin/env node /** * * @typedef {{ * cwd: string, * require: Array, * configNameSearch: string[], * configPath: string, * configBase: string, * modulePath: string, * modulePackage: *, * }} LiftoffEnvironment */ var Liftoff = require("liftoff"); var run = require("../src/run"); var minimist = require('minimist'); const argv = minimist(process.argv.slice(2), { boolean: ["dev", "debug", "d", "v"] }); const Kaba = new Liftoff({ name: "kaba", extensions: { ".js": null }, v8flags: ['--harmony'] }); Kaba.launch({ cwd: argv.cwd, configPath: argv.kabafile, require: argv.require, completion: argv.completion }, (env) => run(env, argv));
JavaScript
0.000003
@@ -228,19 +228,21 @@ ent%0A */%0A -var +const Liftoff @@ -264,19 +264,21 @@ toff%22);%0A -var +const run = r @@ -303,11 +303,13 @@ %22);%0A -var +const min
639fb7ad9e304420242d14e168c191c4f0402c46
update file /lib/fuse.js
lib/fuse.js
lib/fuse.js
var express = require('express'); var bodyParser = require('body-parser'); var cors = require('cors'); var request = require('request'); var events = require('events'); var fh = require('fh-mbaas-api'); var _ = require('underscore'); var fuseRoute = function() { var fuse = new express.Router(); fuse.use(cors()); fuse.use(bodyParser()); fuse.post('/', function(req, res) { console.log(new Date(), 'In fuse route POST / req.body=', req.body); return submitToFuse(req.body, function(error, response, body){ return res.send(body); }); }); return fuse; }; var submitToFuse = function(submission, cb){ var data = transform(submission); var url = process.env.FUSE_URL || 'http://85.190.180.161:8182/cxf/redhat/forum/register'; var options = { "url" : url, "body": submission, "json": true}; request.post(options, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("Well done!") // Show the HTML } cb(error, response, body); }); }; var transform = function(submission) { var data = _.map(submission.submission.formFields, function(item){ //console.log(JSON.stringify(item)); var val = { "fieldCode" : item.fieldId.fieldCode, "fieldValue" : item.fieldValues[0] }; return val; }); console.log(JSON.stringify(data)); return data; } var submissionEventListener = new events.EventEmitter(); submissionEventListener.on('submissionComplete', function(submission){ console.log('New submission received: '); console.log(submission); return submitToFuse(submission, function(error, response, body){ console.log('Received response from Fuse in event handler: ' + response.statusCode); console.log(body); }); }); fh.forms.registerListener(submissionEventListener, function(err){}); module.exports = fuseRoute;
JavaScript
0.000002
@@ -1022,24 +1022,198 @@ ;%0A %7D);%0A%7D;%0A%0A +var mapping = %7B%0A %22FFIRSTNAME%22 : %22name%22,%0A %22FLASTNAME%22 : %22lastName%22,%0A %22FEMAIL%22 : %22email%22,%0A %22FPICTURE%22 : %22picture%22,%0A %22FCOMPANY%22 : %22companyName%22%0A %22FTITLE%22 : %22jobTitle%22%0A%7D;%0A%0A var transfor @@ -1249,20 +1249,26 @@ var -data = _.map +map = %7B%7D;%0A _.each (sub @@ -1363,35 +1363,12 @@ -var val = %7B %22fieldCode%22 : +map%5B item @@ -1389,24 +1389,11 @@ Code -, %22fieldValue%22 : +%5D = ite @@ -1412,26 +1412,8 @@ s%5B0%5D - %7D;%0A return val ;%0A @@ -1642,24 +1642,26 @@ ived: ');%0A +// console.log(
ef2cafcde042e9ca0cc5c3b96152850c29a5fc8c
use kWidget.addReadyCallback instead of timing sensitive jsReadyCallback
modules/KalturaSupport/tests/resources/qunit-kaltura-bootstrap.js
modules/KalturaSupport/tests/resources/qunit-kaltura-bootstrap.js
//must come after qunit-bootstrap.js and after mwEmbedLoader.php if( window.QUnit ){ // Force html5 if not running flash qUnit tests: if( document.URL.indexOf('runFlashQunitTests') === -1 ){ mw.setConfig( 'forceMobileHTML5', true ); } window.QUnit.start(); jsCallbackCalledId = null; asyncTest( "KalturaSupport::PlayerLoaded", function(){ // Player time out in 60 seconds: setTimeout( function(){ ok( false, "Player timed out" ); start(); }, 60000 ); window['kalturaPlayerLoadedCallbackCalled'] = function( playerId ){ ok( true, "Player loaded: " + playerId ); if( typeof jsKalturaPlayerTest == 'function' ){ jsKalturaPlayerTest( playerId ); } // add timeout for async test to register setTimeout( function(){ start(); }, 100); } // check if jscallback ready fired before async test: if( jsCallbackCalledId != null ){ kalturaPlayerLoadedCallbackCalled( jsCallbackCalledId ); } }); if( window['jsCallbackReady'] ){ window['orgJsCallbackReady'] = window['jsCallbackReady']; } window['jsCallbackReady'] = function( videoId ) { // check if the test can access the iframe var domainRegEx = new RegExp(/^((http[s]?):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?$/); var match = document.URL.match( domainRegEx ); var pageDomain = match[3]; var scriptMatch = SCRIPT_LOADER_URL.match( domainRegEx ); if( match && SCRIPT_LOADER_URL[2] == 'http' || SCRIPT_LOADER_URL[2] == 'https' && scriptMatch[3] != pageDomain ) { ok( false, "Error: trying to test across domains, no iframe inspection is possible" + match + ' != ' + pageDomain); stop(); } // Add entry ready listener document.getElementById( videoId ).addJsListener("mediaReady", "kalturaQunitMediaReady"); jsCallbackCalledId = videoId; if( typeof kalturaPlayerLoadedCallbackCalled == 'function' ){ kalturaPlayerLoadedCallbackCalled( videoId ); } if( window['orgJsCallbackReady'] ){ window['orgJsCallbackReady']( videoId ); } }; var mediaReadyCallbacks = []; var mediaReadyAlreadyCalled = false; // Utility function for entry ready testing handler window['kalturaQunitMediaReady'] = function(){ // Run in async call to ensure non-blocking build out is in dom setTimeout(function(){ while( mediaReadyCallbacks.length ){ mediaReadyCallbacks.shift()(); } mediaReadyAlreadyCalled = true; }, 0 ); }; window['kalturaQunitWaitForPlayer'] = function( callback ){ if( mediaReadyAlreadyCalled ){ callback(); return ; } mediaReadyCallbacks.push( callback ); }; }
JavaScript
0
@@ -972,135 +972,36 @@ ;%0D%0A%09 -if( window%5B'jsCallbackReady'%5D )%7B%0D%0A%09%09window%5B'orgJsCallbackReady'%5D = window%5B'jsCallbackReady'%5D;%0D%0A%09%7D%0D%0A%09window%5B'jsCallbackReady'%5D = +%0D%0A%09kWidget.addReadyCallback( fun @@ -1016,17 +1016,16 @@ ideoId ) - %7B%0D%0A%09%09// @@ -1887,98 +1887,10 @@ %7D%0D%0A%09 -%09if( window%5B'orgJsCallbackReady'%5D )%7B%0D%0A%09%09%09window%5B'orgJsCallbackReady'%5D( videoId );%0D%0A%09%09%7D%0D%0A%09 %7D +) ;%0D%0A%0D
cf1a26dcd0d89286bc398438b071ec1be838d2d7
Fix manifest error under IE 8
assets/notifications.js
assets/notifications.js
/** * Notifications * * @class * @param {Object} options Optional configuration options * @return {Notifications} Notifications main instance */ var Notifications = (function(options) { /** * The declared UI libraries * * Each property of this variable must be an object with the `show` callback * field defined, and an optional `types` translation map that will be used * to translate natives types into the used library notification type. * * @type Object */ this.themes = { /** * jQuery Growl * @see https://github.com/ksylvest/jquery-growl */ growl: { types: { success: 'notice' }, show: function (object) { $.growl($.extend({ title: object.title, message: object.description, url: object.url, style: getType(object.type), }, self.opts.options)); } }, /** * NotifIt! * @see http://naoxink.hol.es/notifIt/ */ notifit: { types: { default: 'info' }, show: function (object) { notif($.extend({ timeout: self.opts.delay, clickable: true, multiline: true, msg: "<b>" + object.title + "</b><br /><br />" + object.description, type: getType(object.type) }, self.opts.options)); $("#ui_notifIt").click(function(e) { document.location = object.url; }); } }, /** * Notify.js * @see https://notifyjs.com/ */ notify: { types: { warning: 'warn', default: 'info' }, show: function (object) { $.notify(object.title, getType(object.type), $.extend({ autoHideDelay: self.opts.delay, }, self.opts.options)); } }, /** * Noty * @see http://ned.im/noty/ */ noty: { types: { default: 'information' }, show: function (object) { noty($.extend({ text: object.title, type: getType(object.type), dismissQueue: false, timeout: self.opts.delay, layout: 'topRight', theme: 'defaultTheme', callback: { onCloseClick: function () { document.location = object.url; } } }, self.opts.options)); } }, /** * PNotify * @see http://sciactive.com/pnotify/ */ pnotify: { types: { warning: 'notice', default: 'info' }, show: function (object) { new PNotify($.extend({ title: object.title, text: '<a href="' + object.url + '" style="text-decoration: none;">' + object.description + '</a>', type: getType(object.type), delay: self.opts.delay }, self.opts.options)); } }, /** * Toastr * @see https://codeseven.github.io/toastr/ */ toastr: { types: { default: 'info' }, show: function (object) { toastr[getType(object.type)](object.description, object.title, $.extend({ timeOut: self.opts.delay, onclick: function() { document.location = object.url; } }, self.opts.options)); } } }; var self = this; /** * Options * @type {Object} */ this.opts = $.extend({ pollInterval: 5000, pollSeen: false, xhrTimeout: 2000, delay: 5000, theme: 'growl', counters: [] }, options); /** * Already displayed notifications cache * @type {Array} */ this.displayed = []; /** * Translates a native type to a theme type * * @param type * @returns The translated theme type */ function getType(type) { var types = this.themes[this.opts.theme].types; var translation; if (typeof types !== "undefined" || (translation = types[type] && typeof translation === "undefined")) { return type; } return translation; } /** * Polls the server */ this.poll = function() { $.ajax({ url: this.opts.url, type: "GET", data: { seen: this.opts.pollSeen ? 1 : 0 }, success: function(data) { var engine = self.themes[self.opts.theme]; $.each(data, function (index, object) { if (self.displayed.indexOf(object.id) !== -1) { return; } if (typeof engine !== "undefined") { engine.show(object); self.displayed.push(object.id); } else { console.warn("Unknown engine: " + self.opts.theme); } }); // Update all counters for (var i = 0; i < self.opts.counters.length; i++) { if ($(self.opts.counters[i]).text() != data.length) { $(self.opts.counters[i]).text(data.length); } } }, dataType: "json", complete: setTimeout(function() { self.poll(opts) }, opts.pollInterval), timeout: opts.xhrTimeout }); }; // Fire the initial poll this.poll(); });
JavaScript
0.000001
@@ -1172,39 +1172,41 @@ +' default +' : 'info'%0A @@ -1894,39 +1894,41 @@ +' default +' : 'info'%0A @@ -2288,31 +2288,33 @@ +' default +' : 'informati @@ -3090,39 +3090,41 @@ +' default +' : 'info'%0A @@ -3675,23 +3675,25 @@ +' default +' : 'info' @@ -5736,16 +5736,62 @@ ounters%0A + if (self.opts.counters) %7B%0A @@ -5848,24 +5848,28 @@ gth; i++) %7B%0A + @@ -5954,16 +5954,20 @@ + $(self.o @@ -6002,16 +6002,42 @@ ength);%0A + %7D%0A
c7d3c71187b6ac9e78f82252f245676133a8f9af
Convert to ES6 class
src/lights/SpotLight.js
src/lights/SpotLight.js
import { Light } from './Light.js'; import { SpotLightShadow } from './SpotLightShadow.js'; import { Object3D } from '../core/Object3D.js'; function SpotLight( color, intensity, distance, angle, penumbra, decay ) { Light.call( this, color, intensity ); this.type = 'SpotLight'; this.position.copy( Object3D.DefaultUp ); this.updateMatrix(); this.target = new Object3D(); Object.defineProperty( this, 'power', { get: function () { // intensity = power per solid angle. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf return this.intensity * Math.PI; }, set: function ( power ) { // intensity = power per solid angle. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf this.intensity = power / Math.PI; } } ); this.distance = ( distance !== undefined ) ? distance : 0; this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. this.shadow = new SpotLightShadow(); } SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { constructor: SpotLight, isSpotLight: true, copy: function ( source ) { Light.prototype.copy.call( this, source ); this.distance = source.distance; this.angle = source.angle; this.penumbra = source.penumbra; this.decay = source.decay; this.target = source.target.clone(); this.shadow = source.shadow.clone(); return this; } } ); export { SpotLight };
JavaScript
0.99998
@@ -134,24 +134,21 @@ D.js';%0A%0A -function +class SpotLig @@ -149,16 +149,46 @@ potLight + extends Light %7B%0A%0A%09constructor ( color, @@ -211,15 +211,33 @@ ance + = 0 , angle + = Math.PI / 3 , pe @@ -246,16 +246,20 @@ mbra + = 0 , decay ) %7B%0A @@ -258,31 +258,25 @@ cay += 1 ) %7B%0A%0A%09 -Light.call( this, +%09super( col @@ -289,24 +289,91 @@ tensity );%0A%0A +%09%09Object.defineProperty( this, 'isSpotLight', %7B value: true %7D );%0A%0A%09 %09this.type = @@ -387,16 +387,17 @@ ight';%0A%0A +%09 %09this.po @@ -431,16 +431,17 @@ ltUp );%0A +%09 %09this.up @@ -451,24 +451,25 @@ eMatrix();%0A%0A +%09 %09this.target @@ -493,71 +493,215 @@ ;%0A%0A%09 -Object.defineProperty( this, 'power', %7B%0A%09%09get: function +%09this.distance = distance;%0A%09%09this.angle = angle;%0A%09%09this.penumbra = penumbra;%0A%09%09this.decay = decay; // for physically correct lights, should be 2.%0A%0A%09%09this.shadow = new SpotLightShadow();%0A%0A%09%7D%0A%0A%09get power () %7B%0A%0A -%09 %09%09// @@ -728,33 +728,32 @@ er solid angle.%0A -%09 %09%09// ref: equati @@ -859,17 +859,16 @@ 2.pdf%0A%09%09 -%09 return t @@ -898,28 +898,21 @@ ;%0A%0A%09 -%09%7D,%0A%09 +%7D%0A%0A %09set -: function + power ( po @@ -920,17 +920,16 @@ er ) %7B%0A%0A -%09 %09%09// int @@ -960,17 +960,16 @@ angle.%0A -%09 %09%09// ref @@ -1083,17 +1083,16 @@ 2.pdf%0A%09%09 -%09 this.int @@ -1122,526 +1122,44 @@ I;%0A%0A -%09 %09%7D%0A -%09%7D );%0A%0A%09this.distance = ( distance !== undefined ) ? distance : 0;%0A%09this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;%0A%09this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;%0A%09this.decay = ( decay !== undefined ) ? decay : 1;%09// for physically correct lights, should be 2.%0A%0A%09this.shadow = new SpotLightShadow();%0A%0A%7D%0A%0ASpotLight.prototype = Object.assign( Object.create( Light.prototyp +%0A%09copy( sourc e ) -, %7B%0A%0A%09 -constructor: SpotLight,%0A%0A%09isSpotLight: true,%0A%0A%09copy: function ( source ) %7B%0A%0A%09%09Light.prototype.copy.call( this, +%09super.copy( sou @@ -1396,20 +1396,16 @@ ;%0A%0A%09%7D%0A%0A%7D - );%0A %0A%0Aexport
4e5cc0e2d1f0fb8aa4425bd3dacade76bbb9255f
Bump version
package.js
package.js
Package.describe({ git: 'https://github.com/zimme/meteor-collection-softremovable.git', name: 'zimme:collection-softremovable', summary: 'Add soft remove to collections', version: '1.0.6-beta.1' }); Package.onUse(function(api) { api.versionsFrom('1.0'); api.use([ 'check', 'coffeescript', 'underscore' ]); api.use([ 'matb33:[email protected]', 'zimme:[email protected]' ]); api.use([ 'aldeed:[email protected] || 5.0.0', 'aldeed:[email protected]', 'aldeed:[email protected]' ], ['client', 'server'], {weak: true}); api.imply('zimme:collection-behaviours'); api.addFiles('softremovable.coffee'); });
JavaScript
0
@@ -193,17 +193,17 @@ .6-beta. -1 +2 '%0A%7D);%0A%0AP
1e5e3ea83ffa781a4ade70573bd0d899b7ff057e
Check that javascript methods have params to avoid an unwanted comma
lib/handlebars/javascript.js
lib/handlebars/javascript.js
var format = require('string-template'); var handlebars = require('handlebars'); var hljs = require('highlight.js'); var kebab = require('kebab-case'); /** * Formats a JavaScript plugin constructor name to look like this: * ```js * var elem = new Foundation.Plugin(element, options); * ``` * * @param {string} name - Name of the plugin. * @returns {string} A formatted code sample. */ handlebars.registerHelper('writeJsConstructor', function(name) { var str = 'var elem = new Foundation.'+name+'(element, options);'; return hljs.highlight('js', str).value; }) /** * Formats a JavaScript plugin method to look like this: * ```js * $('#element').foundation('method', param1, param2); * ``` * * @param {object} method - Method data, taken from a JSDoc object. * @returns {string} A formatted code sample. */ handlebars.registerHelper('writeJsFunction', function(method) { var str = '$(\'#element\').foundation(\'' + method.name; if (method.params) { str += '\', '; str += (method.params || []).map(function(val) { return val.name; }).join(', '); str += ');'; } else { str += '\');' } return hljs.highlight('js', str).value; }); /** * Convert JSDoc's module definition to a filename. * @param {string} value - Module name to convert. * @returns {string} A JavaScript filename. */ handlebars.registerHelper('formatJsModule', function(value) { return value.replace('module:', '') + '.js'; }); /** * Format a JavaScript plugin option by converting it to an HTML data attribute. * @param {string} name - Plugin option name. * @returns {string} Plugin option as an HTML data attribute. */ handlebars.registerHelper('formatJsOptionName', function(name) { return 'data-' + kebab(name); }); /** * Format a JavaScript plugin option's default value: * - For string values, remove the quotes on either side. * - For all other values, return as-is. * @param {string} value - Value to process. * @returns {string} Processed value. */ handlebars.registerHelper('formatJsOptionValue', function(name) { if (typeof name === 'undefined') return ''; name = name[0]; if (name.match(/^('|").+('|")$/)) return name.slice(1, -1); else return name; }); /** * Format the name of a JavaScript event. This converts JSDoc's slightly convoluted syntax to match our namespaced event names: `event.zf.pluginname`. * @todo Make this unnecessary by using the actual event names in JSDoc annotations. * @param {string} name - Event name. * @param {string} title - Plugin name, used for the event namespace. * @returns {string} Formatted event name. */ handlebars.registerHelper('formatJsEventName', function(name, title) { title = title.charAt(0).toLowerCase() + title.slice(1); return format('{0}.zf.{1}', [name, title.replace(/(-| )/, '')]); });
JavaScript
0.000001
@@ -977,16 +977,23 @@ d.params +.length ) %7B%0A
ff8900534ca4f8c73727d3152c3d1e794391d393
Allow Search to be general purpose
modules/profiles/server/controllers/profiles.server.controller.js
modules/profiles/server/controllers/profiles.server.controller.js
'use strict'; /** * Module dependencies. */ var path = require('path'), mongoose = require('mongoose'), Profile = mongoose.model('Profile'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')), _ = require('lodash'); /** * Create a Profile */ exports.create = function(req, res) { var profile = new Profile(req.body); // profile.user = req.user; profile.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(profile); } }); }; /** * Show the current Profile */ exports.read = function(req, res) { // convert mongoose document to JSON var profile = req.profile ? req.profile.toJSON() : {}; // Add a custom field to the Article, for determining if the current User is the "owner". // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model. profile.isCurrentUserOwner = req.user && profile.user && profile.user._id.toString() === req.user._id.toString() ? true : false; res.jsonp(profile); }; /** * Update a Profile */ exports.update = function(req, res) { var profile = req.profile ; // console.log("req body" + _.map(req.body)); profile = _.extend(profile , req.body); profile.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(profile); } }); }; /** * Delete an Profile */ exports.delete = function(req, res) { var profile = req.profile ; profile.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(profile); } }); }; /** * List of Profiles with query parameters */ exports.list = function(req, res) { // console.log('in profiles.server.controller'); var query = '{}'; if (req.query.role) { query = { role: req.query.role }; } else if (req.query.mfname && req.query.mlname) { //console.log('req.query.mfname : '+req.query.mfname+', req.query.mlname :'+req.query.mlname); query = { mfname: req.query.mfname , mlname:req.query.mlname }; } else if (req.query.fname && req.query.lname) { if (req.query.mname) { console.log('req.query.fname : '+req.query.fname+', req.query.lname :'+req.query.lname+', req.query.mname :'+req.query.mname); query = { fname: req.query.fname , lname:req.query.lname, mname: req.query.mname }; } else { query = { fname: req.query.fname , lname:req.query.lname }; } } Profile.find(query).exec(function (err, profiles) { if(!err){ res.json(profiles); } else { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } }); }; /** * Profile middleware */ exports.profileByID = function(req, res, next, id) { if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).send({ message: 'Profile is invalid' }); } Profile.findById(id).populate('user', 'displayName').exec(function (err, profile) { if (err) { return next(err); } else if (!profile) { return res.status(404).send({ message: 'No Profile with that identifier has been found' }); } req.profile = profile; next(); }); };
JavaScript
0.000001
@@ -1952,668 +1952,205 @@ var -query = '%7B%7D';%0A if (req.query.role) %7B%0A query = %7B role: req.query.role %7D;%0A %7D else if (req.query.mfname && req.query.mlname) %7B%0A //console.log('req.query.mfname : '+req.query.mfname+', req.query.mlname :'+req.query.mlname);%0A query = %7B mfname: req.query.mfname , mlname:req.query.mlname %7D;%0A %7D else if (req.query.fname && req.query.lname) %7B%0A%09 if (req.query.mname) %7B%0A%09%09console.log('req.query.fname : '+req.query.fname+', req.query.lname :'+req.query.lname+', req.query.mname :'+req.query.mname);%0A%09%09query = %7B fname: req.query.fname , lname:req.query.lname, mname: req.query.mname %7D;%0A%09 %7D else %7B%0A%09%09query = %7B fname: req.query.fname , lname:req.query.lname %7D +keys = _.keys(Profile().schema.paths);%0A var query = %7B%7D;%0A _.forEach(keys, function(value)%7B%0A%09 var path = %22query.%22 + value;%0A%09 var val = _.get(req, path);%0A%09 if (val) %7B%0A%09%09 _.set(query, value, val) ;%0A%09 @@ -2155,16 +2155,18 @@ %09 %7D%0A %7D +); %0A Profi
01a0b8ae8e77e4ab3cfc684cd2c851d9fb294752
Fix bug
client/src/modules/plan/planner/make-idea/make-idea.js
client/src/modules/plan/planner/make-idea/make-idea.js
import angular from 'angular'; // import services for this modules import EventService from '../../../../services/event/event.service'; import ImageSearchService from '../../../../services/images/image.search.service'; // imports for this component import template from './make-idea.html'; import './make-idea.css'; class MakeIdeaController { constructor($state, EventService, $stateParams, ImageSearchService) { this.$inject = ['$state', 'EventService', '$stateParams', 'ImageSearchService']; this.$state = $state; this.EventService = EventService; this.$stateParams = $stateParams; this.ImageSearchService = ImageSearchService; this.title = ''; this.desc = ''; this.imageUrl = ''; this.formWarning = ''; this.images = []; } submit() { if (this.validateForm()) { let newIdea = { title: this.title, description: this.desc, imageUrl: this.imageUrl, planId: this.$stateParams.planId }; this.EventService.submitNewEvent(newIdea).then(resp => { this.$state.go('app.plan.planner.ideas'); }).catch(err => { console.log('Server error: ', err); this.formWarning = 'Error: please try again or contact a server admin'; }); } } validateForm() { if (!this.title) { this.formWarning = 'Please enter a title'; return false; } return true; } imageSearch(query) { this.ImageSearchService.imageSearch(query).then(resp => { this.images = resp; }); } imageClick(e) { this.imageUrl = e.target.currentSrc; $('.make-plan-images img').removeClass('highlight'); $(e.target).addClass('highlight'); } } const MakeIdeaComponent = { restrict: 'E', bindings: {}, template: template, controller: MakeIdeaController }; const MakeIdeaModule = angular.module('app.plan.planner.makeIdea', []) .component('makeIdea', MakeIdeaComponent) .service('EventService', EventService) .service('ImageSearchService', ImageSearchService); export default MakeIdeaModule.name;
JavaScript
0.000001
@@ -1592,20 +1592,20 @@ ('.make- -plan +idea -images
c8f79f329a8f20cb13e393909a9634234fdd3d83
Add missing comma in var declaration.
lib/middleware/auto-reloader.js
lib/middleware/auto-reloader.js
/*! * Module dependencies. */ var path = require('path'), Gaze = require('gaze').Gaze; /** * Middlware to handle auto reload. * * Serves updated content from the www/ */ module.exports = function() { var watches = [path.join(process.cwd(), 'www/*')], watch = new Gaze(watches) outdated = false; watch.on('ready', function(watcher) { }); // the outdated state is set to true when a change in the local file system is made watch.on('all', function(event, filepath) { outdated = true; }); // the app constantly polls the server checking for the outdated state // if the app detects the outdated state to be true, it will force a reload on the page return function(req, res, next) { if (req.url.indexOf('autoreload') >= 0) { res.writeHead(200, { 'Content-Type' : 'text/json' }); res.end(JSON.stringify({ outdated : outdated })); outdated = false; } else { next(); } }; };
JavaScript
0
@@ -294,16 +294,17 @@ watches) +, %0A
8dbda7ef7ad9b5c76ca1fb5987e3cb81167a41bf
Add empty emoji validation
Themes/default/scripts/breezeComponents/moodForm.js
Themes/default/scripts/breezeComponents/moodForm.js
Vue.component('mood-form', { template: ` <div> <message-box v-if="invalidEmoji" v-bind:type="'error'" @close="resetEmojiField()"> Invalid emoji. </message-box> <dl class="settings"> <dt> <span> <label>Mood:</label> </span> </dt> <dd> <input type="text" v-model="mood.emoji" @change="invalidEmoji = validator()"> </dd> <dt> <span> <label>Description:</label> </span> </dt> <dd> <textarea v-model="mood.description"></textarea> </dd> <dt> <span> <label>Enable:</label> </span> </dt> <dd> <input type="checkbox" id="checkbox" v-model="mood.isActive"> </dd> </dl> <input type="submit" value="Save" class="button" @click="onSave()" :disabled='invalidEmoji'> <input type="submit" value="Delete" class="button" @click="$emit('delete')" v-if="!newMood"> </div>`, props: { mood: { default: function () { return { 'emoji': '', 'description': '', 'isActive': true, 'id': 0 } } }, newMood: { type: Boolean, default: false, }, }, data: function (){ return { invalidEmoji: false } }, methods: { onSave: function () { this.$emit('save', this.mood); }, validator: function (){ let emojiRegex = /\p{Extended_Pictographic}/u return !emojiRegex.test(this.mood.emoji) }, resetEmojiField: function (){ this.mood.emoji = '' this.invalidEmoji = false } }, })
JavaScript
0.000001
@@ -138,22 +138,26 @@ %0A%09%09%09 -I +%7B%7B i nvalid - e +E moji -. + %7D%7D %0A%09%3C/ @@ -1259,52 +1259,270 @@ %7D/u%0A -%0A%09%09%09return !emojiRegex.test(this.mood.emoji) +%09%09%09this.invalidEmoji = false%0A%0A%09%09%09if (!this.mood.emoji %7C%7C%0A%09%09%09%090 === this.mood.emoji.length %7C%7C%0A%09%09%09%09!this.mood.emoji.trim())%7B%0A%0A%09%09%09%09return 'Emoji field cannot be empty'%0A%09%09%09%7D%0A%0A%09%09%09if (!emojiRegex.test(this.mood.emoji)) %7B%0A%09%09%09%09return 'Please provide a valid emoji'%0A%09%09%09%7D %0A%09%09%7D
690dc6f7137cbc5dba8853370d147581c5168926
remove debug log.
src/app/lib/axiom_shell/exe/mkdir.js
src/app/lib/axiom_shell/exe/mkdir.js
// Copyright (c) 2014 The Axiom Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import AxiomError from 'axiom/core/error'; import Path from 'axiom/fs/path'; import environment from 'axiom_shell/environment'; import util from 'axiom_shell/util'; export var main = function(executeContext) { executeContext.ready(); var arg = executeContext.arg; if (!arg._ && arg._.length) return Promise.reject(new AxiomError.Missing('path')); var fileSystem = environment.getServiceBinding('filesystems@axiom'); var mkdirNext = function() { if (!arg._.length) return Promise.resolve(null); var pathSpec = arg._.shift(); pathSpec = Path.abs(executeContext.getEnv('$PWD', '/'), pathSpec); console.log(pathSpec); return fileSystem.mkdir(pathSpec).then( function() { return mkdirNext(); }).catch(function(e) { //TODO(grv): handle error here. return mkdirNext(); }); }; return mkdirNext(); }; export default main; main.argSigil = '%';
JavaScript
0
@@ -795,31 +795,8 @@ );%0A%0A -console.log(pathSpec);%0A
1ecc049c8b01b30cb42e4f13285cbaf16fc06b1d
update basic package-file testing
test/testPackageFiles.js
test/testPackageFiles.js
/* jshint -W097 */ /* jshint strict:false */ /* jslint node: true */ /* jshint expr: true */ var expect = require('chai').expect; var fs = require('fs'); describe('Test package.json and io-package.json', function() { it('Test package files', function (done) { console.log(); var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8'); var ioPackage = JSON.parse(fileContentIOPackage); var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8'); var npmPackage = JSON.parse(fileContentNPMPackage); expect(ioPackage).to.be.an('object'); expect(npmPackage).to.be.an('object'); expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist; expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist; expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version); if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) { console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!'); console.log(); } expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist; expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist; if (ioPackage.common.name.indexOf('template') !== 0) { if (Array.isArray(ioPackage.common.authors)) { expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0); if (ioPackage.common.authors.length === 1) { expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <[email protected]>'); } } else { expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <[email protected]>'); } } else { console.log('WARNING: Testing for set authors field in io-package skipped because template adapter'); console.log(); } expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true; expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true; if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') { console.log('WARNING: titleLang is not existing in io-package.json. Please add'); console.log(); } if ( ioPackage.common.title.indexOf('iobroker') !== -1 || ioPackage.common.title.indexOf('ioBroker') !== -1 || ioPackage.common.title.indexOf('adapter') !== -1 || ioPackage.common.title.indexOf('Adapter') !== -1 ) { console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.'); console.log(); } if (ioPackage.common.name.indexOf('vis-') !== 0) { if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) { console.log('WARNING: Admin3 support is missing! Please add it'); console.log(); } if (ioPackage.common.materialize) { expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true; } } var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE'); var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8'); if (fileContentReadme.indexOf('## Changelog') === -1) { console.log('Warning: The README.md should have a section ## Changelog'); console.log(); } expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true; if (!licenseFileExists) { console.log('Warning: The License should also exist as LICENSE file'); console.log(); } if (fileContentReadme.indexOf('## License') === -1) { console.log('Warning: The README.md should also have a section ## License to be shown in Admin3'); console.log(); } done(); }); });
JavaScript
0
@@ -2574,130 +2574,8 @@ ue;%0A - expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;%0A
48344d6cab2b71f97d2637165b38e080182569ea
comment fix
nodeserver/src/client/js/ModelEditor3/Decorators/CircleDecorator/CircleDecorator.js
nodeserver/src/client/js/ModelEditor3/Decorators/CircleDecorator/CircleDecorator.js
"use strict"; define(['logManager', 'clientUtil', 'js/ModelEditor3/Decorators/DefaultDecorator/DefaultDecorator', 'text!js/ModelEditor3/Decorators/CircleDecorator/CircleDecoratorTemplate.html', 'css!ModelEditor3CSS/Decorators/CircleDecorator/CircleDecorator'], function (logManager, util, DefaultDecorator, circleDecoratorTemplate) { var CircleDecorator, __parent__ = DefaultDecorator, __parent_proto__ = DefaultDecorator.prototype, DECORATOR_ID = "CircleDecorator", CANVAS_SIZE = 40; CircleDecorator = function (options) { var opts = _.extend( {}, options); __parent__.apply(this, [opts]); this.logger.debug("CircleDecorator ctor"); }; _.extend(CircleDecorator.prototype, __parent_proto__); CircleDecorator.prototype.DECORATORID = DECORATOR_ID; /*********************** OVERRIDE DECORATORBASE MEMBERS **************************/ CircleDecorator.prototype.$DOMBase = $(circleDecoratorTemplate); //Called right after on_addTo and before the host designer item is added to the canvas DOM CircleDecorator.prototype.on_addTo = function () { this._renderCircle(); //let the parent decorator class do its job first __parent_proto__.on_addTo.apply(this, arguments); }; //Called right after on_addTo and before the host designer item is added to the canvas DOM CircleDecorator.prototype.on_addToPartBrowser = function () { this._renderCircle(); //let the parent decorator class do its job first __parent_proto__.on_addToPartBrowser.apply(this, arguments); }; CircleDecorator.prototype._renderCircle = function () { //find additional CircleDecorator specific UI components this.skinParts.$arrowCanvas = this.$el.find('[id="circleCanvas"]'); this.skinParts.$arrowCanvas[0].height = CANVAS_SIZE; this.skinParts.$arrowCanvas[0].width = CANVAS_SIZE; var ctx = this.skinParts.$arrowCanvas[0].getContext('2d'); if(ctx) { ctx.circle(CANVAS_SIZE / 2, CANVAS_SIZE / 2, CANVAS_SIZE / 2 - 1, true); } }; CircleDecorator.prototype.onRenderGetLayoutInfo = function () { //let the parent decorator class do its job first __parent_proto__.onRenderGetLayoutInfo.apply(this, arguments); this.renderLayoutInfo.nameWidth = this.skinParts.$name.outerWidth(); }; CircleDecorator.prototype.onRenderSetLayoutInfo = function () { var shift = (40 - this.renderLayoutInfo.nameWidth) / 2; this.skinParts.$name.css({ "left": shift }); //let the parent decorator class do its job finally __parent_proto__.onRenderSetLayoutInfo.apply(this, arguments); }; CircleDecorator.prototype.calculateDimension = function () { if (this.hostDesignerItem) { this.hostDesignerItem.width = this.skinParts.$arrowCanvas[0].width; this.hostDesignerItem.height = this.skinParts.$arrowCanvas[0].height + this.skinParts.$name.outerHeight(true); } }; CircleDecorator.prototype.getConnectionAreas = function (/*id*/) { var result = [], width = this.skinParts.$arrowCanvas[0].width, height = this.skinParts.$arrowCanvas[0].height; //by default return the bounding box edges midpoints //top left result.push( {"id": "0", "x": width / 2, "y": 0, "w": 0, "h": 0, "orientation": "N", "len": 10} ); result.push( {"id": "1", "x": width / 2, "y": height, "w": 0, "h": 0, "orientation": "S", "len": 10} ); result.push( {"id": "2", "x": 0, "y": height / 2, "w": 0, "h": 0, "orientation": "W", "len": 10} ); result.push( {"id": "3", "x": width, "y": height / 2, "w": 0, "h": 0, "orientation": "E", "len": 10} ); return result; }; return CircleDecorator; });
JavaScript
0
@@ -3520,16 +3520,176 @@ idpoints +%0A //NOTE: it returns the connection point regardless of being asked for%0A //its own connection ports or some of the subcomponent's connection ports %0A%0A
df17ed4b237cf79e0aec588729872883eb0bb039
switch to using filmStripFrames
lib/game.js
lib/game.js
"use strict"; var Input = require("./input"); var Scene = require("./scene"); var systems = require("./systems"); function clone(obj) { if (obj === undefined) { return undefined; } return JSON.parse(JSON.stringify(obj)); } function splitFilmStripAnimations(animations) { Object.keys(animations).forEach(function(key) { var firstFrame = animations[key][0]; if(firstFrame.filmstrip){ splitFilmStripAnimation(animations[key], firstFrame); } }); } function splitFilmStripAnimation(animation, firstFrame) { if(firstFrame.properties.image.sourceWidth % firstFrame.filmstrip.frames != 0){ console.warn("The \"" + firstFrame.properties.image.name + "\" animation is " + firstFrame.properties.image.sourceWidth + " pixels wide and that is is not evenly divisible by "+ firstFrame.filmstrip.frames +" frames."); } for( var i = 0; i < firstFrame.filmstrip.frames; i++){ var frameWidth = firstFrame.properties.image.sourceWidth / firstFrame.filmstrip.frames; var newFrame = { "time": firstFrame.time, "properties": { "image": { "name": firstFrame.properties.image.name, "sourceX": frameWidth * i, "sourceY": 0, "sourceWidth": frameWidth, "sourceHeight": firstFrame.properties.image.sourceHeight } } }; animation.push(newFrame); } animation.splice(0,1); } function Game(canvas, animations, entities, images, input, require, scenes, sounds, systems) { splitFilmStripAnimations(animations); this.animations = animations; this.canvas = canvas; this.context = canvas.getContext("2d"); this.entities = entities; this.images = images; this.input = new Input(input, canvas); this.require = require; this.scenes = scenes; this.sounds = sounds; this.systems = systems; this.makeScenes(scenes); } Game.prototype.makeScenes = function(sceneList) { Object.keys(sceneList).forEach(function(scene) { if (sceneList[scene].first) { this.scene = this.makeScene(scene, sceneList[scene], {}); } }.bind(this)); }; Game.prototype.makeScene = function(name, sceneData, sceneArgs) { var scene = new Scene(); var data = this.makeSceneData(scene.entities, sceneArgs); scene.simulation.add(function() { data.input.processUpdates(); }); this.installSystems(name, this.systems.simulation, scene.simulation, data); this.installSystems(name, this.systems.renderer, scene.renderer, data); scene.entities.load(clone(this.entities[name])); if (typeof sceneData.onEnter === "string") { var enterScript = this.loadScript(sceneData.onEnter); if (typeof enterScript === "function") { enterScript = enterScript.bind(scene, data); } scene.onEnter = enterScript; } if (typeof sceneData.onExit === "string") { var exitScript = this.loadScript(sceneData.onExit); if (typeof exitScript === "function") { exitScript = exitScript.bind(scene, data); } scene.onExit = exitScript; } return scene; }; Game.prototype.makeSceneData = function(entities, sceneArgs) { return { animations: this.animations, arguments: sceneArgs || {}, canvas: this.canvas, context: this.context, entities: entities, images: this.images, input: this.input, require: this.loadScript.bind(this), sounds: this.sounds, switchScene: this.switchScene.bind(this) }; }; Game.prototype.installSystems = function(scene, systems, ecs, data) { systems.forEach(function(system) { if (system.scenes.indexOf(scene) === -1) { return; } var script = this.loadScript(system.name); if (script === undefined) { console.error("failed to load script", system.name); } script(ecs, data); }.bind(this)); }; Game.prototype.loadScript = function(script) { if (script.indexOf("splatjs:") === 0) { var names = script.substr(8).split("."); return names.reduce(function(obj, name) { return obj[name]; }, systems); } else { return this.require(script); } }; Game.prototype.switchScene = function(name, sceneArgs) { if (this.scene !== undefined) { this.scene.stop(); } this.scene = this.makeScene(name, this.scenes[name], sceneArgs); this.scene.start(this.context); }; module.exports = Game;
JavaScript
0
@@ -384,16 +384,22 @@ ilmstrip +Frames )%7B%0A%09%09%09sp @@ -434,25 +434,13 @@ ions -%5Bkey%5D, firstFrame +, key );%0A%09 @@ -495,23 +495,55 @@ tion +s , -firstFrame) %7B +key) %7B%0A%09var firstFrame = animations%5Bkey%5D%5B0%5D; %0A%09if @@ -601,26 +601,25 @@ me.filmstrip -.f +F rames != 0)%7B @@ -649,40 +649,11 @@ %22 + -firstFrame.properties.image.name +key + %22 @@ -786,26 +786,25 @@ me.filmstrip -.f +F rames +%22 fra @@ -851,26 +851,25 @@ me.filmstrip -.f +F rames; i++)%7B @@ -950,18 +950,17 @@ ilmstrip -.f +F rames;%0A%09 @@ -1258,16 +1258,22 @@ nimation +s%5Bkey%5D .push(ne @@ -1294,16 +1294,22 @@ nimation +s%5Bkey%5D .splice(
5f4df706af690c1bb794ad235f50fcc17df18afc
fix gamejs.transform.rotate sometimes cutting of parts of surface
lib/gamejs/transform.js
lib/gamejs/transform.js
var Surface = require('../gamejs').Surface; var matrix = require('./utils/matrix'); var math = require('./utils/math'); var vectors = require('./utils/vectors'); /** * @fileoverview Rotate and scale Surfaces. */ /** * Returns a new surface which holds the original surface rotate by angle degrees. * @param {Surface} surface * @param {angel} angle Clockwise angle by which to rotate * @returns {Surface} new, rotated surface */ exports.rotate = function (surface, angle) { var origSize = surface.getSize(); var radians = (angle * Math.PI / 180); var newSize = origSize; // find new bounding box if (angle % 90 !== 0) { var rect = surface.getRect(); var points = [ [-rect.width/2, rect.height/2], [rect.width/2, rect.height/2], [-rect.width/2, -rect.height/2], [rect.width/2, -rect.height/2] ]; var rotPoints = points.map(function(p) { return vectors.rotate(p, radians); }); var xs = rotPoints.map(function(p) { return p[0]; }); var ys = rotPoints.map(function(p) { return p[1]; }); var left = Math.min.apply(Math, xs); var right = Math.max.apply(Math, xs); var bottom = Math.min.apply(Math, ys); var top = Math.max.apply(Math, ys); newSize = [right-left, top-bottom]; } var newSurface = new Surface(newSize); var oldMatrix = surface._matrix; surface._matrix = matrix.translate(surface._matrix, origSize[0]/2, origSize[1]/2); surface._matrix = matrix.rotate(surface._matrix, radians); surface._matrix = matrix.translate(surface._matrix, -origSize[0]/2, -origSize[1]/2); var offset = [(newSize[0] - origSize[0]) / 2, (newSize[1] - origSize[1]) / 2]; newSurface.blit(surface, offset); surface._matrix = oldMatrix; return newSurface; }; /** * Returns a new surface holding the scaled surface. * @param {Surface} surface * @param {Array} scale new [widthScale, heightScale] in range; e.g.: [2,2] would double the size * @returns {Surface} new, scaled surface */ exports.scale = function(surface, dims) { var width = dims[0]; var height = dims[1]; var newDims = surface.getSize(); newDims = [newDims[0] * dims[0], newDims[1] * dims[1]]; var newSurface = new Surface(newDims); surface._matrix = matrix.scale(surface._matrix, [width, height]); newSurface.blit(surface); return newSurface; }; /** * Flip a Surface either vertically, horizontally or both. This returns * a new Surface (i.e: nondestructive). * @param {gamejs.Surface} surface */ exports.flip = function(surface, flipHorizontal, flipVertical) { var dims = surface.getSize(); var newSurface = new Surface(dims); var scaleX = 1; var scaleY = 1; var xPos = 0; var yPos = 0; if (flipHorizontal === true) { scaleX = -1; xPos = -dims[0]; } if (flipVertical === true) { scaleY = -1; yPos = -dims[1]; } newSurface.context.save(); newSurface.context.scale(scaleX, scaleY); newSurface.context.drawImage(surface.canvas, xPos, yPos); newSurface.context.restore(); return newSurface; };
JavaScript
0
@@ -628,9 +628,10 @@ e %25 -9 +36 0 !=
3e090aa9a5b3f587d4e50903a07a19a738549c62
Bump version
package.js
package.js
Package.describe({ summary: "Define and create an Admin role when Meteor starts.", version: "0.1.0", name: "brylie:create-admin-role", git: "https://github.com/brylie/meteor-create-admin-role.git" }); Package.on_use(function (api, where) { // Meteor version api.versionsFrom("1.0.1"); // Dependencies api.use("alanning:[email protected]", "server"); api.use("brylie:[email protected]", "server"); // Files api.add_files("server/startup.js", "server"); });
JavaScript
0
@@ -94,17 +94,17 @@ n: %220.1. -0 +1 %22,%0A nam @@ -291,18 +291,16 @@ .0.1%22);%0A - %0A // De
7d50ab042834256fb28bf995cd59ccd5a3cb2f82
change checking Error.errno to Error.code
bin/swig.js
bin/swig.js
#!/usr/bin/env node /*jslint es5: true */ var swig = require('../index'), optimist = require('optimist'), fs = require('fs'), path = require('path'), filters = require('../lib/filters'), utils = require('../lib/utils'), uglify = require('uglify-js'); var command, wrapstart = 'var tpl = ', argv = optimist .usage('\n Usage:\n' + ' $0 compile [files] [options]\n' + ' $0 run [files] [options]\n' + ' $0 render [files] [options]\n' ) .describe({ v: 'Show the Swig version number.', o: 'Output location.', h: 'Show this help screen.', j: 'Variable context as a JSON file.', c: 'Variable context as a CommonJS-style file. Used only if option `j` is not provided.', m: 'Minify compiled functions with uglify-js', 'filters': 'Custom filters as a CommonJS-style file', 'tags': 'Custom tags as a CommonJS-style file', 'options': 'Customize Swig\'s Options from a CommonJS-style file', 'wrap-start': 'Template wrapper beginning for "compile".', 'wrap-end': 'Template wrapper end for "compile".', 'method-name': 'Method name to set template to and run from.' }) .alias('v', 'version') .alias('o', 'output') .default('o', 'stdout') .alias('h', 'help') .alias('j', 'json') .alias('c', 'context') .alias('m', 'minify') .default('wrap-start', wrapstart) .default('wrap-end', ';') .default('method-name', 'tpl') .check(function (argv) { if (argv.v) { return; } if (!argv._.length) { throw new Error(''); } command = argv._.shift(); if (command !== 'compile' && command !== 'render' && command !== 'run') { throw new Error('Unrecognized command "' + command + '". Use -h for help.'); } if (argv['method-name'] !== 'tpl' && argv['wrap-start'] !== wrapstart) { throw new Error('Cannot use arguments "--method-name" and "--wrap-start" together.'); } if (argv['method-name'] !== 'tpl') { argv['wrap-start'] = 'var ' + argv['method-name'] + ' = '; } }) .argv, ctx = {}, out = function (file, str) { console.log(str); }, efn = function () {}, anonymous, files, fn; // What version? if (argv.v) { console.log(require('../package').version); process.exit(0); } // Pull in any context data provided if (argv.j) { ctx = JSON.parse(fs.readFileSync(argv.j, 'utf8')); } else if (argv.c) { ctx = require(argv.c); } if (argv.o !== 'stdout') { argv.o += '/'; argv.o = path.normalize(argv.o); try { fs.mkdirSync(argv.o); } catch (e) { if (e.errno !== 47) { throw e; } } out = function (file, str) { file = path.basename(file); fs.writeFileSync(argv.o + file, str, { flags: 'w' }); console.log('Wrote', argv.o + file); }; } // Set any custom filters if (argv.filters) { utils.each(require(path.resolve(argv.filters)), function (filter, name) { swig.setFilter(name, filter); }); } // Set any custom tags if (argv.tags) { utils.each(require(path.resolve(argv.tags)), function (tag, name) { swig.setTag(name, tag.parse, tag.compile, tag.ends, tag.block); }); } // Specify swig default options if (argv.options) { swig.setDefaults(require(argv.options)); } switch (command) { case 'compile': fn = function (file, str) { var r = swig.precompile(str, { filename: file, locals: ctx }).tpl.toString().replace('anonymous', ''); r = argv['wrap-start'] + r + argv['wrap-end']; if (argv.m) { r = uglify.minify(r, { fromString: true }).code; } out(file, r); }; break; case 'run': fn = function (file, str) { (function () { eval(str); var __tpl = eval(argv['method-name']); out(file, __tpl(swig, ctx, filters, utils, efn)); }()); }; break; case 'render': fn = function (file, str) { out(file, swig.render(str, { filename: file, locals: ctx })); }; break; } argv._.forEach(function (file) { var str = fs.readFileSync(file, 'utf8'); fn(file, str); });
JavaScript
0.000001
@@ -2648,20 +2648,25 @@ (e. -errno !== 47 +code !== %22EEXIST%22 ) %7B%0A
9385b530a4a15df98da2f6cb8f9bfcef7dc2b494
Simplify import
lib/generators/utils.js
lib/generators/utils.js
import fs from 'fs'; import path from 'path'; import _ from 'lodash'; import {mkdirsSync, copySync, outputFileSync} from 'fs-extra'; import {template, capitalize} from 'lodash'; import matchBracket from 'match-bracket'; import locater from 'locater'; import {writeToFile, checkFileExists} from '../utils'; import {logger} from '../logger'; /** * Gets the output path of the file that will be generated. * @param type {String} - the type of file to be generated. See extensionMap * for the supported values. * @param entityName {String} - the name of the file that will be generated * @param [moduleName] {String} - the name of the module under which the file will * be generated * @return String - the output path relative to the app root */ function getOutputPath(type, entityName, moduleName) { const extensionMap = { action: 'js', component: 'jsx', configs: 'js', container: 'js', collection: 'js', method: 'js', publication: 'js' }; let extension = extensionMap[type]; let outputFileName = `${entityName}.${extension}`; if (type === 'collection') { return `./lib/collections/${outputFileName}`; } else if (type === 'method') { return `./server/methods/${outputFileName}`; } else if (type === 'publication') { return `./server/publications/${outputFileName}`; } else { return `./client/modules/${moduleName}/${type}s/${outputFileName}`; } } /** * Gets the path to the generic template inside mantra-cli given the type. * @param type {String} - type of the file being generated. * @return String - the absolute path to the generic template inside mantra-cli * for the given file type. */ function getTemplatePath(type) { let relativePath; if (type === 'collection') { relativePath = '../../templates/lib/collections/generic.tt'; } else if (type === 'method') { relativePath = `../../templates/server/methods/generic.tt`; } else if (type === 'publication') { relativePath = '../../templates/server/publications/generic.tt'; } else { relativePath = `../../templates/client/modules/core/${type}s/generic.tt`; } return path.resolve(__dirname, relativePath); } /** * Reads the content of a generic template for the file type * @param type {String} - type of the file. See getOutputPath's extensionMap for * all valid types * @return Buffer - the content of the template for the given type */ function readTemplateContent(type) { let templatePath = getTemplatePath(type); return fs.readFileSync(templatePath); } /** * Gets the variables to be passed to the generic template to be evaluated by * a template engine. * @param type {String} - type of the template * @param fileName {String} - name of the file being generated * @return Object - key-values pairs of variable names and their values */ function getTemplateVaraibles(type, fileName) { if (type === 'component') { return {componentName: capitalize(fileName)}; } else if (type === 'container') { return { componentName: capitalize(fileName), componentFileName: fileName }; } else if (type === 'collection') { return { collectionName: capitalize(fileName), collectionFileName: fileName }; } else if (type === 'method') { return { collectionName: capitalize(fileName), methodFileName: fileName }; } else if (type === 'publication') { return { collectionName: capitalize(fileName), publicationFileName: fileName }; } return {}; } /** * Updates a relevant index.js file by inserting an import statement at the top * portion of the file, and a statement inside the export block. * Uses locater, and matchBracket to pinpoint the position at which the * statements are to be inserted. * * @param {Object} * - indexFilePath: the path to the index file to be modified * - exportBeginning: the content of the line on which the export block * begins * - insertImport: the import statement to be inserted at the top portion * of the file * - insertExport: the statement to be inserted inside the export block */ export function updateIndexFile({indexFilePath, exportBeginning, insertImport, insertExport}) { function findExportLineTarget() { let indexContent = fs.readFileSync(indexFilePath, {encoding: 'utf-8'}); let exportBeginningRegex = new RegExp(_.escapeRegExp(exportBeginning), 'g'); let exportBeginningPos = locater.findOne(exportBeginningRegex, indexContent); let bracketCursor = exportBeginning.indexOf('{') + 1; // cursor at which the bracket appears on the line where export block starts let matchedBracketPos = matchBracket(indexContent, _.assign(exportBeginningPos, {cursor: bracketCursor})); return matchedBracketPos.line; } // Insert the import statement at the top portion of the file writeToFile(indexFilePath, insertImport, {or: [ {after: {regex: /import .*\n/g, last: true}, asNewLine: true}, {before: {line: 1}, asNewLine: true, _appendToModifier: '\n'} ]} ); // Insert within the export block if needed writeToFile(indexFilePath, insertExport, {before: {line: findExportLineTarget()}, asNewLine: true} ); logger.update(indexFilePath); } export function _generate(type, moduleName, entityName, done) { let templateContent = readTemplateContent(type); let outputPath = getOutputPath(type, entityName, moduleName); let templateVariables = getTemplateVaraibles(type, entityName); let component = template(templateContent)(templateVariables); if (checkFileExists(outputPath)) { logger.exists(outputPath); return; } fs.writeFileSync(outputPath, component); logger.create(outputPath); if (done) { done(); } }
JavaScript
0.000188
@@ -130,53 +130,8 @@ a';%0A -import %7Btemplate, capitalize%7D from 'lodash';%0A impo @@ -168,16 +168,16 @@ acket';%0A + import l @@ -199,16 +199,17 @@ cater';%0A +%0A import %7B @@ -2896,32 +2896,34 @@ %7BcomponentName: +_. capitalize(fileN @@ -2996,24 +2996,26 @@ ponentName: +_. capitalize(f @@ -3130,32 +3130,34 @@ collectionName: +_. capitalize(fileN @@ -3265,32 +3265,34 @@ collectionName: +_. capitalize(fileN @@ -3409,16 +3409,18 @@ onName: +_. capitali @@ -5490,24 +5490,24 @@ ntityName);%0A - let compon @@ -5512,16 +5512,18 @@ onent = +_. template
e9533dea6dc5cbb5bc7e9f3ea561302b454f2987
Revert "Migrated to urbanetic:utility."
package.js
package.js
// Meteor package definition. Package.describe({ name: 'urbanetic:bismuth-utility', version: '0.1.0', summary: 'A set of utilities for working with GIS apps.', git: 'https://github.com/urbanetic/bismuth-reports.git' }); Npm.depends({ 'request': '2.37.0', 'concat-stream': '1.4.7' }); Package.onUse(function (api) { api.versionsFrom('[email protected]'); api.use([ 'coffeescript', 'underscore', 'aramk:[email protected]_1', '[email protected]', 'urbanetic:[email protected]', 'urbanetic:[email protected]', 'urbanetic:[email protected]', 'urbanetic:[email protected]' ], ['client', 'server']); api.use([ 'urbanetic:[email protected]', ], ['client', 'server'], {weak: true}); api.use([ 'jquery', 'less', 'templating' ], 'client'); // TODO(aramk) Perhaps expose the charts through the Vega object only to avoid cluttering the // namespace. api.export([ 'Csv' ], 'client'); api.export([ 'FileLogger', 'Request' ], 'server'); api.export([ 'CounterLog', 'EntityImporter', 'EntityUtils', 'ItemBuffer', 'TaskRunner', 'ProjectUtils' ], ['client', 'server']); api.addFiles([ 'src/Csv.coffee' ], 'client'); api.addFiles([ 'src/FileLogger.coffee', 'src/Request.coffee' ], 'server'); api.addFiles([ 'src/AccountsUtil.coffee', 'src/CounterLog.coffee', 'src/EntityImporter.coffee', 'src/EntityUtils.coffee', 'src/ItemBuffer.coffee', 'src/TaskRunner.coffee', 'src/ProjectUtils.coffee' ], ['client', 'server']); });
JavaScript
0
@@ -431,16 +431,43 @@ 0.1_1',%0A + 'aramk:[email protected]',%0A 'rea @@ -601,39 +601,8 @@ 1.0' -,%0A 'urbanetic:[email protected]' %0A %5D
a1a67ff1118d0b8316cc406c0820407a2cc3a46d
Update systemjs.config.js
generators/app/templates/systemjs/systemjs.config.js
generators/app/templates/systemjs/systemjs.config.js
(function(global) { var paths = { 'npm:': '/node_modules/' }; var map = { 'app': 'app', '@angular/core': 'npm:@angular/core/bundles/core.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',<% if (angularPackages['@angular/http']) { %> '@angular/http': 'npm:@angular/http/bundles/http.umd.js',<% } %> '@angular/router': 'npm:@angular/router/bundles/router.umd.js',<% if (angularPackages['@angular/forms']) { %> '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',<% } %> 'rxjs': 'npm:rxjs' }; // packages tells the System loader how to load when no filename and/or no extension var packages = { app: { main: 'main.js', defaultExtension: 'js' }, rxjs: { defaultExtension: 'js' } }; var config = { paths: paths, map: map, packages: packages }; System.config(config); })(this);
JavaScript
0.000001
@@ -48,16 +48,17 @@ npm:': ' +. /node_mo
8179ad85fca1cfdd859ca513788292130d78fda9
Move CSS to the top.
src/foam/u2/CheckBox.js
src/foam/u2/CheckBox.js
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'foam.u2', name: 'CheckBox', extends: 'foam.u2.tag.Input', documentation: 'Checkbox View.', properties: [ { class: 'Boolean', name: 'data' }, { class: 'Boolean', name: 'showLabel', factory: function() { return !! this.label || this.labelFormatter }, }, { class: 'String', name: 'label' }, { name: 'labelFormatter' } ], methods: [ function initE() { this.SUPER(); this.setAttribute('type', 'checkbox'); var self = this; if ( this.showLabel ) { this.start('label') .addClass(this.myClass('label')) .addClass(this.myClass('noselect')) .callIfElse(this.labelFormatter, this.labelFormatter, function() { this.add(self.label$); }) .on('click', function() { if ( self.getAttribute('disabled') ) return; this.data = ! this.data; }.bind(this)) .end(); } }, function updateMode_(mode) { var disabled = mode === foam.u2.DisplayMode.RO || mode === foam.u2.DisplayMode.DISABLED; this.setAttribute('disabled', disabled); }, function link() { this.data$.linkTo(this.attrSlot('checked')); }, function fromProperty(property) { this.SUPER(property); this.label = property.label; } ], css: ` ^ { margin: 0; padding: 8px; } ^label { color: #444; flex-grow: 1; margin-left: 12px; overflow: hidden; white-space: nowrap; display: inline; } ^noselect { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } ` });
JavaScript
0
@@ -747,16 +747,451 @@ iew.',%0A%0A + css: %60%0A %5E %7B%0A margin: 8px 0;%0A padding: 8px;%0A %7D%0A%0A %5Elabel %7B%0A color: #444;%0A flex-grow: 1;%0A margin-left: 12px;%0A overflow: hidden;%0A white-space: nowrap;%0A display: inline;%0A %7D%0A%0A %5Enoselect %7B%0A -webkit-touch-callout: none;%0A -webkit-user-select: none;%0A -khtml-user-select: none;%0A -moz-user-select: none;%0A -ms-user-select: none;%0A user-select: none;%0A %7D%0A %60,%0A%0A proper @@ -2499,439 +2499,8 @@ %0A %5D -,%0A%0A css: %60%0A %5E %7B%0A margin: 0;%0A padding: 8px;%0A %7D%0A%0A %5Elabel %7B%0A color: #444;%0A flex-grow: 1;%0A margin-left: 12px;%0A overflow: hidden;%0A white-space: nowrap;%0A display: inline;%0A %7D%0A%0A %5Enoselect %7B%0A -webkit-touch-callout: none;%0A -webkit-user-select: none;%0A -khtml-user-select: none;%0A -moz-user-select: none;%0A -ms-user-select: none;%0A user-select: none;%0A %7D%0A %60 %0A%7D);
1294826dc5515d224128cd6f0a97dfcc47674dd7
add the #! marker for npm bin
bin/wstt.js
bin/wstt.js
//@ sourceMappingURL=wst.map // Generated by CoffeeScript 1.6.1 (function() { var argv, client, host, localport, optimist, port, server, wsHost, wst, _, _ref; _ = require("under_score"); wst = require("../lib/wst"); optimist = require('optimist').usage("Run websocket tunnel server or client.\n To run server: wstunnel -s 8080\n To run client: wstunnel -tunnel localport:host:port ws://wshost:wsport\nNow connecting to localhsot:localport is same as connecting to host:port").string("s").string("t").alias('t', "tunnel").describe('s', 'run as server, specify listen port').describe('tunnel', 'run as tunnel client, specify localport:host:port'); argv = optimist.argv; if (_.size(argv) === 2) { return console.log(optimist.help()); } if (argv.s) { server = new wst.server; server.start(argv.s); } else if (argv.t) { client = new wst.client; wsHost = _.last(argv._); _ref = argv.t.split(":"), localport = _ref[0], host = _ref[1], port = _ref[2]; client.start(localport, wsHost, "" + host + ":" + port); } else { return console.log(optimist.help()); } }).call(this);
JavaScript
0.999846
@@ -1,67 +1,24 @@ -//@ sourceMappingURL=wst.map%0A// Generated by CoffeeScript 1.6.1 +#!/usr/bin/env node%0A %0A(fu
92990dd6e481c1ed96df6192125c259505521c32
simplify equivalent requisites
src/linear-converter.js
src/linear-converter.js
/*jshint node:true */ 'use strict'; var rescaleFactory = require('rescale'); var twoOfAKind = require('olsen'); var unitPreset = require('unit-preset'); /** * Returns the linear converter api based on the given adapter * * @param {Object} Decimal instance of decimal library * * @return {Object} Linear converter API */ module.exports = function factory(Decimal) { var rescale = rescaleFactory(Decimal); var api = {}; /** * Linearly converts x as described by a preset * * @param {Number} x The number to be converted * @param {Array} preset The preset that describes the conversion * * @return {Number} The converted x */ api.convert = function convert(x, preset) { preset = preset || unitPreset; return rescale.rescale(x, preset[0], preset[1]); }; /** * Inverts a preset to change the direction of the conversion * * @param {Array} preset The preset to invert * * @return {Array} The inverted preset */ api.invertPreset = function invertPreset(preset) { return api.composePresets(preset.slice().reverse(), unitPreset); }; /** * Composes two presets to create a single preset * * @param {Array} presetA The first preset to compose * @param {Array} presetB The second preset to compose * * @return {Array} The composed preset */ api.composePresets = function composePresets(presetA, presetB) { return [ presetA[0].map(function(x) { return api.convert(x); }), presetA[1].map(function(x) { return api.convert(x, presetB); }) ]; }; /** * Calculates the a coefficient in the f(x) = ax + b function that describes * the given preset. * * @param {Array} preset The preset for which to calculate its a coefficient * * @return {Number} The coefficient a */ api.getCoefficientA = function getCoefficientA(preset) { return new Decimal(preset[1][1].toString()).minus(new Decimal(preset[1][0].toString())) .div(new Decimal(preset[0][1].toString()).minus(new Decimal(preset[0][0].toString()))); }; /** * Calculates the b coefficient in the f(x) = ax + b function that describes * the given preset. * * @param {Array} preset The preset for which to calculate its b coefficient * * @return {Number} The coefficient b */ api.getCoefficientB = function getCoefficientB(preset) { return api.convert(0, preset); }; var presetEquivalenceRequisites = [ api.getCoefficientA, api.getCoefficientB ]; var wrappedPresetEquivalenceRequisites = [ api.getCoefficientA, api.getCoefficientB ].map(wrapPresetEquivalenceRequisite); /** * Check equivalence of two presets * * @param {Array} presetA The first preset to check for equivalence * @param {Array} presetB The second preset to check for equivalence * * @return {Boolean} whether the presets are equivalent or not */ api.equivalentPresets = function equivalentPresets(presetA, presetB) { return wrappedPresetEquivalenceRequisites.every(twoOfAKind(presetA, presetB)); }; /** * Wraps a preset equivalence requisite to return a stringified version * * @param {Function} presetEquivalenceRequisite [description] * * @return {Function} */ function wrapPresetEquivalenceRequisite(presetEquivalenceRequisite) { return function(preset) { return presetEquivalenceRequisite(preset).toString(); }; } return api; };
JavaScript
0.998481
@@ -2509,25 +2509,31 @@ %0A %5D -;%0A%0A var +.map(function wrappe -dP +r(p rese @@ -2557,101 +2557,112 @@ site -s = %5B%0A api.getCoefficientA,%0A api.getCoefficientB%0A %5D.map(wrapPresetEquivalenceRequisite +) %7B%0A return function(preset) %7B%0A return presetEquivalenceRequisite(preset).toString();%0A %7D;%0A %7D );%0A%0A @@ -3015,16 +3015,9 @@ urn -wrappedP +p rese @@ -3086,366 +3086,8 @@ %7D;%0A%0A - /**%0A * Wraps a preset equivalence requisite to return a stringified version%0A *%0A * @param %7BFunction%7D presetEquivalenceRequisite %5Bdescription%5D%0A *%0A * @return %7BFunction%7D%0A */%0A function wrapPresetEquivalenceRequisite(presetEquivalenceRequisite) %7B%0A return function(preset) %7B%0A return presetEquivalenceRequisite(preset).toString();%0A %7D;%0A %7D%0A%0A re
12ee84977acc6eb4d75ebaeb495f7ebfacb2bfde
Fix double event fire on page with no hash - done
core/Controller.js
core/Controller.js
(function() { "use strict"; var ns = "nkf.core"; var self = $.namespace(ns); Controller.className = "Controller"; function Controller() { addEventHandler(); function addEventHandler() { window.onhashchange = function(e) { if (hashChangeAllowed) { $(document).trigger("nkf.core.Controller", { action: "load", actionType: nkf.def.events.type.make, pageName: Controller.getNormalizedObject(Controller.getCurrentPath()).pageName, params: Controller.getNormalizedObject(Controller.getCurrentPath()).params, init: true }); } else { hashChangeAllowed = true; } }; $(document).bind("{ns}.{className}".format({ ns: ns, className: Controller.className }), function(e, data) { if (data.action === "load" && data.actionType === nkf.def.events.type.make) { if (!isInit) { init(); } if (!data) { data = {}; } if (isInit) { data.pageName = data.pageName || Controller.getNormalizedObject(Controller.getCurrentPath()).pageName || "Home"; data.params = data.clear ? data.params : $.extend({}, Controller.getNormalizedObject(Controller.getCurrentPath()).params, data.params); $(document).trigger("nkf.core.Controller", { actionType: nkf.def.events.type.is, action: "load", init: data.init }); Controller.setCurrentPath(data); if (data.init) { ++historyCounter; componentManager.load(data); } } } }); } function init() { if (!nkf.impl) { throw "No implementation found"; } else if (!nkf.impl.components) { throw "No component found"; } else if (!nkf.impl.components.layout) { throw "No layout component found"; } else if (!nkf.impl.components.page) { throw "No page component found"; } isInit = true; } } Controller.getCurrentPath = function() { return window.location.hash.replace(nkf.conf.def.hash, ""); }; Controller.setCurrentPath = function(data) { var output = nkf.conf.def.hash + (data.pageName || Controller.getNormalizedObject(Controller.getCurrentPath()).pageName); if (data.params && $Utils.getObjectSize(data.params)) { var preparedData = $Utils.prepareURLObject(data.params); if ($Utils.getObjectSize(preparedData)) { var serializedData = $Utils.getSerializeObject(preparedData); output += "|" + serializedData; } } hashChangeAllowed = false; window.location.hash = output; hashChangeAllowed = true; }; Controller.getNormalizedObject = function(url) { var output = {}; var splited = Controller.getCurrentPath().split("|"); var pageName = splited[0]; var parameters = splited[1]; output.pageName = pageName; output.params = $Utils.getDeserializedObject(parameters); return output; }; Controller.getHistoryCounter = function() { return historyCounter; }; $.extend(self, { Controller: Controller }); var controller = new Controller(); var componentManager = new self.components.ComponentManager.getInstance(); var $Utils = nkf.core.Utils; var hashChangeAllowed = false; var historyCounter = -1; var isInit = false; })();
JavaScript
0
@@ -1339,32 +1339,34 @@ ms);%0A%0A + $(document).trig @@ -1398,32 +1398,34 @@ , %7B%0A + actionType: nkf. @@ -1448,32 +1448,34 @@ is,%0A + + action: %22load%22,%0A @@ -1466,32 +1466,34 @@ action: %22load%22,%0A + init @@ -1504,16 +1504,18 @@ ta.init%0A + @@ -2760,16 +2760,46 @@ utput;%0A%0A + setTimeout(function() %7B%0A hash @@ -2820,16 +2820,29 @@ = true;%0A + %7D, 100);%0A %7D;%0A%0A
b422cf743a18340e59406247e9f9b334b718df31
Enable elda to persist her own memories
lib/neural/persistence-write.js
lib/neural/persistence-write.js
function configure(memory, network) { function write() { console.log('Write neural network to file system'); return buildIndex(network).then(writeFiles); } function buildIndex(network) { var subjects = network.subjects(); var index = { concepts: [], files: {} }; subjects.map(function(subject) { var fc = subject.charAt(0).toLowerCase() var path = `${fc}-${subject}.json`; index.concepts.push(path); index.files[path] = createFileFor(subject, network); }); return Promise.resolve(index); } function createFileFor(subject, network) { return { predicates: network.serialize(subject) }; } function writeFiles(index) { console.log('I got this far:', index); return memory.write('sample.json', JSON.stringify(index, null, 2)); } return write; } module.exports = configure;
JavaScript
0
@@ -120,26 +120,26 @@ return -buildIndex +mapNetwork (network @@ -178,18 +178,18 @@ ion -buildIndex +mapNetwork (net @@ -275,30 +275,36 @@ : %5B%5D -, %0A - files: %7B%7D%0A +%7D;%0A var fileList = %7B %7D;%0A%0A @@ -414,9 +414,9 @@ %7Bfc%7D -- +/ $%7Bsu @@ -472,19 +472,16 @@ -index.files +fileList %5Bpat @@ -527,16 +527,53 @@ %7D);%0A%0A + fileList%5B%22index.json%22%5D = index;%0A%0A retu @@ -591,21 +591,24 @@ resolve( -index +fileList );%0A %7D%0A%0A @@ -748,21 +748,21 @@ les( -index +files ) %7B%0A cons @@ -761,47 +761,143 @@ -console.log('I got this far:', index);%0A +var doWork = Promise.resolve(true);%0A for (var file in files) %7B%0A var contents = files%5Bfile%5D;%0A doWork.then(function() %7B%0A @@ -920,21 +920,12 @@ ite( -'sample.json' +file , JS @@ -937,21 +937,24 @@ ringify( -index +contents , null, @@ -958,16 +958,51 @@ l, 2));%0A + %7D);%0A %7D%0A return doWork;%0A %7D%0A%0A r
7fc9545bf3b4f70bc64c9d740ebbeff81ce9f3a9
version bumped
package.js
package.js
Package.describe({ summary: 'Flow Components', version: '0.0.25', git: 'https://github.com/meteorhacks/flow-components', name: "meteorhacks:flow-components" }); Package.onUse(function (api) { api.versionsFrom('[email protected]'); api.use('ui'); api.use('templating'); api.use('reactive-var'); api.use('reactive-dict'); api.use('underscore'); api.use('raix:[email protected]'); api.addFiles('lib/client/utils.js', 'client'); api.addFiles('lib/client/action_hub.js', 'client'); api.addFiles('lib/client/component.js', 'client'); api.addFiles('lib/client/component_instance.js', 'client'); api.addFiles('lib/client/api.js', 'client'); api.addFiles('lib/client/lookup.js', 'client'); api.addFiles('lib/client/render.js', 'client'); api.export(['FlowComponents']); });
JavaScript
0
@@ -63,9 +63,9 @@ .0.2 -5 +6 ',%0A
ca2bc50ddc847f5721cdbdeab4ec52fc3b24e8ba
remove exception generation in debug
src/foam/nanos/medusa/ClusterClientDAO.js
src/foam/nanos/medusa/ClusterClientDAO.js
/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.nanos.medusa', name: 'ClusterClientDAO', extends: 'foam.dao.ProxyDAO', documentation: `Marshall put and remove operations to the ClusterServer. `, implements: [ 'foam.nanos.boot.NSpecAware', ], javaImports: [ 'foam.core.ContextAware', 'foam.core.FObject', 'foam.core.X', 'foam.dao.DAO', 'foam.dao.DOP', 'foam.dao.MDAO', 'foam.nanos.logger.Logger', 'foam.nanos.logger.PrefixLogger', 'foam.nanos.pm.PM' ], properties: [ { name: 'nSpec', class: 'FObjectProperty', of: 'foam.nanos.boot.NSpec' }, { name: 'serviceName', class: 'String', javaFactory: ` if ( getNSpec() != null ) { return getNSpec().getName(); } return "na"; ` }, { name: 'clusterServiceName', class: 'String', value: 'cluster' }, { name: 'maxRetryAttempts', class: 'Int', documentation: 'Set to -1 to infinitely retry, 0 to not retry', value: 20 }, { class: 'Int', name: 'maxRetryDelay', value: 20000 }, { // TODO: clear on ClusterConfigDAO update. name: 'config', class: 'FObjectProperty', of: 'foam.nanos.medusa.ClusterConfig', javaFactory: ` ClusterConfigSupport support = (ClusterConfigSupport) getX().get("clusterConfigSupport"); return support.getConfig(getX(), support.getConfigId()); ` }, { name: 'logger', class: 'FObjectProperty', of: 'foam.nanos.logger.Logger', visibility: 'HIDDEN', javaFactory: ` return new PrefixLogger(new Object[] { this.getClass().getSimpleName(), getServiceName() }, (Logger) getX().get("logger")); ` } ], axioms: [ { buildJavaClass: function(cls) { cls.extras.push(` public ClusterClientDAO(foam.core.X x, String serviceName, ClusterConfig config) { setX(x); setServiceName(serviceName); setConfig(config); setMaxRetryAttempts(0); } `); } } ], methods: [ { name: 'put_', javaCode: ` return (FObject) submit(x, DOP.PUT, obj); ` }, { name: 'remove_', javaCode: ` return (FObject) submit(x, DOP.REMOVE, obj); ` }, { name: 'cmd_', javaCode: ` if ( obj instanceof ClusterCommand ) { getLogger().debug("cmd", "ClusterCommand"); return submit(x, DOP.CMD, (FObject) obj); } getLogger().debug("cmd", "delegate", obj.getClass().getSimpleName(), obj.toString(), new Exception("stackTrace")); return getDelegate().cmd_(x, obj); ` }, { name: 'submit', args: [ { name: 'x', type: 'Context' }, { name: 'dop', type: 'DOP' }, { name: 'obj', type: 'FObject' } ], type: 'Object', javaCode: ` ClusterConfigSupport support = (ClusterConfigSupport) x.get("clusterConfigSupport"); PM pm = PM.create(x, getClass().getSimpleName(), getServiceName(), dop); // REVIEW: set context to null after init so it's not marshalled across network. Periodically have contexts being marshalled ClusterCommand cmd = null; if ( obj instanceof ClusterCommand ) { cmd = (ClusterCommand) obj; } else { if ( obj instanceof ContextAware ) { ((ContextAware) obj).setX(null); } cmd = new ClusterCommand(x, getServiceName(), dop, obj); } cmd.addHop(x, dop, "send"); cmd.setX(null); int retryDelay = 10; try { while ( true ) { try { ClusterConfig serverConfig = support.getNextServer(); DAO dao = support.getClientDAO(x, getClusterServiceName(), getConfig(), serverConfig); getLogger().debug("submit", "request", "to", serverConfig.getId(), "dao", dao.getClass().getSimpleName(), dop.getLabel(), obj.getClass().getSimpleName()); Object result = null; if ( DOP.PUT == dop ) { result = dao.put_(x, cmd); } else if ( DOP.REMOVE == dop ) { result = dao.remove_(x, cmd); } else if ( DOP.CMD == dop ) { result = dao.cmd_(x, cmd); if ( result != null ) { // getLogger().debug("submit", "response", "from", serverConfig.getId(), "dao", dao.getClass().getSimpleName(), dop.getLabel(), result.getClass().getSimpleName()); return result; } } if ( obj instanceof ClusterCommand ) { // getLogger().debug("submit", "response", "from", serverConfig.getId(), "dao", dao.getClass().getSimpleName(), dop.getLabel(), (result != null ? result.getClass().getSimpleName() : "null")); cmd.setData((FObject) result); cmd.addHop(x, dop, "reply"); return cmd; } return result; } catch ( ClusterException e ) { getLogger().debug("submit", e.getClass().getSimpleName(), e.getMessage()); pm.error(x, e); throw e; } catch ( RuntimeException e ) { getLogger().debug("submit", e.getMessage()); pm.error(x, e); throw e; } catch ( Throwable t ) { getLogger().debug("submit", t.getMessage()); // getLogger().debug("submit", t); if ( getMaxRetryAttempts() > -1 && cmd.getRetry() >= getMaxRetryAttempts() ) { getLogger().debug("retryAttempt >= maxRetryAttempts", cmd.getRetry(), getMaxRetryAttempts()); pm.error(x, "Retry limit reached.", t); throw new RuntimeException("Rejected, retry limit reached.", t); } cmd.setRetry(cmd.getRetry() + 1); // delay try { retryDelay *= 2; if ( retryDelay > getMaxRetryDelay() ) { retryDelay = 10; } getLogger().debug("retry attempt", cmd.getRetry(), "delay", retryDelay); Thread.sleep(retryDelay); } catch(InterruptedException e) { Thread.currentThread().interrupt(); getLogger().debug("InterruptedException"); pm.error(x, t); throw t; } } } } finally { pm.log(x); } ` }, { name: 'find_', javaCode: ` throw new ClusterException("Unsupported operation: "+DOP.FIND.getLabel(), new UnsupportedOperationException(DOP.FIND.getLabel())); ` }, { name: 'select_', javaCode: ` throw new ClusterException("Unsupported operation: "+DOP.SELECT.getLabel(), new UnsupportedOperationException(DOP.SELECT.getLabel())); ` }, { name: 'removeAll_', javaCode: ` throw new ClusterException("Unsupported operation: "+DOP.REMOVE_ALL.getLabel(), new UnsupportedOperationException(DOP.REMOVE_ALL.getLabel())); ` }, ] });
JavaScript
0.000001
@@ -2740,37 +2740,8 @@ ng() -, new Exception(%22stackTrace%22) );%0A
ce2c2830b91f948d7f08b9e2df8f44094e97ab0a
Change test
src/client/app/people/people.controller.spec.js
src/client/app/people/people.controller.spec.js
/* jshint -W117, -W030 */ describe('PeopleController', function() { var controller; var people = mockData.getMockPeople(); console.debug(people); beforeEach(function() { bard.appModule('app.people'); bard.inject('$controller', '$log', '$q', '$rootScope'); var ds = { getPeople: function() { return $q.when(people); } }; controller = $controller('PeopleController',{ dataservice: ds }); }); it('should exist',function() { expect(controller).to.exist; }); it('should have empty people array before activation',function() { expect(controller.people).to.exist; }); it('should have people after activation',function() { $rootScope.$apply; expect(controller.people).to.have.length.above(0); }); it('should have mock people after activation',function() { $rootScope.$apply; expect(controller.people).to.have.length(people.length); }); });
JavaScript
0.000002
@@ -962,22 +962,22 @@ ngth -(people.length +.of.at.least(1 );%0A
660cd165a1256cbfefc826d6af5f9081498d52a1
Update library
js/jquery.sparql.js
js/jquery.sparql.js
(function( $ ) { $.fn.query = function(query ,options) { if (options) { var opts = $.extend( {}, $.fn.defaults, options); $.fn.defaults = opts; } query = this.prefixesAsString() + query; var json_string = $.ajax( { url: $.fn.defaults.source+"query", data: {"query":query,"output":"json"}, type: "GET", async: false, dataType: 'json' } ).responseText; if (json_string.indexOf('Error') == -1) { var json = $.parseJSON(json_string); return json.results.bindings; } //ERROR return {"error":true,"response":json_string}; //evenutally parse code and other data } $.fn.verbsForObject = function (object) { var results = $(this).query('SELECT distinct ?v where {'+object+' ?v ?o.}'); var verbs = new Array(); for (i = 0; i < results.length; i++) { verbs.push(results[i].v); } return verbs; } $.fn.resolvePrefix = function (str) { for (i = 0; i < $.fn.defaults.prefixes.length; i++) { var prefix = $.fn.defaults.prefixes[i]; if (str.indexOf(prefix.value) == 0) { return prefix.prefix+str.substr(prefix.value.length); } } return str; } $.fn.prefixesAsString = function () { var str = ""; $.each($.fn.defaults.prefixes, function (key, value) { str += "prefix "+key+" <"+value+"> "; }); return str; } // $.fn.query.prefixString = function() { // } // Plugin defaults $.fn.defaults = { "source":"http://localhost:3030/ds/", //Defualt source to use out of the sources "prefix":"prefix cts: <http://www.homermultitext.org/cts/rdf/> prefix cite: <http://www.homermultitext.org/cite/rdf/> prefix hmt: <http://www.homermultitext.org/hmt/rdf/> prefix citedata: <http://www.homermultitext.org/hmt/citedata/> prefix dcterms: <http://purl.org/dc/terms/> prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> prefix xsd: <http://www.w3.org/2001/XMLSchema#> prefix olo: <http://purl.org/ontology/olo/core#>", "prefixes":{ 'cts:':'http://www.homermultitext.org/cts/rdf/', 'cite:': 'http://www.homermultitext.org/cite/rdf/', 'hmt:': 'http://www.homermultitext.org/hmt/rdf/', 'citedata:': 'http://www.homermultitext.org/hmt/citedata/', 'dcterms:':'http://purl.org/dc/terms/', 'rdf:':'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'olo:':'http://purl.org/ontology/olo/core#' } }; }( jQuery ));
JavaScript
0.000001
@@ -291,16 +291,8 @@ urce -+%22query%22 , %0A%09
23ef6099d9a1044169d6ae8cf5ad79b77af1e7e6
Remove comment
config/webpack.prod.js
config/webpack.prod.js
// This file is not used in production. /* eslint-disable import/no-extraneous-dependencies */ const path = require('path'); const autoprefixer = require('autoprefixer'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: './src/index.js', context: path.resolve(__dirname, '..'), output: { filename: 'gypcrete.js', path: path.resolve(__dirname, '../dist'), library: 'gypcrete' }, module: { rules: [ { test: /\.jsx?$/, include: [ path.resolve(__dirname, '../src') ], use: ['babel-loader'] }, { test: /\.scss$/, include: [ path.resolve(__dirname, '../src') ], use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { importLoaders: 1 } }, { loader: 'postcss-loader', options: { plugins: () => [autoprefixer] } }, { loader: 'sass-loader', options: { outputStyle: 'expanded' } } ] }) }, { test: /\.(woff|woff2|otf|ttf|eot|svg)$/, include: [ path.resolve(__dirname, '../src/fonts') ], use: [ { loader: 'file-loader', options: { name: '[name]-[hash:6].[ext]', outputPath: 'fonts/', publicPath: 'fonts/' } } ] } ] }, plugins: [ new ExtractTextPlugin('gypcrete.css') ], externals: { react: 'React' } };
JavaScript
0
@@ -1,44 +1,4 @@ -// This file is not used in production.%0A /* e @@ -48,17 +48,16 @@ cies */%0A -%0A const pa
fb27f9e123428843625784ddfcbe1cfb9663fa12
Bump version.
package.js
package.js
Package.describe({ summary: "Client side uploads for meteor/s3 using signed uploads for meteorjs.", version: "0.1.7-rc.1", git: "https://github.com/jimmiebtlr/meteor-s3-signed-upload.git" }); Package.on_use(function(api){ api.use(['mrt:[email protected]'],'server'); api.use(['aldeed:[email protected]']); api.export(['uploadFile'],'client'); api.export(['S3SignedUploadTmp'],'server'); api.add_files([ 'client.js' ], 'client'); api.add_files([ 'server.js' ], 'server'); });
JavaScript
0
@@ -116,17 +116,17 @@ .1.7-rc. -1 +2 %22,%0A git
36a41fdd15bb9df99941b7eae24292e3c194b56d
Update strategy.js
lib/passport-fitbit/strategy.js
lib/passport-fitbit/strategy.js
/** * Module dependencies. */ var util = require('util') , OAuthStrategy = require('passport-oauth').OAuthStrategy , InternalOAuthError = require('passport-oauth').InternalOAuthError; /** * `Strategy` constructor. * * The Fitbit authentication strategy authenticates requests by delegating to * Fitbit using the OAuth protocol. * * Applications must supply a `verify` callback which accepts a `token`, * `tokenSecret` and service-specific `profile`, and then calls the `done` * callback supplying a `user`, which should be set to `false` if the * credentials are not valid. If an exception occured, `err` should be set. * * Options: * - `consumerKey` identifies client to Fitbit * - `consumerSecret` secret used to establish ownership of the consumer key * - `callbackURL` URL to which Fitbit will redirect the user after obtaining authorization * * Examples: * * passport.use(new FitbitStrategy({ * consumerKey: '123-456-789', * consumerSecret: 'shhh-its-a-secret' * callbackURL: 'https://www.example.net/auth/fitbit/callback' * }, * function(token, tokenSecret, profile, done) { * User.findOrCreate(..., function (err, user) { * done(err, user); * }); * } * )); * * @param {Object} options * @param {Function} verify * @api public */ function Strategy(options, verify) { options = options || {}; options.requestTokenURL = options.requestTokenURL || 'https://api.fitbit.com/oauth/request_token'; options.accessTokenURL = options.accessTokenURL || 'https://api.fitbit.com/oauth/access_token'; options.userAuthorizationURL = options.userAuthorizationURL || 'https://api.fitbit.com/oauth/authorize'; options.sessionKey = options.sessionKey || 'oauth:fitbit'; OAuthStrategy.call(this, options, verify); this.name = 'fitbit'; } /** * Inherit from `OAuthStrategy`. */ util.inherits(Strategy, OAuthStrategy); /** * Retrieve user profile from Fitbit. * * This function constructs a normalized profile, with the following properties: * * - `id` * - `displayName` * * @param {String} token * @param {String} tokenSecret * @param {Object} params * @param {Function} done * @api protected */ Strategy.prototype.userProfile = function(token, tokenSecret, params, done) { this._oauth.get('https://api.fitbit.com/1/user/-/profile.json', token, tokenSecret, function (err, body, res) { if (err) { return done(new InternalOAuthError('failed to fetch user profile', err)); } try { var json = JSON.parse(body); var profile = { provider: 'fitbit' }; profile.id = json.user.encodedId; profile.displayName = json.user.displayName; profile._raw = body; profile._json = json; done(null, profile); } catch(e) { done(e); } }); } /** * Expose `Strategy`. */ module.exports = Strategy;
JavaScript
0.000001
@@ -1691,35 +1691,35 @@ URL %7C%7C 'https:// -api +www .fitbit.com/oaut
95c0da7836c1bb30ad825f0c7fed5ba09ccd15c5
Fix postcss-loader not working due to ExtractTextPlugin syntax error
config/webpack/prod.js
config/webpack/prod.js
var path = require('path'); var webpack = require('webpack'); var postcssAssets = require('postcss-assets'); var postcssNext = require('postcss-cssnext'); var stylelint = require('stylelint'); var ManifestPlugin = require('webpack-manifest-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var config = { bail: true, resolve: { root: path.resolve(__dirname), extensions: ['', '.ts', '.tsx', '.js', '.jsx'] }, entry: { app: './src/client.tsx', vendor: [ './src/vendor/main.ts', 'react', 'react-dom', 'react-router', 'react-helmet', 'react-redux', 'react-router-redux', 'redux', 'redux-connect', 'redux-thunk' ] }, output: { path: path.resolve('./build/public'), publicPath: '/public/', filename: 'js/[name].[chunkhash].js' }, module: { preLoaders: [ { test: /\.tsx?$/, loader: 'tslint' } ], loaders: [ { test: /\.tsx?$/, loader: 'ts-loader' }, { test: /\.jsx$/, loader: 'babel?presets[]=es2015' }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.css$/, include: path.resolve('./src/app'), loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]', 'postcss-loader' ) }, { test: /\.css$/, exclude: path.resolve('./src/app'), loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader' ) }, { test: /\.eot(\?.*)?$/, loader: 'file?name=fonts/[hash].[ext]' }, { test: /\.(woff|woff2)(\?.*)?$/, loader: 'file-loader?name=fonts/[hash].[ext]' }, { test: /\.ttf(\?.*)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream&name=fonts/[hash].[ext]' }, { test: /\.svg(\?.*)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml&name=fonts/[hash].[ext]' }, { test: /\.(jpe?g|png|gif)$/i, loader: 'url?limit=1000&name=images/[hash].[ext]' } ] }, postcss: function () { return [ stylelint({ files: '../../src/app/*.css' }), postcssNext(), postcssAssets({ relative: true }) ]; }, tslint: { failOnHint: true }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'js/[name].[chunkhash].js', minChunks: Infinity }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new ExtractTextPlugin('css/[name].[hash].css'), new ManifestPlugin({ fileName: '../manifest.json' }), new webpack.DefinePlugin({ 'process.env': { BROWSER: JSON.stringify(true), NODE_ENV: JSON.stringify('production') } }) ] }; module.exports = config;
JavaScript
0
@@ -1331,33 +1331,37 @@ 'style-loader', -%0A + %5B%0A 'css-l @@ -1453,16 +1453,18 @@ + 'postcss @@ -1464,32 +1464,44 @@ postcss-loader'%0A + %5D%0A )%0A @@ -1647,27 +1647,18 @@ loader', -%0A +%5B 'css-loa @@ -1653,32 +1653,33 @@ ', %5B'css-loader' +%5D %0A )%0A
7e2bf12307b552cdd10ae5ced7edbf9da6787f8b
Configure the size of the conkeror completions buffer
conkeror/conkerorrc.js
conkeror/conkerorrc.js
// Load URLs from the command line in new buffers instead of new // windows. url_remoting_fn = load_url_in_new_buffer; // Load download buffers in the background in the current window, // instead of in new windows. download_buffer_automatic_open_target = OPEN_NEW_BUFFER_BACKGROUND; // Automatically follow unambiguous links hints_auto_exit_delay = 500; hints_ambiguous_auto_exit_delay = 0; // Display properties of the current selected node during // the hints interaction. hints_display_url_panel = true; // Default directory for downloads and shell commands. cwd = get_home_directory(); cwd.append("download"); // Automatically handle some MIME types internally. content_handlers.set("application/pdf", content_handler_save); // External programs for handling various MIME types. external_content_handlers.set("application/pdf", "xpdf"); //external_content_handlers.set("video/*", "urxvtc -e mplayer"); // External editor, Emacs of course. editor_shell_command = "e -c --wait"; // View source in your editor. view_source_use_external_editor = true; // Auto-completion options when using find-url url_completion_use_history = true; url_completion_use_bookmarks = true; url_completion_use_webjumps = true;
JavaScript
0.000001
@@ -1201,16 +1201,100 @@ ebjumps = true;%0A +%0A// Other options%0Aminibuffer_completion_rows = 30; // size of the completion buffer%0A
d60bc7a0003f96ac3983eb2045f6cbfab4e3dc19
add new rows after last row
js/app/sai/editor.js
js/app/sai/editor.js
/*jslint browser: true, eqeq: true, white: true, plusplus: true */ /*global angular, console, alert*/ (function () { 'use strict'; var app = angular.module('keira2'); app.controller("SmartAIEditorController", function ($scope, $rootScope, $stateParams) { /* At start we have no row selected */ $scope.selectedRow = -1; /* Show only basic informations */ $scope.showBasicInformations = true; /* Default new row */ $scope.defaultNewRow = { entryorguid : parseInt($stateParams.entryOrGuid, 10), source_type : parseInt($stateParams.sourceType, 10), id : 0, link : 0, event_type : 0, event_phase_mask : 0, event_chance : 100, event_flags : 0, event_param1 : 0, event_param2 : 0, event_param3 : 0, event_param4 : 0, action_type : 0, action_param1 : 0, action_param2 : 0, action_param3 : 0, action_param4 : 0, action_param5 : 0, action_param6 : 0, target_type : 0, target_param1 : 0, target_param2 : 0, target_param3 : 0, target_x : 0.0, target_y : 0.0, target_z : 0.0, target_o : 0.0, comment : '' }; /* Type check */ $scope.parseValues = function() { $scope.selected.id = parseInt($scope.selected.id, 10); $scope.selected.link = parseInt($scope.selected.link, 10); $scope.selected.event_type = parseInt($scope.selected.event_type, 10); $scope.selected.event_phase_mask = parseInt($scope.selected.event_phase_mask, 10); $scope.selected.event_chance = parseInt($scope.selected.event_chance, 10); $scope.selected.event_flags = parseInt($scope.selected.event_flags, 10); $scope.selected.event_param1 = parseInt($scope.selected.event_param1, 10); $scope.selected.event_param2 = parseInt($scope.selected.event_param2, 10); $scope.selected.event_param3 = parseInt($scope.selected.event_param3, 10); $scope.selected.event_param4 = parseInt($scope.selected.event_param4, 10); $scope.selected.action_type = parseInt($scope.selected.action_type, 10); $scope.selected.action_param1 = parseInt($scope.selected.action_param1, 10); $scope.selected.action_param2 = parseInt($scope.selected.action_param2, 10); $scope.selected.action_param3 = parseInt($scope.selected.action_param3, 10); $scope.selected.action_param4 = parseInt($scope.selected.action_param4, 10); $scope.selected.action_param5 = parseInt($scope.selected.action_param5, 10); $scope.selected.action_param6 = parseInt($scope.selected.action_param6, 10); $scope.selected.target_type = parseInt($scope.selected.target_type, 10); $scope.selected.target_param1 = parseInt($scope.selected.target_param1, 10); $scope.selected.target_param2 = parseInt($scope.selected.target_param2, 10); $scope.selected.target_param3 = parseInt($scope.selected.target_param3, 10); $scope.selected.target_x = parseFloat($scope.selected.target_x, 10); $scope.selected.target_y = parseFloat($scope.selected.target_y, 10); $scope.selected.target_z = parseFloat($scope.selected.target_z, 10); $scope.selected.target_o = parseFloat($scope.selected.target_o, 10); }; /* Select and edit a row from collection */ $scope.selectRow = function(rows, index) { $scope.selectedRow = index; $scope.selected = rows[index]; }; /* Delete selected row from collection */ $scope.deleteSelectedRowFrom = function(rows) { if (!$rootScope.isEntrySelected()) { return; } rows.splice($scope.selectedRow, 1); }; /* Add a new row to collection */ $scope.addNewRow = function(rows) { if (!$rootScope.isEntrySelected()) { return; } var newRow = angular.copy($scope.defaultNewRow); newRow.id = rows.length; rows.splice(0, 0, angular.copy(newRow)); }; }); }());
JavaScript
0.000026
@@ -4184,17 +4184,27 @@ .splice( -0 +rows.length , 0, ang
f7ae50457a18b109da51485ac9e0f39f0695108b
add 5 second delay
lib/plugins/offline-messages.js
lib/plugins/offline-messages.js
/** * Automatically removes and emits 'message:info' events * for all pending chat messages. * * Use this plugin if you want to get rid of pending notifications * related to offline messages. * @example * bot.use(vapor.plugins.offlineMessages); * @param {Object} VaporAPI Instance of the API class. * @module */ var ByteBuffer = require('bytebuffer'); var util = require('util'); exports.name = 'offline-messages'; exports.plugin = function(VaporAPI) { var client = VaporAPI.getClient(); var Steam = VaporAPI.getSteam(); var utils = VaporAPI.getUtils(); // Handle 'ready' event VaporAPI.registerHandler({ emitter: 'vapor', event: 'ready' }, function() { client.send({ msg: Steam.EMsg.ClientFSGetFriendMessageHistoryForOfflineMessages, proto: {} }, new Steam.Internal.CMsgClientFSGetFriendMessageHistoryForOfflineMessages().toBuffer() ); } ); // Handle 'ClientFSGetFriendMessageHistoryResponse' EMsg VaporAPI.registerHandler({ emitter: 'client', event: 'message' }, function(header, body) { if(header.msg === Steam.EMsg.ClientFSGetFriendMessageHistoryResponse) { var data = ByteBuffer.wrap(body, ByteBuffer.LITTLE_ENDIAN); var response = Steam.Internal.CMsgClientFSGetFriendMessageHistoryResponse.decode(data); var unreadMessages = response.messages.filter(function(message) { return message.unread; }); VaporAPI.emitEvent('message:info', '# of pending chat messages: ' + unreadMessages.length); unreadMessages.forEach(function(message) { var sid = utils.accountIDToSteamID(message.accountid); var user = utils.getUserDescription(sid); var messageText = util.format('[%s] %s said: %s', utils.getTimestamp(message.timestamp), user, message.message ); VaporAPI.emitEvent('message:info', messageText); }); } } ); };
JavaScript
0.000001
@@ -717,24 +717,64 @@ unction() %7B%0A + setTimeout(function() %7B%0A @@ -807,16 +807,20 @@ + + msg: Ste @@ -898,16 +898,20 @@ + proto: %7B @@ -912,16 +912,20 @@ oto: %7B%7D%0A + @@ -951,16 +951,20 @@ + new Stea @@ -1053,16 +1053,42 @@ + );%0A %7D, 5000 );%0A
8d699be7f38eedb9dcc95be5ab7635606b2b0c8e
patch release - Bump to version 1.4.1
package.js
package.js
Package.describe({ summary: "Accounts Templates styled for Zurb Foundation.", version: "1.4.0", name: "useraccounts:foundation", git: "https://github.com/meteor-useraccounts/foundation.git", }); Package.on_use(function(api, where) { api.versionsFrom("[email protected]"); api.use([ "less", "templating", ], "client"); api.use([ "useraccounts:core", ], ["client", "server"]); api.imply([ "useraccounts:[email protected]", ], ["client", "server"]); api.add_files([ "lib/at_error.html", "lib/at_error.js", "lib/at_form.html", "lib/at_form.js", "lib/at_input.html", "lib/at_input.js", "lib/at_nav_button.html", "lib/at_nav_button.js", "lib/at_oauth.html", "lib/at_oauth.js", "lib/at_pwd_form.html", "lib/at_pwd_form.js", "lib/at_pwd_form_btn.html", "lib/at_pwd_form_btn.js", "lib/at_pwd_link.html", "lib/at_pwd_link.js", "lib/at_result.html", "lib/at_result.js", "lib/at_sep.html", "lib/at_sep.js", "lib/at_signin_link.html", "lib/at_signin_link.js", "lib/at_signup_link.html", "lib/at_signup_link.js", "lib/at_social.html", "lib/at_social.js", "lib/at_terms_link.html", "lib/at_terms_link.js", "lib/at_title.html", "lib/at_title.js", "lib/full_page_at_form.html", "lib/at_foundation.less" ], ["client"]); }); Package.on_test(function(api) { api.use([ "useraccounts:foundation", "useraccounts:[email protected]", ]); api.use([ "accounts-password", "tinytest", "test-helpers" ], ["client", "server"]); api.add_files([ "tests/tests.js" ], ["client", "server"]); });
JavaScript
0
@@ -89,25 +89,25 @@ rsion: %221.4. -0 +1 %22,%0A name: @@ -464,33 +464,33 @@ counts:[email protected]. -0 +1 %22,%0A %5D, %5B%22clie @@ -1643,17 +1643,17 @@ [email protected]. -0 +1 %22,%0A %5D
f1b3d2fa22e01f1dbde0761795ecf17e4324a22c
allow css sister file for a knockout component [TASK-887] this was useful for refactoring the RESKE search tabs to isolate styles but still use the plugin component loader.
src/client/modules/app/services/ko-component.js
src/client/modules/app/services/ko-component.js
define([ 'require', 'promise' ], function ( require, Promise ) { 'use strict'; function factory(config) { var runtime = config.runtime; var components = {}; function start() { return true; } function stop() { return true; } function pluginHandler(serviceConfig, pluginConfig) { return Promise.try(function () { return Promise.all(serviceConfig.map(function (componentConfig) { // keep a map of loaded components if (components[componentConfig.name]) { throw new Error('Component already loaded "' + componentConfig.name); } // simply require the module to register the component, or components. // oops, that would break the model... return new Promise(function (resolve, reject) { var modulePath = [pluginConfig.moduleRoot, componentConfig.module].join('/'); require([modulePath], function (result) { resolve(result); }, function (err) { reject(err); }); }); })); }); } return { // lifecycle interface start: start, stop: stop, // plugin interface pluginHandler: pluginHandler }; } return { make: function (config) { return factory(config); } }; });
JavaScript
0
@@ -996,19 +996,65 @@ dulePath +s = +%5B%5D;%0A modulePaths.push( %5BpluginC @@ -1104,18 +1104,212 @@ oin('/') +) ;%0A + if (componentConfig.css) %7B%0A modulePaths.push('css!' + %5BpluginConfig.moduleRoot, componentConfig.module%5D.join('/'));%0A %7D%0A @@ -1332,17 +1332,16 @@ require( -%5B modulePa @@ -1342,17 +1342,17 @@ dulePath -%5D +s , functi @@ -1889,8 +1889,9 @@ %7D;%0A%7D); +%0A
5786efaaf14300f73ae5e253902fec24756b4db0
Use my own CDN
js/index.js
js/index.js
import "babel-polyfill"; import React from "react"; import { render } from "react-dom"; import { Provider } from "react-redux"; import getStore from "./store"; import WindowManager from "./components/WindowManager"; import Browser from "./browser"; import MainWindow from "./components/MainWindow"; import PlaylistWindow from "./components/PlaylistWindow"; import EqualizerWindow from "./components/EqualizerWindow"; import Winamp from "./winamp"; import Hotkeys from "./hotkeys"; import Skin from "./components/Skin"; if (new Browser(window).isCompatible) { const hash = window.location.hash; // Turn on the incomplete playlist window const playlist = hash.includes("playlist"); // Turn on the incomplete equalizer window const equalizer = hash.includes("equalizer"); const winamp = Winamp; const store = getStore(winamp); render( <Provider store={store}> <div> <Skin> {/* This is not technically kosher, since <style> tags should be in the <head>, but browsers don't really care... */} </Skin> <WindowManager> <MainWindow fileInput={winamp.fileInput} mediaPlayer={winamp.media} /> {playlist && <PlaylistWindow />} {equalizer && <EqualizerWindow fileInput={winamp.fileInput} />} </WindowManager> </div> </Provider>, document.getElementById("winamp2-js") ); winamp.dispatch = store.dispatch; const cdnUrl = "https://cdn.rawgit.com/captbaritone/winamp2-js/master/"; const assetBase = process.env.NODE_ENV === "production" ? cdnUrl : ""; winamp.init({ volume: 50, balance: 0, mediaFile: { url: `${assetBase}mp3/llama-2.91.mp3`, name: "1. DJ Mike Llama - Llama Whippin' Intro" }, skinUrl: `${assetBase}skins/base-2.91.wsz` }); new Hotkeys(winamp, store); } else { document.getElementById("winamp").style.display = "none"; document.getElementById("browser-compatibility").style.display = "block"; }
JavaScript
0
@@ -1447,35 +1447,46 @@ s:// -cdn.rawgit.com/captbaritone +d38dnrh1liu4f5.cloudfront.net/projects /win @@ -1497,15 +1497,8 @@ -js/ -master/ %22;%0A
62c792183eba411ad71e5d3a14adc138b98afea9
debug line for missing streaming client
lib/websocket/transports/engineio/index.js
lib/websocket/transports/engineio/index.js
// Engine.IO server-side wrapper 'use strict'; var fs = require('fs'), http = require('http'); var openSocketsById = {}; module.exports = function(ss, messageEmitter, config){ config = config || {}; config.server = config.server || {}; config.client = config.client || {}; // Send Engine.IO client-side code var clientPath = ss.require.resolve('engine.io-client/engine.io.js', { warn:'Please add "engine.io-client" as an npm dependency'}); if (clientPath) { var engineioClient = fs.readFileSync(clientPath, 'utf8'); ss.client.send('lib', 'engine.io-client', engineioClient, {minified: false}); // tested this with minified: true ; worked fine. } // Send socketstream-transport module var code = fs.readFileSync(__dirname + '/wrapper.js', 'utf8'); ss.client.send('mod', 'socketstream-transport', code); // Tell the SocketStream client to use this transport, passing any client-side config along to the wrapper ss.client.send('code', 'transport', "require('socketstream').assignTransport(" + JSON.stringify(config.client) + ");"); // Return API for sending events // Note the '0' message prefix (which signifies the responderId) is reserved for sending events var api = { get server() { if (!this._server) { this._server = http.createServer(function(req,res) { return ss.http.middleware(req,res); }); // Create a new Engine.IO server and bind to /ws var engine = ss.require('engine.io'), ws = this.ws = engine.attach(this._server, config.server); // Handle incoming connections ws.on('connection', onConnection); } return this._server; }, event: eventFn }; return api; function onConnection(socket) { var sessionId = ss.session.extractSocketSessionId(socket.request); if (sessionId) { socket.sessionId = sessionId; // Store this here before it gets cleaned up after the websocket upgrade socket.remoteAddress = socket.request.connection.remoteAddress; // Get real IP if behind proxy var xForwardedFor = socket.request.headers['x-forwarded-for']; if (xForwardedFor) { socket.remoteAddress = xForwardedFor.split(',')[0]; } // Allow this connection to be addressed by the socket ID openSocketsById[socket.id] = socket; ss.session.find(socket.sessionId, socket.id, function(session){ socket.send('X|OK'); }); // changed from data socket.on('message', function(msg) { try { var i,responderId,content,meta; if ( (i = msg.indexOf('|')) > 0) { responderId = msg.substr(0, i); content = msg.substr(i+1); } else { throw('Message does not contain a responderId');} meta = {socketId: socket.id, sessionId: socket.sessionId, clientIp: socket.remoteAddress, transport: 'engineio'}; // Invoke the relevant Request Responder, passing a callback function which // will automatically direct any response back to the correct client-side code messageEmitter.emit(responderId, content, meta, function(data){ return socket.send(responderId + '|' + data); }); } catch (e) { ss.log.error('Invalid websocket message received:', msg); } }); // If the browser disconnects, remove this connection from openSocketsById socket.on('close', function() { if(openSocketsById[socket.id]) { delete openSocketsById[socket.id]; } }); } } function eventFn() { return { // Send the same message to every open socket all: function(msg) { for (var id in openSocketsById) { if (openSocketsById.hasOwnProperty(id)) { openSocketsById[id].send('0|' + msg + '|null'); } } }, // Send an event to a specific socket // Note: 'meta' is typically the name of the channel socketId: function(id, msg, meta) { var socket = openSocketsById[id]; if (socket) { return socket.send('0|' + msg + '|' + meta); } else { return false; } } } } }
JavaScript
0.000001
@@ -664,24 +664,107 @@ ed fine.%0A %7D + else %7B%0A debug('Streaming will not work without the clientside transport.');%0A %7D %0A%0A // Send
1d1646cb770dd97340c5644ebac6de81c1c62aa4
Bump version number.
package.js
package.js
Package.describe({ summary: "Send e-mails with attachments.", version: "1.0.8", git: "www.github.com/priyadarshy/email-att" }); Package.on_use(function(api) { api.versionsFrom('[email protected]'); api.addFiles('ashutosh:email-att.js'); }); Package.on_test(function(api) { api.use('tinytest'); api.use('ashutosh:email-att'); api.addFiles('ashutosh:email-att-tests.js'); }); Npm.depends({ "simplesmtp": "0.3.10", "stream-buffers": "0.2.5", "mailcomposer": "0.1.15" });
JavaScript
0
@@ -81,9 +81,9 @@ 1.0. -8 +9 %22,%0A @@ -130,24 +130,131 @@ l-att%22%0A%7D);%0A%0A +Npm.depends(%7B%0A %22simplesmtp%22: %220.3.10%22,%0A %22stream-buffers%22: %220.2.5%22,%0A %22mailcomposer%22: %220.1.15%22%0A%7D);%0A%0A Package.on_u @@ -510,110 +510,4 @@ );%0A%0A -Npm.depends(%7B%0A %22simplesmtp%22: %220.3.10%22,%0A %22stream-buffers%22: %220.2.5%22,%0A %22mailcomposer%22: %220.1.15%22%0A%7D);%0A
c2f45672d998ea216f19a0ad8d13b641d7967fe5
Add function stopAnime() to stop animations
Animable.js
Animable.js
/** * Animable.js * * https://github.com/JWhile/Animable.js * * version 1.0.0 */ var anime; (function(){ // namespace // class Animation function Animation(id, from, to, time, update) { this.id = id; // :int this.from = from; // :float this.diff = to - from; // :float this.start = Date.now(); // :long this.time = time; // :int this.update = update; // :function } // function next(long now):boolean Animation.prototype.next = function(now) { var n = (now - this.start) / this.time; if(n >= 1) { this.update(this.diff + this.from); return true; } this.update(n * this.diff + this.from); return false; }; var lastAnimId = 0; // :int var animations = []; // :Array<Animation> var loop = false; // :boolean // function next():void var next = function() { loop = (animations.length > 0); if(loop) { newFrame(next); var now = Date.now(); for(var i = 0; i < animations.length; ++i) { if(animations[i].next(now)) { animations.splice(i, 1); --i; } } } }; // function anime(function update, float from, float to, int time):int anime = function(update, from, to, time) { animations.push(new Animation(++lastAnimId, from, to, time, update)); if(!loop) { newFrame(next); } return lastAnimId; }; if(typeof Builder === 'function') { // function anime(String property, int to, int time, function callback = null):@Chainable Builder.prototype.anime = function(property, to, time, callback) { var self = this; var style = Builder.getStyle(this.node, property); var unit = (style.match(/em$|px$|%$/i) || [''])[0]; anime(function(value) { if(value === to) { if(callback != null) { callback(); } } self.node.style[property] = value + unit; }, parseInt(style), to, time); return this; }; } })();
JavaScript
0.000004
@@ -90,16 +90,26 @@ ar anime +,stopAnime ;%0A%0A(func @@ -1429,16 +1429,252 @@ Id;%0A%7D;%0A%0A +// function stopAnime(int id):void%0AstopAnime = function(id)%0A%7B%0A for(var i = 0; i %3C animations.length; ++i)%0A %7B%0A if(animations%5Bi%5D.id === id)%0A %7B%0A animations.splice(i, 1);%0A%0A --i;%0A %7D%0A %7D%0A%7D;%0A%0A if(typeo
d1720eec6054afe091ed4c3176a7355ff0f460b3
Fix __tests__/sceanrio-map/transit-editor/stop-layer.js code so it passes standard lin
__tests__/scenario-map/transit-editor/stop-layer.js
__tests__/scenario-map/transit-editor/stop-layer.js
/* global describe, it, expect, jest */ import { mount } from 'enzyme' import React from 'react' import { Map } from 'react-leaflet' import Leaflet from '../../../test-utils/mock-leaflet' import { mockStops } from '../../../test-utils/mock-data.js' import StopLayer from '../../../lib/scenario-map/transit-editor/stop-layer' describe('Component > Transit-Editor > StopLayer', () => { it('renders correctly', () => { const props = { stops: mockStops } // mount component mount( <Map> <StopLayer {...props} /> </Map> , { attachTo: document.getElementById('test') } ) Leaflet // not sure how to assert }) })
JavaScript
0.000003
@@ -19,22 +19,8 @@ , it -, expect, jest */%0A
d6d31d151bc0829dbecad800c542f2eeb73cf6d6
Add appropriate event handling to "Search" button.
ode/public/js/search.js
ode/public/js/search.js
// Models var SearchTarget = Backbone.Model.extend({ defaults: { features: new Backbone.Collection([]), strings: new Backbone.Collection([]), }, addFeatures: function(names) { _.each(names, function(n) { this.get('features').add(new Feature({ name: n })); }, this); }, addStrings: function(strings) { _.each(strings, function(s) { this.get('strings').add(new String({ content: s })); }, this); }, search: function() { alert('Pretending to do some serious searching ...'); }, }); var Feature = Backbone.Model.extend({ defaults: { value: '' } }); var String = Backbone.Model.extend({}); // Views var SearchTargetView = Backbone.View.extend({ render: function() { this._addFeatureField(); this._addStringField(); return this; }, _addFeatureField: function() { this._addSearchField('#features'); }, _addStringField: function() { this._addSearchField('#strings'); }, _addSearchField: function(blockID) { var searchField = $.div('search-field col-md-11'); searchField.append($.textInput()); this.$(blockID).append(searchField); var controls = $.div('controls col-md-1'); controls.append($.plusButton()); this.$(blockID).append(controls); }, events: { 'click #search-button': '_performSearch', }, _performSearch: function() { var searchFeatures = this._getSearchParams('#features'); this.model.addFeatures(searchFeatures); var searchStrings = this._getSearchParams('#strings'); this.model.addStrings(searchStrings); this.model.search(); }, _getSearchParams: function(blockID) { return _.map(this.$(blockID).find('input'), function(field) { return $(field).val(); }); }, }); // Application $(document).ready(function() { var searchTarget = new SearchTarget(); var searchTargetView = new SearchTargetView({ model: searchTarget, el: '.container-full', }); searchTargetView.render(); });
JavaScript
0
@@ -214,24 +214,247 @@ nction(n) %7B%0A + if (n.match(/%5E%3C.+%3E.*/i)) %7B%0A var name = n.slice(1, n.indexOf('%3E'));%0A var value = n.slice(n.indexOf('%3E') + 1);%0A this.get('features').add(new Feature(%7B name: name, value: value %7D));%0A %7D else %7B%0A this.g @@ -495,24 +495,32 @@ ame: n %7D));%0A + %7D%0A %7D, this)
0f32ffd59ddfbe14f7384cfa1431b5c76ee22a3e
hasFetchTrades = false
js/coinexchangeio.js
js/coinexchangeio.js
"use strict"; // --------------------------------------------------------------------------- const Exchange = require ('./base/Exchange'); const { ExchangeError } = require ('./base/errors'); // --------------------------------------------------------------------------- module.exports = class coinexchangeio extends Exchange { describe () { return this.deepExtend (super.describe (), { 'id': 'coinexchangeio', 'name': 'CoinExchange.io', 'countries': '', 'rateLimit': 1000, // obsolete metainfo interface 'hasPrivateAPI': false, 'hasFetchCurrencies': true, 'hasFetchTickers': true, // new metainfo interface 'has': { 'fetchCurrencies': true, 'fetchTickers': true, }, 'urls': { 'logo': 'https://www.coinexchange.io/assets/images/logo_new_3.png', 'api': 'https://www.coinexchange.io/api/v1', 'www': 'https://www.coinexchange.io/', 'doc': 'https://coinexchangeio.github.io/slate/', 'fees': 'https://www.coinexchange.io/fees', }, 'api': { 'public': { 'get': [ 'getcurrency', 'getcurrencies', 'getmarkets', 'getmarketsummaries', 'getmarketsummary', 'getorderbook', ], }, }, 'fees': { 'trading': { 'maker': 0.0015, 'taker': 0.0015, }, }, 'precision': { 'amount': 8, 'price': 8, }, }); } commonCurrencyCode (currency) { return currency; } async fetchCurrencies (params = {}) { let currencies = await this.publicGetCurrencies (params); let precision = this.precision['amount']; let result = {}; for (let i = 0; i < currencies.length; i++) { let currency = currencies[i]; let id = currency['CurrencyID']; let code = this.commonCurrencyCode (currency['TickerCode']); let active = currency['WalletStatus'] == 'online'; let status = 'ok'; if (!active) status = 'disabled'; result[code] = { 'id': id, 'code': code, 'name': currency['Name'], 'active': active, 'status': status, 'precision': precision, 'limits': { 'amount': { 'min': undefined, 'max': Math.pow (10, precision), }, 'price': { 'min': Math.pow (10, -precision), 'max': Math.pow (10, precision), }, 'cost': { 'min': undefined, 'max': undefined, }, 'withdraw': { 'min': undefined, 'max': Math.pow (10, precision), }, }, 'info': currency, }; } return result; } async fetchMarkets () { let markets = await this.publicGetMarkets (); let result = []; for (let i = 0; i < markets.length; i++) { let market = markets[i]; let id = market['MarketID']; let base = this.commonCurrencyCode (market['MarketAssetCode']); let quote = this.commonCurrencyCode (market['BaseCurrencyCode']); let symbol = base + '/' + quote; result.push ({ 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'active': true, 'lot': undefined, 'info': market, }); } return result; } parseTicker (ticker, market = undefined) { if (!market) { let marketId = ticker['MarketID']; market = this.marketsById[marketId]; } let symbol = undefined; if (market) symbol = market['symbol']; let timestamp = this.milliseconds (); return { 'symbol': symbol, 'timestamp': timestamp, 'datetime': this.iso8601 (timestamp), 'high': parseFloat (ticker['HighPrice']), 'low': parseFloat (ticker['LowPrice']), 'bid': parseFloat (ticker['BidPrice']), 'ask': parseFloat (ticker['AskPrice']), 'vwap': undefined, 'open': undefined, 'close': undefined, 'first': undefined, 'last': parseFloat (ticker['LastPrice']), 'change': parseFloat (ticker['Change']), 'percentage': undefined, 'average': undefined, 'baseVolume': undefined, 'quoteVolume': parseFloat (ticker['Volume']), 'info': ticker, }; } async fetchTicker (symbol, params = {}) { await this.loadMarkets (); let market = this.market (symbol); let ticker = await this.publicGetMarketsummary (this.extend ({ 'market_id': market['id'], }, params)); return this.parseTicker (ticker, market); } async fetchTickers (symbols = undefined, params = {}) { await this.loadMarkets (); let tickers = await this.publicGetMarketsummaries (params); let result = {}; for (let i = 0; i < tickers.length; i++) { let ticker = this.parseTicker (tickers[i]); let symbol = ticker['symbol']; result[symbol] = ticker; } return result; } async fetchOrderBook (symbol, params = {}) { await this.loadMarkets (); let orderbook = await this.publicGetOrderbook (this.extend ({ 'market_id': this.marketId (symbol), }, params)); return this.parseOrderBook (orderbook, undefined, 'BuyOrders', 'SellOrders', 'Price', 'Quantity'); } sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) { let url = this.urls['api'] + '/' + path; if (api == 'public') { params = this.urlencode (params); if (params.length) url += '?' + params; } return { 'url': url, 'method': method, 'body': body, 'headers': headers }; } async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) { let response = await this.fetch2 (path, api, method, params, headers, body); let success = this.safeInteger (response, 'success'); if (success != 1) { throw new ExchangeError (response['message']); } return response['result']; } }
JavaScript
0.999997
@@ -609,24 +609,61 @@ PI': false,%0A + 'hasFetchTrades': false,%0A @@ -782,24 +782,62 @@ 'has': %7B%0A + 'fetchTrades': false,%0A
47e52fa6a01e8f4b692f72c6cf2b43544d90baaa
Fix bug service weather
core/processing.js
core/processing.js
'use strict'; const core = require('./core.js'); const fd = require('./field.js'); const serv = require('./../services/services.js'); const servWeather = require('./../services/weatherService.js'); const db = require('./../AslanDBConnector.js'); /* * Fonction qui traite les réponses de type bonjour */ function processingGrettings(information, response) { if(information != undefined && response != undefined && information.first_name != undefined) { var fields = fd.extractFields(response.result.fulfillment.speech); console.log(fields); if(fields.indexOf("{prenom}") != -1) { var answer = fd.replaceField(response.result.fulfillment.speech, "{prenom}", information.first_name); core.prepareMessage(answer); } } else { core.prepareMessage(response.result.fulfillment.speech); } } function processingHour(response) { if(response != undefined && response.result != undefined && response.result.parameters != undefined && response.result.parameters.ville != undefined) { var fields = fd.extractFields(response.result.fulfillment.speech); console.log(fields); if(fields.indexOf("{heure}") != -1) { console.log(response.result.parameters.ville); serv.getTimeAt(response.result.parameters.ville, function(hour) { var answer = fd.replaceField(response.result.fulfillment.speech, "{heure}",hour); answer = fd.replaceField(answer, "{\"ville\":[\"" + response.result.parameters.ville + "\"]}", response.result.parameters.ville); core.prepareMessage(answer); }); } } else { core.prepareMessage(response.result.fulfillment.speech); } } function processingFountain(response) { if(response != undefined && response.result != undefined && response.result.parameters != undefined && response.result.parameters.location != undefined) { serv.nearestFontaines(response.result.parameters.location, 20, function(foutains) { message["attachment"] = foutains; core.prepareMessage(message); }); } else { core.prepareMessage(response.result.fulfillment.speech); } } function processingCitizen(response) { if(response != undefined && response.result != undefined && response.result.parameters != undefined && response.result.parameters.ville != undefined) { var fields = fd.extractFields(response.result.fulfillment.speech); console.log(fields); if(fields.indexOf("{heure}") != -1) { console.log(response.result.parameters.ville); serv.getTimeAt(response.result.parameters.ville, function(hour) { var answer = fd.replaceField(response.result.fulfillment.speech, "{heure}",hour); answer = fd.replaceField(answer, "{\"ville\":[\"" + response.result.parameters.ville + "\"]}", response.result.parameters.ville); console.log(answer); core.prepareMessage(answer); }); } } else { core.prepareMessage(response.result.fulfillment.speech); } } function processingDate(response) { } function processingWeather(response, location) { if(response != undefined && response.result != undefined && response.result.parameters != undefined) { var fields = fd.extractFields(response.result.fulfillment.speech); console.log(fields); if(fields.indexOf("{meteo}") != -1) { var coord = ""; if(location) { } else if(response.result.parameters.ville != undefined){ coord = response.result.parameters.ville; } servWeather.JSONP_LocalWeather(coord, formattedDate(), function(response) { console.log(response); var weather = response.data.current_condition['0'].lang_fr + ", " + response.data.current_condition['0'].temp_C + "°"; var answer = fd.replaceField(response.result.fulfillment.speech, "{meteo}", weather); if(response.result.parameters.ville != undefined){ answer = fd.replaceField(answer, "{\"ville\":[\"" + response.result.parameters.ville + "\"]}", response.result.parameters.ville); } core.prepareMessage(answer); }); } else { core.prepareMessage(response.result.fulfillment.speech); } } else { core.prepareMessage(response.result.fulfillment.speech); } } function processingRestaurant(response, location) { if(response != undefined && response.result != undefined && response.result.parameters != undefined) { var fields = fd.extractFields(response.result.fulfillment.speech); console.log(fields); if(fields.indexOf("{location:[]") != -1) { db.insertData("conversation", object, function(err, data) { console.log(err); }); core.prepareMessage(response.result.fulfillment.speech); } else if (fields.indexOf("{restaurants}") != -1 && location != null){ /*serv.getTimeAt(response.result.parameters.ville, function(hour) { var answer = fd.replaceField(response.result.fulfillment.speech, "{heure}",hour); answer = fd.replaceField(answer, "{\"ville\":[\"" + response.result.parameters.ville + "\"]}", response.result.parameters.ville); console.log(answer); core.prepareMessage(answer); });*/ } else { core.prepareMessage(response.result.fulfillment.speech); } } else { core.prepareMessage(response.result.fulfillment.speech); } } function formattedDate(d = new Date) { let month = String(d.getMonth() + 1); let day = String(d.getDate()); const year = String(d.getFullYear()); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; return `${year}-${month}-${day}/`; } exports.processingGrettings = processingGrettings; exports.processingHour = processingHour; exports.processingFountain = processingFountain; exports.processingCitizen = processingCitizen; exports.processingDate = processingDate; exports.processingWeather = processingWeather; exports.processingRestaurant = processingRestaurant;
JavaScript
0.000008
@@ -3235,37 +3235,40 @@ sult.parameters. -ville +geo-city != undefined)%7B%0A @@ -3306,21 +3306,24 @@ ameters. -ville +geo-city ;%0A%09%09%09%7D%0A%09 @@ -3644,211 +3644,8 @@ r);%0A -%09%09%09%09if(response.result.parameters.ville != undefined)%7B%0A%09%09%09%09%09answer = fd.replaceField(answer, %0A%09%09%09%09%09%09%22%7B%5C%22ville%5C%22:%5B%5C%22%22 + response.result.parameters.ville + %22%5C%22%5D%7D%22, response.result.parameters.ville);%0A%09%09%09%09%7D%0A %09%09%09%09
cf3fbb52c425f8386bb3847adc1a589917007a69
add underscore
package.js
package.js
Package.describe({ name: "tmeasday:publish-counts", summary: "Publish the count of a cursor, in real time", version: "0.7.3", git: "https://github.com/percolatestudio/publish-counts.git" }); Package.on_use(function (api, where) { api.versionsFrom("[email protected]"); api.use(['blaze', 'templating'], 'client', { weak: true }); api.use('mongo', 'client'); api.add_files('client/publish-counts.js', 'client'); api.add_files('server/publish-counts.js', 'server'); api.export('Counts'); api.export('publishCount', 'server'); }); Package.on_test(function (api) { api.use([ 'tmeasday:publish-counts', 'tinytest', 'mongo', 'facts']); api.add_files([ 'tests/helper.js', 'tests/has_count_test.js', 'tests/count_test.js', 'tests/count_local_collection_test.js', 'tests/count_non_reactive_test.js', 'tests/count_from_field_shallow_test.js', 'tests/count_from_field_fn_shallow_test.js', 'tests/count_from_field_fn_deep_test.js', 'tests/count_from_field_length_shallow_test.js', 'tests/count_from_field_length_fn_shallow_test.js', 'tests/count_from_field_length_fn_deep_test.js', 'tests/field_limit_count_test.js', 'tests/field_limit_count_from_field_test.js', 'tests/field_limit_count_from_field_fn_test.js', 'tests/field_limit_count_from_field_length_test.js', 'tests/field_limit_count_from_field_length_fn_test.js', 'tests/no_ready_test.js', 'tests/no_warn_test.js', 'tests/observe_handles_test.js', ]); });
JavaScript
0.99977
@@ -352,32 +352,67 @@ go', 'client');%0A + api.use('underscore', 'server');%0A api.add_files(
c6a7db35eb048997543094503aed2a079c0e30e1
include play option for nav
js/components/nav.js
js/components/nav.js
// Create the nav component. var nav = {}; // Create the nav view-model. nav.vm = { init: function() { console.log ("nav vm init"); } } // Create the nav controller. nav.controller = function() { nav.vm.init (); } // Create the nav view. nav.view = function() { return m("header", [ m("div", {class: "title-header"}, [ m("h1", "Adventure Guild") ]), m("div", {class: "nav-header"}, [ m("div", {class: "nav-collapse"}, [ m("ul", [ m("li", [ m("a", {href: "#"}, "Home") ]), m("li", [ m("a", {href: "#"}, "Game") ]), m("li", [ m("a", {href: "#"}, "Forums") ]), m("li", [ m("a", {href: "#"}, "Shop") ]), ]) ]) ]), m("hr", {class: "hr-gradient"}) ]); }
JavaScript
0
@@ -602,12 +602,87 @@ , %22 -Game +About%22)%0A %5D),%0A m(%22li%22, %5B%0A m(%22a%22, %7Bhref: %22#%22%7D, %22Play %22)%0A
b7b6195cfc4bf558179fa90cab573eacf3101a54
Extract IIFE into separate function
js/modules/debug.js
js/modules/debug.js
const isFunction = require('lodash/isFunction'); const isNumber = require('lodash/isNumber'); const isObject = require('lodash/isObject'); const isString = require('lodash/isString'); const random = require('lodash/random'); const range = require('lodash/range'); const sample = require('lodash/sample'); const Message = require('./types/message'); const { deferredToPromise } = require('./deferred_to_promise'); const { sleep } = require('./sleep'); // See: https://en.wikipedia.org/wiki/Fictitious_telephone_number#North_American_Numbering_Plan const SENDER_ID = '+12126647665'; exports.createConversation = async ({ ConversationController, numMessages, WhisperMessage, } = {}) => { if (!isObject(ConversationController) || !isFunction(ConversationController.getOrCreateAndWait)) { throw new TypeError('"ConversationController" is required'); } if (!isNumber(numMessages) || numMessages <= 0) { throw new TypeError('"numMessages" must be a positive number'); } if (!isFunction(WhisperMessage)) { throw new TypeError('"WhisperMessage" is required'); } const conversation = await ConversationController.getOrCreateAndWait(SENDER_ID, 'private'); conversation.set({ active_at: Date.now(), unread: numMessages, }); await deferredToPromise(conversation.save()); const conversationId = conversation.get('id'); await Promise.all(range(0, numMessages).map(async (index) => { await sleep(index * 100); console.log(`Create message ${index + 1}`); const message = new WhisperMessage(createRandomMessage({ conversationId })); return deferredToPromise(message.save()); })); }; const SAMPLE_MESSAGES = [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Integer et rutrum leo, eu ultrices ligula.', 'Nam vel aliquam quam.', 'Suspendisse posuere nunc vitae pulvinar lobortis.', 'Nunc et sapien ex.', 'Duis nec neque eu arcu ultrices ullamcorper in et mauris.', 'Praesent mi felis, hendrerit a nulla id, mattis consectetur est.', 'Duis venenatis posuere est sit amet congue.', 'Vestibulum vitae sapien ultricies, auctor purus vitae, laoreet lacus.', 'Fusce laoreet nisi dui, a bibendum metus consequat in.', 'Nulla sed iaculis odio, sed lobortis lacus.', 'Etiam massa felis, gravida at nibh viverra, tincidunt convallis justo.', 'Maecenas ut egestas urna.', 'Pellentesque consectetur mattis imperdiet.', 'Maecenas pulvinar efficitur justo a cursus.', ]; const ATTACHMENT_SAMPLE_RATE = 0.33; const createRandomMessage = ({ conversationId } = {}) => { if (!isString(conversationId)) { throw new TypeError('"conversationId" must be a string'); } const sentAt = Date.now() - random(100 * 24 * 60 * 60 * 1000); const receivedAt = sentAt + random(30 * 1000); const hasAttachment = Math.random() <= ATTACHMENT_SAMPLE_RATE; const attachments = hasAttachment ? [createRandomInMemoryAttachment()] : []; const type = sample(['incoming', 'outgoing']); const commonProperties = { attachments, body: sample(SAMPLE_MESSAGES), conversationId, received_at: receivedAt, sent_at: sentAt, timestamp: receivedAt, type, }; const message = (() => { switch (type) { case 'incoming': return Object.assign({}, commonProperties, { flags: 0, source: conversationId, sourceDevice: 1, }); case 'outgoing': return Object.assign({}, commonProperties, { delivered: 1, delivered_to: [conversationId], expireTimer: 0, recipients: [conversationId], sent_to: [conversationId], synced: true, }); default: throw new TypeError(`Unknown message type: '${type}'`); } })(); return Message.initializeSchemaVersion(message); }; const MEGA_BYTE = 1e6; const createRandomInMemoryAttachment = () => { const numBytes = (1 + Math.ceil((Math.random() * 50))) * MEGA_BYTE; const array = new Uint32Array(numBytes).fill(1); const data = array.buffer; const fileName = Math.random().toString().slice(2); return { contentType: 'application/octet-stream', data, fileName, size: numBytes, }; };
JavaScript
0.999724
@@ -3188,19 +3188,201 @@ e = -(() =%3E %7B%0A +_createMessage(%7B commonProperties, conversationId, type %7D);%0A return Message.initializeSchemaVersion(message);%0A%7D;%0A%0Aconst _createMessage = (%7B commonProperties, conversationId, type %7D = %7B%7D) =%3E %7B%0A sw @@ -3395,26 +3395,24 @@ type) %7B%0A - case 'incomi @@ -3412,26 +3412,24 @@ 'incoming':%0A - return @@ -3475,18 +3475,16 @@ - - flags: 0 @@ -3481,26 +3481,24 @@ flags: 0,%0A - sour @@ -3521,26 +3521,24 @@ Id,%0A - - sourceDevice @@ -3544,32 +3544,28 @@ e: 1,%0A - %7D);%0A - case 'ou @@ -3575,26 +3575,24 @@ ing':%0A - return Objec @@ -3620,26 +3620,24 @@ operties, %7B%0A - deli @@ -3650,26 +3650,24 @@ 1,%0A - delivered_to @@ -3678,34 +3678,32 @@ onversationId%5D,%0A - expireTi @@ -3718,18 +3718,16 @@ - recipien @@ -3740,34 +3740,32 @@ onversationId%5D,%0A - sent_to: @@ -3791,18 +3791,16 @@ - synced: @@ -3805,18 +3805,16 @@ : true,%0A - %7D) @@ -3819,18 +3819,16 @@ %7D);%0A - default: @@ -3828,18 +3828,16 @@ efault:%0A - th @@ -3896,71 +3896,9 @@ ;%0A - %7D%0A %7D)();%0A%0A return Message.initializeSchemaVersion(message); +%7D %0A%7D;%0A
c2e250212a7dee0ab19cf613494ac0fcf78c8a2c
Update localfiles.js
lib/middleware/localfiles.js
lib/middleware/localfiles.js
'use strict'; (function (module) { var fs = require('fs'); var url = require('url'); var path = require('path'); var mime = require('connect').static.mime; function charset(type) { var t = mime.charsets.lookup(type); return t ? ';charset=' + t : ''; } function create(options) { var verbose = options.verbose; var prefixes = options.prefixes; return function (request, response, next) { if ('GET' != request.method && 'HEAD' != request.method) { return next(); } var pathname = url.parse(request.url).pathname, filename, type; if (/\/appsuite\/api\//.test(pathname)) { return next(); } //remove base directories (only /appsuite/ and /base/) //TODO: handle custom base directories (?) pathname = pathname.replace(/^\/appsuite\//, '/'); pathname = pathname.replace(/^\/base\//, '/'); pathname = pathname.replace(/^\/v=[^\/]+\//, '/'); pathname = pathname.replace(/^\/$/, '/core'); filename = prefixes.map(function (p) { return path.join(p, pathname); }) .filter(function (filename) { return (path.existsSync(filename) && fs.statSync(filename).isFile()); })[0]; if (!filename) { if (verbose.local || verbose['local:error']) console.log('localfile not found: ', pathname); return next(); } var stream = fs.createReadStream(filename); if (pathname === '/core' || pathname === '/signin') { type = 'text/html'; var replaceVersion = require('../replace_version').createReplaceStream(prefixes); stream = stream.pipe(replaceVersion); } else if (pathname === '/boot.js') { var replaceVersion = require('../replace_version').createPrependStream(prefixes); stream = stream.pipe(replaceVersion); type = mime.lookup(filename); } else { type = mime.lookup(filename); } // set headers if (verbose.local) console.log(filename); response.setHeader('Content-Type', type + charset(type)); response.setHeader('Expires', '0'); stream.pipe(response); return true; }; } module.exports = { create: create }; }(module));
JavaScript
0
@@ -1135,20 +1135,18 @@ %5C/$/, '/ -core +ui ');%0A @@ -1669,16 +1669,38 @@ name === + '/ui' %7C%7C pathname === '/core'
f2ff5df7730fc0574cce5366310aed4b3763a5ca
Version bump
package.js
package.js
Package.describe({ git: 'https://github.com/zimme/meteor-collection-behaviours.git', name: 'zimme:collection-behaviours', summary: 'Define and attach behaviours to collections', version: '1.0.5-rc.2' }); Package.onUse(function(api) { api.versionsFrom('1.0'); api.use([ 'check', 'coffeescript', 'mongo' ]); api.addFiles([ 'lib/behaviours.coffee', 'lib/mongo.coffee' ]); api.export('CollectionBehaviours'); });
JavaScript
0.000001
@@ -195,16 +195,16 @@ '1. -0.5 +1.0 -rc. -2 +1 '%0A%7D)
389cb80d9df55432dfcac52fcb88a7644b44eed8
Apply Common Upgrade to Popover classes
js/mylib/popover.js
js/mylib/popover.js
// ---------------------------------------------------------------- // Popover Class class PopoverModel extends CommonModel { constructor({ name = 'Popover', selector = null, help = 'popover', trigger = 'hover' } = {}) { super({ name: name }); this.NAME = name; this.SELECTOR = selector; this.HELP = help; this.TRIGGER = trigger; } } class PopoverView extends CommonView { constructor(_model = new PopoverModel()) { super(_model); this.setPopover(); } setPopover() { if (this.model.SELECTOR != null) { $(this.model.SELECTOR).attr('data-toggle', 'popover'); $(this.model.SELECTOR).attr('data-content', this.model.HELP); $(this.model.SELECTOR).attr('data-trigger', this.model.TRIGGER); $(this.model.SELECTOR).popover(); } } } // ---------------------------------------------------------------- // Controllers class PopoverController extends CommonController { constructor(_obj) { super({ name: 'Popover Controller' }); this.model = new PopoverModel(_obj); this.view = new PopoverView(this.model); } }
JavaScript
0
@@ -84,101 +84,228 @@ ss%0A%0A -class PopoverModel extends CommonModel %7B%0A constructor(%7B%0A name = 'Popover',%0A selector = +// ----------------------------------------------------------------%0A// Model%0A%0Aclass PopoverModel extends CommonModel %7B%0A constructor(%0A _setting = %7B%7D, %0A _initSetting = %7B%0A NAME: 'Popover Object',%0A SELECTOR: nul @@ -315,14 +315,15 @@ -help = + HELP: 'po @@ -338,17 +338,18 @@ -trigger = + TRIGGER: 'ho @@ -359,17 +359,15 @@ '%0A -%7D = %7B%7D)%0A + %7D%0A ) %7B%0A @@ -379,147 +379,369 @@ per( -%7B%0A name: name%0A %7D);%0A %0A this.NAME = name;%0A this.SELECTOR = selector;%0A this.HELP = help;%0A this.TRIGGER = trigger;%0A %7D%0A%7D +_setting, _initSetting);%0A %7D%0A%7D%0A%0A// ----------------------------------------------------------------%0A// View%0A%0Aclass PopoverView extends CommonView %7B%0A constructor(%0A _setting = %7B%7D, %0A _initSetting = %7B%0A NAME: 'Popover View'%0A %7D%0A ) %7B%0A super(_setting, _initSetting);%0A %7D%0A%7D%0A%0A// ----------------------------------------------------------------%0A// Event %0A%0Acl @@ -743,36 +743,37 @@ t%0A%0Aclass Popover -View +Event extends CommonV @@ -763,36 +763,37 @@ t extends Common -View +Event %7B%0A constructor @@ -797,83 +797,122 @@ tor( -_model = new PopoverModel()) %7B%0A super(_model);%0A %0A this.setPopover( +%0A _setting = %7B%7D, %0A _initSetting = %7B%0A NAME: 'Popover Event'%0A %7D%0A ) %7B%0A super(_setting, _initSetting );%0A @@ -943,29 +943,29 @@ if (this. -model +MODEL .SELECTOR != @@ -978,37 +978,37 @@ %7B%0A $(this. -model +MODEL .SELECTOR).attr( @@ -1039,37 +1039,37 @@ );%0A $(this. -model +MODEL .SELECTOR).attr( @@ -1089,21 +1089,21 @@ ', this. -model +MODEL .HELP);%0A @@ -1107,37 +1107,37 @@ );%0A $(this. -model +MODEL .SELECTOR).attr( @@ -1157,21 +1157,21 @@ ', this. -model +MODEL .TRIGGER @@ -1186,21 +1186,21 @@ $(this. -model +MODEL .SELECTO @@ -1307,17 +1307,16 @@ ntroller -s %0A%0Aclass @@ -1378,34 +1378,56 @@ tor( -_obj) %7B%0A super( +%0A _setting = %7B%7D, %0A _initSetting = %7B%0A name @@ -1426,12 +1426,12 @@ -name +NAME : 'P @@ -1452,105 +1452,210 @@ ler' +, %0A -%7D);%0A %0A this.model = new PopoverModel(_obj);%0A this.view = new PopoverView(this.model + MODEL: new PopoverModel(),%0A VIEW: new PopoverView(),%0A EVENT: new PopoverEvent(),%0A VIEW_OBJECT: false%0A %7D%0A ) %7B%0A super(_setting, _initSetting);%0A %0A this.EVENT.setPopover( );%0A
0646dfbf4ce1f4f33fd39c2e43eccb4258688b4f
Allow adding of VC's to topics table - code needs to be unique per project
modules/vcs/client/controllers/vc.controller.js
modules/vcs/client/controllers/vc.controller.js
'use strict'; angular.module ('vcs') // ------------------------------------------------------------------------- // // controller for listing vcs // // ------------------------------------------------------------------------- .controller ('controllerVcList', ['$scope', '$rootScope', '$stateParams', 'VcModel', 'NgTableParams', 'PILLARS', function ($scope, $rootScope, $stateParams, VcModel, NgTableParams, PILLARS) { //console.log ('controllerVcList is running'); var self = this; // // map out any supporting data // self.pillars = PILLARS.map (function (e) { return {id:e,title:e}; }); self.project = $stateParams.project; // // set or reset the collection // var setData = function () { VcModel.forProject ($stateParams.project).then (function (data) { // console.log ('controllerVcList data received: ', data); self.collection = data; self.tableParams = new NgTableParams ({count: 10}, {dataset: data}); }); }; // // listen for when to reset // var unbind = $rootScope.$on('refreshVcList', function() { setData(); }); $scope.$on('$destroy', unbind); // // finally, set the data // setData(); }]) .controller ('controllerAddTopicModal', ['$modalInstance', '$scope', '_', '$stateParams', 'codeFromTitle', 'VcModel', 'TopicModel', 'PILLARS', function ($modalInstance, $scope, _, $stateParams, codeFromTitle, VcModel, TopicModel, PILLARS) { var self = this; self.data = null; self.current = []; self.currentObjs = []; self.project = $stateParams.project; TopicModel.forType('Valued Component').then( function (data) { self.data = data; $scope.$apply(); }); this.toggleItem = function (item) { // console.log("item:",item); var idx = self.current.indexOf(item._id); // console.log(idx); if (idx === -1) { self.currentObjs.push(item); self.current.push(item._id); } else { _.remove(self.currentObjs, {_id: item._id}); _.remove(self.current, function(n) {return n === item._id;}); } }; this.ok = function () { // console.log("data:",self.currentObjs[0]); var savedArray = []; // console.log("length: ",self.currentObjs.length); _.each( self.currentObjs, function(obj, idx) { // console.log("Adding " + obj.description + " to Valued Components"); VcModel.getNew().then(function (m) { m.project = $scope.project; // TODO: Should we be getting these names from the UI? m.name = obj.name; m.code = codeFromTitle(obj.name); // console.log("saving:",m); VcModel.saveCopy(m).then(function (saved) { savedArray.push(saved); if (idx === self.currentObjs.length-1) { // Return the collection back to the caller $modalInstance.close(savedArray); } }); }); }); }; this.cancel = function () { // console.log ('cancel clicked'); $modalInstance.dismiss('cancel'); }; }]) // ------------------------------------------------------------------------- // // controller for editing or adding vcs // // ------------------------------------------------------------------------- .controller ('controllerEditVcModal', ['$modalInstance', '$scope', '_', 'codeFromTitle', 'VcModel', 'TopicModel', 'PILLARS', function ($modalInstance, $scope, _, codeFromTitle, VcModel, TopicModel, PILLARS) { // console.log ('controllerEditVcModal is running'); var self = this; // // pull the mode and other info from the scope inputs // this.mode = $scope.mode; // // set up any data from services that needs massaging // this.pillars = PILLARS; // ------------------------------------------------------------------------- // // set up handlers and functions on scope // // ------------------------------------------------------------------------- this.selectTopic = function () { var self = this; TopicModel.getTopicsForPillar (this.vc.pillar).then (function (topics) { self.topics = topics; $scope.$apply(); }); }; this.ok = function () { // console.log ('save clicked'); this.vc.code = codeFromTitle (this.vc.name); // console.log ('new code = ', this.vc.code); if (this.mode === 'add') { VcModel.saveModel ().then (function (result) { $modalInstance.close(result); }); } else if (this.mode === 'edit') { VcModel.saveModel ().then (function (result) { $scope.vc = _.cloneDeep (result); $modalInstance.close(result); }); } else { $modalInstance.dismiss ('cancel'); } }; this.cancel = function () { // console.log ('cancel clicked'); $modalInstance.dismiss('cancel'); }; // // finally, deal with the mode and setting data up for each one // and kick off the directive // if (this.mode === 'add') { this.dmode = 'Add'; VcModel.getNew ().then (function (model) { self.vc = model; self.selectTopic (); }); } else if (this.mode === 'edit') { this.dmode = 'Edit'; this.vc = VcModel.getCopy ($scope.vc); VcModel.setModel (this.vc); this.selectTopic (); } else { this.dmode = 'View'; this.vc = $scope.vc; this.selectTopic (); } }]) ;
JavaScript
0
@@ -2461,24 +2461,39 @@ tle(obj.name ++m.project.code );%0A%09%09%09%09%09// c
3a6258f1d687258745ed874fe1042ef62bea8fd1
Bump version
package.js
package.js
Package.describe({ name: 'dispatch:configuration', summary: 'App configuration manager with inheritance', version: '0.1.5' }); Package.onUse(function(api) { api.use([ '[email protected]', '[email protected]', '[email protected]', 'aldeed:[email protected]', 'aldeed:[email protected]', 'dispatch:[email protected]', 'gfk:[email protected]' ]); api.imply('aldeed:simple-schema'); api.addFiles([ 'lib/configuration.js', 'lib/user.js' ], ['client', 'server']); api.addFiles([ 'lib/server/server.js', 'lib/server/publish.js', 'lib/server/write.js', 'lib/server/methods.js', ], 'server'); api.addFiles([ 'lib/client/client.js' ], 'client'); api.export('Configuration'); }); Package.onTest(function(api) { api.use('sanjo:[email protected]'); api.use([ 'mongo', 'tracker', 'dispatch:configuration', 'aldeed:simple-schema' ]); api.addFiles([ 'tests/inheritance.js' ]); api.addFiles([ 'tests/server-only/bulk.js', 'tests/server-only/setSchema.js' ], 'server'); });
JavaScript
0
@@ -119,17 +119,17 @@ n: '0.1. -5 +6 '%0A%7D);%0A%0AP
0d2dd2e99bdcfa03a6d718a9e9f6d4cf0b69ce5c
Refresh the login page after 30 minutes to prevent CSRF error (Issue #158)
js/login.js
js/login.js
$(document).ready(function(){ $("form#login_form").submit(function(){ /* all the client side validation */ return validate(); }); $("input#email").blur(function(){ $(this).val($(this).val().trim()); }); /* must trim the password values here because they get trimmed on the pw set page */ $("input#password").blur(function(){ $(this).val($(this).val().trim()); }); }); function validate() { /* lowercase the email */ $("#email").val($("#email").val().toLowerCase()); if ($("#email").val().length < 1) { $("#auth_fail_msg").text("A valid email address is required in order to authenticate."); $("#auth_fail_msg").show(); return false; } if ($("#email").val().length > 255) { $("#auth_fail_msg").text("Email address should not exceed 255 characters in length."); $("#auth_fail_msg").show(); return false; } if (!isValidEmailAddress($("#email").val())) { $("#auth_fail_msg").text("The email address does not appear to follow the proper form."); $("#auth_fail_msg").show(); return false; } if ($("#password").val().length < 1) { $("#auth_fail_msg").text("A password is required in order to authenticate."); $("#auth_fail_msg").show(); return false; } if ($("#password").val().length > 128) { $("#auth_fail_msg").text("The maximum length of a password is 128 characters."); $("#auth_fail_msg").show(); return false; } $("#auth_fail_msg").hide(); return true; } function isValidEmailAddress(emailAddress) { /* I know this is not a perfectly valid email validation expression just checking to make sure the email entered *seems* like an email address. On the server side, we will put it through additional checking and actually validate the email with an email loop. */ var pattern = /^([\S-\.]+@([\S-]+\.)+[\S-]{2,10})?$/ //var pattern = new RegExp(""); return emailAddress.length > 0 && pattern.test(emailAddress); }
JavaScript
0
@@ -1,8 +1,23 @@ +'use strict';%0A%0A $(docume @@ -438,20 +438,149 @@ %7D);%0A +%0A +/* refresh the page after ~30 minutes, otherwise they will receive a CSRF expired error */%0A setTimeout(refreshPage, 1799000); %0A%0A%7D);%0A%0A%0A @@ -2279,10 +2279,84 @@ ss);%0A%7D%0A%0A +function refreshPage()%0A%7B%0A%0A window.location.replace(window.location);%0A%0A%7D %0A%0A
4aaffec8781e6984485c97e448728422b1ba3f6f
patch release - Bump to version 1.0.1
package.js
package.js
Package.describe({ summary: "Accounts Templates unstyled.", version: "1.0.0", name: "useraccounts:unstyled", git: "https://github.com/meteor-useraccounts/unstyled.git", }); Package.on_use(function(api, where) { api.versionsFrom("[email protected]"); api.use([ "less", "templating", ], "client"); api.use([ "useraccounts:core", ], ["client", "server"]); api.imply([ "useraccounts:[email protected]", ], ["client", "server"]); api.add_files([ "lib/at_error.html", "lib/at_error.js", "lib/at_form.html", "lib/at_form.js", "lib/at_input.html", "lib/at_input.js", "lib/at_oauth.html", "lib/at_oauth.js", "lib/at_pwd_form.html", "lib/at_pwd_form.js", "lib/at_pwd_form_btn.html", "lib/at_pwd_form_btn.js", "lib/at_pwd_link.html", "lib/at_pwd_link.js", "lib/at_result.html", "lib/at_result.js", "lib/at_sep.html", "lib/at_sep.js", "lib/at_signin_link.html", "lib/at_signin_link.js", "lib/at_signup_link.html", "lib/at_signup_link.js", "lib/at_social.html", "lib/at_social.js", "lib/at_terms_link.html", "lib/at_terms_link.js", "lib/at_title.html", "lib/at_title.js", "lib/full_page_at_form.html", "lib/at_unstyled.css" ], ["client"]); }); Package.on_test(function(api) { api.use([ "useraccounts:unstyled", "useraccounts:[email protected]", ]); api.use([ "accounts-password", "tinytest", "test-helpers" ], ["client", "server"]); api.add_files([ "tests/tests.js" ], ["client", "server"]); });
JavaScript
0
@@ -71,25 +71,25 @@ rsion: %221.0. -0 +1 %22,%0A name: @@ -442,33 +442,33 @@ counts:[email protected]. -0 +1 %22,%0A %5D, %5B%22clie @@ -1550,17 +1550,17 @@ [email protected]. -0 +1 %22,%0A %5D
678a6304c34e7ca583b310f4ffd129822c78d12b
clean up
lib/observable/emit/index.js
lib/observable/emit/index.js
'use strict' var Emitter = require('../../emitter') var _emit = Emitter.prototype.emit var Event = require('../../event') // context optmizations as well -- have to reduce amount of fires -- the ignore stuff can be optmized exports.inject = [ require('../instances'), require('./instances'), require('./context') ] var overridemap = { } exports.define = { emit (key, data, event, ignore) { if (event === false) { return } let trigger if (event === void 0) { if (ignore) { return } event = new Event(this, key) trigger = true } if ( !event.isTriggered && (trigger || event.origin === this && event.type === key && // look up prop faster event.context == this._context) // eslint-disable-line ) { trigger = event.isTriggered = true // double check properties } let on = this._on if (on) { // this is a very slow way lets make it better let override = on._properties._overrides[key] if (override) { key = override } let emitter = on[key] if (!ignore) { if (emitter) { let context = this._context this.emitInstances(emitter, data, event, key) this.emitContext(emitter, data, event) // data, event, bind, key, trigger, ignore emitter.emitInternal(data, event, this, key, trigger, ignore) // emitter.push(this, event.push(emitter), data) // emitter.emit(data, event, this) if (!context) { this.clearContext() } } else { // this is a bit dirty and heavy! this.emitInstances(void 0, data, event, key) } } } if (trigger) { event.trigger() } } }
JavaScript
0.000001
@@ -219,17 +219,16 @@ ptmized%0A -%0A exports. @@ -321,32 +321,8 @@ %0A%5D%0A%0A -var overridemap = %7B%0A%0A%7D%0A%0A expo
4bdbefb01229ae9af6501b9a79fec9fcb3827a50
Update dependency
package.js
package.js
Package.describe({ name: 'aramk:checkbox', summary: 'A reactive checkbox widget', version: '1.0.0', git: 'https://github.com/aramk/meteor-checkbox.git' }); Package.on_use(function(api) { api.versionsFrom('[email protected]'); api.use([ 'templating', 'underscore', 'jquery', 'urbanetic:[email protected]' ], 'client'); api.use([ 'semantic:[email protected]' ], 'client', {weak: true}); api.add_files([ 'src/checkbox.html', 'src/checkbox.js' ], 'client'); });
JavaScript
0.000001
@@ -372,11 +372,11 @@ s@2. -0.8 +1.2 '%0A
0ca713b17795769db0e9f8e63889a82beefcc915
add Bacon.UI.ajax for "static" AJAX
Bacon.UI.js
Bacon.UI.js
(function() { var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; function nonEmpty(x) { return x && x.length > 0 } Bacon.UI = {} Bacon.UI.textFieldValue = function(textfield, initValue) { function getValue() { return textfield.val() } function autofillPoller() { if (textfield.attr("type") == "password") return Bacon.interval(100) else if (isChrome) return Bacon.interval(100).take(20).map(getValue).filter(nonEmpty).take(1) else return Bacon.never() } if (initValue !== null) { textfield.val(initValue) } return textfield.asEventStream("keyup input"). merge(textfield.asEventStream("cut paste").delay(1)). merge(autofillPoller()). map(getValue).toProperty(getValue()).skipDuplicates() } Bacon.UI.optionValue = function(option) { function getValue() { return option.val() } return option.asEventStream("change").map(getValue).toProperty(getValue()) } Bacon.UI.checkBoxGroupValue = function(checkboxes, initValue) { function selectedValues() { return checkboxes.filter(":checked").map(function(i, elem) { return $(elem).val()}).toArray() } if (initValue) { checkboxes.each(function(i, elem) { $(elem).attr("checked", initValue.indexOf($(elem).val()) >= 0) }) } return checkboxes.asEventStream("click").map(selectedValues).toProperty(selectedValues()) } Bacon.Observable.prototype.pending = function(src) { return src.map(true).merge(this.map(false)).toProperty(false) } Bacon.EventStream.prototype.ajax = function() { return this["switch"](function(params) { return Bacon.fromPromise($.ajax(params)) }) } Bacon.UI.radioGroupValue = function(options) { var initialValue = options.filter(':checked').val() return options.asEventStream("change").map('.target.value').toProperty(initialValue) } })();
JavaScript
0.000002
@@ -1423,32 +1423,118 @@ edValues())%0A %7D%0A + Bacon.UI.ajax = function(params) %7B%0A return Bacon.fromPromise($.ajax(params))%0A %7D%0A Bacon.Observab @@ -1722,69 +1722,21 @@ h%22%5D( -function(params) %7B return Bacon.fromPromise($.ajax(params)) %7D +Bacon.UI.ajax )%0A
0999c3fd68e6ef3304c2397b796e5bfe1f4c7743
Add decode/encode URI to Evince
lib/openers/evince-opener.js
lib/openers/evince-opener.js
/** @babel */ import Opener from '../opener' import url from 'url' const EVINCE_OBJECT = '/org/gnome/evince/Evince' const EVINCE_APPLICATION_INTERFACE = 'org.gnome.evince.Application' const DAEMON_SERVICE = 'org.gnome.evince.Daemon' const DAEMON_OBJECT = '/org/gnome/evince/Daemon' const DAEMON_INTERFACE = 'org.gnome.evince.Daemon' const WINDOW_INTERFACE = 'org.gnome.evince.Window' const GTK_APPLICATION_OBJECT = '/org/gtk/Application/anonymous' const GTK_APPLICATION_INTERFACE = 'org.freedesktop.Application' function syncSource (uri, point) { atom.workspace.open(url.parse(uri).pathname).then(editor => editor.setCursorBufferPosition(point)) } export default class EvinceOpener extends Opener { constructor () { super() this.windows = {} this.initialize() } async initialize () { try { if (process.platform === 'linux') { const dbus = require('dbus-native') this.bus = dbus.sessionBus() this.daemon = await this.getInterface(DAEMON_SERVICE, DAEMON_OBJECT, DAEMON_INTERFACE) } } catch (e) {} } async getWindow (filePath, texPath) { if (this.windows[texPath]) return this.windows[texPath] // First find the internal document name const documentName = await this.findDocument(filePath) // Get the application interface and get the window list of the application const evinceApplication = await this.getInterface(documentName, EVINCE_OBJECT, EVINCE_APPLICATION_INTERFACE) const windowNames = await this.getWindowList(evinceApplication) // Get the window interface of the of the first (only) window and get the // GTK/FreeDesktop application interface so we can activate the window const interfaces = { evinceWindow: await this.getInterface(documentName, windowNames[0], WINDOW_INTERFACE), gtkApplication: await this.getInterface(documentName, GTK_APPLICATION_OBJECT, GTK_APPLICATION_INTERFACE) } interfaces.evinceWindow.on('SyncSource', syncSource) interfaces.evinceWindow.on('Closed', () => delete this.windows[texPath]) this.windows[texPath] = interfaces // This seems to help with future syncs interfaces.evinceWindow.SyncView(texPath, [0, 0], 0) return interfaces } async open (filePath, texPath, lineNumber) { try { const interfaces = await this.getWindow(filePath, texPath) if (!this.shouldOpenInBackground()) { interfaces.gtkApplication.Activate({}) } // SyncView seems to want to activate the window sometimes interfaces.evinceWindow.SyncView(texPath, [lineNumber, 0], 0) return true } catch (error) { latex.log.error('An error occured while trying to run Evince opener') return false } } canOpen (filePath) { return !!this.daemon } hasSynctex () { return true } canOpenInBackground () { return true } getInterface (serviceName, objectPath, interfaceName) { return new Promise((resolve, reject) => { this.bus.getInterface(serviceName, objectPath, interfaceName, (error, interfaceInstance) => { if (error) { reject(error) } else { resolve(interfaceInstance) } }) }) } getWindowList (evinceApplication) { return new Promise((resolve, reject) => { evinceApplication.GetWindowList((error, windowNames) => { if (error) { reject(error) } else { resolve(windowNames) } }) }) } findDocument (filePath) { return new Promise((resolve, reject) => { const uri = url.format({ protocol: 'file:', slashes: true, pathname: filePath }) this.daemon.FindDocument(uri, true, (error, documentName) => { if (error) { reject(error) } else { resolve(documentName) } }) }) } }
JavaScript
0.000009
@@ -552,51 +552,90 @@ %7B%0A -atom.workspace.open(url.parse(uri).pathname +const filePath = decodeURI(url.parse(uri).pathname)%0A atom.workspace.open(filePath ).th @@ -3616,16 +3616,24 @@ format(%7B +%0A protoco @@ -3643,16 +3643,24 @@ 'file:', +%0A slashes @@ -3666,16 +3666,24 @@ s: true, +%0A pathnam @@ -3685,24 +3685,34 @@ thname: +encodeURI( filePath %7D)%0A @@ -3703,20 +3703,28 @@ filePath +)%0A %7D)%0A +%0A th
5cbf2c4b97f5493199654ab77522b9c545c339e6
Refactor CompanyList reducer so it's more readable
src/client/components/CompanyLists/reducer.js
src/client/components/CompanyLists/reducer.js
import _ from 'lodash' import { COMPANY_LISTS__LISTS_LOADED, COMPANY_LISTS__SELECT, COMPANY_LISTS__COMPANIES_LOADED, COMPANY_LISTS__FILTER, COMPANY_LISTS__ORDER, } from '../../actions' import { RECENT } from './Filters' const initialState = { orderBy: RECENT, } export default (state = initialState, { type, ...action }) => ({ ...state, ...({ [COMPANY_LISTS__LISTS_LOADED]: ({ result }) => ({ lists: _.mapValues(result, (title) => ({ title })), selectedId: Object.keys(result)[0], }), [COMPANY_LISTS__COMPANIES_LOADED]: ({ payload, result }) => ({ lists: { ...state.lists, [payload]: { ...state.lists[payload], companies: result, }, }, }), [COMPANY_LISTS__SELECT]: ({ id }) => ({ selectedId: id, query: '' }), [COMPANY_LISTS__FILTER]: _.identity, [COMPANY_LISTS__ORDER]: _.identity, }[type] || (() => state))(action), })
JavaScript
0.000001
@@ -286,16 +286,19 @@ efault ( +%0A state = @@ -310,16 +310,18 @@ alState, +%0A %7B type, @@ -325,52 +325,80 @@ pe, -...action +id, result, payload, query, orderBy %7D +%0A ) =%3E -( %7B%0A -...state,%0A ...( +switch (type) %7B%0A -%5B +case COMP @@ -424,30 +424,45 @@ ADED -%5D: (%7B result %7D) =%3E (%7B%0A +:%0A return %7B%0A ...state,%0A @@ -521,16 +521,18 @@ ,%0A + selected @@ -559,33 +559,37 @@ lt)%5B0%5D,%0A -%7D), + %7D %0A -%5B +case COMPANY_LIST @@ -611,45 +611,51 @@ ADED -%5D: (%7B payload, result %7D) =%3E (%7B +:%0A return %7B%0A ...state, %0A + list @@ -655,24 +655,26 @@ lists: %7B%0A + ...s @@ -685,16 +685,18 @@ .lists,%0A + @@ -710,32 +710,34 @@ d%5D: %7B%0A + ...state.lists%5Bp @@ -755,16 +755,18 @@ + companie @@ -776,16 +776,18 @@ result,%0A + @@ -799,24 +799,30 @@ + %7D,%0A -%7D), + %7D %0A -%5B +case COMP @@ -842,25 +842,50 @@ LECT -%5D: (%7B id %7D) =%3E (%7B +:%0A return %7B%0A ...state,%0A sel @@ -896,16 +896,24 @@ dId: id, +%0A query: @@ -918,18 +918,27 @@ : '' - %7D),%0A %5B +,%0A %7D%0A case COMP @@ -958,99 +958,143 @@ LTER -%5D: _.identity,%0A %5BCOMPANY_LISTS__ORDER%5D: _.identity,%0A %7D%5Btype%5D %7C%7C (() =%3E state))(action),%0A%7D) +:%0A return %7B ...state, query %7D%0A case COMPANY_LISTS__ORDER:%0A return %7B ...state, orderBy %7D%0A default:%0A return state%0A %7D%0A%7D %0A
bbaf942410dbdf8f4a602adf27c6a3d9a2c2af8d
Update minified JS.
console-history.min.js
console-history.min.js
/** * Console History v1.0.0 * console-history.min.js * * Licensed under the MIT License. * * Written by Sander Laarhoven <[email protected]> * For Doorbell.io <3 * https://github.com/lesander/console-history * https://sander.tech - https://doorbell.io */ console.log("** All console logging functions on this page are intercepted and locally stored at `console.history` **\nCall the original, un-modified, log functions with `console._log`, `console._warn` and so on.");console._log=console.log;console._info=console.info;console._warn=console.warn;console._error=console.error;console._debug=console.debug;console.history=[];console.log=function(){return console._collect("log",arguments)}console.info=function(){return console._collect("info",arguments)}console.warn=function(){return console._collect("warn",arguments)}console.error=function(){return console._collect("error",arguments)}console.debug=function(){return console._collect("debug",arguments)}console._collect=function(type,args){args;arguments;var time=new Date().toUTCString();if(!type){var type="log"}if(!args||args.length===0){return}console["_"+type].apply(console,args);console.history.push({"type":type,"timestamp":time,"arguments":args})}
JavaScript
0
@@ -262,17 +262,16 @@ .io%0A */%0A - console. @@ -476,17 +476,17 @@ so on.%22) -; +, console. @@ -501,17 +501,17 @@ sole.log -; +, console. @@ -528,17 +528,17 @@ ole.info -; +, console. @@ -555,17 +555,17 @@ ole.warn -; +, console. @@ -584,17 +584,17 @@ le.error -; +, console. @@ -613,17 +613,17 @@ le.debug -; +, console. @@ -632,17 +632,17 @@ story=%5B%5D -; +, console. @@ -689,32 +689,33 @@ log%22,arguments)%7D +, console.info=fun @@ -756,32 +756,33 @@ nfo%22,arguments)%7D +, console.warn=fun @@ -823,32 +823,33 @@ arn%22,arguments)%7D +, console.error=fu @@ -892,32 +892,33 @@ ror%22,arguments)%7D +, console.debug=fu @@ -969,16 +969,17 @@ uments)%7D +, console. @@ -1000,24 +1000,13 @@ ion( -type,args)%7Bargs; +a,b)%7B argu @@ -1019,21 +1019,19 @@ var -time= +c=( new Date ().t @@ -1026,17 +1026,16 @@ new Date -( ).toUTCS @@ -1050,63 +1050,42 @@ if(! -type)%7Bvar type +a)var a =%22log%22 -%7Dif(!args%7C%7Cargs.length===0)%7Breturn%7D +;if(b&&0!==b.length)%7B cons @@ -1092,20 +1092,17 @@ ole%5B%22_%22+ -type +a %5D.apply( @@ -1113,14 +1113,123 @@ ole, -args); +b);var d=!1;try%7Bthrow Error(%22%22)%7Dcatch(e)%7Bfor(var f=e.stack.split(%22%5Cn%22),d=%5B%5D,g=4;g%3Cf.length;g++)d.push(f%5Bg%5D.trim())%7D cons @@ -1250,21 +1250,15 @@ sh(%7B -%22 type -%22:type,%22 +:a, time @@ -1266,16 +1266,11 @@ tamp -%22:time,%22 +:c, argu @@ -1278,14 +1278,20 @@ ents -%22:args +:b,stack:d %7D)%7D +%7D; %0A
46ccda869826624a6e30ed18d7835c1933383303
debug redirect uri
googleauth.js
googleauth.js
'use strict' import express from 'express' import qs from 'querystring' import fetch from 'node-fetch' import wga from 'wga' import jwt from 'jsonwebtoken' let google_client_id = process.env.GOOGLE_API_CLIENT_ID let google_client_secret = process.env.GOOGLE_API_CLIENT_SECRET let allowed_email = process.env.JWT_ALLOWED_EMAIL let jwt_secret = process.env.JWT_SECRET let router = express.Router() router.get('/google/login', (req, res) => { let callback_uri = req.protocol + '://' + req.get('host') + req.baseUrl + '/google/callback' let query_params = { scope: 'email', redirect_uri: callback_uri, response_type: 'code', client_id: google_client_id } res.redirect('http://accounts.google.com/o/oauth2/auth?' + qs.stringify(query_params)) }) router.get('/google/callback', wga(async (req, res) => { // get the code and exchange for access token let code = req.query.code if (!code) { console.error('cannot get code from query, cannot continue authentication') return res.redirect('/') } let response = await fetch('https://www.googleapis.com/oauth2/v3/token', { method: 'POST', headers: { "Content-type": "application/x-www-form-urlencoded" }, body: qs.stringify({ code: code, client_id: google_client_id, client_secret: google_client_secret, redirect_uri: req.protocol + '://' + req.get('host') + req.baseUrl + '/google/callback', grant_type: "authorization_code" }) }) let tokenInfo = await response.json() // the tokenInfo should contains id_token, and email can be extract from it if (!tokenInfo || !tokenInfo.id_token) { console.error('cannot find id_token from google response: ' + tokenInfo) } else { // extract email from id_token, and issue jwt_token, field = email let decoded = jwt.decode(tokenInfo.id_token) if (decoded.email === allowed_email) { // sign jwt and set cookie let token = jwt.sign({ email: allowed_email }, jwt_secret, { expiresInMinutes: 60 }) console.log('issue jwt: ' + token) res.cookie('jwt', token, { expires: new Date(Date.now() + 3600000), httpOnly: true }) } } res.redirect('/') })) export default router
JavaScript
0.000001
@@ -532,16 +532,44 @@ llback'%0A + console.log(callback_uri)%0A let qu
335fd2471ee7c12243da4872061391a1ff4853e4
update "js/formValidation.js" module (see msg)
js/formValidation.js
js/formValidation.js
/* * * */ define(function() { /* * Finding the form by ID is faster than finding it by its name. See the * jsPerf test at: http://jsperf.com/finding-input-fields. */ var allFields = document.getElementById("contact").getElementsByTagName("input"); for (key in allFields) { var theFields = allFields[key]; theFields.onblur = function() { if(this.value === "") { console.log("nope"); } } }; });
JavaScript
0
@@ -102,24 +102,42 @@ name -. See the %0A * + for the most %0A * part. See the jsP @@ -194,17 +194,16 @@ s.%0A */ - %0A var a @@ -348,16 +348,22 @@ s%5Bkey%5D;%0A + %0A t @@ -439,38 +439,128 @@ -console.log(%22nope%22);%0A %7D +var spanName = this.name + %22-error%22;%0A document.getElementById(spanName).innerHTML = this.name + %22 is required%22; %0A @@ -560,24 +560,25 @@ d%22;%0A +%7D %0A %7D%0A @@ -570,23 +570,24 @@ %7D%0A %7D%0A +%0A %7D;%0A%0A%7D);
0edaa5215359d5af78d56385381bb4678c69dce1
use `fromOptions` for read/write concern
lib/operations/command_v2.js
lib/operations/command_v2.js
'use strict'; const OperationBase = require('./operation').OperationBase; const resolveReadPreference = require('../utils').resolveReadPreference; class CommandOperationV2 extends OperationBase { constructor(parent, options) { super(options); this.ns = parent.s.namespace.withCollection('$cmd'); this.readPreference = resolveReadPreference(parent, this.options); this.readConcern = resolveReadConcern(parent, this.options); this.writeConcern = resolveWriteConcern(parent, this.options); this.explain = false; // TODO(NODE-2056): make logger another "inheritable" property if (parent.s.logger) { this.logger = parent.s.logger; } else if (parent.s.db && parent.s.db.logger) { this.logger = parent.s.db.logger; } } executeCommand(server, cmd, callback) { if (this.logger && this.logger.isDebug()) { this.logger.debug(`executing command ${JSON.stringify(cmd)} against ${this.ns}`); } let fullResponse = this.options.full; if (this.explain) { cmd = { explain: cmd }; fullResponse = false; } server.command(this.ns.toString(), cmd, this.options, (err, result) => { if (err) { callback(err, null); return; } if (fullResponse) { callback(null, result); return; } callback(null, result.result); }); } } function resolveWriteConcern(parent, options) { return options.writeConcern || parent.writeConcern; } function resolveReadConcern(parent, options) { return options.readConcern || parent.readConcern; } module.exports = CommandOperationV2;
JavaScript
0.000001
@@ -140,16 +140,114 @@ ference; +%0Aconst ReadConcern = require('../read_concern');%0Aconst WriteConcern = require('../write_concern'); %0A%0Aclass @@ -1524,17 +1524,9 @@ urn -options.w +W rite @@ -1528,24 +1528,45 @@ WriteConcern +.fromOptions(options) %7C%7C parent.w @@ -1641,17 +1641,9 @@ urn -options.r +R eadC @@ -1648,16 +1648,37 @@ dConcern +.fromOptions(options) %7C%7C pare
990908ddc85ce80728437d312997c6ff3f73e29d
Add 'check' dependency
package.js
package.js
Package.describe({ name: "zeroasterisk:throttle", summary: "A secure means of rate limiting, debounce even in a cluster (emails, etc)", version: "0.3.4", git: "https://github.com/zeroasterisk/Meteor-Throttle.git" }); Package.onUse(function (api) { api.versionsFrom("0.9.0"); api.use(['meteor', 'underscore'], 'server'); // Export the object 'Throttle' to packages or apps that use this package. api.export('Throttle', 'server'); api.addFiles('throttle.js', ['server']); }); Package.onTest(function (api) { api.use("zeroasterisk:throttle"); api.use('[email protected]'); api.addFiles('throttle_tests.js', ['client', 'server']); });
JavaScript
0
@@ -313,16 +313,25 @@ erscore' +, 'check' %5D, 'serv
d6412bafb45552507179ab69456a431b22c901c9
Bump version to 1.5.0.
package.js
package.js
Package.describe({ name: "froatsnook:shopify", version: "1.4.4", summary: "Shopify API Access", git: "https://github.com/froatsnook/meteor-shopify", documentation: "README.md" }); Package.onUse(function(api) { api.versionsFrom("1.0.3.1"); api.use("check", ["client", "server"]); api.use("http", ["client", "server"]); api.use("underscore", ["client", "server"]); api.use("webapp", "server"); api.use("froatsnook:[email protected]", ["client", "server"]); api.addFiles("lib/01-shopify.js", ["client", "server"]); api.addFiles("lib/02-APIMethods.js", ["client", "server"]); api.addFiles("lib/api.js", ["client", "server"]); api.addFiles("lib/Authenticators.js", ["client", "server"]); api.addFiles("lib/AuthRedirect.js", "server"); api.addFiles("lib/DefaultScopes.js", ["client", "server"]); api.addFiles("lib/Keyset.js", ["server"]); api.addFiles("lib/ProxyAPICache.js", ["server"]); api.export("Shopify", ["client", "server"]); }); Package.onTest(function(api) { Npm.depends({ "express": "4.12.2" }); api.use("tinytest"); api.use("webapp", "server"); api.use("check"); api.use("tracker"); api.use("froatsnook:[email protected]"); api.use("froatsnook:shopify"); api.addFiles("test/shopify-api-simulator.js", ["server"]); api.addFiles("test/shopify-tests.js"); });
JavaScript
0
@@ -64,11 +64,11 @@ %221. -4.4 +5.0 %22,%0A
c11db9e27567db47b339672f05a9c17706cbf819
Update openClosedVines.user.js
openClosedVines.user.js
openClosedVines.user.js
// ==UserScript== // @name Auto open sensitive Vines // @namespace http://nindogo.tumblr.com/ // @author Ni Ndogo // @version 0.1.1.0 // @description open vines that are hidden due to sensitivity. // @match https://vine.co/* // @downloadURL https://github.com/nindogo/test_repo/raw/master/openClosedVines.user.js // @require https://github.com/nindogo/test_repo/raw/master/mutation-summary.js // @run-at document-end // @copyright 2014+, Nindogo // ==/UserScript== var observer = new MutationSummary({ callback: openVines, queries: [{ element: 'button.small', elementAttributes: "button.small" // optional }] }); function openVines(summay) { console.log(summay[0].added); openVines2(summay[0].added); } function openVines2(u) { var i, x; //x = document.getElementsByClassName("small"); x=u; console.log(x.length); for (i = (x.length - 1); i > -1; i--) { console.log(i); console.log(x[i]); try { x[i].click(); } catch (error) { console.log("during " + i + " I caught error: " + error.type + " with message: " + error.message); } } }
JavaScript
0
@@ -30,19 +30,14 @@ -Auto o +O pen -s +S ensi @@ -108,12 +108,11 @@ -Ni N +nin dogo @@ -152,20 +152,37 @@ iption +This userscript open +s vines t @@ -189,11 +189,17 @@ hat -are +have been hid @@ -221,16 +221,29 @@ itivity. + (Adult, etc) %0A// @mat @@ -717,24 +717,26 @@ mmay) %7B%0A +// console.log( @@ -889,24 +889,26 @@ x=u;%0A +// console.log( @@ -962,32 +962,34 @@ i--) %7B%0A +// console.log(i);%0A @@ -988,32 +988,34 @@ log(i);%0A +// console.log(x%5Bi%5D
1ea3640cc0749d83d8f125a3327c35c58d0eede7
Bump version to 2.4.7
package.js
package.js
Package.describe({ name: 'jagi:astronomy', version: '2.4.6', summary: 'Model layer for Meteor', git: 'https://github.com/jagi/meteor-astronomy.git' }); Npm.depends({ lodash: '4.17.4' }); Package.onUse(function(api) { api.versionsFrom('1.3'); api.use([ 'ecmascript', 'es5-shim', 'ddp', 'mongo', 'check', 'minimongo', 'ejson', 'mdg:[email protected]' ], ['client', 'server']); api.mainModule('lib/main.js', ['client', 'server']); // For backward compatibility. api.export('Astro', ['client', 'server']); }); //////////////////////////////////////////////////////////////////////////////// Package.onTest(function(api) { api.use([ 'practicalmeteor:mocha', 'tinytest', 'ecmascript', 'es5-shim', 'insecure', 'mongo', 'ejson', 'jagi:[email protected]' ], ['client', 'server']); api.addFiles('test/utils.js', ['client', 'server']); // Core. api.addFiles([ 'test/core/inherit.js', 'test/core/extend.js', 'test/core/state.js', 'test/core/ejson.js' ], ['client', 'server']); // Modules. // Modules - Behaviors. api.addFiles([ 'test/modules/behaviors/create.js', 'test/modules/behaviors/apply.js' ], ['client', 'server']); // Modules - Validators. api.addFiles([ 'test/modules/validators/create.js', 'test/modules/validators/apply.js', 'test/modules/validators/validate.js', 'test/modules/validators/validate_callback.js' ], ['client', 'server']); // Modules - Storage. api.addFiles([ 'test/modules/storage/is_new.js', 'test/modules/storage/init.js', 'test/modules/storage/type_field.js', 'test/modules/storage/transform.js', 'test/modules/storage/document_insert.js', 'test/modules/storage/document_update.js', 'test/modules/storage/document_remove.js', 'test/modules/storage/class_insert.js', 'test/modules/storage/class_update.js', 'test/modules/storage/class_remove.js', 'test/modules/storage/reload.js', 'test/modules/storage/copy.js', ], ['client', 'server']); // Modules - Events. api.addFiles([ 'test/modules/events/order.js', 'test/modules/events/propagation.js', 'test/modules/events/cancelable.js' ], ['client', 'server']); // Modules - Fields. api.addFiles([ 'test/modules/fields/cast.js', 'test/modules/fields/default.js', 'test/modules/fields/definition.js', 'test/modules/fields/enum.js', 'test/modules/fields/get.js', 'test/modules/fields/merge.js', 'test/modules/fields/optional.js', 'test/modules/fields/raw.js', 'test/modules/fields/set.js' ], ['client', 'server']); // Modules - Indexes. api.addFiles([ // 'test/indexes/indexes_definition.js' ], 'server'); // Modules - Methods. api.addFiles([ 'test/modules/helpers/definition.js' ], ['client', 'server']); });
JavaScript
0
@@ -54,17 +54,17 @@ n: '2.4. -6 +7 ',%0A sum @@ -838,9 +838,9 @@ 2.4. -6 +7 '%0A
9ab39fa2824fad61d7d396159bb56929a5d9be16
fix merge conflict
js/ocean.js
js/ocean.js
var Wave = function(game, x, y, width, height) { this.game = game; Phaser.Image.call(this, this.game, x, y, 'wave'); //this.alpha = 1; var scaleX = width / this.width * 1.5; var scaleY = height / this.height * 1.5; this.scale.setTo(scaleX, scaleY); this.initialPos = { x: x, y: y }; // looks ugly, should be es6 already! this.animOffset = Math.random() * Math.PI * 2; } Wave.prototype = Object.create(Phaser.Image.prototype); Wave.prototype.constructor = Wave; Wave.prototype.updateWorld = function(shipMotion){ var w = this.width; var h = this.height; var gw = this.game.scale.bounds.width; var gh = this.game.scale.bounds.height; this.initialPos.x -= shipMotion.x; this.initialPos.y -= shipMotion.y; if (this.initialPos.x < -w ){ this.initialPos.x += gw + w * 2; }else if (this.initialPos.x > gw + h){ this.initialPos.x -= gw + w * 2; } if (this.initialPos.y < -h){ this.initialPos.y += gh + h * 2; }else if(this.initialPos.y > gh + h){ this.initialPos.y -= gh + h * 2; } }; Wave.prototype.update = function() { this.x = this.initialPos.x; this.y = this.initialPos.y; modulatePosition(this, 2.5, 4, 1, this.animOffset); } var Ocean = function(game) { this.game = game; Phaser.Group.call(this, this.game); var display = { width: game.scale.bounds.width, height: game.scale.bounds.height } var wavesPerRow = 24; var wavesPerColumn = 22; var waveSize = { width: display.width / (wavesPerRow - 1), // for overlap height: display.height / (wavesPerColumn - 1) }; this.waves = []; for(var y = -1; y < 23; y++) { var offsetX = random(0,120); for(var x = -1; x < 25; x++) { var wave = new Wave( this.game, x * waveSize.width - offsetX, y * waveSize.height, waveSize.width, waveSize.height ); this.add(wave); this.waves.push(wave); } } } Ocean.prototype = Object.create(Phaser.Group.prototype); Ocean.prototype.constructor = Ocean; Ocean.prototype.update = function() { Phaser.Group.prototype.update.call(this); //this.children.update(); // this.sort('zIndex', Phaser.Group.SORT_ASCENDING); /*this.children.sort(function(a, b) { return b.initialPos.y; });*/ } Ocean.prototype.updateWorld = function(shipMotion){ this.waves.forEach(function(wave){ wave.updateWorld(shipMotion); }); this.children.sort(function(a,b){ return a.y - b.y; }); this.children.forEach(function(child, index){ child.z = child.index; }); };
JavaScript
0.000003
@@ -333,16 +333,56 @@ lready!%0A +%0A%09this.tint = 0xc35918; // ASSAM color%0A%0A %09this.an
04fe258219797e85547cfbb45c8b4f4a73afd6ef
remove undifined function handleFocus
src/components/AddFolderForm/AddFolderForm.js
src/components/AddFolderForm/AddFolderForm.js
import React, {Component, PropTypes} from 'react'; import {Field, reduxForm} from 'redux-form'; import MenuItem from 'material-ui/MenuItem'; import FlatButton from 'material-ui/FlatButton'; import injectF from './../../helpers/injectF'; import injectMuiReduxFormHelper from './../../helpers/injectMuiReduxFormHelper'; import DICTIONARY_LANGS from './../../constants/dictionaryLangs'; import validate from './addFolderFormValidate'; import asyncValidate from './addFolderFormAsyncValidate'; const styles = require('./AddFolderForm.scss'); @reduxForm({ form: 'addFolderForm', asyncValidate, validate }) @injectF @injectMuiReduxFormHelper export default class AddFolderForm extends Component { static propTypes = { renderTextField: PropTypes.func.isRequired, onTargetLanguagesChange: PropTypes.func.isRequired, renderSelectField: PropTypes.func.isRequired, handleSubmit: PropTypes.func.isRequired, targetLanguages: PropTypes.array.isRequired, f: PropTypes.func.isRequired, onCancelButtonTouchTap: PropTypes.func.isRequired, values: PropTypes.object }; renderLangMenuItems(key) { return DICTIONARY_LANGS.map(({value, text}) => { return <MenuItem key={`${key}-${value}`} value={value} primaryText={text} />; }); } renderContentFields = () => { const {f, targetLanguages} = this.props; const DEFAULT_CONTENT_FILEDS = [ {textId: 'category', value: 'category'}, {textId: 'sect', value: 'sect'} ]; const fields = []; ['target-entry-lang', 'explaination-lang', 'original-lang', 'source-lang'].forEach((textId) => { (targetLanguages || []).forEach((lang) => { fields.push({textId, params: {lang: f(lang)}, value: `${textId}-${lang}`}); }); }); return fields.concat(DEFAULT_CONTENT_FILEDS) .map(({value, textId, params}) => { return <MenuItem key={`content-field-${value}`} value={value} primaryText={f(textId, params)} />; }); }; handleBlur = (event) => { // fix leaving a form takes two clicks // https://github.com/erikras/redux-form/issues/860 const {relatedTarget} = event; if (relatedTarget && ('button' === relatedTarget.getAttribute('type'))) { event.preventDefault(); } }; render() { const {handleSubmit, f, onCancelButtonTouchTap, renderTextField, renderSelectField, onTargetLanguagesChange} = this.props; return ( <form className={styles.addFolderForm} onSubmit={handleSubmit}> <div className={styles.formBody}> <div> <Field name="folderName" component={renderTextField} label={f('folder-name')} onFocus={this.handleFocus} onBlur={this.handleBlur} autoFocus /> </div> <div> <Field name="sourceLanguage" component={renderSelectField} label={f('source-language')}> {this.renderLangMenuItems('source-lang')} </Field> </div> <div> <Field name="targetLanguages" component={renderSelectField} onChange={onTargetLanguagesChange} label={f('target-language')} multiple> {this.renderLangMenuItems('target-lang')} </Field> </div> <div> <Field name="contentFields" component={renderSelectField} label={f('content-fields')} multiple fullWidth> {this.renderContentFields()} </Field> </div> <div> <Field name="source" component={renderTextField} label={f('source')} /> </div> </div> <div className={styles.formFooter}> <FlatButton type="button" label="Cancel" onTouchTap={onCancelButtonTouchTap} /> <FlatButton type="submit" label="Submit" primary /> </div> </form> ); } }
JavaScript
0.000002
@@ -2633,35 +2633,8 @@ e')%7D - onFocus=%7Bthis.handleFocus%7D onB
970c254ec4feddda6c59cbbf6a5bad6efdd39bc4
Disable NoFragmentCyclesRule
packages/relay-compiler/graphql-compiler/core/GraphQLValidator.js
packages/relay-compiler/graphql-compiler/core/GraphQLValidator.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @providesModule GraphQLValidator * @format */ 'use strict'; const Profiler = require('./GraphQLCompilerProfiler'); const util = require('util'); const { formatError, FragmentsOnCompositeTypesRule, KnownArgumentNamesRule, KnownTypeNamesRule, LoneAnonymousOperationRule, NoFragmentCyclesRule, NoUnusedVariablesRule, PossibleFragmentSpreadsRule, ProvidedNonNullArgumentsRule, ScalarLeafsRule, UniqueArgumentNamesRule, UniqueFragmentNamesRule, UniqueInputFieldNamesRule, UniqueOperationNamesRule, UniqueVariableNamesRule, validate, ValuesOfCorrectTypeRule, VariablesAreInputTypesRule, VariablesDefaultValueAllowedRule, VariablesInAllowedPositionRule, } = require('graphql'); import type {DocumentNode, GraphQLSchema} from 'graphql'; function validateOrThrow( document: DocumentNode, schema: GraphQLSchema, rules: Array<Function>, ): void { const validationErrors = validate(schema, document, rules); if (validationErrors && validationErrors.length > 0) { const formattedErrors = validationErrors.map(formatError); const errorMessages = validationErrors.map( e => (e.source ? `${e.source.name}: ${e.message}` : e.message), ); const error = new Error( util.format( 'You supplied a GraphQL document with validation errors:\n%s', errorMessages.join('\n'), ), ); (error: any).validationErrors = formattedErrors; throw error; } } module.exports = { GLOBAL_RULES: [ KnownArgumentNamesRule, // TODO #19327202 Relay Classic generates some fragments in runtime, so Relay // Modern queries might reference fragments unknown in build time //KnownFragmentNamesRule, NoFragmentCyclesRule, // TODO #19327144 Because of @argumentDefinitions, this validation // incorrectly marks some fragment variables as undefined. // NoUndefinedVariablesRule, // TODO #19327202 Queries generated dynamically with Relay Classic might use // unused fragments // NoUnusedFragmentsRule, NoUnusedVariablesRule, // TODO #19327202 Relay Classic auto-resolves overlapping fields by // generating aliases //OverlappingFieldsCanBeMergedRule, ProvidedNonNullArgumentsRule, UniqueArgumentNamesRule, UniqueFragmentNamesRule, UniqueInputFieldNamesRule, UniqueOperationNamesRule, UniqueVariableNamesRule, ], LOCAL_RULES: [ // TODO #13818691: make this aware of @fixme_fat_interface // FieldsOnCorrectTypeRule, FragmentsOnCompositeTypesRule, KnownTypeNamesRule, // TODO #17737009: Enable this after cleaning up existing issues // KnownDirectivesRule, LoneAnonymousOperationRule, PossibleFragmentSpreadsRule, ScalarLeafsRule, VariablesDefaultValueAllowedRule, ValuesOfCorrectTypeRule, VariablesAreInputTypesRule, VariablesInAllowedPositionRule, ], validate: Profiler.instrument(validateOrThrow, 'GraphQLValidator.validate'), };
JavaScript
0
@@ -476,32 +476,8 @@ le,%0A - NoFragmentCyclesRule,%0A No @@ -1830,16 +1830,17 @@ e%0A // + KnownFra @@ -1858,16 +1858,173 @@ ule,%0A + // TODO: #25618795 Because of @argumentDefinitions, this validation%0A // incorrectly flags a subset of fragments using @include/@skip as recursive.%0A // NoFragm
81fee764c73a9c16c5e6899af4ca00cc5aedce30
use gpsi promise
lib/plugins/gpsi/analyzer.js
lib/plugins/gpsi/analyzer.js
'use strict'; var Promise = require('bluebird'), log = require('intel'), gpagespeed = require('gpagespeed'); gpagespeed = Promise.promisify(gpagespeed); module.exports = { analyzeUrl: function(url, options) { log.info('Sending url ' + url + ' to test on Page Speed Insights'); const args = {url}; if (options.gpsi.key) { args.key = options.gpsi.key; } else { args.nokey = true; } args.strategy = "desktop"; if(options.mobile) { args.strategy = "mobile"; } return gpagespeed(args); } };
JavaScript
0
@@ -16,41 +16,8 @@ var -Promise = require('bluebird'),%0A log @@ -79,53 +79,8 @@ );%0A%0A -gpagespeed = Promise.promisify(gpagespeed);%0A%0A modu
eb2b0b00959f5f0f01dda05b7b8fc45bad54715c
Add comment to package.js
package.js
package.js
(function () { 'use strict'; var chimpVersion = '0.19.4'; var meteorChimpVersion = '_1'; Package.describe({ name: 'xolvio:cucumber', summary: 'CucumberJS for Velocity', version: chimpVersion + meteorChimpVersion, git: 'https://github.com/xolvio/chimp.git', debugOnly: true }); Npm.depends({ 'chimp': chimpVersion, 'colors': '1.1.2', 'fs-extra': '0.24.0', "tail-forever": "0.3.11", 'freeport': '1.0.5' }); Package.onUse(function (api) { api.versionsFrom('[email protected]'); api.use([ 'underscore', 'http', 'velocity:[email protected]', 'velocity:[email protected]', 'simple:[email protected]', 'sanjo:[email protected]' ], ['server', 'client']); api.use([ 'velocity:[email protected]' ], 'client'); api.addAssets([ 'meteor/src/sample-tests/feature.feature', 'meteor/src/sample-tests/steps.js', 'meteor/src/sample-tests/package.json', 'meteor/src/sample-tests/fixture.js' ], 'server'); api.addFiles(['meteor/src/hub-server.js'], 'server'); api.addFiles(['meteor/src/mirror-server.js'], 'server'); }); })();
JavaScript
0
@@ -26,16 +26,205 @@ rict';%0A%0A + /**%0A * This package.js file is used for Meteor package management%0A * http://docs.meteor.com/#/full/packagejs%0A *%0A * Not using Meteor? Ignore this, and look at package.json%0A */%0A%0A var ch
cbcb66112633cb583eb85e37c043cc8cb639a15c
fix blur event for multiselect
js/ld-ui-elements.js
js/ld-ui-elements.js
//get mulitselect options and add to a new div, also create a new button to display //selected options and toggle the new options div. Also hide the current select. function multiSelect(selectElem) { var selectObject = {select: selectElem}; var options = selectElem.getElementsByTagName('option'); var multi = $("<div class='ld-multi-select'>"); multi.css("max-width", selectObject.width); var button = selectObject.button = $("<span class='btn-select'>"); button.on('click', function(event) {toggleOptionsPanel(selectObject);}); var display = selectObject.display = $("<span class='placeholder'>"); button.append(display); var optPanel = selectObject.optPanel = $("<div class='option-panel' tabindex=-1>"); optPanel.on('blur', function() { //need to remove button click tempurally button.off('click'); selectObject.optPanel.removeClass('show-selection'); setTimeout(function() { button.on('click', function(event) {toggleOptionsPanel(selectObject);}); }, 100) }) list =$("<ul class='option-group'>"); optPanel.append(list); optPanel.on('mousedown', function(event){ startSelectGroup(selectObject, event)}) list.on('scroll', function(event){ turnOffSelectEvents(selectObject); }) for (var i = 0; i < options.length; i++) { var label = $("<li class='option' value="+ options[i].value + ">" + options[i].textContent + "</li>"); label.on('mousedown', function(event) { optionSelectStart(selectObject, event) }); list.append(label); } multi.append(button); multi.append(optPanel); $(selectElem).after(multi); selectElem.style.display = "none"; updateDisplay(selectObject); } function optionSelectStart(selectObject, event) { if (!event.ctrlKey) { selectObject.optPanel.find('li').each(function(index, element) { var elementObj = $(element) resetOption(elementObj); }) } else { selectObject.optPanel.find('li.selected').each(function(index, element) { $(element).addClass('locked'); }); } $(event.currentTarget).addClass('locked selected'); } function resetOption(elementObj) { elementObj.removeClass('locked'); elementObj.removeClass('selected'); elementObj.off('mouseenter', addSelectClass); elementObj.off('mouseleave', removeSelectClass); } function toggleOptionsPanel(selectObject) { if (selectObject.optPanel.hasClass('show-selection')) { return } selectObject.optPanel.addClass('show-selection'); selectObject.optPanel.find('li').each(function(index, element) { var elementObj = $(element); resetOption(elementObj); selectedItems = $(selectObject.select).find("[value='" + element.value + "']:selected") if (selectedItems.length > 0) { elementObj.addClass('selected'); } }) selectObject.optPanel.focus(); } function startSelectGroup(selectObject, event){ event.preventDefault(); selectObject.optPanel.on('mouseup', function(){ endSelectGroup(selectObject)}) selectObject.optPanel.on('mouseleave', function(){ $(document).on('mouseup', function(){endSelectGroup(selectObject)}); }) setSelectGroup(selectObject); var position = event.clientY; var diff = null; selectObject.optPanel.off('mousemove'); selectObject.optPanel.on('mousemove', function(event) { if (diff != null && Math.abs(diff) > Math.abs(event.clientY - position)) { //reverse setSelectGroup(selectObject); } diff = event.clientY - position; }) } function setSelectGroup(selectObject) { selectObject.optPanel.find('li').each(function(index, element) { if ($(element).hasClass('locked')) { return } if ($(element).hasClass('selected')) { $(element).off('mouseenter', addSelectClass); $(element).on('mouseleave', removeSelectClass); } else { $(element).on('mouseenter', addSelectClass); $(element).off('mouseleave', removeSelectClass); } }) } function endSelectGroup(selectObject) { var selected = []; selectObject.optPanel.find('li').each(function(index, element) { if ($(element).hasClass("selected")) { selected.push(element.value); } }) $(selectObject.select).val(selected); selectObject.select.onchange(); turnOffSelectEvents(selectObject); toggleOptionsPanel(selectObject); updateDisplay(selectObject); } function turnOffSelectEvents(selectObject) { selectObject.optPanel.off("mouseup"); selectObject.optPanel.off("mousemove"); selectObject.optPanel.off("mouseleave"); $(document).off("mouseup"); selectObject.optPanel.find('li').each(function(index, element) { var elementObj = $(element); elementObj.off('mouseenter', addSelectClass); elementObj.off('mouseleave', removeSelectClass); }) } function updateDisplay(selectObject) { var count = $(selectObject.select).find("option").length var selectedCount = $(selectObject.select).find(":selected").length selectObject.display.text(selectedCount + "/" + count); } function addSelectClass(event) { $(event.currentTarget).addClass('selected'); } function removeSelectClass(event) { $(event.currentTarget).removeClass('selected'); }
JavaScript
0.000001
@@ -2022,23 +2022,139 @@ -%7D)%0A %7D else %7B +$(event.currentTarget).addClass('locked selected');%0A %7D)%0A %7D else %7B%0A $(event.currentTarget).toggleClass('selected'); %0A @@ -2297,64 +2297,8 @@ %7D%0A - $(event.currentTarget).addClass('locked selected');%0A %7D%0Afu @@ -2621,30 +2621,75 @@ ) %7B%0A -return +selectObject.optPanel.removeClass('show-selection') %0A %7D%0A s @@ -4663,41 +4663,59 @@ -toggleOptionsPanel(selectObject); +selectObject.optPanel.removeClass('show-selection') %0A
def8d559c9f09076d5d6e42b00a7d5061e3b0b81
Use USDDisplay for displaying Steem and SBD values in SteemTrendingCharts component (#1044)
src/components/Sidebar/SteemTrendingCharts.js
src/components/Sidebar/SteemTrendingCharts.js
import React, { Component } from 'react'; import Trend from 'react-trend'; import fetch from 'isomorphic-fetch'; import _ from 'lodash'; import Promise from 'bluebird'; import { FormattedMessage } from 'react-intl'; import Loading from '../Icon/Loading'; import './SteemTrendingCharts.less'; const getSteemPriceHistory = () => fetch('https://min-api.cryptocompare.com/data/histoday?fsym=STEEM&tsym=USD&limit=7').then(res => res.json(), ); const getSteemDollarPriceHistory = () => fetch('https://min-api.cryptocompare.com/data/histoday?fsym=SBD&tsym=USD&limit=7').then(res => res.json(), ); class SteemTrendingCharts extends Component { state = { steemPriceHistory: [], steemDollarPriceHistory: [], loading: false, }; componentDidMount() { this.getSteemPriceHistories(); } getSteemPriceHistories = () => { this.setState({ loading: true, }); Promise.all([getSteemPriceHistory(), getSteemDollarPriceHistory()]).then((response) => { const steemPriceHistory = _.map(response[0].Data, data => data.close); const steemDollarPriceHistory = _.map(response[1].Data, data => data.close); this.setState({ steemPriceHistory, steemDollarPriceHistory, loading: false, }); }); }; render() { const { steemPriceHistory, steemDollarPriceHistory, loading } = this.state; const currentSteemPrice = _.last(steemPriceHistory); const currentSteemDollarPrice = _.last(steemDollarPriceHistory); const previousSteemPrice = _.nth(steemPriceHistory, -2); const previousSteemDollarPrice = _.nth(steemDollarPriceHistory, -2); const steemPriceIncrease = currentSteemPrice > previousSteemPrice; const steemDollarPriceIncrease = currentSteemDollarPrice > previousSteemDollarPrice; return ( <div className="SteemTrendingCharts"> <h4 className="SteemTrendingCharts__title"> <i className="iconfont icon-chart SteemTrendingCharts__icon" /> <FormattedMessage id="market" defaultMessage="Market" /> <i role="presentation" onClick={this.getSteemPriceHistories} className="iconfont icon-refresh SteemTrendingCharts__icon-refresh" /> </h4> <div className="SteemTrendingCharts__divider" /> <div className="SteemTrendingCharts__chart-header"> <FormattedMessage id="steem" defaultMessage="Steem" /> {!loading && <span className="SteemTrendingCharts__chart-value"> {`$${currentSteemPrice}`} {steemPriceIncrease ? <i className="iconfont icon-caret-up SteemTrendingCharts__chart-caret-up" /> : <i className="iconfont icon-caretbottom SteemTrendingCharts__chart-caret-down" />} </span>} </div> {loading ? <Loading /> : <Trend data={steemPriceHistory} stroke={'#4757b2'} strokeWidth={5} />} <div className="SteemTrendingCharts__divider" /> <div className="SteemTrendingCharts__chart-header"> <FormattedMessage id="steem_dollar" defaultMessage="Steem Dollar" /> {!loading && <span className="SteemTrendingCharts__chart-value"> {`$${currentSteemDollarPrice} `} {steemDollarPriceIncrease ? <i className="iconfont icon-caret-up SteemTrendingCharts__chart-caret-up" /> : <i className="iconfont icon-caretbottom SteemTrendingCharts__chart-caret-down" />} </span>} </div> {loading ? <Loading /> : <Trend data={steemDollarPriceHistory} stroke={'#4757b2'} strokeWidth={5} />} </div> ); } } export default SteemTrendingCharts;
JavaScript
0
@@ -284,16 +284,76 @@ s.less'; +%0Aimport USDDisplay from '../../components/Utils/USDDisplay'; %0A%0Aconst @@ -2578,36 +2578,50 @@ %3E%0A -%7B%60$$ +%3CUSDDisplay value= %7BcurrentSteemPri @@ -2623,18 +2623,19 @@ emPrice%7D -%60%7D + /%3E %0A @@ -3318,12 +3318,26 @@ -%7B%60$$ +%3CUSDDisplay value= %7Bcur @@ -3362,10 +3362,10 @@ ce%7D -%60%7D +/%3E %0A
910f12ab51ed54970bab5111cc57e7ce2c425e68
Update title screen instructions
js/screens/title.js
js/screens/title.js
game.TitleScreen = me.ScreenObject.extend({ init: function () { this._super(me.ScreenObject, 'init'); this.font = null; this.ground1 = null; this.ground2 = null; this.logo = null; }, onResetEvent: function () { me.audio.stop("theme"); game.data.newHiScore = false; me.game.world.addChild(new BackgroundLayer('bg', 1)); me.input.bindKey(me.input.KEY.ENTER, "enter", true); me.input.bindKey(me.input.KEY.SPACE, "enter", true); me.input.bindPointer(me.input.mouse.LEFT, me.input.KEY.ENTER); game.doppler.callback = function() { // simulate space bar key down me.input.triggerKeyEvent(me.input.KEY.ENTER, true); // key up after 200ms for next action setTimeout(function () { me.input.triggerKeyEvent(me.input.KEY.ENTER, false); }, 200); }; this.handler = me.event.subscribe(me.event.KEYDOWN, function (action, keyCode, edge) { if (action === "enter") { me.state.change(me.state.PLAY); } }); //logo var logoImg = me.loader.getImage('logo'); this.logo = new me.Sprite( me.game.viewport.width / 2 - 170, -logoImg, logoImg ); me.game.world.addChild(this.logo, 10); var that = this; var logoTween = me.pool.pull("me.Tween", this.logo.pos) .to({y: me.game.viewport.height / 2 - 100}, 1000) .easing(me.Tween.Easing.Exponential.InOut).start(); this.ground1 = me.pool.pull("ground", 0, me.video.renderer.getHeight() - 96); this.ground2 = me.pool.pull("ground", me.video.renderer.getWidth(), me.video.renderer.getHeight() - 96); me.game.world.addChild(this.ground1, 11); me.game.world.addChild(this.ground2, 11); me.game.world.addChild(new (me.Renderable.extend({ // constructor init: function () { // size does not matter, it's just to avoid having a zero size // renderable this._super(me.Renderable, 'init', [0, 0, 100, 100]); this.text = me.device.touch ? 'Tap to start' : 'PRESS SPACE OR CLICK LEFT MOUSE BUTTON TO START \n\t\t\t\t\t\t\t\t\t\t\tPRESS "M" TO MUTE SOUND'; this.font = new me.Font('gamefont', 20, '#000'); }, draw: function (renderer) { var context = renderer.getContext(); var measure = this.font.measureText(context, this.text); var xpos = me.game.viewport.width / 2 - measure.width / 2; var ypos = me.game.viewport.height / 2 + 50; this.font.draw(context, this.text, xpos, ypos); } })), 12); }, onDestroyEvent: function () { // unregister the event me.event.unsubscribe(this.handler); me.input.unbindKey(me.input.KEY.ENTER); me.input.unbindKey(me.input.KEY.SPACE); me.input.unbindPointer(me.input.mouse.LEFT); this.ground1 = null; this.ground2 = null; me.game.world.removeChild(this.logo); this.logo = null; } });
JavaScript
0.000001
@@ -1968,24 +1968,179 @@ %5D);%0A +this.text1 = 'Allow access to your microphone';%0A this.text2 = 'Swipe your hand upwards past it to start the game and make the bird fly!';%0A // this.text = @@ -2418,16 +2418,17 @@ text();%0A +%0A @@ -2431,17 +2431,276 @@ var -m +text1Measure = this.font.measureText(context, this.text1);%0A var xpos = me.game.viewport.width / 2 - text1Measure.width / 2;%0A var ypos = me.game.viewport.height / 2 + 50;%0A this.font.draw(context, this.text1, xpos, ypos);%0A%0A var text2M easure = @@ -2740,16 +2740,17 @@ his.text +2 );%0A @@ -2792,17 +2792,22 @@ h / 2 - -m +text2M easure.w @@ -2857,34 +2857,34 @@ rt.height / 2 + +7 5 -0 ;%0A this.f @@ -2910,16 +2910,17 @@ his.text +2 , xpos, @@ -2926,16 +2926,19 @@ ypos);%0A +%0A%0A%0A %7D%0A
c32a9fee2afa6c74cc0f380cb3c06a3895eb8446
fix jquery fail status
js/peter.js
js/peter.js
(function($) { $(function() { $('.form-horizontal').on('submit', function() { if ($('#inputStudentNum').val() === "") { alert('Please enter username!!'); return false; } $.post('/user/login', { 'school_id' : $('#inputStudentNum').val() }, function(response) { if (response.status === 0) { // Success! //console.log(response.data); //alert(JSON.stringify(response.data)); location.href = '/'; //var term = $('#inputStudentNum').val(); } else { // Fail. alert(response.data); } }, 'json'); return false; }); }); })(jQuery);
JavaScript
0.000001
@@ -298,229 +298,90 @@ %09%09%09%09 -if (response.status === 0) %7B%0A%09%09%09%09%09// Success!%0A%09%09%09%09%09//console.log(response.data);%0A%09%09%09%09%09//alert(JSON.stringify(response.data));%0A%09%09%09%09%09location.href = '/';%0A%09%09%09%09%09//var term = $('#inputStudentNum').val();%0A%09%09%09%09%7D%0A%09%09%09%09else +// Success!%0A%09%09%09%09location.href = '/';%0A%09%09%09%7D, 'json')%0A%09%09%09.fail(function(jqxhr) %7B%0A%09%09%09%09 -%09 // F @@ -393,23 +393,28 @@ %09%09%09%09 -%09 alert( +jqxhr. response .dat @@ -413,16 +413,20 @@ onse +JSON .data);%0A %09%09%09%09 @@ -425,26 +425,12 @@ a);%0A -%09 %09%09%09%7D -%0A%09%09%09%7D, 'json' );%0A%09
fd2365df325498a00c678721189862b6685636c7
add res.response
lib/init.js
lib/init.js
var PipeStream = require('pipestream'); var Transform = PipeStream.Transform; var util = require('./util'); var config = require('./config'); function addErrorEvents(req, res) { var clientReq, clientRes; req.on('dest', function(_req) { clientReq = _req.on('error', util.noop); }).on('error', abort) .on('close', abort); res.on('src', function(_res) { clientRes = _res.on('error', abort); }).on('error', abort); function abort(err) { if (clientReq) { if (clientReq.abort) { clientReq.abort(); } else if (clientReq.destroy) { clientReq.destroy(); } } res.destroy(); } } function addTransforms(req, res) { var reqTextPipeStream, resZipPipeStream, resIconvPipeStream, svrRes; req.addTextTransform = function(transform) { if (!reqTextPipeStream) { reqTextPipeStream = util.getPipeIconvStream(req.headers, true); delete req.headers['content-length']; req.add(reqTextPipeStream); } reqTextPipeStream.add(transform); return req; }; function initZipTransform() { if (!resZipPipeStream) { resZipPipeStream = new PipeStream(); removeContentLength(); res.add(function(src, next) { var pipeZipStream = util.getPipeZipStream(res.headers); pipeZipStream.addHead(resZipPipeStream); if (resIconvPipeStream) { var pipeIconvStream = util.getPipeIconvStream(res.headers); pipeIconvStream.add(resIconvPipeStream); pipeZipStream.add(pipeIconvStream); } next(src.pipe(pipeZipStream)); }); } return resZipPipeStream; } res.addZipTransform = function(transform, head, tail) { initZipTransform()[head ? 'addHead' : (tail ? 'addTail' : 'add')](transform); return res; }; res.addTextTransform = function(transform, head, tail) { if (!resIconvPipeStream) { initZipTransform(); resIconvPipeStream = new PipeStream(); } resIconvPipeStream[head ? 'addHead' : (tail ? 'addTail' : 'add')](transform); return res; }; res.on('src', function(_res) { svrRes = _res; removeContentLength(); }); function removeContentLength() { if (svrRes && (resZipPipeStream || resIconvPipeStream)) { delete svrRes.headers['content-length']; } } } module.exports = function(req, res, next) { PipeStream.wrapSrc(req); PipeStream.wrapDest(res); addTransforms(req, res); addErrorEvents(req, res); var socket = req.socket || {}; socket[config.CLIENT_IP_HEAD] = req.headers[config.CLIENT_IP_HEAD] = socket[config.CLIENT_IP_HEAD] || util.getClientIp(req); if (req.headers[config.HTTPS_FIELD] || req.socket.isHttps) {//防止socket长连接导致新请求的头部无法加util.HTTPS_FIELD req.socket.isHttps = true; req.isHttps = true; delete req.headers[config.HTTPS_FIELD]; } var responsed; res.response = function(_res) { if (responsed) { return; } responsed = true; if (_res.realUrl) { req.realUrl = res.realUrl = _res.realUrl; } res.headers = _res.headers; res.trailers = _res.trailers; res.statusCode = _res.statusCode = _res.statusCode || 0; res.src(_res); removeDisableProps(req, _res.headers); res.trailers && res.addTrailers(res.trailers); }; next(); };
JavaScript
0.000031
@@ -2982,49 +2982,8 @@ s);%0A -%09%09removeDisableProps(req, _res.headers);%0A %09%09re
4f053c5fdd665e4d3dd1ccd630014e79d15c377f
patch release - Bump to version 0.9.13
package.js
package.js
Package.describe({ summary: "Accounts Templates styled for Twitter Bootstrap.", version: "0.9.12", name: "splendido:accounts-templates-bootstrap", git: "https://github.com/splendido/accounts-templates-bootstrap.git", }); Package.on_use(function(api, where) { api.versionsFrom("[email protected]"); api.use([ "less", "templating", ], "client"); api.use([ "splendido:accounts-templates-core", ], ["client", "server"]); api.imply([ "splendido:[email protected]", ], ["client", "server"]); api.add_files([ "lib/at_error.html", "lib/at_error.js", "lib/at_form.html", "lib/at_form.js", "lib/at_input.html", "lib/at_input.js", "lib/at_oauth.html", "lib/at_oauth.js", "lib/at_pwd_form.html", "lib/at_pwd_form.js", "lib/at_pwd_form_btn.html", "lib/at_pwd_form_btn.js", "lib/at_pwd_link.html", "lib/at_pwd_link.js", "lib/at_result.html", "lib/at_result.js", "lib/at_sep.html", "lib/at_sep.js", "lib/at_signin_link.html", "lib/at_signin_link.js", "lib/at_signup_link.html", "lib/at_signup_link.js", "lib/at_social.html", "lib/at_social.js", "lib/at_terms_link.html", "lib/at_terms_link.js", "lib/at_title.html", "lib/at_title.js", "lib/full_page_at_form.html", "lib/at_bootstrap.less" ], ["client"]); }); Package.on_test(function(api) { api.use([ "splendido:accounts-templates-bootstrap", "splendido:[email protected]", ]); api.use([ "accounts-password", "tinytest", "test-helpers" ], ["client", "server"]); api.add_files([ "tests/tests.js" ], ["client", "server"]); });
JavaScript
0
@@ -92,25 +92,25 @@ sion: %220.9.1 -2 +3 %22,%0A name: @@ -527,33 +527,33 @@ [email protected] -2 +3 %22,%0A %5D, %5B%22clie @@ -1671,17 +1671,17 @@ [email protected] -2 +3 %22,%0A %5D
c9c5bc66945e87413b791761055c3ba00add7682
Add helper action to bundle pile dispersing and coloring
src/components/fragments/fragments-actions.js
src/components/fragments/fragments-actions.js
export const ADD_PILES = 'ADD_PILES'; export const addPiles = piles => ({ type: ADD_PILES, payload: { piles } }); export const DISPERSE_PILES = 'DISPERSE_PILES'; export const dispersePiles = piles => ({ type: DISPERSE_PILES, payload: { piles } }); export const RECOVER_PILES = 'RECOVER_PILES'; export const recoverPiles = piles => ({ type: RECOVER_PILES, payload: { piles } }); export const REMOVE_PILES = 'REMOVE_PILES'; export const removePiles = piles => ({ type: REMOVE_PILES, payload: { piles } }); export const SET_ANIMATION = 'SET_ANIMATION'; export const setAnimation = animation => ({ type: SET_ANIMATION, payload: { animation: !!animation } }); export const SET_ARRANGE_MEASURES = 'SET_ARRANGE_MEASURES'; export const setArrangeMeasures = arrangeMeasures => ({ type: SET_ARRANGE_MEASURES, payload: { arrangeMeasures } }); export const SET_CELL_SIZE = 'SET_CELL_SIZE'; export const setCellSize = cellSize => ({ type: SET_CELL_SIZE, payload: { cellSize } }); export const SET_COVER_DISP_MODE = 'SET_COVER_DISP_MODE'; export const setCoverDispMode = coverDispMode => ({ type: SET_COVER_DISP_MODE, payload: { coverDispMode } }); export const SET_LASSO_IS_ROUND = 'SET_LASSO_IS_ROUND'; export const setLassoIsRound = lassoIsRound => ({ type: SET_LASSO_IS_ROUND, payload: { lassoIsRound } }); export const SET_MATRIX_ORIENTATION = 'SET_MATRIX_ORIENTATION'; export const setMatrixOrientation = orientation => ({ type: SET_MATRIX_ORIENTATION, payload: { orientation } }); export const SET_MATRIX_FRAME_ENCODING = 'SET_MATRIX_FRAME_ENCODING'; export const setMatrixFrameEncoding = frameEncoding => ({ type: SET_MATRIX_FRAME_ENCODING, payload: { frameEncoding } }); export const SET_PILE_MODE = 'SET_PILE_MODE'; export const setPileMode = (mode, pile) => ({ type: SET_PILE_MODE, payload: { mode, pile } }); export const SET_PILES = 'SET_PILES'; export const setPiles = piles => ({ type: SET_PILES, payload: { piles } }); export const SET_PILES_COLORS = 'SET_PILES_COLORS'; export const setPilesColors = pilesColors => ({ type: SET_PILES_COLORS, payload: { pilesColors } }); export const SET_SHOW_SPECIAL_CELLS = 'SET_SHOW_SPECIAL_CELLS'; export const setShowSpecialCells = showSpecialCells => ({ type: SET_SHOW_SPECIAL_CELLS, payload: { showSpecialCells } }); export const STACK_PILES = 'STACK_PILES'; export const stackPiles = pileStacks => ({ type: STACK_PILES, payload: { pileStacks } }); export const TRASH_PILES = 'TRASH_PILES'; export const trashPiles = piles => ({ type: TRASH_PILES, payload: { piles } }); export const UPDATE_FGM_CONFIG = 'UPDATE_FGM_CONFIG'; export const updateConfig = config => ({ type: UPDATE_FGM_CONFIG, payload: { config } });
JavaScript
0
@@ -245,32 +245,250 @@ %7B piles %7D%0A%7D);%0A%0A +export const DISPERSE_PILES_WITH_COLOR = 'DISPERSE_PILES_WITH_COLOR';%0A%0Aexport const dispersePilesWithColors = piles =%3E (dispath) =%3E %7B%0A dispath(dispersePiles(piles.piles));%0A dispath(setPilesColors(piles.colors));%0A%7D;%0A%0A export const REC
8f1e82991d97fc8a16a6b7e79baa9a7566d08a56
add "libbitcoin team" to default list of contacts when creating new wallet.
js/model/contacts.js
js/model/contacts.js
'use strict'; define(['bitcoinjs-lib', 'util/btc'], function(Bitcoin, BtcUtils) { var Crypto = Bitcoin.CryptoJS; /** * Contacts (Address book). * @param {Object} store Object store * @constructor */ function Contacts(store, identity) { this.store = store; this.identity = identity this.contacts = this.store.init('contacts', [ { name: 'DarkWallet team', address: '31oSGBBNrpCiENH3XMZpiP6GTC4tad4bMy' } ]); this.validAddresses = [ identity.wallet.versions.address, identity.wallet.versions.stealth.address, identity.wallet.versions.p2sh ] this.initContacts(); } /** * Update contacts after loading them. * @private */ Contacts.prototype.initContacts = function() { var self = this; var updated; // TODO Remove when Darkwallet 1.0 release this.contacts.forEach(function(contact) { if (!contact) { return; } if (!contact.pubKeys) { self.updateKey(contact, contact.address, 0); contact.mainKey = 0; updated = true; self.updateContactHash(contact); // delete address since now is contained inside contact.pubKeys delete contact.address; } }); if (updated) { console.log("updated contacts", this.contacts); // this.store.save(); } }; /** * Update address for a contact * @param {Object} contact Dictionary with a field address to feed the hash */ Contacts.prototype.prepareAddress = function(data) { var addresses = []; // {pubKey: ..., address: ..., data: ..., type: ...} var pubKey; try { // for now show uncompressed for contacts from uncompressed pubkeys pubKey = BtcUtils.extractPublicKey(data, (data.length == 130) ? false : true); } catch (e) { } var newKey = {data: data, pubKey: pubKey, type: 'address'}; if (BtcUtils.isAddress(data, this.validAddresses)) { newKey.address = data; if (data[0] == '6') { newKey.type = 'stealth'; } } else if (pubKey) { var pubKeyHash = Bitcoin.crypto.hash160(pubKey); var address = new Bitcoin.Address(pubKeyHash, this.identity.wallet.versions.address).toString(); newKey.address = address; newKey.type = 'pubkey'; } else { console.log("cant decode address properly!"); newKey.address = data; newKey.type = 'unknown'; } return newKey; }; /** * Update fingerprint hash for a contact * @param {Object} contact Dictionary with a field address to feed the hash */ Contacts.prototype.updateContactHash = function(contact) { contact.hash = this.generateAddressHash(contact.pubKeys[contact.mainKey].address); }; /** * Generate fingerprint hash for some address * @param {String} address address to generate the hash from */ Contacts.prototype.generateAddressHash = function(address) { return Crypto.SHA256(address).toString(); }; /** * Generate fingerprint hash for some data * @param {String} data address or pubkey to generate the hash from */ Contacts.prototype.generateContactHash = function(data) { var newKey = this.prepareAddress(data); return Crypto.SHA256(newKey.address).toString(); }; /** * Find Contact by pubkey * @param {Object} pubKey Public key to find. * @return {Object|null} The contact if it is there */ Contacts.prototype.findByPubKey = function (pubKey) { var toCheck = pubKey.toString(); var compressed = (pubKey.length == 33); for(var i in this.contacts) { for(var j in this.contacts[i].pubKeys) { var address = this.contacts[i].pubKeys[j].data; var cPubKey; try { cPubKey = BtcUtils.extractPublicKey(address, compressed); } catch(e) { // not a good address continue; } if (cPubKey.toString() == toCheck) { return this.contacts[i]; } } } }; /** * Find Contact by address * @param {Object} address Address to find * @return {Object|null} The contact if it is there */ Contacts.prototype.findByAddress = function (address) { for(var i in this.contacts) { for(var j in this.contacts[i].pubKeys) { var cAddress = this.contacts[i].pubKeys[j].address; if (cAddress == address) { return this.contacts[i]; } } } }; /** * Add a contact to the address book * @param {Object} contact Contact information. */ Contacts.prototype.addContact = function (contact) { contact.pubKeys = []; this.updateKey(contact, contact.address, 0); delete contact.address; contact.mainKey = 0; this.updateContactHash(contact); this.contacts.push(contact); this.store.save(); }; /** * Add key */ Contacts.prototype.addContactKey = function (contact, data) { var newKey = this.prepareAddress(data); if (!contact.pubKeys) { contact.pubKeys = []; } contact.pubKeys.push(newKey); this.store.save(); // delete address since now is contained inside contact.pubKeys }; /** * Sets key index as main key * Will also update the contact hash to reflect new main identity. */ Contacts.prototype.setMainKey = function (contact, index) { if (index >= contact.pubKeys.length) { throw Error("Key does not exist"); } contact.mainKey = index; this.updateContactHash(contact); this.store.save(); } /** * Update a key from given user input */ Contacts.prototype.updateKey = function (contact, data, index) { var newKey = this.prepareAddress(data); if (!contact.pubKeys || !contact.pubKeys.length) { if (index) { throw Error("Trying to update key with index from contact with no keys"); } contact.pubKeys = [newKey]; } else { for(var par in newKey) { contact.pubKeys[index][par] = newKey[par]; } } }; /** * Edit a contact in the address book * @param {Object} contact Contact information. * @throws {Error} When trying to update a non-existing contact */ Contacts.prototype.updateContact = function (contact, data, index) { if (this.contacts.indexOf(contact) == -1) { throw Error("This is not an already existing contact!"); } if (data) { this.updateKey(contact, data, index); } this.updateContactHash(contact); this.store.save(); }; /** * Delete a contact from the address book * @param {String} contact Contact information. * @throws {Error} When trying to delete a non-existing contact */ Contacts.prototype.deleteContact = function (contact) { var i = this.contacts.indexOf(contact); if (i == -1) { throw Error("Contact does not exist!"); } this.contacts.splice(i, 1); this.store.save(); }; return Contacts; });
JavaScript
0
@@ -409,16 +409,96 @@ tad4bMy' + %7D,%0A %7B name: 'libbitcoin team', address: '1Fufjpf9RM2aQsGedhSpbSCGRHrmLMJ7yY' %7D%0A %5D);
10a989a003ec4d2b8c9e2bb72b7d342a4412b3d0
make icon optional in action button
src/components/views/elements/ActionButton.js
src/components/views/elements/ActionButton.js
/* Copyright 2017 Vector Creations Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import AccessibleButton from './AccessibleButton'; import dis from '../../../dispatcher'; import sdk from '../../../index'; import Analytics from '../../../Analytics'; export default React.createClass({ displayName: 'RoleButton', propTypes: { size: PropTypes.string, tooltip: PropTypes.bool, action: PropTypes.string.isRequired, mouseOverAction: PropTypes.string, label: PropTypes.string.isRequired, iconPath: PropTypes.string.isRequired, }, getDefaultProps: function() { return { size: "25", tooltip: false, }; }, getInitialState: function() { return { showTooltip: false, }; }, _onClick: function(ev) { ev.stopPropagation(); Analytics.trackEvent('Action Button', 'click', this.props.action); dis.dispatch({action: this.props.action}); }, _onMouseEnter: function() { if (this.props.tooltip) this.setState({showTooltip: true}); if (this.props.mouseOverAction) { dis.dispatch({action: this.props.mouseOverAction}); } }, _onMouseLeave: function() { this.setState({showTooltip: false}); }, render: function() { const TintableSvg = sdk.getComponent("elements.TintableSvg"); let tooltip; if (this.state.showTooltip) { const RoomTooltip = sdk.getComponent("rooms.RoomTooltip"); tooltip = <RoomTooltip className="mx_RoleButton_tooltip" label={this.props.label} />; } return ( <AccessibleButton className="mx_RoleButton" onClick={this._onClick} onMouseEnter={this._onMouseEnter} onMouseLeave={this._onMouseLeave} aria-label={this.props.label} > <TintableSvg src={this.props.iconPath} width={this.props.size} height={this.props.size} /> { tooltip } </AccessibleButton> ); }, });
JavaScript
0
@@ -1104,35 +1104,24 @@ Types.string -.isRequired ,%0A %7D,%0A%0A @@ -2179,16 +2179,198 @@ %7D%0A%0A + const icon = this.props.iconPath ?%0A (%3CTintableSvg src=%7Bthis.props.iconPath%7D width=%7Bthis.props.size%7D height=%7Bthis.props.size%7D /%3E) :%0A undefined;%0A%0A @@ -2654,98 +2654,16 @@ -%3CTintableSvg src=%7Bthis.props.iconPath%7D width=%7Bthis.props.size%7D height=%7Bthis.props.size%7D /%3E +%7B icon %7D %0A
2b291f716e4184ecbc8690464ffcaee8f46e8784
Fix showing success message on wrong place
ckanext/requestdata/fanstatic/modal-form.js
ckanext/requestdata/fanstatic/modal-form.js
'use strict'; /* modal-form * * This JavaScript module creates a modal and responds to actions * */ this.ckan.module('modal-form', function($) { var api = { get: function(action, params, api_ver = 3) { var base_url = ckan.sandbox().client.endpoint; params = $.param(params); var url = base_url + '/api/' + api_ver + '/action/' + action + '?' + params; return $.getJSON(url); }, post: function(action, data, api_ver = 3) { var base_url = ckan.sandbox().client.endpoint; var url = base_url + '/api/' + api_ver + '/action/' + action; return $.post(url, JSON.stringify(data), "json"); } }; return { initialize: function() { $.proxyAll(this, /_on/); this.el.on('click', this._onClick); }, // Whether or not the rendered snippet has already been received from CKAN. _snippetReceived: false, _onClick: function(event) { var is_current_user_a_maintainer = this.options.is_current_user_a_maintainer var dialogResult = true if (is_current_user_a_maintainer === 'True') { var dialogResult = window.confirm('Request own dataset\n\nWARNING: You are a maintainer of the dataset you are requesting. Do you wish to continue making this request?') } if (dialogResult) { var base_url = ckan.sandbox().client.endpoint; if (!this.options.is_logged_in) { if(this.options.is_hdx == 'True'){ showOnboardingWidget('#loginPopup'); return; } location.href = base_url + this.options.redirect_url return; } var payload = { message_content: this.options.message_content, package_name: this.options.post_data.package_name, maintainers: JSON.stringify(this.options.post_data.maintainers), requested_by: this.options.post_data.requested_by, sender_id: this.options.post_data.sender_id } if (!this._snippetReceived) { this.sandbox.client.getTemplate(this.options.template_file, payload, this._onReceiveSnippet); this._snippetReceived = true; } else if (this.modal) { this.modal.modal('show'); } var success_msg = document.querySelector('#request-success-container'); if (success_msg) { success_msg.parentElement.removeChild(success_msg); } } }, _onReceiveSnippet: function(html) { this.sandbox.body.append(this.createModal(html)); this.modal.modal('show'); var backdrop = $('.modal-backdrop'); if (backdrop) { backdrop.on('click', this._onCancel); } }, createModal: function(html) { if (!this.modal) { var element = this.modal = jQuery(html); element.on('click', '.btn-primary', this._onSubmit); element.on('click', '.btn-cancel', this._onCancel); element.modal({ show: false }); this.modalFormError = this.modal.find('.alert-error') } return this.modal; }, _onSubmit: function(event) { var base_url = ckan.sandbox().client.endpoint; var url = base_url + this.options.submit_action || ''; var data = this.options.post_data || ''; var form = this.modal.find('form') var formElements = $(form[0].elements) var submit = true var formData = new FormData(); // Clear form errors before submitting the form. this._clearFormErrors(form) for (var item in data) { formData.append(item, data[item]) } // Add field data to payload data $.each(formElements, function(i, element) { var value = element.value.trim() if (element.required && value === '') { var hasError = element.parentElement.querySelector('.error-block') if (!hasError) { this._showInputError(element, 'Missing value') } submit = false } else { if (element.type == 'file') { if (element.files.length > 0) { formData.append(element.name, element.files[0], element.value) // If a file has been attached, than move the request to archive // and mark it that data has been shared formData.append('state', 'archive') formData.append('data_shared', true) } } else { formData.append(element.name, element.value) } } }.bind(this)) if (submit) { $.ajax({ url: url, data: formData, processData: false, contentType: false, type: 'POST' }) .done(function(data) { data = JSON.parse(data) if (data.error && data.error.fields) { for(var key in data.error.fields){ this._showFormError(data.error.fields[key]); } } else if (data.success) { this._showSuccessMsg(data.message); if (this.options.disable_action_buttons) { this._disableActionButtons(); } if (this.options.refresh_on_success) { location.reload(); } } }.bind(this)) .error(function(error) { this._showFormError(error.statusText) }.bind(this)) } }, _onCancel: function(event) { this._snippetReceived = false; this._clearFormErrors() this._resetModalForm(); }, _showInputError: function(element, message) { var div = document.createElement('div'); div.className = 'error-block'; div.textContent = message; element.parentElement.appendChild(div); }, _clearFormErrors: function() { var errors = this.modal.find('.error-block') $.each(errors, function(i, error) { error.parentElement.removeChild(error) }) this.modalFormError.addClass('hide') this.modalFormError.text('') }, _showFormError: function(message) { this.modalFormError.removeClass('hide') this.modalFormError.text(message) }, _showSuccessMsg: function(msg) { var div = document.createElement('div'); div.className = "alert alert-success alert-dismissable fade in"; div.id = 'request-success-container' div.textContent = msg; div.style.marginTop = '25px'; var currentDiv = document.getElementsByClassName("requested-data-message"); currentDiv[0].style.display = 'block'; currentDiv[0].appendChild(div); this._resetModalForm(); }, _resetModalForm: function(){ this.modal.modal('hide'); // Clear form fields this.modal.find('form')[0].reset(); }, _disableActionButtons: function() { this.el.attr('disabled', 'disabled'); this.el.siblings('.btn').attr('disabled', 'disabled'); } }; });
JavaScript
0.000039
@@ -7658,41 +7658,123 @@ v = -document.getElementsByClassName(%22 +$('.requested-data-message')%0A%0A if (currentDiv.length %3E 1) %7B%0A currentDiv = this.el.next('. requ @@ -7791,17 +7791,17 @@ -message -%22 +' );%0A @@ -7811,45 +7811,55 @@ -currentDiv%5B0%5D.style. +%7D%0A currentDiv.css(' display - = +', 'block' ;%0A @@ -7850,24 +7850,25 @@ ay', 'block' +) ;%0A @@ -7883,29 +7883,20 @@ tDiv -%5B0%5D .append -Child (div) -; %0A
8a4afe3d8a60e6431ef070acb85676b096c85c48
Fix race condition in tests.
lib/jobs.js
lib/jobs.js
var async = require('async'), moment = require('moment'), events = require('events'), _ = require('lodash'), shouldStillProcess, pg = require('pg'), Transaction = require('pg-transaction'), debug = require('debug')('pg-jobs'); /** * @param Object options Options hash containing: * - db (mandatory DB URI) * - pollInterval pollInterval - How often to poll for new jobs when idle (ms). */ module.exports = function(options) { var Jobs = {}; var jobsModel = require('../models/jobs'); // Expose jobs model when we are testing so we can set up stuff on the Db. if (process.env.NODE_ENV === 'test') { Jobs.jobsModel = jobsModel; } Jobs.eventEmitter = new events.EventEmitter(); /** * @param {Object} job The data you want to save for the job. This is * freeform and up to you. * @param {int} processIn The job will not get service until this many ms have elapsed. Set to null if you do not want to service it again. * @param {function} done Callback. */ Jobs.create = function(jobData, processIn, done) { pg.connect(options.db, connected); function connected(err, db, cb) { if (err) return complete(err); jobsModel.write(db, null, processIn, jobData, complete); function complete(err, jobId) { cb(); // Return the client to the pool done(err, jobId); } } }; function updateJob(db, jobSnapshot, newJobData, processIn, cb) { processIn = processIn || null; jobsModel.write(db, jobSnapshot.job_id, processIn, newJobData, complete); function complete(err) { if (err) return cb(err); Jobs.eventEmitter.emit('jobUpdated'); cb(); } } function serviceJob(db, jobContainer, userJobIterator, callback) { return userJobIterator(jobContainer.job_id, jobContainer.data, processingComplete); function processingComplete(err, newJobData, processIn) { if (err) { return callback(err); } else { jobsModel.setProcessedNow(db, jobContainer.job_id); updateJob(db, jobContainer, newJobData, processIn, callback); } } } Jobs.stopProcessing = function() { shouldStillProcess = false; }; Jobs.continueProcessing = function() { return shouldStillProcess; }; /** * Examines and services jobs in the 'jobs' array, repeatedly, forever, unless * stopProcessing() is called. * Call this once to start processing jobs. * @param {function} serviceJob Iterator function to be run on jobs requiring * service. * @param {function} done callback to receive errors pertaining to running * process() - i.e. db connection issues. Also called when stopProcessing() is * called. */ Jobs.process = function(processFunction, done) { shouldStillProcess = true; done = done || function() {}; pg.connect(options.db, connected); function connected(err, db, releaseClient) { if (err) return done(err); async.whilst(Jobs.continueProcessing, iterator, finish); function iterator(callback) { setImmediate(function() { Jobs.eventEmitter.emit('maybeServiceJob'); debug('Getting next job to process...'); jobsModel.nextToProcess(db, getJobProcessor(false, db, processFunction, callback)); }); } function finish(err) { releaseClient(); Jobs.eventEmitter.emit('stopProcess'); done(); } } }; Jobs.processNow = function(jobId, processFunction, done) { done = done || function() {}; pg.connect(options.db, connected); function connected(err, db, releaseClient) { if (err) return done(err); debug('seeking lock for', jobId); jobsModel.obtainLock(db, jobId, gotLock); function gotLock(err) { debug('obtained lock for', jobId); if (err) return done(err); jobsModel.getDataForJob(db, jobId, gotData); } var gotData = getJobProcessor(true, db, processFunction, processed); function processed(err) { if (err) return done(err); releaseClient(); debug('client released', err); done(err); } } }; /* Return a function that will be given the job to process it. * @param {function} processFunction The user's worker. * @param {function} User callback. */ function getJobProcessor(now, db, processFunction, callback) { return function(err, jobSnap) { if (err) return callback(err); if (!jobSnap) { if (now) return callback(new Error('Could not locate job')); Jobs.eventEmitter.emit('drain'); debug('No job found, sleeping...'); return setTimeout(callback, options.pollInterval || 1000); } debug('Processing job...'); processJob(jobSnap); }; function processJob(jobSnap) { var tx = new Transaction(db); tx.begin(); serviceJob(tx, jobSnap, processFunction, function(err) { if (err) { debug('Job serviced with error.'); tx.rollback(txDone); } else { debug('Job serviced without error.'); tx.commit(txDone); Jobs.eventEmitter.emit(now ? 'processNowCommitted' : 'processCommitted'); } function txDone() { jobsModel.unlock(db, jobSnap.job_id); callback(err); } }); } } return Jobs; }; // vim: set et sw=2 ts=2 colorcolumn=80:
JavaScript
0
@@ -5152,32 +5152,70 @@ commit(txDone);%0A + %7D%0A function txDone() %7B%0A Jobs.e @@ -5286,46 +5286,8 @@ ');%0A - %7D%0A function txDone() %7B%0A
f5f22a184d86228f3a63f1ac2c83e33001d6eb6f
Add comment
client/app/dbpGrabber/dbpGrabber.service.js
client/app/dbpGrabber/dbpGrabber.service.js
'use strict'; angular.module('biyblApp') .service('dbpGrabber', function () { // AngularJS will instantiate a singleton by calling "new" on this function langmap: { 'ar': ['ARZVDVO2ET', 'ARZVDVN2ET', 'العربية'], 'bg': ['BULBBSO2ET', 'BULBBSN2ET', 'Български'], 'bn': ['BNGCLVO2ET', 'BNGCLVN2ET', 'বাংলা'], 'cs': ['CZCK13O2ET', 'CZCK13N2ET', 'Čeština'], 'da': ['DAND33O2ET', 'DAND33N2ET', 'Dansk'], 'de': ['GERD71O2ET', 'GERD71N2ET', 'Deutsch'], 'en': ['ENGESVO2ET', 'ENGESVN2ET', 'English'], 'es': ['SPNWTCO1ET', 'SPNWTCN1ET', 'Español'], 'fa': ['', 'PESTPVN2ET', 'پارسی'], 'fr': ['FRNPDCO2ET', 'FRNPDCN2ET', 'Français'], 'hi': ['', 'HNSWBTN2ET', 'हिन्दी'], 'hr': ['HRVCBVO2ET', 'HRVCBVN2ET', 'Hrvatski'], 'hu': ['HUNK90O2ET', 'HUNK90N2ET', 'Magyar'], 'id': ['INZNTVO2ET', 'INZNTVN2ET', 'Bahasa Indonesia'], 'it': ['ITAR27O2ET', 'ITAR27N2ET', 'Italiano'], 'kr': ['', '', '한국의'], 'ku': ['', '', 'سۆرانی'], 'mr': ['', 'MARWTCN1ET', 'मराठी'], 'nl': ['NLDDSVO2ET', 'NLDDSVN2ET', 'Nederlands'], 'no': ['', '', 'Norsk'], 'pa': ['', 'PANWTCN2ET', 'ਪੰਜਾਬੀ'], 'pl': ['POLPBGO2ET', 'POLPBGN2ET', 'Polski'], 'pt': ['PORBSPO2ET', 'PORBSPN2ET', 'Português'], 'ro': ['', 'RONBSRN2ET', 'Română'], 'ru': ['RUSS76O2ET', 'RUSS76N2ET', 'Русский'], 'so': ['SOMSIMO2ET', 'SOMSIMN2ET', 'Somali'], 'sq': ['ALSABVO2ET', 'ALSABVN2ET', 'Shqip'], 'sr': ['', '', 'Српски'], 'ur': ['', '', 'اردو'], 'zh_simp': ['CHNUN1O2ET', 'CHNUN1N2ET', '汉语'], 'zh_trad': ['CHNUNVO2ET', 'CHNUNVN2ET', '汉语'], }, ot_books: ['Gen', 'Exod', 'Lev', 'Num', 'Deut', 'Josh', 'Judg', 'Ruth', '1Sam', '2Sam', '1Kgs', '2Kgs', '1Chr', '2Chr', 'Ezra', 'Neh', 'Esth', 'Job', 'Ps', 'Prov', 'Eccl', 'Song', 'Isa', 'Jer', 'Lam', 'Ezek', 'Dan', 'Hos', 'Joel', 'Amos', 'Obad', 'Jonah', 'Mic', 'Nah', 'Hab', 'Zeph', 'Hag', 'Zech', 'Mal' ], // given "Gen.1.1","Gen.1.3" // will return "&book_id=Gen&chapter_id=1&verse_start=1&verse_end=3" refToDBPParams: function(ref, ref2) { var parts = ref.split('.'); var b = parts[0]; var c = parts[1]; var ret = "&book_id=" + b + "&chapter_id=" + c; if (parts.length == 3) { ret = ret + "&verse_start=" + parts[2]; if (ref != ref2) { var parts2 = ref2.split('.'); if ((parts[0] != parts2[0]) || (parts[1] != parts2[1])) throw('Cross-chapter references are not supported by the api'); ret = ret + "&verse_end=" + parts2[2]; } } else if (parts.length == 2) { // entire chapter // no change } else throw(['Unusual osiRef', ref]); return ret; }, // given a language and a reference (used only for the book), // returns the DAM ID (digitalbibleplatform's translation identifier) getDam: function(lang, ref) { var damIndex = 1; if (ref.split('.')[0] in ot_books) damIndex = 0; if (!(lang in langmap)) { // Unknown language; fall back to English. // TODO fall back to a customizable language lang = "en"; } var dam = langmap[lang][damIndex]; // Some languages haven't an OT; in that case fall back to English // TODO fall back to a customizable language if (!dam) dam = langmap['en'][damIndex]; return dam; }, // turns "Gen.1.1" and "Gen.1.5" into array of ref+verse hashes osiToVerse: function(range, lang, first, last) { var url = "http://dbt.io/text/verse?v=2&key=f241660c7e9b26ddf60d73b1d9fe5856"; url = url + "&markup=osis"; url = url + "&dam_id=" + getDam(lang, first); url = url + refToDBPParams(first, last); var self = this; self.ref = range; var promise = $http.get(url); promise.then(function(response) { console.log(response.data); self.text = response.data; }).catch(function(e) { throw e; }); }, return { // range: either "Gen.1.1-Gen.1.3" or "Gen.1.1" // lang: something like "en" or "fr" osiRangeToVerse: function(range, lang) { var pairs = range.split('-'); if (pairs.length == 2) osiToVerse(range, lang, pairs[0], pairs[1]); else osiToVerse(range, lang, pairs[0], pairs[0]); }, } });
JavaScript
0
@@ -3706,23 +3706,177 @@ of -ref+verse hashe +verse data%0A // e.g.: http://dbt.io/text/verse?v=2&key=f241660c7e9b26ddf60d73b1d9fe5856&dam_id=FRNDBYN2ET&book_id=Rev&chapter_id=1&verse_start=1&verse_end=2&markup=osi s%0A
b2467a479458fbaf7c4200482eb3dcc19bb6a8ae
Remove stepSize from TNumber (https://github.com/phetsims/phet-io/issues/490)
js/types/TNumber.js
js/types/TNumber.js
// Copyright 2016, University of Colorado Boulder /** * * @author Sam Reid (PhET Interactive Simulations) * @author Andrew Adare */ define( function( require ) { 'use strict'; // modules var assertTypeOf = require( 'PHET_IO/assertions/assertTypeOf' ); var phetioNamespace = require( 'PHET_IO/phetioNamespace' ); var phetioInherit = require( 'PHET_IO/phetioInherit' ); var RangeWithValue = require( 'DOT/RangeWithValue' ); var TObject = require( 'PHET_IO/types/TObject' ); var validUnits = [ 'amperes', 'becquerels', 'centimeters', 'coulombs', 'degrees Celsius', 'farads', 'grams', 'gray', 'henrys', 'henries', 'hertz', 'joules', 'katals', 'kelvins', 'liters', 'liters/second', 'lumens', 'lux', 'meters', 'moles', 'moles/liter', 'nanometers', 'newtons', 'ohms', 'pascals', 'percent', 'radians', 'seconds', 'siemens', 'sieverts', 'steradians', 'tesla', 'unitless', 'volts', 'watts', 'webers' ]; var TNumber = function( units, options ) { assert && assert( units, 'All TNumbers should specify units' ); assert && assert( validUnits.indexOf( units ) >= 0, units + ' is not recognized as a valid unit of measurement' ); options = _.extend( { type: 'FloatingPoint', // either 'FloatingPoint' | 'Integer' range: new RangeWithValue( -Infinity, Infinity ), stepSize: null, // This will be used for slider increments // TODO: enforce that values is of Array type values: null // null | {Number[]} if it can only take certain possible values, specify them here, like [0,2,8] }, options ); return phetioInherit( TObject, 'TNumber(' + units + ')', function( instance, phetioID ) { TObject.call( this, instance, phetioID ); assertTypeOf( instance, 'number' ); }, {}, { units: units, type: options.type, range: options.range, stepSize: options.stepSize, values: options.values, documentation: 'Wrapper for the built-in JS number type (floating point, but also represents integers)', fromStateObject: function( stateObject ) { return stateObject; }, toStateObject: function( value ) { return value; } } ); }; phetioNamespace.register( 'TNumber', TNumber ); return TNumber; } );
JavaScript
0
@@ -1988,42 +1988,8 @@ ge,%0A - stepSize: options.stepSize,%0A
99d2038f03513083dde80252fd3817e4fa4723ce
refactor stream linking
lib/link.js
lib/link.js
var Stream = require('./stream'); var Load = require('./load'); var Parse = require('./parse'); module.exports = function Link (scope, event, options) { var node = Stream.Node(options); // load instance, parse event and get flow stream sequences Load(scope, node, event[0], options).once('_flow_load', function (instance) { Parse(scope, node, instance, event[1], options).once('_flow_event', function (event) { var seq, link, first; event.s.forEach(function (sequence) { if (sequence.s) { seq = Stream.Seq(options, sequence.s); seq.on('error', node.emit.bind(node, 'error')); } if (sequence.p) { // pipe to flow event if (typeof sequence.p[1] === 'string') { link = sequence.p[0].flow(sequence.p[1], options); // call stream handler } else { options._ = sequence.a || {}; link = sequence.p[1].call(sequence.p[0], options); } link.on('error', node.emit.bind(node, 'error')); seq = seq ? seq.pipe(link) : link; } if (!first) { first = seq; } }); // TODO end even // TODO error event // set sequence on node node.link(first); }); }); return node; } /* var input = initial.i; var first = true; var errEvent; var handleError = function (err) { // emit error on origin ouput stream initial.o.emit('error', err); // write error to error event if (event_stream.r) { errEvent = errEvent || instance.flow(event_stream.r, options); if (errEvent.ready) { errEvent.i.write(err); } else { errEvent.i.on('ready', function () { errEvent.i.write(err); }); } // end error stream on initial end initial.o.on('end', errEvent.i.end.bind(errEvent)); } // TODO keep streams piped // https://github.com/nodejs/node/issues/3045#issuecomment-142975237 }; // end handler if (event_stream.e) { initial.o.on('end', function () { if (!initial.i._errEH) { instance.flow(event_stream.e, options).i.on('ready', function () { endEvent.i.end(options); }); } }); } // read out data if no data listener is added, to prevent buffer overflow if (!initial.o._events.data) { initial.o.on('data', function (chunk) { console.error(new Error('Flow: Uncaught data chunk: Event:',instance._name + '/' + event)); }); } */
JavaScript
0.000014
@@ -1,18 +1,50 @@ var -Stream +Node = require('./node');%0Avar Sequence = requi @@ -50,21 +50,23 @@ ire('./s -tream +equence ');%0Avar @@ -197,23 +197,16 @@ node = -Stream. Node(opt @@ -480,21 +480,20 @@ eq, -link, first; +first, prev; %0A @@ -536,24 +536,69 @@ equence) %7B%0A%0A + // create sequence transform%0A @@ -650,17 +650,15 @@ = S -tream.Seq +equence (opt @@ -752,34 +752,169 @@ -%7D%0A + first = first %7C%7C seq;%0A prev = prev ? prev.pipe(seq) : seq;%0A %7D%0A%0A // link to next node %0A @@ -1052,36 +1052,35 @@ -link +seq = sequence.p%5B0%5D @@ -1107,24 +1107,25 @@ options);%0A%0A +%0A @@ -1262,20 +1262,19 @@ -link +seq = seque @@ -1355,20 +1355,19 @@ -link +seq .on('err @@ -1427,142 +1427,299 @@ -seq = seq ? seq.pipe(link) : link;%0A %7D%0A%0A if (!first) %7B%0A first = seq;%0A %7D +first = first %7C%7C seq;%0A prev = prev ? prev.pipe(seq) : seq;%0A %7D%0A %7D);%0A%0A // end event%0A if (sequence.e) %7B%0A var endNode = instance.flow(sequence.e);%0A node.on('end', endNode.write.bind(endNode, true)); %0A @@ -1720,34 +1720,32 @@ );%0A %7D -); %0A%0A // @@ -1749,53 +1749,183 @@ // -TODO end even%0A // TODO error event +error event%0A if (sequence.r) %7B%0A var errNode = instance.flow(sequence.r);%0A node.on('error', errNode.write.bind(errNode));%0A %7D %0A%0A @@ -1985,16 +1985,22 @@ nk(first +, prev );%0A @@ -2037,1249 +2037,6 @@ e;%0A%7D -%0A%0A/*%0Avar input = initial.i;%0Avar first = true;%0Avar errEvent;%0Avar handleError = function (err) %7B%0A%0A // emit error on origin ouput stream%0A initial.o.emit('error', err);%0A%0A // write error to error event%0A if (event_stream.r) %7B%0A errEvent = errEvent %7C%7C instance.flow(event_stream.r, options);%0A if (errEvent.ready) %7B%0A errEvent.i.write(err);%0A %7D else %7B%0A errEvent.i.on('ready', function () %7B%0A errEvent.i.write(err);%0A %7D);%0A %7D%0A%0A // end error stream on initial end%0A initial.o.on('end', errEvent.i.end.bind(errEvent));%0A %7D%0A%0A // TODO keep streams piped%0A // https://github.com/nodejs/node/issues/3045#issuecomment-142975237%0A%7D;%0A%0A// end handler%0Aif (event_stream.e) %7B%0A initial.o.on('end', function () %7B%0A if (!initial.i._errEH) %7B%0A instance.flow(event_stream.e, options).i.on('ready', function () %7B%0A endEvent.i.end(options);%0A %7D);%0A %7D%0A %7D);%0A%7D%0A%0A// read out data if no data listener is added, to prevent buffer overflow%0Aif (!initial.o._events.data) %7B%0A initial.o.on('data', function (chunk) %7B%0A console.error(new Error('Flow: Uncaught data chunk: Event:',instance._name + '/' + event));%0A %7D);%0A%7D%0A*/ +; %0A
8790cbc4d041adeeb7efc22382bede78666d2dbe
Update Example
Batchler.js
Batchler.js
/* Batchler.js, (c) 2015, Michael Fisher, v. 0.0.0 */ if(!this['console']) { this['console'] = function (message) {}; } var Batchler = {}; Batchler.Request = function () { /* Execute function. This function is called by the request's executer. The success and fail callbacks should include a call to the executer's callback function. */ this.execute = null; return this; }; Batchler.Requests = {}; /* Executes requests synchronously. */ Batchler.Requests.SyncExecuter = function () { var queue = []; var queueIndex = 0; var running = false; this.percentComplete = Math.round(((queueIndex / queue.length) * 100)); this.add = function (request) { queue.push(request); console.log('Synchronous request added.') }; this.callback = function (result) { if (result) { console.log(result); } if (queueIndex == queue.length) { this.complete(); } if (queueIndex < queue.length) { queue[queueIndex].execute(this); queueIndex += 1; } }; this.run = function () { if (running === false) { running = true; console.log('Sync executer running.'); this.callback(); } }; this.complete = function () { console.log('Sync executer requests complete.') }; return this; }; /* Executes requests asynchronously. */ Batchler.Requests.AsyncExecuter = function () { var queue = []; var completed = 0; var running = false; this.percentComplete = Math.round(((completed / queue.length) * 100)); this.add = function (request) { console.log('Asynchronous request added.'); queue.push(request); }; this.callback = function (result) { if (result) { console.log(result); } if (completed == queue.length) { this.complete(); } if (completed < queue.length) { completed++; } }; this.run = function () { if (running === false) { running = true; for (var ii in queue) { queue[ii].execute(this); } console.log('Async executer running.') } }; this.complete = function () { console.log('Async executer requests complete.') }; return this; };
JavaScript
0.000001
@@ -169,26 +169,30 @@ () %7B%0A -/* E +this.e xecute + = functio @@ -196,120 +196,169 @@ tion -. This function is called by the request's executer. The success and fail callbacks should include a call to the +(executer) %7B%0A function success() %7B%0A if(executer) %7B%0A executer.callback('Success');%0A %7D%0A %7D%0A function fail() %7B%0A if(executer) %7B%0A exe @@ -366,19 +366,17 @@ uter -'s +. callback fun @@ -375,43 +375,35 @@ back - function. */%0A this.execute = null +('Fail');%0A %7D%0A %7D%0A %7D ;%0A
a12bd91424e8834b451bb2fda96e9be65250d757
remove usless log
js/oa.contourRepo.js
js/oa.contourRepo.js
OA.ContourRepo = function(userSetting) { Array.call(this); var repo = this; var curr = 0; var counter = 0; var init = function() { return repo; }; this.setIndex = function(p3ds){ if (p3ds.cid != null) {console.error(2) curr = p3ds.cid; } } this.push = function(p3ds) { var original = Array.prototype.push; if (p3ds.cid != null) { return; } original.apply(this, arguments); curr = repo.length; p3ds.cid = curr; }; this.getBefore = function() { if (curr > 0) { curr = curr -1; var res = repo[curr]; if (res) { return res; } else { curr = 0; return null; } }else{ return repo[0]; } }; this.getAfter = function() { if (curr < repo.length-1) { curr = curr +1; var res = repo[curr]; if (res) { return res; } else { curr = repo.length-1; return null; } }else{ return repo[repo.length-1]; } // var res = repo[curr + 1]; // if (res) { // return res; // } else { // curr = repo.length - 1; // return null; // } }; return init(); }; OA.ContourRepo.prototype = Object.create(Array.prototype);
JavaScript
0
@@ -209,17 +209,16 @@ (p3ds)%7B%0A -%0A @@ -244,24 +244,8 @@ l) %7B -console.error(2) %0A
ad196a01087daca8a13df41b5e81593c25b932c5
prepend # to indicate we match exactly the context query
js/tests.js
js/tests.js
var parser = new excellent.Parser('@', ['channel', 'contact', 'date', 'extra', 'flow', 'step']); describe("finding expressions", function() { it("find expressions with and without parentheses", function() { expect(parser.expressions('Hi @contact.name from @(flow.sender)')).toEqual([ {start: 3, end: 16, text: '@contact.name', closed: false}, {start: 22, end: 36, text: '@(flow.sender)', closed: true} ]); }); it("ignores invalid top levels", function() { expect(parser.expressions('Hi @contact.name from @nyaruka')).toEqual([ {start: 3, end: 16, text: '@contact.name', closed: false} ]); }); it("ignore parentheses inside string literals", function() { expect(parser.expressions('Hi @(LEN("))"))')).toEqual([ {start: 3, end: 15, text: '@(LEN("))"))', closed: true} ]); }); }); describe("get expression context", function() { it("finds context for expression without parentheses", function() { expect(parser.expressionContext('Hi @contact.na')).toBe('contact.na'); }); it("finds context for expression with parentheses", function() { expect(parser.expressionContext('Hi @contact.name from @(flow.sen')).toBe('(flow.sen'); }); it("don't include a closed expression", function() { expect(parser.expressionContext('Hi @contact.name from @(flow.sender)')).toBeNull(); }); }); describe("get auto-complete context", function() { it("finds context for expression without parentheses", function() { expect(parser.autoCompleteContext('Hi @contact.na')).toBe('contact.na'); }); it("finds context for expression with parentheses", function() { expect(parser.autoCompleteContext('Hi @contact.name from @(flow.sen')).toBe('flow.sen'); }); it("no context if last typed thing can't be an identifier", function() { expect(parser.autoCompleteContext('Hi @contact.name from @(flow.sender + ')).toBeNull(); }); it("no context if in a string literal", function() { expect(parser.autoCompleteContext('Hi @(CONCAT("@con')).toBeNull(); expect(parser.autoCompleteContext('Hi @("!" & "@con')).toBeNull(); }); it("ignore parenthesis triggering functions completions for variables", function() { expect(parser.autoCompleteContext("Hi @(contact.age")).toBe('contact.age'); }); it('ignore the parenthesis triggering functions completions for functions', function() { expect(parser.autoCompleteContext("Hi @(SUM")).toBe('SUM'); }); it("matches the function without parameters", function() { expect(parser.autoCompleteContext("Hi @(SUM(")).toBe('#SUM'); }); it("matches the function missing balanced parentheses", function() { expect(parser.autoCompleteContext("Hi @(SUM(dads, ABS(number))")).toBeNull(); expect(parser.autoCompleteContext("Hi @(SUM(dads, ABS(number)")).toBe('#SUM'); }); it("ignores trailing spaces in function parameters", function () { expect(parser.autoCompleteContext("Hi @(SUM( ")).toBe('#SUM'); expect(parser.autoCompleteContext("Hi @(SUM( ")).toBe('#SUM'); expect(parser.autoCompleteContext("Hi @(SUM(dads, ABS(number)) ")).toBeNull(); expect(parser.autoCompleteContext("Hi @(SUM(dads, ABS(number) ")).toBe('#SUM'); }); it("matches the variable in function parameters", function() { expect(parser.autoCompleteContext("Hi @(SUM(contact.date_added")).toBe('contact.date_added'); }); it('matches the function with incomplete parameters without trailing space', function () { expect(parser.autoCompleteContext("Hi @(SUM(contact.date_added,")).toBe('#SUM'); }); it('matches the function with incomplete parameters with trailing space', function () { expect(parser.autoCompleteContext("Hi @(SUM(contact.date_added, ")).toBe('#SUM'); }); it('ignore the function with balanced parentheses', function(){ expect(parser.autoCompleteContext("Hi @(SUM(contact.date_added, step)")).toBeNull(); expect(parser.autoCompleteContext("Hi @(SUM(contact.date_added, ABS(step.value)")).toBe('#SUM'); expect(parser.autoCompleteContext("Hi @(SUM(contact.date_added, ABS(step.value))")).toBeNull(); }); it('ignore string literal in parameters', function () { expect(parser.autoCompleteContext('Hi @(SUM(contact.date_added, "foo ( bar", step)')).toBeNull(); expect(parser.autoCompleteContext('Hi @(SUM(contact.date_added, "foo ( bar", ABS(step.value)')).toBe('#SUM'); }); });
JavaScript
0.00002
@@ -2403,32 +2403,241 @@ age');%0A %7D);%0A%0A + it(%22ignore trailing spaces after varibles inside parenthenses triggering function completions%22, function() %7B%0A expect(parser.autoCompleteContext(%22Hi @(contact.age %22)).toBe('contact.age');%0A %7D);%0A%0A it('ignore t