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
4537e98e039b5e26952bd2ebf6072897046c9d6e
Improve sentence formatting
app/components/audit_log/row.js
app/components/audit_log/row.js
import React from 'react'; import PropTypes from 'prop-types'; import Relay from 'react-relay/classic'; import styled from 'styled-components'; import FriendlyTime from '../shared/FriendlyTime'; import Icon from '../shared/Icon'; import Panel from '../shared/Panel'; import Spinner from '../shared/Spinner'; const renderData = (data, depth = 0) => { if (typeof data === 'string') { return data; } if (depth > 10) { return <i>Nesting too deep!</i>; } if (!data) { return "" + data; } const keys = Object.keys(data).sort(); if (!keys.length) { return data.toStri; } return ( <dl> {keys.reduce( (accumulator, property) => ( accumulator.concat([ <dt key={`dt:${property}`} className="semi-bold" > {property} </dt>, <dd key={`dd:${property}`}> {renderData(data[property], depth + 1)} </dd> ]) ), [] )} </dl> ); }; const TransitionMaxHeight = styled.div` transition: max-height 400ms; `; const RotatableIcon = styled(Icon)` transform: rotate(${(props) => props.rotate ? -90 : 90}deg); trasform-origin: center 0; transition: transform 200ms; `; class AuditLogRow extends React.PureComponent { static propTypes = { auditEvent: PropTypes.shape({ __typename: PropTypes.string.isRequired, uuid: PropTypes.string.isRequired, occurredAt: PropTypes.string.isRequired, data: PropTypes.string, actor: PropTypes.object.isRequired, subject: PropTypes.object.isRequired, context: PropTypes.object.isRequired }).isRequired, relay: PropTypes.object.isRequired }; state = { isExpanded: false }; render() { return ( <Panel.Row> <div> <div className="flex items-center" onClick={this.handleHeaderClick} > <span className="flex-auto flex mr2"> <FriendlyTime value={this.props.auditEvent.occurredAt} /> {` `} {this.renderEventSentence()} </span> <div className="flex-none"> <RotatableIcon icon="chevron-right" rotate={this.state.isExpanded} /> </div> </div> <TransitionMaxHeight className="mxn3 overflow-hidden" style={{ maxHeight: this.state.isExpanded ? 1000 : 0, overflowY: 'auto' }} > <hr className="p0 mt2 mb0 mx0 bg-gray" style={{ border: 'none', height: 1 }} /> <div className="mx3 mt2 mb0"> {this.renderDetails()} </div> </TransitionMaxHeight> </div> </Panel.Row> ); } renderEventSentence() { const { __typename: eventTypeName, actor, subject, context } = this.props.auditEvent; const eventVerb = eventTypeName .replace(/^Audit|Event$/g, '') .replace(/(^|[a-z0-9])([A-Z][a-z0-9])/g, '$1 $2') .split(/\s+/) .pop() .toLowerCase(); let subjectName = subject.name; if (eventTypeName === 'AuditOrganizationCreatedEvent') { subjectName = `${subjectName} 🎉`; } const contextName = context.__typename.replace(/^Audit|Context$/g, ''); return ( <span> <span className="semi-bold">{actor.name}</span> {` ${eventVerb} `} <span className="semi-bold">{subjectName}</span> {` via `} <span title={context.requestIpAddress} className="semi-bold" > {contextName} </span> </span> ); } renderDetails() { if (this.state.loading) { return ( <div className="center"> <Spinner style={{ margin: 9.5 }} /> </div> ); } if (!this.props.auditEvent.data) { return; } return renderData(JSON.parse(this.props.auditEvent.data)) || <i>No changes</i>; } handleHeaderClick = () => { const isExpanded = !this.state.isExpanded; this.setState({ loading: true, isExpanded }, () => { this.props.relay.setVariables( { hasExpanded: true }, (readyState) => { if (readyState.done) { this.setState({ loading: false }); } } ); }); }; } export default Relay.createContainer(AuditLogRow, { initialVariables: { hasExpanded: false }, fragments: { auditEvent: () => Relay.QL` fragment on AuditEvent { __typename uuid occurredAt data @include(if: $hasExpanded) actor { __typename ...on User { uuid name } } subject { __typename ...on Organization { slug name } ...on Pipeline { slug name organization { slug } } } context { __typename ...on AuditWebContext { requestIpAddress } } } ` } });
JavaScript
0.999999
@@ -1996,100 +1996,8 @@ 2%22%3E%0A - %3CFriendlyTime value=%7Bthis.props.auditEvent.occurredAt%7D /%3E%0A %7B%60 %60%7D%0A @@ -2991,20 +2991,25 @@ st event -Verb +TypeSplit = event @@ -3133,41 +3133,115 @@ s+/) +;%0A %0A - .pop()%0A .toLowerCase( +const eventVerb = eventTypeSplit.pop().toLowerCase();%0A%0A const eventType = eventTypeSplit.join(' ' );%0A%0A @@ -3567,16 +3567,29 @@ entVerb%7D + $%7BeventType%7D %60%7D%0A @@ -3782,16 +3782,16 @@ xtName%7D%0A - @@ -3794,24 +3794,152 @@ %3C/span%3E%0A + %7B%60 %60%7D%0A %3CFriendlyTime%0A capitalized=%7Bfalse%7D%0A value=%7Bthis.props.auditEvent.occurredAt%7D%0A /%3E%0A %3C/span
1b2246fb6b255a7c63b1a04825f7c9ed454642ee
Remove unused import from error-display
app/components/error-display.js
app/components/error-display.js
import Ember from 'ember'; const { Component, computed, isPresent } = Ember; export default Component.extend({ classNames: ['error-display'], content: null, revisedContent: computed('content.[]', { get() { const content = this.get('content'); return content.map((error) => { let errorObject = {}; errorObject.mainMessage = error.message; errorObject.stack = error.stack; if (isPresent(error.errors)) { errorObject.statusCode = error.errors[0].status; errorObject.message = error.errors[0].title; } return errorObject; }); } }).readOnly(), showDetails: false, totalErrors: computed('content.[]', { get() { const contentLength = this.get('content').length; return contentLength > 1 ? `There are ${contentLength} errors` : 'There is 1 error'; } }).readOnly(), actions: { toggleDetails() { this.set('showDetails', !this.get('showDetails')); } } });
JavaScript
0
@@ -52,19 +52,8 @@ uted -, isPresent %7D =
e8166227617e3836d3207bae854bb0d06bd58353
fix #789
app/controllers/activityMask.js
app/controllers/activityMask.js
$.attrs = arguments[0] || {}; var activityIndicator; $.open = function(msg) { var style; if (OS_IOS) { style = Ti.UI.iPhone.ActivityIndicatorStyle.BIG; } else { style = Ti.UI.ActivityIndicatorStyle.BIG; } activityIndicator = Ti.UI.createActivityIndicator({ color : 'white', font : { fontSize : 16, fontWeight : 'bold' }, message : msg, style : style, height : Ti.UI.SIZE, width : Ti.UI.SIZE }); $.activityView.add(activityIndicator); activityIndicator.show(); $.activityView.open(); }; $.close = function() { $.activityView.close(); }; $.showMsg = function(msg) { activityIndicator.hide(); if (!$.msgView) { $.msgView = Ti.UI.createView({ width : Ti.UI.SIZE, height : Ti.UI.SIZE, layout : "vertical" }); $.activityView.add($.msgView); } if (!$.msgLabel) { $.msgLabel = Ti.UI.createLabel({ width : Ti.UI.SIZE, height : Ti.UI.SIZE, text : msg, color : 'white', font : { fontSize : 16, fontWeight : 'bold' } }); $.msgView.add($.msgLabel); $.saperatorView = Ti.UI.createView({ width : 10, height : 20 }); $.msgView.add($.saperatorView); } if (!$.confirmButton) { $.confirmButton = Ti.UI.createButton({ title : "确定" }); $.confirmButton.addEventListener("singletap", function() { $.close(); }); $.msgView.add($.confirmButton); } $.msgView.show(); };
JavaScript
0.000002
@@ -23,16 +23,98 @@ %7C%7C %7B%7D;%0A +%0Aif (OS_ANDROID) %7B%0A%09$.getView().addEventListener('androidback', function()%7B%7D);%0A%7D%0A%0A var acti
ad52ff266bdd8dd32eded55902cba94adfc0004b
Create product order api
app/routes/ProductOrderRoutes.js
app/routes/ProductOrderRoutes.js
'use strict'; var productOrder = require('../../app/controllers/ProductOrderControllers'); module.exports = function (app) { app.route('/productorder/:productOrderId') .get(productOrder.show) .put(productOrder.update); app.route('/productorder/:profileId') .get(productOrder.show) app.route('/productorder') .get(productOrder.get) .post(productOrder.create); app.param('productOrderId', productOrder.getProductOrderById); app.param('profileId', productOrder.getProductOrderByProfileId); };
JavaScript
0.000005
@@ -260,24 +260,32 @@ roductorder/ +profile/ :profileId')
e9157eec27773629cc64f3dd21bf1fc7a56d028f
use objectMode, because fuck buffers
code-blocks.js
code-blocks.js
var arrayify = require('arrayify') var duplexer = require('duplexer') var split = require('split') var through = require('through2') var FENCE = /^\`\`\`([\w_-]+)?\s*$/ module.exports = function createTransform (types) { var last = "" var types = arrayify(types) var block = false; var collector = through(function eachLine (line, enc, callback) { line = line.toString() var match = line.match(FENCE) if (match) { if (block !== false) { // output the block this.push(block) block = false } else if (!types.length || types.indexOf(match[1]) > -1) { // start a new block block = "" } } else if (block !== false) { block += line + "\n" } callback() }) var splitter = split() splitter.pipe(collector) return duplexer(splitter, collector) }
JavaScript
0.000001
@@ -309,16 +309,36 @@ through( +%7BobjectMode: true%7D, function
60b11e817a36088f7209dce9e874b68a6b019980
Fix to work with new edinburghcityscope-utils version
cityscope-data-starter.js
cityscope-data-starter.js
var insertLoopbackData = require('./cityscope-data-importer').insertLoopbackData; var edinburghcityscopeUtils = require('edinburghcityscope-utils'); var getModelUrlFromDcatInfo = edinburghcityscopeUtils.getModelUrlFromDcatInfo; var getDataFromURL = edinburghcityscopeUtils.getDataFromURL; var featureCollectionToFeatureArray = edinburghcityscopeUtils.featureCollectionToFeatureArray; var dcatDataUrl=''; process.argv.forEach(function(element){ var valueArray = element.split('='); if (valueArray[0]=='dcat-data-url') { dcatDataUrl=valueArray[1]; } }); if (dcatDataUrl=='') { console.log('dcat-data-url not set, exiting.'); } else { console.log('Data url is '+dcatDataUrl); console.log('Getting dcat data.'); getDataFromURL(dcatDataUrl,function(callback){ console.log('Got dcat data'); console.log('Getting model and data information.'); getModelUrlFromDcatInfo(callback,function(callback){ var loopbackModel = callback.model; console.log('Model is '+callback.model); console.log('Data url is '+callback.datasetUrl); console.log('Getting data.'); getDataFromURL(callback.datasetUrl,function(callback){ if (loopbackModel=='GeoJSONFeature') { console.log('Got data, converting to feature array.'); var json = featureCollectionToFeatureArray(callback); console.log('Conversion complete, importing.'); } insertLoopbackData(loopbackModel,json); console.log('Import finished!'); }); }); }); }
JavaScript
0
@@ -749,32 +749,38 @@ ataUrl,function( +error, callback)%7B%0A co @@ -774,16 +774,70 @@ lback)%7B%0A + if (error)%0A %7B%0A throw error;%0A %7D%0A else %7B%0A conso @@ -861,16 +861,18 @@ data');%0A + conso @@ -921,16 +921,18 @@ .');%0A + getModel @@ -972,24 +972,26 @@ (callback)%7B%0A + var loo @@ -1020,24 +1020,26 @@ model;%0A + console.log( @@ -1064,32 +1064,34 @@ ck.model);%0A + + console.log('Dat @@ -1125,24 +1125,26 @@ Url);%0A%0A + console.log( @@ -1166,16 +1166,18 @@ );%0A + + getDataF @@ -1204,32 +1204,38 @@ setUrl,function( +error, callback)%7B%0A @@ -1225,24 +1225,110 @@ ,callback)%7B%0A + if (error)%0A %7B%0A throw error;%0A %7D%0A else %7B%0A if (l @@ -1362,26 +1362,34 @@ re')%0A -%7B%0A + %7B%0A con @@ -1445,24 +1445,28 @@ );%0A + + var json = f @@ -1508,32 +1508,36 @@ back);%0A + console.log('Con @@ -1579,11 +1579,19 @@ + + %7D%0A%0A + @@ -1632,32 +1632,36 @@ l,json);%0A + console.log('Imp @@ -1673,24 +1673,47 @@ inished!');%0A + %7D%0A%0A %7D);%0A %7D);%0A @@ -1713,18 +1713,17 @@ %7D);%0A %7D -); +%0A %0A %7D);%0A%0A%7D
7b0f049b4fc75d6265ca7115e6c90c0b075ce358
Fix API example of fetching profile info
client/FxaRelierClient.js
client/FxaRelierClient.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * The Firefox Accounts Relier Client. * * @module FxaRelierClient */ define([ 'client/auth/api', 'client/token/api', 'client/profile/api' ], function (AuthAPI, TokenAPI, ProfileAPI) { 'use strict'; /** * The entry point. Create and use an instance of the FxaRelierClient. * * @class FxaRelierClient (start here) * @constructor * @param {string} clientId - the OAuth client ID for the relier * @param {Object} [options={}] - configuration * @param {String} [options.clientSecret] * Client secret. Required to use the {{#crossLink "TokenAPI"}}Token{{/crossLink}} API. * @param {String} [options.contentHost] * Firefox Accounts Content Server host * @param {String} [options.oauthHost] * Firefox Accounts OAuth Server host * @param {String} [options.profileHost] * Firefox Accounts Profile Server host * @param {Object} [options.window] * window override, used for unit tests * @param {Object} [options.lightbox] * lightbox override, used for unit tests * @param {Object} [options.channel] * channel override, used for unit tests * @example * var fxaRelierClient = new FxaRelierClient(<client_id>); */ function FxaRelierClient(clientId, options) { if (! clientId) { throw new Error('clientId is required'); } /** * Authenticate users in the browser. Implements {{#crossLink "AuthAPI"}}{{/crossLink}}. * @property auth * @type {Object} * * @example * var fxaRelierClient = new FxaRelierClient('<client_id>'); * fxaRelierClient.auth.signIn({ * state: <state>, * redirectUri: <redirect_uri>, * scope: 'profile' * }); */ this.auth = new AuthAPI(clientId, options); /** * Manage tokens on the server. Implements {{#crossLink "TokenAPI"}}{{/crossLink}}. * @property token * @type {Object} * * @example * var fxaRelierClient = new FxaRelierClient('<client_id>', { * clientSecret: <client_secret> * }); * fxaRelierClient.token.tradeCode(<code>) * .then(function (token) { * // do something awesome with the token like get * // profile information. See profile. * }); */ this.token = new TokenAPI(clientId, options); /** * Fetch profile information on the server. Implements {{#crossLink "ProfileAPI"}}{{/crossLink}}. * @property profile * @type {Object} * * @example * var fxaRelierClient = new FxaRelierClient('<client_id>', { * clientSecret: <client_secret> * }); * fxaRelierClient.token.tradeCode(<code>) * .then(function (token) { * return fxaRelierClient.fetch(token); * }) * .then(function (profile) { * // display some profile info. * }); */ this.profile = new ProfileAPI(clientId, options); } FxaRelierClient.prototype = { auth: null }; return FxaRelierClient; });
JavaScript
0
@@ -3002,16 +3002,24 @@ rClient. +profile. fetch(to
7d113a9af137bd938893560312883e96f1c22206
add Object key deep search function
components/Deck/ContentModulesPanel/ContentDiffviewPanel/diff_funcs.js
components/Deck/ContentModulesPanel/ContentDiffviewPanel/diff_funcs.js
import createElement from 'virtual-dom/create-element'; import VNode from 'virtual-dom/vnode/vnode'; import VText from 'virtual-dom/vnode/vtext'; const convertHTML = require('html-to-vdom')({ VNode: VNode, VText: VText }); import $ from 'jquery'; //TODO FUnction that takes a string and returns a FUnction applying createElement(convertHTML()); const markText = (oldt, newt, mode) => { const uploaded = `<p class="txtdeleted">${oldt}</p><p class="txtadded">${newt}</p>`; const created = `<span class="txtdeleted">${oldt}</span><span class="txtadded">${newt}</span>`; return mode ? uploaded : created; }; //TODO ADD HEAVY PROPS CHECK const handleTEXT = (el, source, mode) => { console.warn('TEXT'); const oldText = el.vNode.text; const newText = el.patch.text; const markedText = markText(oldText, newText, mode); source = source.replace(oldText, markedText); return source; }; const handleINSERT = (el, source) => { console.warn('INSERTED'); let elem = createElement(el.patch); $(elem).addClass('added'); let root = createElement(convertHTML(source)); $(root).append(elem); source = root.outerHTML; return source; }; const handleREMOVE = (el, source) => { console.warn('REMOVE'); // elem = createElement(el.vNode); // $(elem).addClass('deleted'); // console.log(elem); const tag = el.vNode.tagName; const text = el.vNode.children[0].text; let root = createElement(convertHTML(source)); $(root).find(`${tag}:contains('${text}')`).addClass('deleted'); source = root.outerHTML; return source; }; const handlePROPS = (el, source) => { console.warn('PROPS'); const tag = el.vNode.tagName; const patchType = Object.keys(el.patch)[0]; const patch = Object.keys(el.patch[`${patchType}`])[0]; const vals = Object.values(el.patch[`${patchType}`])[0]; // console.log(`Patch type: ${patchType}, Patch: ${patch}, Value: ${vals}`); // elem = createElement(el.vNode); // $(elem).addClass('modified'); let root = createElement(convertHTML(source)); //TODO. UPDATE SEARCH. TEXT ONLY FINDS IF FIRST CHILD AND NOT DEEPLY NESTED. BY ID IS GOOD if (patchType === 'style' && vals) { let text = el.vNode.children[0].text; let _id = el.vNode.properties.attributes._id; if (_id) { let targetElement = $(root).find(`${tag}[_id='${_id}']`); targetElement.addClass('modified'); } else if (tag) { let targetElement = $(root).find(`${tag}:contains('${text}')`); targetElement.addClass('modified'); // targetElement.css(`${patch}`, `${vals}`); } } else if (patchType === 'attributes') { el.vNode.properties[`${patchType}`][`${patch}`] = vals; //$(root).find(`${tag}.${vals}`).addClass('modified'); } source = root.outerHTML; return source; }; const preprocessSrc = (source, mode) => { source = source.replace(/&nbsp;/g, ' ') .replace(/(?:\r\n|\r|\n)/g, ''); if (mode) { //uploaded slide let root = createElement(convertHTML(source)); $(root).find('.drawing-container').remove(); $(root).find('span:empty').remove(); //$(root).find('div:empty').remove(); source = root.outerHTML; } else { //created slide //wrap in a root node source = `<div class='root'>${source}</div>`; } return source; }; const setKeys = (source) => { //apply keys for proper change detection source = convertHTML({ getVNodeKey: function(attributes) { return attributes.id; } }, source); return source; }; /** * @params: @ PatchObject:list of diff changes @ string:initSrc - apply changes on top of this source string @ string:mode: uploaded/created */ const detectnPatch = (list, initSrc, mode) => { let elem; console.group(); console.info('Changes'); list.map((el) => { switch (el.type) { case 0: console.warn('NONE'); break; case 1: initSrc = handleTEXT(el, initSrc, mode); break; case 2: console.warn('VNODE'); elem = createElement(el.vNode); break; case 3: console.warn('WIDGET'); elem = createElement(el.vNode); break; case 4: initSrc = handlePROPS(el, initSrc); break; case 5: console.warn('ORDER'); elem = createElement(el.patch); break; case 6: initSrc = handleINSERT(el, initSrc); break; case 7: initSrc = handleREMOVE(el, initSrc); break; default: console.warn('default'); } }); console.groupEnd(); return initSrc; }; module.exports = { preprocess: preprocessSrc, construct: detectnPatch, setKeys: setKeys };
JavaScript
0.000001
@@ -247,16 +247,40 @@ jquery'; +%0Aimport _ from 'lodash'; %0A%0A//TODO @@ -372,16 +372,464 @@ ML());%0A%0A +const deepSearch = (obj, key) =%3E %7B%0A if (_.has(obj, key)) // or just (key in obj)%0A return %5Bobj%5D;%0A // elegant:%0A // return _.flatten(_.map(obj, function(v) %7B%0A // return typeof v == %22object%22 ? fn(v, key) : %5B%5D;%0A // %7D), true);%0A%0A // or efficient:%0A let res = %5B%5D;%0A _.forEach(obj, (v) =%3E %7B%0A if (typeof v == 'object' && (v = deepSearch(v, key)).length)%0A res.push.apply(res, v);%0A %7D);%0A return res;%0A%7D;%0A%0A const ma @@ -1740,137 +1740,88 @@ -// elem = createElement(el.vNode);%0A // $(elem).addClass('deleted') +const tag = el.vNode.tagName ;%0A - // cons -ole.log(elem);%0A const tag = el.vNode.tagName +t textArray = deepSearch(el.vNode, 'text') ;%0A @@ -1835,33 +1835,25 @@ text = -el.vNode.children +textArray %5B0%5D.text @@ -4557,31 +4557,113 @@ -initSrc = handleTEXT(el +const textArray = deepSearch(el, 'text');%0A initSrc = handleTEXT(textArray%5B0%5D, textArray%5B1%5D , in
83fe3ee679848908516b28c9f8f9164afb4f6fd7
add template-options to schema-form directive, where the value is a JSON.parse()-able object that overrides computed templateOptions. The object takes the form { '<field name>': { '<template option>': optionValue, ... }, ... } This is useful for changing label/input classes, etc, without forcing them in the model.
client/form/schemaForm.js
client/form/schemaForm.js
angular .module('isa.form') .directive('schemaForm', schemaFormDirective); function schemaFormDirective() { return { template: '<formly-form model="model" fields="formlyFields" options="formlyOptions"></formly-form>', require: '^schema', scope: { model: '=', fields: '@', hideLabel: '@' }, link: function(scope, elem, attr, schemaCtrl) { var fieldNames = attr.fields.split(','); scope.formlyFields = formFromSchema(schemaCtrl.$schema, fieldNames); scope.formlyOptions = { formState: { hideLabel: "true" === attr.hideLabel } }; } } } function isaFormService() { return { fromSchema: formFromSchema }; } function formFromSchema(schema, fields) { var answer = []; _.each(fields, function(field) { var item = schema.schema(field); // If it isn't a schema field, it's probably inline template. if (!item) { answer.push(field); return; } // Set up some simple defaults var fieldDef = { key: field, type: 'isaInput', templateOptions: {}, ngModelAttrs: { '{{options.key}}': { value: 'schema-field' } } }; // Copy common attributes from toplevel schema to the template options var to = fieldDef.templateOptions; _.each(['label', 'placeholder', 'min', 'max'], function (attr) { to[attr] = item[attr]; }); if (item.type === Number) { to.type = 'number'; } else if (item.type === Date) { fieldDef.type = 'isaDate'; } // Copy Isometrica-specific attributes over if (item.isa) { _.each(['helpId', 'placeholder'], function (attr) { to[attr] = item.isa[attr]; }); if (item.isa.fieldType) { fieldDef.type = item.isa.fieldType; } if (item.isa.inputType) { to.type = item.isa.inputType; } } if (item.hasOwnProperty('optional') && item.optional) { to.required = false; } else { to.required = true; } answer.push(fieldDef); }); return answer; }
JavaScript
0.000404
@@ -102,20 +102,24 @@ rective( +$log ) %7B%0A - return @@ -316,16 +316,44 @@ deLabel: + '@',%0A templateOptions: '@'%0A @@ -530,16 +530,581 @@ Names);%0A + if (attr.templateOptions) %7B%0A try %7B%0A var overrides = JSON.parse(attr.templateOptions);%0A _.each(overrides, function(val, key) %7B%0A var fieldDef = _.findWhere(scope.formlyFields, %7Bkey: key%7D);%0A if (fieldDef) %7B%0A _.extend(fieldDef.templateOptions, val);%0A %7D%0A else %7B%0A $log.warn('Did not find field def for', key);%0A %7D%0A %7D)%0A %7D%0A catch (e) %7B%0A $log.warn('While parsing', attr.templateOptions);%0A $log.warn(e);%0A %7D%0A %7D%0A%0A sc @@ -1222,94 +1222,15 @@ %7D%0A + %7D%0A%7D%0A%0A -function isaFormService() %7B%0A return %7B%0A fromSchema: formFromSchema%0A %7D;%0A%0A%7D%0A%0A func
78406ddbeb90a85c664827c0b990b4864db3617a
Fix and ungodly number of linter errors
client/map-scripts/map.js
client/map-scripts/map.js
navigator.geolocation.getCurrentPosition(function(position) { makeMap({lat: position.coords.latitude, lng: position.coords.longitude}); }, function(err) { console.error(err); }); var map; var marker; var destinationMarker; var makeMap = function(currentLatLngObj) { map = new google.maps.Map(document.getElementById('map'), { center: currentLatLngObj, zoom: 13 }); marker = new google.maps.Marker({ position: currentLatLngObj, map: map, animation: google.maps.Animation.DROP, icon: '/assets/bolt.png' }); destinationMarker = new google.maps.Marker({ position: randomCoordsAlongCircumference(currentLatLngObj, 1), map: map, animation: google.maps.Animation.DROP, icon: '/assets/finish-line.png' // change to finish line image }); }; var randomCoordsAlongCircumference = function(originObj, radius) { var randomTheta = Math.random() * 2 * Math.PI; return { lat: originObj.lat + (radius / 69 * Math.cos(randomTheta)), lng: originObj.lng + (radius / 69 * Math.sin(randomTheta)) }; };
JavaScript
0
@@ -42,16 +42,17 @@ function + (positio @@ -62,17 +62,30 @@ %7B%0A -makeMap(%7B +var mapToMake = %7B%0A lat: @@ -110,16 +110,20 @@ atitude, +%0A lng: po @@ -149,13 +149,35 @@ tude -%7D); +%0A %7D;%0A makeMap(mapToMake); %0A%7D, @@ -184,16 +184,17 @@ function + (err) %7B%0A @@ -219,16 +219,17 @@ r);%0A%7D);%0A +%0A var map; @@ -260,24 +260,24 @@ tionMarker;%0A - var makeMap @@ -286,16 +286,17 @@ function + (current @@ -872,16 +872,17 @@ function + (originO @@ -1085,12 +1085,13 @@ ta))%0A %7D;%0A%7D; +%0A
5c541716df7d50dca393e90f4d280aea6551afce
Remove stray text that got into the js file.
article/static/article/js/article.js
article/static/article/js/article.js
$(function() { $(".lazyload").css("display", "initial"); $(".scrollToTop").hide(); $(".full-row .info a").on("click", function() { $("body").animate({ scrollTop: $(".article-title").offset().top }, 1000); $(".full-row .info").animate({ toggleClass: "hidden" }, 1000); }); $(document).on("scroll", function() {co if ($(window).scrollTop() < 10) { $(".full-row .info").removeClass("hidden"); $(".scrollToTop").hide(); } else { $(".full-row .info").addClass("hidden"); $(".scrollToTop").show(); } }); $(".scrollToTop").on("click", function() { $("body").animate({ scrollTop: 0 }, 1000); }); $('.rich-text img').each(function() { $(this).wrap('<a class="gallery" href="javascript:void(0)"></a>'); }); $('.rich-text .gallery').magnificPopup({ type: 'image', tLoading: 'Loading image #%curr%...', image: { titleSrc: function(item) { var el = item.el; var parent = item.el.closest("p"); var sibling = parent.next("p"); var ital = sibling.find("i"); if (ital.length > 0 && ital.text().trim().length > 0) { return sibling.html(); } else { return null; } } }, gallery: { enabled: true, navigateByImgClick: true, preload: false }, callbacks: { elementParse: function(item) { var nextItem = $(this.items[this.index + 1]); $(nextItem).find("img").addClass("lazypreload"); var $this = $(item.el).find("img"); var src = $this.attr("data-src") || $this.prop("currentSrc") || $this.attr("src"); item.src = src; } } }); });
JavaScript
0
@@ -342,10 +342,8 @@ () %7B -co %0A%09if
a1d9739f9c4c32b2bea09c2b878d1f8e5939bc53
remove "bad" e2e test.
client/spec/login_spec.js
client/spec/login_spec.js
var Login = require('./../node_modules/superdesk-core/spec/helpers/pages').login; var waitForSuperdesk = require('./../node_modules/superdesk-core/spec/helpers/utils').waitForSuperdesk; describe('login', () => { var modal; beforeEach(() => { browser.ignoreSynchronization = true; modal = new Login(); }); it('form renders modal on load', () => { expect(modal.btn.isDisplayed()).toBe(true); browser.ignoreSynchronization = false; }); it('user can log in', () => { modal.login('admin', 'admin'); waitForSuperdesk().then(() => { browser.ignoreSynchronization = false; expect(modal.btn.isDisplayed()).toBe(false); expect(browser.getCurrentUrl()).toBe(browser.baseUrl + '/#/liveblog'); element(by.css('button.current-user')).click(); expect( element(by.css('.user-info .displayname')) .waitReady() .then((elem) => elem.getText()) ).toBe('admin'); }); }); it('user can log out', () => { modal.login('admin', 'admin'); waitForSuperdesk().then(() => { browser.ignoreSynchronization = false; element(by.css('button.current-user')).click(); // wait for sidebar animation to finish browser.wait(() => element(by.buttonText('SIGN OUT')).isDisplayed(), 200); element(by.buttonText('SIGN OUT')).click(); browser.wait(() => element(by.id('login-btn')), 5000); }); }); it('unknown user can\'t log in', () => { modal.login('foo', 'bar'); expect(modal.btn.isDisplayed()).toBe(true); expect(browser.getCurrentUrl()).not.toBe(browser.baseUrl + '/#/liveblog'); expect(modal.error.isDisplayed()).toBe(true); }); });
JavaScript
0.000005
@@ -1572,24 +1572,106 @@ %7D);%0A%0A + /**%0A * @TODO fix the not displaying error modal just for travis%0A *%0A * it('unknown @@ -1695,32 +1695,35 @@ in', () =%3E %7B%0A + * modal.login @@ -1735,35 +1735,38 @@ ', 'bar');%0A +* + expect(modal.btn @@ -1792,24 +1792,27 @@ e(true);%0A + * expect( @@ -1880,27 +1880,30 @@ log');%0A +* + expect(modal @@ -1940,17 +1940,28 @@ e);%0A -%7D); + * %7D);%0A */ %0A%7D);%0A%0A
7930ee4bcbc56a4b048263fdba84df4729eb2ef7
Return dispatch in the try block.
client/src/actions/app.js
client/src/actions/app.js
import {createAction} from 'redux-actions'; import axios from 'axios'; export const FETCH_APP_REQUEST = 'FETCH_APP_REQUEST'; export const FETCH_APP_SUCCESS = 'FETCH_APP_SUCCESS'; export const FETCH_APP_FAILURE = 'FETCH_APP_FAILURE'; export const RESET_STORE_AT_KEY = 'RESET_STORE_AT_KEY'; const fetchIndexRequest = createAction(FETCH_APP_REQUEST); const fetchIndexSuccess = createAction(FETCH_APP_SUCCESS); const fetchIndexFailure = createAction(FETCH_APP_FAILURE); export const fetchApp = () => async (dispatch) => { dispatch(fetchIndexRequest()); let response; try { response = await axios.get('v1/index'); } catch (err) { const reducedAction = (err instanceof Error) ? fetchIndexFailure(err) : fetchIndexFailure(err.response); return dispatch(reducedAction); } return dispatch(fetchIndexSuccess(response.data)); }; export const resetStoreAtKey = (key, initialState) => (dispatch) => { const resetStoreAtKeyAction = createAction(RESET_STORE_AT_KEY); return dispatch(resetStoreAtKeyAction({key, initialState})); };
JavaScript
0
@@ -555,72 +555,106 @@ %0A%0A -let response;%0A%0A try %7B%0A response = await axios.get('v1/index' +try %7B%0A const %7Bdata%7D = await axios.get('v1/index');%0A%0A return dispatch(fetchIndexSuccess(data) );%0A @@ -823,62 +823,8 @@ %0A %7D -%0A%0A return dispatch(fetchIndexSuccess(response.data)); %0A%7D;%0A
c142fe82557f82965f1a9884fb62c6854f1ecd25
Create homeId instance variable from route
client/views/home/home.js
client/views/home/home.js
Template.home.helpers({ 'residents': function () { // Get all residents for current home var homeId = this._id; return Residents.find({'homeId': homeId}); } });
JavaScript
0
@@ -46,16 +46,57 @@ on () %7B%0A + var instance = Template.instance();%0A%0A // G @@ -150,18 +150,26 @@ d = -this._i +instance.homeI d;%0A +%0A @@ -215,12 +215,167 @@ %7D);%0A %7D%0A%7D);%0A +%0ATemplate.home.created = function () %7B%0A var instance = this;%0A%0A // Set current Home ID from router%0A instance.homeId = Router.current().params.homeId;%0A%7D;%0A
4eaca8f11758b5ce65364cd39832a41bea8134d2
reset to latest on empty search
clientapp/views/layout.js
clientapp/views/layout.js
var HumanView = require('human-view'); var templates = require('templates'); module.exports = HumanView.extend({ template: templates.layout, events: { 'click .js-login': 'login', 'click .js-logout': 'logout', 'click .js-view-latest': 'landing', 'click .js-view-pathways': 'pathways', 'click .js-view-badges': 'badges', 'click .js-view-tag': 'tag', 'click .user-panel': 'dashboard', 'keyup .search-input': 'search' }, render: function () { this.renderAndBind(this.model); this.registerBindings(this.model.currentUser, { classBindings: { 'hideLoggedIn': '.js-login-item', 'hideLoggedOut': '.js-logout-item, .js-user-panel' }, textBindings: { 'email': '.js-user-email' } }); this.$container = $('#pages', this.$el); return this; }, login: function (e) { this.model.startLogin(); e.preventDefault(); }, logout: function (e) { this.model.logout(); e.preventDefault(); }, landing: function (evt) { window.app.router.navigateTo('/'); // TODO: generalize the following to all(?) dropdown buttons var dropdown = $(evt.currentTarget).closest('.f-dropdown'); Foundation.libs.dropdown.close(dropdown); }, pathways: function (evt) { window.app.router.navigateTo('y/pathway/'); }, badges: function (evt) { window.app.router.navigateTo('y/badge/'); }, tag: function (evt) { var tag = $(evt.target).text(); if (tag[0] === '#') tag = tag.slice(1); window.app.router.navigateTo('t/' + tag + '/'); }, dashboard: function (evt) { window.app.router.navigateTo('dashboard'); }, search: function (evt) { console.log(evt.keyCode); if (evt.keyCode === 13) { console.log('it was enter!'); var search = this.$('.search-input').val(); window.app.router.navigateTo('s/' + encodeURIComponent(search.trim()) + '/'); } } });
JavaScript
0
@@ -1677,38 +1677,8 @@ ) %7B%0A - console.log(evt.keyCode);%0A @@ -1707,44 +1707,8 @@ ) %7B%0A - console.log('it was enter!');%0A @@ -1749,24 +1749,51 @@ ut').val();%0A + if (search.trim())%0A window @@ -1860,24 +1860,78 @@ ()) + '/');%0A + else%0A window.app.router.navigateTo('/');%0A %7D%0A %7D%0A%7D)
8e49a54a031689934828dadbf414aa19f36c6e79
Use WeakMap for cache.
src/events.js
src/events.js
import './polyfills'; import { log } from './debug/logger'; import { TamiaError } from './util'; let handlersCache = {}; /** * Attach event handler. * * @param {HTMLElement} elem Element. * @param {string} eventName Event name. * @param {Function} handler Handler function. */ export function on(elem, eventName, handler) { if (DEBUG) { if (!handler) { throw new TamiaError(`Handler for ${eventName} event is not a function.`); } handler.displayName = `${eventName} event handler`; } let wrappedHandler = (event) => { let details = event.detail || []; if (DEBUG) { log(`Event ${event.type} on`, event.target, 'Details:', details); } handler(event, ...details); }; handlersCache[handler] = wrappedHandler; elem.addEventListener(eventName, wrappedHandler, false); } /** * Remove event handler. * * @param {HTMLElement} elem Element. * @param {string} eventName Event name. * @param {Function} handler Handler function. */ export function off(elem, eventName, handler) { let wrappedHandler = handlersCache[handler]; elem.removeEventListener(eventName, wrappedHandler, false); handlersCache[handler] = null; } /** * Trigger custom DOM event. * * @param {HTMLElement} elem Element. * @param {string} eventName Event name. * @param {*} detail... Extra data. */ export function trigger(elem, eventName, ...detail) { let params = { bubbles: true, cancelable: false, detail, }; elem.dispatchEvent(new window.CustomEvent(eventName, params)); } /** * Trigger native DOM event (like `click`). * * @param {HTMLElement} elem Element. * @param {string} eventName Event name. */ export function triggerNative(elem, eventName) { let event = document.createEvent('HTMLEvents'); event.initEvent(eventName, true, false); elem.dispatchEvent(event); } /** * Register events on the document. * * @param {object} handlers Handlers list. * * Example: * * registerGlobalEvents({ * 'tamia.form.enable': (event, ...details) => { ... }, * }); */ export function registerGlobalEvents(handlers) { for (let eventName in handlers) { on(document, eventName, handlers[eventName]); } }
JavaScript
0
@@ -99,26 +99,29 @@ let -handlersCache = %7B%7D +cache = new WeakMap() ;%0A%0A/ @@ -693,25 +693,17 @@ );%0A%09%7D;%0A%09 -handlersC +c ache%5Bhan @@ -1019,25 +1019,17 @@ ndler = -handlersC +c ache%5Bhan @@ -1101,17 +1101,9 @@ );%0A%09 -handlersC +c ache
74e2db26a3ad2334dbf91324d6fb0af7624bdb33
Fix double whitespace in name (fix only for console output.
src/format.js
src/format.js
'use strict'; const helpers = require('./helpers/helpers.js'); const Table = require('cli-table'); module.exports = format; const FORMATTERS = { 'dataForConsole': formatForConsole, 'updatesForConsole': formatUpdates, 'lastSeenTime': formatLastSeenTime, 'reportMusic': formatReportMusic, 'reportGeneral': formatReportGeneral }; function format(type) { const formatter = FORMATTERS[type]; if (typeof formatter === 'function') { let args = [].slice.call(arguments, 1); return formatter.apply(null, args); } console.error('No formatter for type', item.type); } function formatForConsole(data, logs_written=0) { let launch_date = helpers.getProcessLaunchDate(); let name = data.Name.split(' ').map(s => s.trim()).join(' '); let result = `App launched on ${launch_date}\n`; result += `User name: ${name}\n`; result += `User ID: ${data.user_id}\n`; result += `Logs written: ${logs_written}\n\n`; result += `>>> Checked on ${data.timestamp} <<<\n\n`; result += `${name} -- ${data['Last seen']}`; if (data.isFromMobile) { result += ' [Mobile]'; } result += '\n'; result += `Current status: ${data['Current status']}\n`; return result; } function formatUpdates(updates) { let result = '\nUPDATES\n'; for (let k in updates) { result += `${k}: ${updates[k].current}\n`; } return result; } function formatReportMusic(docs) { if (!docs.length) { return 'No music tracks were found'; } let table = new Table({ head: ['Track', 'Times played'] }); docs.forEach(doc => { table.push([doc.track, doc.play_count]); }); return table.toString(); } function formatReportGeneral(doc) { let result = ''; for (let k in doc) { if (k === '_id') continue; result += `${k.trim().replace(':', '')}: ${doc[k]}\n`; } return result; } function formatLastSeenTime(last_seen) { const regex = /\d{1,2}\:\d{2}\s{1}(am|pm){1}/i; if (regex.test(last_seen)) { let time = last_seen.match(regex)[0]; time = helpers.convertTimeTo24hrs(time); last_seen = last_seen.replace(regex, time); } return last_seen; }
JavaScript
0
@@ -742,43 +742,22 @@ ame. -split +replace (' + ' -).map(s =%3E s.trim()).join( +, ' ')
9b6f377d55828ca7336eeb6b1918abd1ef158436
delete redundant code
src/global.js
src/global.js
/** * @fileOverview global config * @author huangtonger@aliyun.com */ const version = require('./version'); module.exports = { trackable: true, defaultNodeSize: 40, defaultGuideSize: 100, nodeStyle: { lineWidth: 1 }, guideStyle: { }, labelStyle: { fill: '#595959', textAlign: 'center', textBaseline: 'middle' }, groupStyle: { stroke: '#CED4D9', fill: '#F2F4F5', radius: 2 }, groupBackgroundPadding: [ 40, 10, 10, 10 ], updateDuration: 450, enterDuration: 450, leaveDuration: 450, updateEasing: 'easeQuadOut', enterEasing: 'easeQuadOut', leaveEasing: 'easeQuadOut', version };
JavaScript
0.001743
@@ -170,33 +170,8 @@ 40,%0A - defaultGuideSize: 100,%0A no @@ -207,29 +207,8 @@ %7D,%0A - guideStyle: %7B%0A %7D,%0A la
c76d5882f1e78a4df1727b96cdf430387d631a2f
Add comments to the helper functions
src/helper.js
src/helper.js
'use strict'; function isObject(param) { return Object.prototype.toString.call(param) === '[object Object]'; } function isArray(param) { return Object.prototype.toString.call(param) === '[object Array]'; } function keys(obj) { return Object.keys(obj); } function extend(obj) { if (!isObject(obj)) { return obj; } var source, prop; for (var i = 1, length = arguments.length; i < length; i++) { source = arguments[i]; for (prop in source) { if (Object.hasOwnProperty.call(source, prop)) { obj[prop] = source[prop]; } } } return obj; } module.exports = { keys: keys, isArray: isArray, isObject: isObject, extend: extend };
JavaScript
0
@@ -8,16 +8,116 @@ rict';%0A%0A +/**%0A * Check if param is object%0A * @param %7Bany%7D param Parameter to check%0A * @return %7Bboolean%7D%0A */%0A function @@ -208,24 +208,123 @@ ect%5D'; %0A%7D%0A%0A +/**%0A * Check if param is array%0A * @param %7Bany%7D param Parameter to check%0A * @return %7Bboolean%7D%0A */%0A function isA @@ -415,60 +415,275 @@ %0A%7D%0A%0A -function keys(obj) %7B%0A return Object.keys(obj);%0A%7D%0A +/**%0A * Get object's keys%0A * @param %7Bobject%7D obj%0A * @return %7Barray%7D Array of the keys%0A */%0Afunction keys(obj) %7B%0A return Object.keys(obj);%0A%7D%0A%0A/**%0A * Extend object by other obect(s)%0A * @param %7Bobject%7D obj Object to extend%0A * @return %7Bobject%7D Extended object%0A */ %0Afun
4474a073c539ed3e2a4c04f49580b45c37b3aca8
make debug output optional
src/index.es6
src/index.es6
'use strict' var Leaf = require('./leaf') var utils = require('./utils') class BPlusIndex { constructor (config={}) { this.bf = config.branchingFactor || 3 this.root = new Leaf() } dumpTree (leaf) { leaf = leaf || this.root var struct = { id: leaf.id, keys: leaf.keys, // values: leaf.values, children: [] } for (let child of leaf.children) { struct.children.push(this.dumpTree(child)) } return struct } get (key) { var leaf = this._findLeaf(key) // console.log(leaf) return leaf.get(key) } insert (key, val) { var leaf = this._findLeaf(key) leaf.insertData(key, val) // console.log(JSON.stringify(this.dumpTree(), null, 2)) this._splitLeaf(leaf) } // Private Methods _findLeaf (key, leaf) { leaf = leaf || this.root if (leaf.children.length === 0) { return leaf } else { for (let i = 0; i <= leaf.size(); i++) { // console.log(`idx=${i} - key=${key} - leaf.keys=${leaf.keys} - leaf.id=${leaf.id}`) if (key < leaf.keys[i] || i === leaf.size()) { return this._findLeaf(key, leaf.children[i]) } } } } _splitLeaf (leaf) { if (leaf.size() >= this.bf) { // console.log(`SPLIT LEAF ${leaf.id}`) var splitPoint = Math.floor(leaf.size() / 2) var parent = leaf.parent var prev = leaf.prev var next = leaf.next var children = leaf.children var keys = leaf.keys var values = leaf.values var leftLeaf = new Leaf() var rightLeaf = new Leaf() if (prev != null) { prev.next = leftLeaf } if (next != null) { next.prev = rightLeaf } leftLeaf.parent = parent leftLeaf.prev = prev leftLeaf.next = rightLeaf leftLeaf.children = children.slice(0, splitPoint) leftLeaf.keys = keys.slice(0, splitPoint) leftLeaf.values = values.slice(0, splitPoint) rightLeaf.parent = parent rightLeaf.prev = leftLeaf rightLeaf.next = next rightLeaf.children = children.slice(splitPoint) rightLeaf.keys = keys.slice(splitPoint) rightLeaf.values = values.slice(splitPoint) if (parent === null) { // If we are splitting the root if (leaf.values.length > 0) { parent = this.root = new Leaf() parent.children = [leftLeaf, rightLeaf] parent.keys = [keys[splitPoint]] leftLeaf.parent = parent rightLeaf.parent = parent // console.log('SPLIT ROOT VALUES') // console.log(JSON.stringify(this.dumpTree(), null, 2)) } else { parent = this.root = new Leaf() parent.children = [leftLeaf, rightLeaf] parent.keys = [keys[splitPoint]] leftLeaf.parent = parent leftLeaf.children = children.slice(0, splitPoint + 1) for (let child of leftLeaf.children) { child.parent = leftLeaf } rightLeaf.parent = parent rightLeaf.keys = keys.slice(splitPoint + 1) rightLeaf.children = children.slice(splitPoint + 1) for (let child of rightLeaf.children) { child.parent = rightLeaf } // console.log('SPLIT ROOT NODE') // console.log(JSON.stringify(this.dumpTree(), null, 2)) } } else { var childPos = parent.children.indexOf(leaf) if (leaf.values.length > 0) { utils.replaceAt(parent.keys, leftLeaf.keys[0], childPos - 1) utils.replaceAt(parent.children, leftLeaf, childPos) utils.insertAt(parent.keys, rightLeaf.keys[0], childPos) utils.insertAt(parent.children, rightLeaf, childPos + 1) // console.log('SPLIT BRANCH VALUES') // console.log(JSON.stringify(this.dumpTree(), null, 2)) this._splitLeaf(parent) } else { rightLeaf.keys = keys.slice(splitPoint + 1) leftLeaf.children = children.slice(0, splitPoint + 1) for (let child of leftLeaf.children) { child.parent = leftLeaf } rightLeaf.children = children.slice(splitPoint + 1) for (let child of rightLeaf.children) { child.parent = rightLeaf } // utils.replaceAt(parent.keys, leftLeaf.keys[0], childPos - 1) utils.replaceAt(parent.children, leftLeaf, childPos) utils.insertAt(parent.keys, keys[splitPoint], childPos) utils.insertAt(parent.children, rightLeaf, childPos + 1) // console.log('SPLIT BRANCH NODE') // console.log(JSON.stringify(this.dumpTree(), null, 2)) this._splitLeaf(parent) } } } } } module.exports = BPlusIndex
JavaScript
0.00002
@@ -157,16 +157,55 @@ or %7C%7C 3%0A + this.debug = config.debug %7C%7C false%0A this @@ -527,34 +527,30 @@ (key) %7B%0A -var leaf = +return this._findL @@ -561,49 +561,8 @@ key) -%0A // console.log(leaf)%0A return leaf .get @@ -663,69 +663,8 @@ al)%0A - // console.log(JSON.stringify(this.dumpTree(), null, 2))%0A
96ab8b820d7022a1d770549cefcb037e23d9bff6
Update demo app.js to use Window instead of Stage
src/js/app.js
src/js/app.js
/** * Welcome to Pebble.js! * * This is where you write your app. */ var UI = require('ui'); var Vector2 = require('vector2'); var wind = new UI.Card({ title: 'Pebble.js', icon: 'images/menu_icon.png', body: 'Saying Hello World' }); wind.show(); wind.on('click', 'up', function(e) { var menu = new UI.Menu(); menu.items(0, [{ title: 'Hello World!', subtitle: 'Subtitle text' }, { title: 'Item #2' }]); menu.show(); }); wind.on('click', 'select', function(e) { var stage = new UI.Stage(); var textfield = new UI.Text({ text: 'Yo!', position: new Vector2(10, 10), size: new Vector2(100, 30), }); stage.add(textfield); stage.show(); }); wind.on('click', 'down', function(e) { var card = new UI.Card(); card.title('A Pebble.js Card'); card.subtitle('With subtitle'); card.body('This is the simplest window you can push to the screen.'); card.show(); });
JavaScript
0
@@ -130,20 +130,20 @@ );%0A%0Avar -w +ma in -d = new U @@ -239,20 +239,20 @@ d'%0A%7D);%0A%0A -w +ma in -d .show(); @@ -249,28 +249,28 @@ in.show();%0A%0A -w +ma in -d .on('click', @@ -363,16 +363,20 @@ World!', +%0A subtitl @@ -429,16 +429,119 @@ %0A %7D%5D);%0A + menu.on('select', function(e) %7B%0A console.log('Selected item: ' + e.section + ' ' + e.item);%0A %7D);%0A menu.s @@ -544,36 +544,36 @@ nu.show();%0A%7D);%0A%0A -w +ma in -d .on('click', 'se @@ -599,21 +599,20 @@ %7B%0A var -stage +wind = new U @@ -617,13 +617,14 @@ UI. -Stage +Window ();%0A @@ -747,21 +747,20 @@ %7D);%0A -stage +wind .add(tex @@ -774,13 +774,12 @@ ;%0A -stage +wind .sho @@ -788,20 +788,20 @@ );%0A%7D);%0A%0A -w +ma in -d .on('cli
0d5cf5b22d5ffd3f12fba5a8a86cca78eecf5df4
Remove ES6 constructs
postal-react-mixin.js
postal-react-mixin.js
/** * Copyright 2015-2016, Ludwig Shcubert. * All rights reserved. * * @providesModule PostalReactMixin * @typechecks static-only */ 'use strict'; import Postal from 'postal'; const PostalReactMixin = { _defaultPostalChannel: 'PostalReactMixinChannel', /** * Exposed methods */ subscribe: function( topic, callback ) { this._postalSubscriptions[topic] = Postal.subscribe({ channel: this.channel || this._defaultPostalChannel, topic: topic, callback: callback }).context(this); }, publish: function( topic, data ) { Postal.publish({ channel: this.channel || this._defaultPostalChannel, topic: topic, data: data }); }, /** * React component lifecycle methods */ componentWillMount: function() { if (!this.hasOwnProperty("_postalSubscriptions")) { this._postalSubscriptions = {}; } for (const topic in this.subscriptions) { if (this.subscriptions.hasOwnProperty(topic)) { const callback = this.subscriptions[topic]; this.subscribe(topic, callback); } } }, componentWillUnmount: function() { this._unsubscribe(); }, /** * Internal methods */ _unsubscribe: function() { for (const topic in this._postalSubscriptions) { if (this._postalSubscriptions.hasOwnProperty(topic)) { this._postalSubscriptions[topic].unsubscribe(); } } this._postalSubscriptions = {}; } }; module.exports = PostalReactMixin;
JavaScript
0.000003
@@ -84,17 +84,17 @@ sModule -P +p ostalRea @@ -152,35 +152,37 @@ ';%0A%0A -import Postal from +var postal = require( 'postal' ;%0A%0Ac @@ -181,33 +181,26 @@ tal' +) ;%0A%0A -const PostalReactMixin +module.exports = %7B @@ -227,17 +227,17 @@ annel: ' -P +p ostalRea @@ -368,17 +368,17 @@ opic%5D = -P +p ostal.su @@ -566,17 +566,17 @@ ) %7B%0A -P +p ostal.pu @@ -883,37 +883,35 @@ %0A %7D%0A for ( -const +var topic in this.s @@ -988,21 +988,19 @@ -const +var callbac @@ -1234,13 +1234,11 @@ or ( -const +var top @@ -1450,40 +1450,4 @@ %0A%0A%7D; -%0A%0Amodule.exports = PostalReactMixin;
c1558463914493141021fa814cea3f2d13c48f57
send feedback on button press
src/js/app.js
src/js/app.js
var UI = require('ui'); var ajax = require('ajax'); var Vibe = require('ui/vibe'); var Voice = require('ui/voice'); var main = new UI.Card({ title: 'Blobs', body: 'Press center to record a new note.', }); main.show(); main.on('click', 'select', function(e) { var card = new UI.Card({ title: 'New Note', subtitle: 'Press select to save it', }); Voice.dictate('start', false, function(e) { if (e.err) { card.body('Error: ' + e.err); console.log('Error: ' + e.err); card.show(); return; } var content = e.transcription; card.on('click', 'select', function(e) { var feedbackCard = new UI.Card(); console.log(e.button); ajax( { url: 'http://requestb.in/1cpmxfm1', method: 'post', type: 'json', data: {'content': content}, }, function(data, status, req) { console.log('Req failed: ', data, status, req); console.log(data); console.log(status); console.log(req); Vibe.vibrate('long'); feedbackCard.title('Failed :('); feedbackcard.body('status:'+status); feedbackcard.show(); }, function(data, status, req) { Vibe.vibrate(); feedbackCard.title('Note saved!'); feedbackcard.show(); console.log('Req for saving note: ' + status + '/' +data); } ); }); card.body(e.transcription); card.show(); }); });
JavaScript
0
@@ -608,24 +608,46 @@ nction(e) %7B%0A + Vibe.vibrate();%0A var fe
39ee4d7117bc5f06661190773fb9ad080ac8f572
Check for new interactions before waiting for a timeout
src/js/app.js
src/js/app.js
console.log('app.js'); var App = Backbone.View.extend({ initialize: function() { _.bindAll(this); }, /** * If config and accounts are ready start init */ ready: function() { console.log('app ready'); if (config.ready && accounts.ready) { this.init(); } }, /** * Config and accounts are ready to go */ init: function() { console.log('app.init'); if (this.model.get('frequency', false)) { this.setInterval(this.model.get('frequency', false)); } }, /** * Set interval to poll API */ setInterval: function(interval) { console.log('app.setInterval', interval); if (this.intervalId) { this.clearInterval(this.intervalId); } var intervalId = setInterval(this.triggerInterval, interval * 1000); this.intervalId = intervalId; return this; }, /** * Clear existing interval */ clearInterval: function() { console.log('app.clearInterval', this.intervalId); clearInterval(this.intervalId); delete this.intervalId return this; }, /** * Trigger invervals to check for data */ triggerInterval: function() { console.log('app.triggerInterval'); if (this.model.get('actions', false)) { this.trigger('interval'); } return this; }, /** * When config.frequency chanages clear the existing interval and set a new one */ changeInterval: function(model, value) { console.log('app.changeInterval', model.changed.frequency); if (model.changed && model.changed.frequency) { this.clearInterval(this.intervalId); } if (value) { this.setInterval(value); } return this; } });
JavaScript
0
@@ -505,32 +505,64 @@ false));%0A %7D%0A + interactions.checkForNew();%0A %7D,%0A%0A%0A /**%0A
6023a4dce9083de5445a18caa1c6bd1c16c851ce
refresh stops after settings, real configuration page
src/js/app.js
src/js/app.js
var UI = require('ui'); var ajax = require('ajax'); var Vector2 = require('vector2'); var Accel = require('ui/accel'); var Vibe = require('ui/vibe'); var Settings = require('settings'); // Show splash screen while waiting for data var splashWindow = new UI.Window(); // Text element to inform user var text = new UI.Text({ position: new Vector2(0, 0), size: new Vector2(144, 168), text:'Downloading weather data...', font:'GOTHIC_28_BOLD', color:'black', textOverflow:'wrap', textAlign:'center', backgroundColor:'white' }); console.log("Is this the correct program ????") //warming up the server ajax({ url: 'https://fast-lowlands-9940.herokuapp.com', type: 'json' }) // Add to splashWindow and show splashWindow.add(text); splashWindow.show(); var options = JSON.parse(Settings.option('settings') || '[]' ) var menuItems = options.map(function(stop, i){ return { subtitle: stop.name, title: stop.stop + "/" + stop.line, stop: stop.stop, line: stop.line } }) // Construct Menu to show to user var resultsMenu = new UI.Menu({ sections: [{ title: 'Stops', items: menuItems }] }); var selectedDetail, updating = false function refreshDetail(e){ var event = e updating = true console.log("Refreshing info for stop", e.item.title) var title = e.item.title ajax({ url: 'https://fast-lowlands-9940.herokuapp.com/stops/' + e.item.stop, type: 'json' },function(data){ updating = false var content = data.timetable .map(function(row){ return row.line +' ' +row.time }).join('\n') for(var rowIndex in data.timetable){ if(data.timetable[rowIndex].line == e.item.line){ var time44 = data.timetable[rowIndex].time break } } if(time44 && ~~time44.indexOf(":")){ var eta = parseInt(time44) } var delay if (eta <= 2){ delay = 30 }else if(eta <= 5){ delay = 60 }else if(eta <=10){ delay = 120 }else { delay = 300 } delay=delay||30 console.log("Delay is "+delay+" s") if(time44 == "Due"){ Vibe.vibrate('double'); } if(selectedDetail){ selectedDetail.hide() } var detailCard = selectedDetail = new UI.Card({ title: title + " (" + delay/60 + "')", body: content, scrollable:true }); detailCard.show(); Vibe.vibrate('short'); var timerId = setTimeout(function(){ console.log("Timer running") refreshDetail(event); }, delay*1000); console.log("Setting up timer " + timerId + " delay " + delay) detailCard.on('hide', function(){ console.log('hiding card, remove timer '+ timerId) clearTimeout(timerId) }) detailCard.on('click','select', function(e){ console.log("force updating") if(!updating) { refreshDetail(event); }else{ console.log('already updating') } }) },function(){ updating = false }) } resultsMenu.on('select', refreshDetail) // Show the Menu, hide the splash resultsMenu.show(); splashWindow.hide(); Settings.config({ url: "http://output.jsbin.com/layotu", }, function(){ console.log('opened') },function (e){ Settings.option("settings", JSON.stringify(e.options)) // Show the raw response if parsing failed if (e.failed) { console.log(e.response); } })
JavaScript
0
@@ -850,16 +850,49 @@ %5B%5D' )%0A%0A +%0Afunction makeMenu(options)%7B%0A var menu @@ -931,16 +931,20 @@ op, i)%7B%0A + retu @@ -956,16 +956,20 @@ + + subtitle @@ -981,16 +981,20 @@ p.name,%0A + @@ -1037,16 +1037,20 @@ + + stop: st @@ -1066,16 +1066,20 @@ + line: st @@ -1090,18 +1090,30 @@ ine%0A + %7D%0A -%7D)%0A%0A + %7D)%0A%0A // C @@ -1138,24 +1138,28 @@ how to user%0A + var resultsM @@ -1178,16 +1178,20 @@ .Menu(%7B%0A + sect @@ -1203,24 +1203,28 @@ %5B%7B%0A + + title: 'Stop @@ -1227,16 +1227,20 @@ Stops',%0A + @@ -1264,14 +1264,85 @@ -%7D%5D%0A%7D); + %7D%5D%0A %7D);%0A%0A return resultsMenu%0A%7D%0A%0Avar resultsMenu = makeMenu(options) %0A%0Ava @@ -3645,34 +3645,66 @@ http +s :// -output.jsbin.com/layotu +carlo-colombo.github.io/dublin-bus-pebble-configurator %22,%0A%7D @@ -3820,16 +3820,148 @@ ions))%0A%0A + options = e.options%0A resultsMenu.hide()%0A resultsMenu.hide()%0A resultsMenu = makeMenu(e.options)%0A resultsMenu.show()%0A%0A // S
028199561c62a6da719e7e6d317052fd78917c60
Use mousedown instead of click
Leaflet.Sleep.js
Leaflet.Sleep.js
L.Map.mergeOptions({ sleep: true, sleepTime: 750, wakeTime: 750, sleepNote: true, hoverToWake: true }); L.Map.Sleep = L.Handler.extend({ addHooks: function () { this.sleepNote = L.DomUtil.create('p', 'sleep-note', this._map._container); this._sleepMap(); this._enterTimeout = null; this._exitTimeout = null; var mapStyle = this._map.getContainer().style; mapStyle.WebkitTransition += 'opacity .5s'; mapStyle.MozTransition += 'opacity .5s'; var noteString = this._map.options.wakeMessage || ('Click ' + (this._map.options.hoverToWake?'or Hover ':'') + 'to Wake'); var style = this.sleepNote.style; if( this._map.options.sleepNote ){ this.sleepNote.appendChild(document.createTextNode( noteString )); style.maxWidth = '150px'; style.transitionDuration = '.2s'; style.zIndex = 5000; style.opacity = '.6'; style.margin = 'auto'; style.textAlign = 'center'; style.borderRadius = '4px'; style.top = '50%'; style.position = 'relative'; style.padding = '5px'; style.border = 'solid 2px black'; style.background = 'white'; } }, removeHooks: function () { if (!this._map.scrollWheelZoom.enabled()){ this._map.scrollWheelZoom.enable(); } L.DomUtil.setOpacity( this._map._container, 1); L.DomUtil.setOpacity( this.sleepNote, 0); this._removeSleepingListeners(); this._removeAwakeListeners(); }, _wakeMap: function () { this._stopWaiting(); this._map.scrollWheelZoom.enable(); L.DomUtil.setOpacity( this._map._container, 1); this.sleepNote.style.opacity = 0; this._addAwakeListeners(); }, _sleepMap: function () { this._stopWaiting(); this._map.scrollWheelZoom.disable(); L.DomUtil.setOpacity( this._map._container, .7); this.sleepNote.style.opacity = .4; this._addSleepingListeners(); }, _wakePending: function () { this._map.once('click', this._wakeMap, this); if (this._map.options.hoverToWake){ var self = this; this._map.once('mouseout', this._sleepMap, this); self._enterTimeout = setTimeout(function(){ self._map.off('mouseout', self._sleepMap, self); self._wakeMap(); } , self._map.options.wakeTime); } }, _sleepPending: function () { var self = this; self._map.once('mouseover', self._wakeMap, self); self._exitTimeout = setTimeout(function(){ self._map.off('mouseover', self._wakeMap, self); self._sleepMap(); } , self._map.options.sleepTime); }, _addSleepingListeners: function(){ this._map.once('mouseover', this._wakePending, this); }, _addAwakeListeners: function(){ this._map.once('mouseout', this._sleepPending, this); }, _removeSleepingListeners: function(){ this._map.options.hoverToWake && this._map.off('mouseover', this._wakePending, this); this._map.off('mousedown click', this._wakeMap, this); }, _removeAwakeListeners: function(){ this._map.off('mouseout', this._sleepPending, this); }, _stopWaiting: function () { this._removeSleepingListeners(); this._removeAwakeListeners(); var self = this; if(this._enterTimeout) clearTimeout(self._enterTimeout); if(this._exitTimeout) clearTimeout(self._exitTimeout); this._enterTimeout = null; this._exitTimeout = null; } }); L.Map.addInitHook('addHandler', 'sleep', L.Map.Sleep);
JavaScript
0.000001
@@ -1966,21 +1966,25 @@ p.once(' -click +mousedown ', this. @@ -2953,14 +2953,8 @@ down - click ', t
0de541d2e31153a80fe1d314c4e3679601a8b863
Add Links to more XML like tools.
presentation/index.js
presentation/index.js
// Import React import React from "react"; // Import Spectacle Core tags import { Appear, // BlockQuote, // Cite, CodePane, Deck, Fill, Heading, Image, Layout, // Link, ListItem, List, Markdown, // Quote, Slide, Spectacle, Text // Table, // TableRow, // TableHeaderItem, // TableItem } from "spectacle"; // Import image preloader util import preloader from "spectacle/lib/utils/preloader"; // Import theme import createTheme from "spectacle/lib/themes/default"; import CodeSplit from "./codesplit"; import TwoPane from './TwoPane'; import Code from "./Code"; // Import Examples import Example from './Example'; // Require CSS import 'normalize.css'; import "spectacle/lib/themes/default/index.css"; const images = { coding: require("../assets/coding.jpg"), control: require("../assets/control.jpg"), website: require("../assets/website.jpg"), }; preloader(images); const theme = createTheme({ primary: "#3b5998" }); const grey = "rgba(125, 125, 125, 0.8)"; theme.screen.progress.bar.bar.background = grey; theme.screen.controls.nextIcon.fill = grey; theme.screen.controls.prevIcon.fill = grey; export default class Presentation extends React.Component { render() { return ( <Spectacle theme={theme}> <Deck transition={["fade", "slide"]} transitionDuration={500} progress="bar"> <Slide bgColor="primary"> <Heading size={1} caps textColor="tertiary"> JSX </Heading> <Text textSize="1.5em" margin="100px 0px 0px 0px" textColor="tertiary"> Fabian Beliza & Jonas Faber </Text> </Slide> <Slide bgColor="tertiary"> <Heading size={4} caps lineHeight={1.5} textColor="primary"> Inhalt </Heading> <List textColor="secondary" textAlign="left"> <Appear><ListItem>Was ist JSX?</ListItem></Appear> <Appear><ListItem>Bezug zu XML</ListItem></Appear> <Appear><ListItem>Beispiele</ListItem></Appear> </List> </Slide> <Slide bgColor="tertiary" notes="Type-Safe, Errors werden während compilierung erkannt."> <Heading size={4} caps lineHeight={1.5} textColor="primary"> Was ist JSX? </Heading> <List textColor="secondary" textAlign="left"> <Appear><ListItem>XML-ähnliche Syntax-Erweiterung zu ECMAScript</ListItem></Appear> <Appear><ListItem>Wird von Preprozessoren transformiert</ListItem></Appear> <Appear><ListItem>Optimierungen während Kompilierung in JS</ListItem></Appear> <Appear><ListItem>Type-Safe</ListItem></Appear> <Appear><ListItem>Vereinfacht Templating (HTML-Syntax)</ListItem></Appear> <Appear><ListItem>Besonders im Zusammenhang mit React zu finden</ListItem></Appear> </List> </Slide> <Slide bgColor="tertiary"> <Heading size={4} caps lineHeight={1.5} textColor="primary"> Bezug zu XML </Heading> <List textColor="secondary" textAlign="left"> <Appear><ListItem><Markdown source="`< JSXElementName JSXAttributes(optional) / >`" /></ListItem></Appear> <Appear><ListItem>Strukturierung mit child-Elementen</ListItem></Appear> <Appear><ListItem>Baumstruktur</ListItem></Appear> </List> </Slide> <Slide bgColor="tertiary"> <Code template={Example.jsx} /> </Slide> </Deck> </Spectacle> ); } }
JavaScript
0
@@ -173,19 +173,16 @@ ayout,%0A - // Link,%0A @@ -3561,32 +3561,710 @@ %3C/Slide%3E%0A%0A + %3CSlide bgColor=%22tertiary%22%3E%0A %3CHeading size=%7B4%7D caps lineHeight=%7B1.5%7D textColor=%22primary%22%3E%0A Andere XML-%C3%84hnliche Spracherg%C3%A4nzungen%0A %3C/Heading%3E%0A %3CAppear%3E%0A %3CList textColor=%22secondary%22 textAlign=%22left%22%3E%0A %3CListItem%3E%3CLink href=%22https://github.com/insin/msx%22%3EMSL (JSX for Mithrill)%3C/Link%3E%3C/ListItem%3E%0A %3CListItem%3E%3CLink href=%22https://github.com/pzavolinsky/elmx%22%3Eelmx (JSX for Elm)%3C/Link%3E%3C/ListItem%3E%0A %3CListItem%3E%3CLink href=%22https://github.com/treycordova/nativejsx%22%3Enativejsx (JSX without React)%3C/Link%3E%3C/ListItem%3E%0A %3C/List%3E%0A %3C/Appear%3E%0A %3C/Slide%3E%0A %3C/Deck%3E%0A
377c7759cd0e073376b23fc9dc3c7c2e4fd151e9
Add click handler
priv/static/js/app.js
priv/static/js/app.js
$(function() { $("#clickable td").on("click", function() { console.log(this); }); $("#clickable td[data-coords='0,0']").html("<div class='circle white'></div>"); $("#clickable td[data-coords='0,1']").html("<div class='circle black'></div>"); $("#clickable td[data-coords='0,2']").html("<div class='circle white'></div>"); $("#clickable td[data-coords='1,0']").html("<div class='circle white'></div>"); $("#clickable td[data-coords='1,1']").html("<div class='circle white'></div>"); $("#clickable td[data-coords='1,2']").html("<div class='circle black'></div>"); $("#clickable td[data-coords='2,0']").html("<div class='circle black'></div>"); $("#clickable td[data-coords='2,1']").html("<div class='circle black'></div>"); $("#clickable td[data-coords='2,2']").html("<div class='circle black'></div>"); });
JavaScript
0.000001
@@ -8,16 +8,29 @@ ion() %7B%0A + var i = 0;%0A $(%22#cl @@ -75,24 +75,122 @@ -console.log(this +i++;%0A var color = (i %25 2 == 0) ? 'black' : 'white';%0A $(this).html(%22%3Cdiv class='circle %22 + color + %22'%3E%3C/div%3E%22 );%0A
69379d2336805d57ad6a820fb7becfd390e1585b
add 2px of vertical padding to features in layout
src/JBrowse/View/Layout2.js
src/JBrowse/View/Layout2.js
define( ['dojo/_base/declare'], function( declare ) { return declare( null, { constructor: function( args ) { this.pitchX = args.pitchX || 10; this.pitchY = args.pitchY || 10; this.bitmap = []; this.rectangles = {}; this.maxTop = 0; }, /** * @returns {Number} top position for the rect */ addRect: function(id, left, right, height) { // assumptions: // - most of the rectangles being laid out will be // nearly the same size if( this.rectangles[id] ) return this.rectangles[id].top * this.pitchY; var pLeft = Math.floor( left / this.pitchX ); var pRight = Math.floor( right / this.pitchX ); var pHeight = Math.floor( height / this.pitchY ); var midX = Math.floor((pLeft+pRight)/2); var rectangle = { id: id, l: pLeft, r: pRight, mX: midX, h: pHeight }; for( var top=0; top <= this.pTotalHeight; top++ ){ if(! this._collides(rectangle,top) ) break; } rectangle.top = top; this._addRectToBitmap( rectangle ); this.rectangles[id] = rectangle; //delete rectangle.mX; // don't need to store the midpoint this.pTotalHeight = Math.max( this.pTotalHeight||0, top+pHeight ); return top * this.pitchY; }, _collides: function( rect, top ) { var bitmap = this.bitmap; //var mY = top + rect.h/2; // Y midpoint: ( top+height + top ) / 2 // test the left first, then right, then middle var mRow = bitmap[top]; if( mRow && ( mRow[rect.l] || mRow[rect.r] || mRow[rect.mX]) ) return true; // finally, test exhaustively var maxY = top+rect.h; for( var y = top; y < maxY; y++ ) { var row = bitmap[y]; if( row ) for( var x = rect.l; x <= rect.r; x++ ) if( row[x] ) return true; } return false; }, /** * make a subarray if it does not exist * @private */ _autovivify: function( array, subscript ) { return array[subscript] || (function() { var a = []; array[subscript] = a; return a; })(); }, _addRectToBitmap: function( rect ) { var bitmap = this.bitmap; var av = this._autovivify; // finally, test exhaustively var yEnd = rect.top+rect.h; for( var y = rect.top; y < yEnd; y++ ) { var row = av(bitmap,y); for( var x = rect.l; x <= rect.r; x++ ) row[x]=true; } }, /** * Given a basepair range, deletes all data dealing with the features */ discardRange: function( left, right ) { }, hasSeen: function( id ) { return !! this.rectangles[id]; }, cleanup: function() { }, getTotalHeight: function() { return this.pTotalHeight * this.pitchY; } } ); });
JavaScript
0
@@ -278,16 +278,56 @@ op = 0;%0A + this.vertPadding = 2; // pixels%0A %7D,%0A%0A @@ -796,21 +796,39 @@ ath. -floor +ceil ( +( height ++this.vertPadding) / t
e7b8a3143641c362dca94b358bacc9e900eaf30e
Improve logging for failed scotman log
collect-versions/index.js
collect-versions/index.js
var _ = require('underscore'), bower = require('bower'), childProcess = require('child_process'), fs = require('fs'), request = require('request'), util = require('util'), semver = require('semver'), yeoman = require('yeoman-generator'); var CollectVersions = module.exports = function CollectVersions(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.argument('type', {desc: 'Version type. May be one of {scotsman, bower, hapi, npm}', required: true}); if (this.type === 'scotsman' || this.type === 'hapi') { this.argument('url', {desc: 'Remote version list url', required: true}); } else if (this.type !== 'bower' && this.type !== 'npm') { throw new Error('First argument must be one of {scotsman, bower, hapi, npm}'); } }; util.inherits(CollectVersions, yeoman.generators.Base); CollectVersions.prototype.exec = function() { if (this.type === 'scotsman') { this._scotsman(); } else if (this.type === 'hapi') { this._hapi(); } else if (this.type === 'bower') { this._bowerLS(); } else if (this.type === 'npm') { this._npmLS(); } }; CollectVersions.prototype._scotsman = function() { var done = this.async(), self = this; request(this.url, function(err, response, body) { if (err) { throw err; } var ls = (/<pre>((?:\n|.)*?)<\/pre>/.exec(body) || [])[1]; self.versions = parseVersions(ls); self.versions[0].bowerRoot = true; done(); }); }; CollectVersions.prototype._bowerLS = function() { var done = this.async(), self = this; childProcess.exec('bower ls --offline', function(err, stdout, stderr) { self.versions = parseVersions(stdout); self.versions[0].bowerRoot = true; done(); }); }; CollectVersions.prototype._hapi = function() { var done = this.async(), self = this; request(this.url, function(err, response, body) { if (err) { throw err; } var versions = JSON.parse(body); self.versions = versions; done(); }); }; CollectVersions.prototype._npmLS = function() { var done = this.async(), self = this; childProcess.exec('npm ls --json', function(err, stdout, stderr) { function deepPluck(name, obj) { var dependencies; if (obj.dependencies) { dependencies = _.map(obj.dependencies, function(info, name) { return deepPluck(name, info); }); return { name: name, version: obj.version, dependencies: dependencies }; } else { return { name: name, version: obj.version }; } } var list = JSON.parse(stdout); self.versions = [ deepPluck(list.name, list) ]; done(); }); }; CollectVersions.prototype.output = function() { if (!this.quiet) { console.log(JSON.stringify(this.versions, undefined, 2)); } }; function parseVersions(ls) { var versions = [], matcher = /(\S+)#(\S+)/g, match; while (match = matcher.exec(ls)) { versions.push({ name: match[1], version: match[2] }); } return versions; }
JavaScript
0.000001
@@ -1300,36 +1300,99 @@ r) %7B%0A throw + new Error('Failed to load scotsman url %22' + self.url + '%22 ' + err +) ;%0A %7D%0A%0A var
4c0fe9311d44e867a849bae082f71130553f1004
update TimeItems
src/_TimeItems/TimeItems.js
src/_TimeItems/TimeItems.js
/** * @file TimeItems component * @author sunday(sunday.wei@derbysoft.com) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import Event from '../_vendors/Event'; export default class TimeItems extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); this.clickHandle = ::this.clickHandle; this.mousemoveHandle = ::this.mousemoveHandle; this.mouseoutHandle = ::this.mouseoutHandle; } clickHandle(value) { if (this.refs.timeItems) { this.scrollTo(this.refs.timeItems, (+value) * 30, 200); } this.props.onChange && this.props.onChange(value); } mousemoveHandle() { this.refs.timeItems.style.overflowY = 'auto'; } scrollTo(element, to, duration) { // jump to target if duration zero if (duration <= 0) { element.scrollTop = to; return; } let difference = to - element.scrollTop; let perTick = difference / duration * 10; setTimeout(() => { element.scrollTop = element.scrollTop + perTick; if (element.scrollTop === to) return; this.scrollTo(element, to, duration - 10); }, 10); }; mouseoutHandle() { this.refs.timeItems.style.overflowY = 'hidden'; } componentDidMount() { const {value} = this.props; if (this.refs.timeItems) { const el = this.refs.timeItems; this.scrollTo(this.refs.timeItems, (+value) * 30, 0) } Event.addEvent(this.refs.timeItems, 'mouseover', this.mousemoveHandle); Event.addEvent(this.refs.timeItems, 'mouseout', this.mouseoutHandle); } componentWillUnmount() { Event.removeEvent(this.refs.timeItems, 'mouseover', this.mousemoveHandle); Event.removeEvent(this.refs.timeItems, 'mouseout', this.mouseoutHandle); } render() { const {className, style, data, value} = this.props, {width} = style; let liStyle = {}; if (width == '100%') { liStyle.paddingLeft = '140px'; } else if (width == '50%') { liStyle.paddingLeft = '60px'; } else { liStyle.paddingLeft = '36px'; } return ( <div className={`timeItems ${className ? className : ''}`} style={style} ref="timeItems"> <ul className="timeList"> { data && data.length ? data.map((item, key) => { return ( <li className={`timeItem ${item.value ? '' : 'disabled'} ${item.text == value ? 'active' : ''}`} key={key} style={liStyle} onClick={() => { if (item.value) { this.clickHandle(item.text); } }}> {item.text} </li> ); }) : null } </ul> </div> ); } } TimeItems.propTypes = { className: PropTypes.string, style: PropTypes.object, data: PropTypes.array };
JavaScript
0
@@ -240,24 +240,157 @@ omponent %7B%0A%0A + static propTypes = %7B%0A className: PropTypes.string,%0A style: PropTypes.object,%0A data: PropTypes.array%0A %7D;%0A%0A construc @@ -1688,16 +1688,17 @@ * 30, 0) +; %0A @@ -3611,120 +3611,4 @@ %7D%0A%7D -%0A%0ATimeItems.propTypes = %7B%0A className: PropTypes.string,%0A style: PropTypes.object,%0A data: PropTypes.array%0A%7D;
0f4f791a32973f0f589c6b870a2fe7ab62f180b2
remove .only() test
src/__tests__/index.test.js
src/__tests__/index.test.js
import gitExecAndRestage from "../"; import TestEnvironment from "TestEnvironment"; import path from "path"; describe("git-exec-and-restage", () => { const env = new TestEnvironment(); beforeEach(() => env.setup()); afterEach(() => env.cleanup()); it("no command, no args and no files staged", async () => { await expect(gitExecAndRestage()).rejects.toMatchSnapshot(); }); it("with command, no args and no files", async () => { await env.mockBin("prettier"); await gitExecAndRestage(["prettier"]); expect(await env.log).toMatchSnapshot(); }); it("with command and arguments, no files", async () => { await env.mockBin("prettier"); await gitExecAndRestage(["prettier", "--write", "--"]); expect(await env.log).toMatchSnapshot(); }); it("with command, arguments, fully staged file, no partials", async () => { await env.mockBin("prettier"); await env.setAllStagedFiles(["fullystaged.js"]); await gitExecAndRestage(["prettier", "--write", "--", "fullystaged.js"]); expect(await env.log).toMatchSnapshot(); }); it("with command+args, mix of fully and partially staged files", async () => { await env.mockBin("prettier"); await env.setAllStagedFiles(["fullystaged.js", "partiallystaged.js"]); await env.setPartialFiles(["partiallystaged.js"]); await gitExecAndRestage([ "prettier", "--write", "--", "fullystaged.js", "partiallystaged.js" ]); expect(await env.log).toMatchSnapshot(); }); it("with command+args, files implicit", async () => { await env.mockBin("prettier"); await env.setAllStagedFiles(["fullystaged.js", "partiallystaged.js"]); await env.setPartialFiles(["partiallystaged.js"]); await gitExecAndRestage(["prettier", "--write", "--"]); expect(await env.log).toMatchSnapshot(); }); it.only("with command+args, files implicit with invalid HEAD", async () => { await env.mockBin("prettier"); await env.setAllStagedFiles( ["fullystaged.js", "partiallystaged.js"], true /* fail on HEAD */ ); await env.setPartialFiles(["partiallystaged.js"]); await gitExecAndRestage(["prettier", "--write", "--"]); expect(await env.log).toMatchSnapshot(); }); it("with command+args, pick one of multiple files", async () => { await env.mockBin("prettier"); await env.setAllStagedFiles([ "fullystaged1.js", "fullystaged2.js", "partiallystaged1.js", "partiallystaged2.js" ]); await env.setPartialFiles(["partiallystaged1.js", "partiallystaged2.js"]); await gitExecAndRestage(["prettier", "--write", "--", "fullystaged1.js"]); expect(await env.log).toMatchSnapshot(); }); it("with command+args and mixed status, absolute paths", async () => { await env.mockBin("prettier"); await env.setAllStagedFiles(["fullystaged.js", "partiallystaged.js"]); await env.setPartialFiles(["partiallystaged.js"]); await gitExecAndRestage([ "prettier", "--write", "--", path.join(process.cwd(), "fullystaged.js"), path.join(process.cwd(), "partiallystaged.js") ]); expect(await env.log).toMatchSnapshot(); }); });
JavaScript
0.003284
@@ -1840,13 +1840,8 @@ it -.only (%22wi
9a9eaabf3316172770226a77ff7ba3c19a0b6a95
stop handling error:tile for infobox
lib/assets/core/javascripts/cartodb3/deep-insights-integration/map-integration.js
lib/assets/core/javascripts/cartodb3/deep-insights-integration/map-integration.js
var _ = require('underscore'); var checkAndBuildOpts = require('../helpers/required-opts'); var VisNotifications = require('../vis-notifications'); var AppNotifications = require('../app-notifications'); var REQUIRED_OPTS = [ 'diDashboardHelpers', 'editorModel', 'mapDefinitionModel', 'stateDefinitionModel', 'visDefinitionModel' ]; /** * Only manage **MAP**, **STATE** and **VIS** actions between Deep-Insights (CARTO.js) and Builder * */ module.exports = { track: function (options) { checkAndBuildOpts(options, REQUIRED_OPTS, this); this._map = this._diDashboardHelpers.getMap(); this._vis = this._diDashboardHelpers.visMap(); this._mapDefinitionModel.on('change:minZoom change:maxZoom', _.debounce(this._onMinMaxZoomChanged.bind(this), 300), this); this._mapDefinitionModel.on('change:scrollwheel', this._onScrollWheelChanged, this); this._mapDefinitionModel.on('change:legends', this._onLegendsChanged, this); this._mapDefinitionModel.on('change:layer_selector', this._onLayerSelectorChanged, this); var saveStateDefinition = _.debounce(this._saveStateDefinition.bind(this), 500); this._diDashboardHelpers.getDashboard().onStateChanged(saveStateDefinition); this._stateDefinitionModel.on('boundsSet', this._onBoundsSet, this); this._vis.on('mapViewSizeChanged', this._setMapViewSize, this); this._editorModel.on('change:settingsView', this._onEditorSettingsChanged, this); this._editorModel.on('change:edition', this._onEditionChanged, this); this._map.on('reload', this._visReload, this); this._map.on('change:error', this._visErrorChange, this); this._vis.on('error:tile', function (error) { error.type = 'unknown'; AppNotifications.addNotification(error); }, this); VisNotifications.track(this._map); this._onScrollWheelChanged(); // Needed to image export feature this._getVisMetadata(); this.setMapConverters(); this._setMapViewSize(); return this; }, _onMinMaxZoomChanged: function () { var currentZoom = this._vis.get('zoom'); var maxZoom = this._mapDefinitionModel.get('maxZoom'); var minZoom = this._mapDefinitionModel.get('minZoom'); this._vis.set({ minZoom: minZoom, maxZoom: maxZoom, zoom: Math.min(currentZoom, maxZoom) }); }, _saveStateDefinition: function () { var state = this._diDashboardHelpers.getDashboard().getState(); this._stateDefinitionModel.updateState(state); this._getVisMetadata(); }, _onScrollWheelChanged: function () { var scrollwheel = this._mapDefinitionModel.get('scrollwheel'); var method = scrollwheel ? 'enableScrollWheel' : 'disableScrollWheel'; var map = this._vis; map && map[method] && map[method](); }, _onLegendsChanged: function () { var legends = this._mapDefinitionModel.get('legends'); this._map.settings.set('showLegends', legends); }, _onLayerSelectorChanged: function () { var layerSelector = this._mapDefinitionModel.get('layer_selector'); this._map.settings.set('showLayerSelector', layerSelector); }, _setMapViewSize: function () { this._mapDefinitionModel.setMapViewSize( this._vis.getMapViewSize() ); }, setMapConverters: function () { var map = this._diDashboardHelpers.visMap(); this._mapDefinitionModel.setConverters({ pixelToLatLng: map.pixelToLatLng(), latLngToPixel: map.latLngToPixel() }); }, _onBoundsSet: function (bounds) { this._diDashboardHelpers.setBounds(bounds); }, _onEditorSettingsChanged: function () { var settingsView = this._editorModel.get('settingsView'); this._map.settings.set('layerSelectorEnabled', settingsView); }, _onEditionChanged: function () { this._diDashboardHelpers.forceResize(); }, _getVisMetadata: function () { var vis = this._map; var map = this._diDashboardHelpers.visMap(); var layers = this._diDashboardHelpers.getLayers(); var imageExportMetadata = { zoom: map.get('zoom'), mapType: map.getBaseLayer().get('baseType'), style: layers.at(0).get('style'), attribution: map.get('attribution'), provider: map.get('provider') }; this._mapDefinitionModel.setImageExportMetadata(imageExportMetadata); this._mapDefinitionModel.setStaticImageURLTemplate(vis.getStaticImageURL.bind(vis)); }, _visReload: function () { this._getVisMetadata(); this._visDefinitionModel.trigger('vis:reload'); this._visDefinitionModel.recordChange(); }, _visErrorChange: function () { this._visDefinitionModel && this._visDefinitionModel.trigger('vis:error', this._map.get('error')); } };
JavaScript
0
@@ -144,64 +144,8 @@ s'); -%0Avar AppNotifications = require('../app-notifications'); %0A%0Ava @@ -1579,149 +1579,8 @@ is); -%0A this._vis.on('error:tile', function (error) %7B%0A error.type = 'unknown';%0A AppNotifications.addNotification(error);%0A %7D, this); %0A%0A
21fec19aef95c75c0963d31ba6a79a1b9f3fef38
Add tab-pane-item-view test
lib/assets/core/test/spec/cartodb3/components/tab-pane/tab-pane-item-view.spec.js
lib/assets/core/test/spec/cartodb3/components/tab-pane/tab-pane-item-view.spec.js
var _ = require('underscore'); var TabPaneItemView = require('../../../../../javascripts/cartodb3/components/tab-pane/tab-pane-item-view'); var Backbone = require('backbone'); var CoreView = require('backbone/core-view'); describe('components/tab-pane-item-view', function () { beforeEach(function () { this.model = new Backbone.Model({ createButtonView: function () { return new CoreView(); } }); this.view = new TabPaneItemView({ model: this.model }); this.view.render(); }); it('should select the view', function () { this.view.$el.click(); expect(this.view.model.get('selected')).toBeTruthy(); expect(this.view.$el.hasClass('is-selected')).toBeTruthy(); }); it('should add the selected class on the start', function () { var view = new TabPaneItemView({ model: new Backbone.Model({ selected: true, createButtonView: function () { return new CoreView(); } }) }).render(); expect(view.$el.hasClass('is-selected')).toBeTruthy(); }); describe('with tooltip', function () { describe('.render', function () { it('should render properly', function () { expect(this.model.set('tooltip', 'help')); this.view.render(); expect(_.size(this.view._subviews)).toBe(3); }); }); }); it('should not have any leaks', function () { expect(this.view).toHaveNoLeaks(); }); });
JavaScript
0.000001
@@ -1061,16 +1061,372 @@ %0A %7D);%0A%0A + it('should add the disabled class on the start if item is disabled', function () %7B%0A var view = new TabPaneItemView(%7B%0A model: new Backbone.Model(%7B%0A disabled: true,%0A createButtonView: function () %7B%0A return new CoreView();%0A %7D%0A %7D)%0A %7D).render();%0A%0A expect(view.$el.hasClass('is-disabled')).toBeTruthy();%0A %7D);%0A%0A descri
984aaa0156451edb3ab5b6da0115f01e110b898d
Put the most recent learner’s name on the notification
kolibri/plugins/coach/assets/src/modules/coachNotifications/getters.js
kolibri/plugins/coach/assets/src/modules/coachNotifications/getters.js
import groupBy from 'lodash/groupBy'; import get from 'lodash/get'; import find from 'lodash/find'; import maxBy from 'lodash/maxBy'; import { NotificationObjects } from '../../constants/notificationsConstants'; import { partitionCollectionByEvents, getCollectionsForAssignment } from './gettersUtils'; const { LESSON, RESOURCE, QUIZ } = NotificationObjects; export function summarizedNotifications(state, getters, rootState, rootGetters) { const summaryEvents = []; const classSummary = rootGetters['classSummary/notificationModuleData']; // Group notifications by certain shared values // Resource Completed/Needs Help - Same Node and Lesson // Lesson/Quiz Completed - Same Lesson/Quiz const groupedNotifications = groupBy(state.notifications, n => { if (n.object === RESOURCE) { // Contains both Needs Help and Resource Completed-typed notifications return `${n.type}_${n.lesson_id}_${n.contentnode_id}`; } if (n.object === LESSON) { return `${n.type}_${n.lesson_id}`; } if (n.object === QUIZ) { return `${n.type}_${n.quiz_id}`; } }); for (let groupCode in groupedNotifications) { const allEvents = groupedNotifications[groupCode]; // Use first event in list as exemplar for summary object const firstEvent = allEvents[0]; // Get the ID of the most recent event in the collection const lastId = maxBy(allEvents, n => Number(n.id)).id; const { object, type, event } = firstEvent; // Set details about Lesson or Quiz let assignment; if (object === RESOURCE || object === LESSON) { assignment = { id: firstEvent.lesson_id, type: 'lesson', name: firstEvent.lesson, }; } if (object === QUIZ) { assignment = { id: firstEvent.quiz_id, type: 'exam', // using 'exam' here since it matches string used in ContentIcon name: firstEvent.quiz, }; } // If notification is for a single Resource, set up details about it let resource = {}; if (object === RESOURCE) { resource = { id: firstEvent.contentnode_id, content_id: get(classSummary.contentNodes, [firstEvent.contentnode_id, 'content_id'], ''), type: firstEvent.contentnode_kind, name: firstEvent.resource, }; } const assigneeCollections = getCollectionsForAssignment({ classSummary, assignment, }); // If 'assigneeCollections' is null, then the quiz or lesson was deleted if (assigneeCollections === null) continue; // Iterate through each of the assignee collections and create one // summarizing notification for each. for (let collIdx in assigneeCollections) { const collection = assigneeCollections[collIdx]; const partitioning = partitionCollectionByEvents({ classSummary, events: allEvents, collectionId: collection.collection, collectionType: collection.collection_kind, }); // If 'partitioning' is null, then the assignee collection is a learnergroup // that has been deleted. if (partitioning === null || partitioning.hasEvent.length === 0) continue; const firstUser = find(allEvents, { user_id: partitioning.hasEvent[0] }); summaryEvents.push({ type, object, event, groupCode: groupCode + '_' + collIdx, lastId, assignment, resource, collection: { id: collection.collection, type: collection.collection_kind, name: collection.name, }, learnerSummary: { firstUserName: firstUser.user, firstUserId: firstUser.user_id, total: partitioning.hasEvent.length, completesCollection: partitioning.rest.length === 0, // not used for Needs Help }, }); } } return summaryEvents; }
JavaScript
0
@@ -1,16 +1,54 @@ +import orderBy from 'lodash/orderBy';%0A import groupBy f @@ -3234,16 +3234,24 @@ = find( +orderBy( allEvent @@ -3257,43 +3257,110 @@ ts, -%7B user_id: partitioning.hasEvent%5B0%5D +'timestamp', %5B'desc'%5D), event =%3E %7B%0A return partitioning.hasEvent.includes(event.user_id);%0A %7D);
dee097081f6bd0ace74f60d53cc3c36379100d56
Remove unused args
lib/assets/javascripts/cartodb3/data/analysis-definition-node-model.js
lib/assets/javascripts/cartodb3/data/analysis-definition-node-model.js
var _ = require('underscore'); var $ = require('jquery'); var cdb = require('cartodb.js'); var camshaftReference = require('./camshaft-reference'); var nodeIds = require('./analysis-definition-node-ids.js'); /** * Base model for an analysis definition node. * May point to one or multiple nodes in turn (referenced by ids). */ module.exports = cdb.core.Model.extend({ initialize: function (attrs, opts) { if (!this.id) { var sourceId = this.sourceIds()[0]; this.set('id', nodeIds.next(sourceId)); } }, /** * @override {Backbone.prototype.parse} flatten the provided analysis data and create source nodes if there are any. */ parse: function (r) { var sourceNames = camshaftReference.getSourceNamesForAnalysisType(r.type); var parsedParams = _.reduce(r.params, function (memo, val, name) { var sourceName = sourceNames[sourceNames.indexOf(name)]; if (sourceName) { this.collection.add(val); memo[this._sourceIdAttrName(name)] = val.id; } else { memo[name] = val; } return memo; }, {}, this); return _.defaults( _.omit(r, 'params'), parsedParams ); }, /** * @override {Backbone.prototype.toJSON} unflatten the internal structure to the expected nested JSON data structure. */ toJSON: function () { // TODO how to unflatten? var sourceNames = camshaftReference.getSourceNamesForAnalysisType(this.get('type')); var paramNames = camshaftReference.getParamNamesForAnalysisType(this.get('type')); // Undo the parsing of the params previously done in .parse() (when model was created) var rawParams = _.reduce(paramNames, function (memo, name) { if (_.contains(sourceNames, name)) { var sourceId = this.get(this._sourceIdAttrName(name)); memo[name] = this.collection.get(sourceId).toJSON(); } else { memo[name] = this.get(name); } return memo; }, {}, this); return { id: this.id, type: this.get('type'), params: rawParams }; }, /** * @param {Boolean} [retryIfRejected = false] - Set to true to force a new deferred value * @return {Object} A promise, which when resolved contains a {String}, e.g. 'line', 'point', 'polygon' */ getOutputGeometryType: function (retryIfRejected) { var deferred = this.get('deferred_output_geometry_type'); if (_.result(deferred, 'state') === 'rejected' && retryIfRejected) { deferred = null; } if (!deferred) { deferred = $.Deferred(); this.set('deferred_output_geometry_type', deferred); this._fetchGeometryType(deferred); } return deferred.promise(); }, destroy: function () { this.collection.remove(this); }, /** * @return {Array} e.g. ['c3', 'b2'] */ sourceIds: function () { var sourceNames = camshaftReference.getSourceNamesForAnalysisType(this.get('type')); return _.map(sourceNames, function (name) { return this.get(this._sourceIdAttrName(name)); }, this); }, _sourceIdAttrName: function (name) { return name + '_id'; }, /** * @protected * @param {Object} deferred object */ _fetchGeometryType: function (deferred) { var definition = this.toJSON(); var geometryType = camshaftReference.getOutputGeometryForType(definition); deferred.resolve(geometryType); } });
JavaScript
0.000011
@@ -394,19 +394,8 @@ on ( -attrs, opts ) %7B%0A
9b4bbd5e66899735afa4571e9788a166c7c9c673
requests query 1
src/main/resources/public/world/worldScript.js
src/main/resources/public/world/worldScript.js
var wwd = new WorldWind.WorldWindow("canvasOne"); wwd.addLayer(new WorldWind.BMNGOneImageLayer()); wwd.addLayer(new WorldWind.BingAerialLayer()); wwd.addLayer(new WorldWind.CompassLayer()); wwd.addLayer(new WorldWind.CoordinatesDisplayLayer(wwd)); wwd.addLayer(new WorldWind.ViewControlsLayer(wwd)); <!--add placemark layer--> var placemarkLayer = new WorldWind.RenderableLayer("Placemark Layer"); wwd.addLayer(placemarkLayer); var placemarkAttributes = new WorldWind.PlacemarkAttributes(null); placemarkAttributes.imageOffset = new WorldWind.Offset( WorldWind.OFFSET_FRACTION, 0.5, WorldWind.OFFSET_FRACTION, 0.5); placemarkAttributes.labelAttributes.color = WorldWind.Color.YELLOW; placemarkAttributes.labelAttributes.offset = new WorldWind.Offset( WorldWind.OFFSET_FRACTION, 0.5, WorldWind.OFFSET_FRACTION, 1.5); placemarkAttributes.imageSource = WorldWind.configuration.baseUrl + "images/crosshair.png"; //pushpins/plain-red.png"; var placemark = new WorldWind.Placemark(new WorldWind.Position(-30, -54, 1.0), false, placemarkAttributes); wwd.navigator.range = 300.0;//(1 - thisLayer.zoomIncrement); wwd.redraw(); function showPosition(position) { let lat = position.coords.latitude; let lon = position.coords.longitude; let acu = position.coords.accuracy; let altitude = position.coords.altitude; let altitudeAccuracy = position.coords.altitudeAccuracy; let heading = position.coords.heading; let speed = position.coords.speed; let timestamp = position.coords.timestamp; var position = new WorldWind.Position(lat, lon, 0.0); placemark.position=position; placemark.label = "Ud esta aqui!\n" + "Lat " + placemark.position.latitude.toPrecision(4).toString() + "\n" + "Lon " + placemark.position.longitude.toPrecision(5).toString(); placemark.alwaysOnTop = true; placemarkLayer.addRenderable(placemark); //wwd.goTo(new WorldWind.Position(lat,lon,100)); wwd.navigator.lookAtLocation.latitude=position.latitude; wwd.navigator.lookAtLocation.longitude=position.longitude; //this.wwd.navigator.range); wwd.redraw(); } if (navigator.geolocation) { // alert("getting location"); navigator.geolocation.watchPosition(showPosition); } else { alert("Geolocation is not supported by this browser."); // x.innerHTML = "Geolocation is not supported by this browser."; } <!-- fin de placemarks--> <!-- 3d shapes--> var polygonLayer = new WorldWind.RenderableLayer(); wwd.addLayer(polygonLayer); var polygonAttributes = new WorldWind.ShapeAttributes(null); polygonAttributes.interiorColor = new WorldWind.Color(0, 1, 1, 0.75); polygonAttributes.outlineColor = WorldWind.Color.BLUE; polygonAttributes.drawOutline = true; polygonAttributes.applyLighting = true; var boundaries = []; boundaries.push(new WorldWind.Position(20.0, -75.0, 700000.0)); boundaries.push(new WorldWind.Position(25.0, -85.0, 700000.0)); boundaries.push(new WorldWind.Position(20.0, -95.0, 700000.0)); var polygon = new WorldWind.Polygon(boundaries, polygonAttributes); polygon.extrude = true; polygonLayer.addRenderable(polygon); /* var serviceAddress = "https://neo.sci.gsfc.nasa.gov/wms/wms?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.3.0"; var layerName = "MOD_LSTD_CLIM_M"; var createLayer = function (xmlDom) { var wms = new WorldWind.WmsCapabilities(xmlDom); var wmsLayerCapabilities = wms.getNamedLayer(layerName); var wmsConfig = WorldWind.WmsLayer.formLayerConfiguration(wmsLayerCapabilities); var wmsLayer = new WorldWind.WmsLayer(wmsConfig); wwd.addLayer(wmsLayer); }; var logError = function (jqXhr, text, exception) { console.log("There was a failure retrieving the capabilities document: " + text + " exception: " + exception); }; <!-- call jquery serviceAdress y createLayer on success--> $.get(serviceAddress).done(createLayer).fail(logError); */ function addPathPoligon(pathString){ const path = JSON.parse(pathString); console.log(path); var boundaries = []; // boundaries.push(new WorldWind.Position(20.0, -75.0, 700000.0)); // boundaries.push(new WorldWind.Position(25.0, -85.0, 700000.0)); // boundaries.push(new WorldWind.Position(20.0, -95.0, 700000.0)); // // var polygon = new WorldWind.Polygon(boundaries, polygonAttributes); // polygon.extrude = true; // polygonLayer.addRenderable(polygon); } function requestPoligons(){ const API_URL="https://www.ursulagis.com/last_poligon"; const xhr = new XMLHttpRequest(); function onResponse(){ if(this.readyState===4 && this.status === 200){ const data = JSON.parse(this.response) data.map(r=>addPathPoligon(r.path)); //console.log(data); } } xhr.addEventListener('load',onResponse); xhr.open("GET",API_URL); xhr.send(); } const interval = setInterval(requestPoligons, 30*1000);//30segs //clearInterval(interval); // thanks @Luca D'Amico
JavaScript
0.999995
@@ -4012,24 +4012,94 @@ thString)%7B%0D%0A +%09pathString=pathString.replace('%5C%22', '');%0D%0A%09console.log(pathString);%0D%0A %09const path
9e89dc448c44b7f09639923cc20e31b1ac3ef06e
Add DEfault text for max failures of cmd healthchecks
plugins/services/src/js/service-configuration/ServiceHealthChecksConfigSection.js
plugins/services/src/js/service-configuration/ServiceHealthChecksConfigSection.js
import React from 'react'; import {Table} from 'reactjs-components'; import { getColumnClassNameFn, getColumnHeadingFn, getDisplayValue, renderMillisecondsFromSeconds } from '../utils/ServiceConfigDisplayUtil'; import ConfigurationMapEditAction from '../components/ConfigurationMapEditAction'; import ServiceConfigBaseSectionDisplay from './ServiceConfigBaseSectionDisplay'; import Util from '../../../../../src/js/utils/Util'; class ServiceHealthChecksConfigSection extends ServiceConfigBaseSectionDisplay { /** * @override */ shouldExcludeItem() { const {appConfig} = this.props; return !Util.findNestedPropertyInObject(appConfig, 'healthChecks.length'); } /** * @override */ getDefinition() { const {onEditClick} = this.props; return { tabViewID: 'healthChecks', values: [ { key: 'healthChecks', heading: 'Health Checks', headingLevel: 1 }, { key: 'healthChecks', heading: 'Service Endpoint Health Checks', headingLevel: 2 }, { key: 'healthChecks', render(healthChecks) { let serviceEndpointHealthChecks = healthChecks.filter( (healthCheck) => { return ['HTTP', 'HTTPS', 'TCP'].includes(healthCheck.protocol); } ); const columns = [ { heading: getColumnHeadingFn('Protocol'), prop: 'protocol', render(prop, row) { return getDisplayValue(row[prop]); }, className: getColumnClassNameFn(), sortable: true }, { heading: getColumnHeadingFn('Path'), prop: 'path', className: getColumnClassNameFn(), render(prop, row) { return getDisplayValue(row[prop]); }, sortable: true }, { heading: getColumnHeadingFn('Grace Period'), prop: 'gracePeriodSeconds', className: getColumnClassNameFn(), render: renderMillisecondsFromSeconds, sortable: true }, { heading: getColumnHeadingFn('Interval'), prop: 'intervalSeconds', className: getColumnClassNameFn(), render: renderMillisecondsFromSeconds, sortable: true }, { heading: getColumnHeadingFn('Timeout'), prop: 'timeoutSeconds', className: getColumnClassNameFn(), render: renderMillisecondsFromSeconds, sortable: true }, { className: getColumnClassNameFn(), heading: getColumnHeadingFn('Max Failures'), prop: 'maxConsecutiveFailures', render(prop, row) { return getDisplayValue(row[prop]); }, sortable: true } ]; if (onEditClick) { columns.push({ heading() { return null; }, className: 'configuration-map-action', prop: 'edit', render() { return ( <ConfigurationMapEditAction onEditClick={onEditClick} tabViewID="healthChecks" /> ); } }); } return ( <Table key="service-endpoint-health-checks" className="table table-simple table-align-top table-break-word table-fixed-layout flush-bottom" columns={columns} data={serviceEndpointHealthChecks} /> ); } }, { heading: 'Command Health Checks', headingLevel: 2 }, { key: 'healthChecks', render(healthChecks) { let commandHealthChecks = healthChecks.filter((healthCheck) => { return healthCheck.protocol === 'COMMAND'; }); const columns = [ { heading: getColumnHeadingFn('Command'), prop: 'command', render: (prop, row) => { const command = row[prop] || {}; let value = getDisplayValue(command.value); if (!command.value) { return value; } return ( <pre className="flush transparent wrap"> {value} </pre> ); }, className: getColumnClassNameFn(), sortable: true }, { heading: getColumnHeadingFn('Grace Period'), prop: 'gracePeriodSeconds', className: getColumnClassNameFn(), render: renderMillisecondsFromSeconds, sortable: true }, { heading: getColumnHeadingFn('Interval'), prop: 'intervalSeconds', className: getColumnClassNameFn(), render: renderMillisecondsFromSeconds, sortable: true }, { heading: getColumnHeadingFn('Timeout'), prop: 'timeoutSeconds', className: getColumnClassNameFn(), render: renderMillisecondsFromSeconds, sortable: true }, { heading: getColumnHeadingFn('Max Failures'), prop: 'maxConsecutiveFailures', className: getColumnClassNameFn(), sortable: true } ]; if (onEditClick) { columns.push({ heading() { return null; }, className: 'configuration-map-action', prop: 'edit', render() { return ( <ConfigurationMapEditAction onEditClick={onEditClick} tabViewID="environment" /> ); } }); } return ( <Table key="command-health-checks" className="table table-simple table-align-top table-break-word table-fixed-layout flush-bottom" columns={columns} data={commandHealthChecks} /> ); } } ] }; } } module.exports = ServiceHealthChecksConfigSection;
JavaScript
0.000002
@@ -5763,32 +5763,83 @@ %7B%0A + className: getColumnClassNameFn(),%0A @@ -5951,41 +5951,98 @@ -className: getColumnClassNameFn() +render(prop, row) %7B%0A return getDisplayValue(row%5Bprop%5D);%0A %7D ,%0A
3790a3a44e082d75144914639a095122c43937a8
Add JSDoc comments
lib/node_modules/@stdlib/math/constants/float64-sqrt-half/lib/index.js
lib/node_modules/@stdlib/math/constants/float64-sqrt-half/lib/index.js
'use strict'; // sqrt(1/2) var SQRT_HALF = 7.07106781186547524400844362104849039284835937688474036588339868995366239231053519425193767163820786367506923115e-01; // EXPORTS // module.exports = SQRT_HALF;
JavaScript
0
@@ -13,19 +13,379 @@ ;%0A%0A/ -/ sqrt(1/2) +**%0A* Square root of %601/2%60.%0A*%0A* @module @stdlib/math/constants/float64-sqrt-half%0A* @type %7BNumber%7D%0A*%0A* @example%0A* var SQRT_HALF = require( '@stdlib/math/constants/float64-sqrt-half' );%0A* // returns 0.7071067811865476%0A*/%0A%0A%0A// CONSTANT //%0A%0A/**%0A* Square root of %601/2%60.%0A*%0A* %60%60%60 equation%0A* %5Csqrt%7B%5Cfrac%7B1%7D%7B2%7D%7D%0A* %60%60%60%0A*%0A* @constant%0A* @type %7BNumber%7D%0A* @default 0.7071067811865476%0A*/ %0Avar
2c92996d599a52ec661787c117a9ff34c3674528
Remove references to BuilderRow
src/main/webapp/components/BuilderDataTable.js
src/main/webapp/components/BuilderDataTable.js
import * as React from 'react'; import {BuilderRow} from './BuilderRow'; const HEADERS = ['no', 'text', 'log']; export const BuilderDataTable = props => { return ( <table className='data-table'> <thead> <tr>{HEADERS.map(header => <th>{header}</th>)}</tr> </thead> <tbody> {props.data.map(datapoint => <tr> {HEADERS.forEach(header => <td>{datapoint[header]}</td>)} </tr> )} </tbody> </table> ); }
JavaScript
0
@@ -28,49 +28,8 @@ ct'; -%0Aimport %7BBuilderRow%7D from './BuilderRow'; %0A%0Aco
2c195c0b0400ee5ed0274283368e52c5c41c3a1c
Add password to the available service buttons if it's included
packages/accounts-password/password_client.js
packages/accounts-password/password_client.js
(function () { Accounts.createUser = function (options, callback) { options = _.clone(options); // we'll be modifying options if (!options.password) throw new Error("Must set options.password"); var verifier = Meteor._srp.generateVerifier(options.password); // strip old password, replacing with the verifier object delete options.password; options.srp = verifier; Accounts.callLoginMethod({ methodName: 'createUser', methodArguments: [options], userCallback: callback }); }; // @param selector {String|Object} One of the following: // - {username: (username)} // - {email: (email)} // - a string which may be a username or email, depending on whether // it contains "@". // @param password {String} // @param callback {Function(error|undefined)} Meteor.loginWithPassword = function (selector, password, callback) { var srp = new Meteor._srp.Client(password); var request = srp.startExchange(); if (typeof selector === 'string') if (selector.indexOf('@') === -1) selector = {username: selector}; else selector = {email: selector}; request.user = selector; // Normally, we only set Meteor.loggingIn() to true within // Accounts.callLoginMethod, but we'd also like it to be true during the // password exchange. So we set it to true here, and clear it on error; in // the non-error case, it gets cleared by callLoginMethod. Accounts._setLoggingIn(true); Meteor.apply('beginPasswordExchange', [request], function (error, result) { if (error || !result) { Accounts._setLoggingIn(false); error = error || new Error("No result from call to beginPasswordExchange"); callback && callback(error); return; } var response = srp.respondToChallenge(result); Accounts.callLoginMethod({ methodArguments: [{srp: response}], validateResult: function (result) { if (!srp.verifyConfirmation({HAMK: result.HAMK})) throw new Error("Server is cheating!"); }, userCallback: callback}); }); }; // @param oldPassword {String|null} // @param newPassword {String} // @param callback {Function(error|undefined)} Accounts.changePassword = function (oldPassword, newPassword, callback) { if (!Meteor.user()) { callback && callback(new Error("Must be logged in to change password.")); return; } var verifier = Meteor._srp.generateVerifier(newPassword); if (!oldPassword) { Meteor.apply('changePassword', [{srp: verifier}], function (error, result) { if (error || !result) { callback && callback( error || new Error("No result from changePassword.")); } else { callback && callback(); } }); } else { // oldPassword var srp = new Meteor._srp.Client(oldPassword); var request = srp.startExchange(); request.user = {id: Meteor.user()._id}; Meteor.apply('beginPasswordExchange', [request], function (error, result) { if (error || !result) { callback && callback( error || new Error("No result from call to beginPasswordExchange")); return; } var response = srp.respondToChallenge(result); response.srp = verifier; Meteor.apply('changePassword', [response], function (error, result) { if (error || !result) { callback && callback( error || new Error("No result from changePassword.")); } else { if (!srp.verifyConfirmation(result)) { // Monkey business! callback && callback(new Error("Old password verification failed.")); } else { callback && callback(); } } }); }); } }; // Sends an email to a user with a link that can be used to reset // their password // // @param options {Object} // - email: (email) // @param callback (optional) {Function(error|undefined)} Accounts.forgotPassword = function(options, callback) { if (!options.email) throw new Error("Must pass options.email"); Meteor.call("forgotPassword", options, callback); }; // Resets a password based on a token originally created by // Accounts.forgotPassword, and then logs in the matching user. // // @param token {String} // @param newPassword {String} // @param callback (optional) {Function(error|undefined)} Accounts.resetPassword = function(token, newPassword, callback) { if (!token) throw new Error("Need to pass token"); if (!newPassword) throw new Error("Need to pass newPassword"); var verifier = Meteor._srp.generateVerifier(newPassword); Accounts.callLoginMethod({ methodName: 'resetPassword', methodArguments: [token, verifier], userCallback: callback}); }; // Verifies a user's email address based on a token originally // created by Accounts.sendVerificationEmail // // @param token {String} // @param callback (optional) {Function(error|undefined)} Accounts.verifyEmail = function(token, callback) { if (!token) throw new Error("Need to pass token"); Accounts.callLoginMethod({ methodName: 'verifyEmail', methodArguments: [token], userCallback: callback}); }; })();
JavaScript
0
@@ -5388,12 +5388,69 @@ %7D; +%0A%0A Accounts._loginButtons.loginServices.push('password'); %0A%7D)();%0A -%0A
8974e27827c338182b627696bb4d497518351d06
use just the internal logging in drive()
src/plugin/component.plugin.testdrive-drive.js
src/plugin/component.plugin.testdrive-drive.js
/* ** ComponentJS -- Component System for JavaScript <http://componentjs.com> ** Copyright (c) 2009-2014 Ralf S. Engelschall <http://engelschall.com> ** ** This Source Code Form is subject to the terms of the Mozilla Public ** License (MPL), version 2.0. If a copy of the MPL was not distributed ** with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* global API function: execute a usecase */ $cs.drive = function () { /* global setTimeout: false */ /* global clearTimeout: false */ /* determine parameters */ var params = $cs.params("drive", arguments, { name: { pos: 0, req: true, valid: "string" }, conf: { pos: 1, def: {}, valid: "object" }, timeout: { def: 0 } }); /* sanity check usecase */ var uc = usecase[params.name]; if (!_cs.isdefined(uc)) throw _cs.exception("drive", "invalid usecase name \"" + params.name + "\""); /* create promise */ var promise = new $cs.promise(); var response = promise.proxy; var resolved = false; /* optionally reject promise on timeout */ var to = null; if (params.timeout > 0) { to = setTimeout(function () { to = null; if (!resolved) { /* reject promise because of timeout */ resolved = true; $cs.debug(1, "drive: usecase \"" + params.name + "\", TIMEOUT after " + params.timeout + " ms"); promise.reject(new Error("usecase \"" + params.name + "\": timeout")); } }, params.timeout); } /* determine configuration */ var conf = {}; _cs.extend(conf, uc.conf); _cs.extend(conf, params.conf); /* execute usecase */ $cs.debug(1, "drive: usecase \"" + params.name + "\" (" + usecase[params.name].desc + "), EXECUTING" + (_cs.keysof(params.conf).length > 0 ? " with configuration " + _cs.json(params.conf) : "") + (params.timeout > 0 ? " and timeout of " + params.timeout + " ms" : "")); var result; try { result = uc.func.apply(conf, [ conf ]); } catch (ex) { if (!resolved) { /* reject promise because of exception */ resolved = true; $cs.debug(1, "drive: usecase \"" + params.name + "\", EXCEPTION: " + ex.message); promise.reject(new Error("usecase \"" + params.name + "\": " + ex.message)); } } /* clear still pending timer */ if (to !== null) { clearTimeout(to); to = null; } /* in case of no errors and no timeout, handle promise response */ if (!resolved) { if ( (typeof result === "object" || typeof result === "function") && typeof result.then === "function" ) /* replace our response promise with the given one */ response = result; else /* fulfill our response promise */ promise.fulfill(true); } response = response.then(null, function (e) { /* global console: true */ /* eslint no-console: 0 */ console.log("testdrive: ERROR: ", e); return e; }); /* return response promise */ return response; };
JavaScript
0
@@ -3094,111 +3094,72 @@ -/* global console: true */%0A /* eslint no-console: 0 */%0A console.log(%22testdrive: ERROR: %22, +$cs.debug(1, %22drive: usecase %5C%22%22 + params.name + %22%5C%22 failed: %22 + e);
98e6020baf1e8d4904bb3c4a751e3cb030e80e34
Migrate core/interfaces/i_delete_area.js named requires
core/interfaces/i_delete_area.js
core/interfaces/i_delete_area.js
/** * @license * Copyright 2021 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview The interface for a component that can delete a block or bubble * that is dropped on top of it. * @author kozbial@google.com (Monica Kozbial) */ 'use strict'; goog.module('Blockly.IDeleteArea'); goog.module.declareLegacyNamespace(); goog.require('Blockly.IDragTarget'); goog.requireType('Blockly.IDraggable'); /** * Interface for a component that can delete a block or bubble that is dropped * on top of it. * @extends {Blockly.IDragTarget} * @interface */ const IDeleteArea = function() {}; /** * Returns whether the provided block or bubble would be deleted if dropped on * this area. * This method should check if the element is deletable and is always called * before onDragEnter/onDragOver/onDragExit. * @param {!Blockly.IDraggable} element The block or bubble currently being * dragged. * @param {boolean} couldConnect Whether the element could could connect to * another. * @return {boolean} Whether the element provided would be deleted if dropped on * this area. */ IDeleteArea.prototype.wouldDelete; exports = IDeleteArea;
JavaScript
0
@@ -338,24 +338,43 @@ mespace();%0A%0A +const IDraggable = goog.require @@ -373,16 +373,20 @@ .require +Type ('Blockl @@ -396,19 +396,37 @@ Drag -Target');%0A%0A +gable');%0Aconst IDragTarget = goog @@ -425,36 +425,32 @@ t = goog.require -Type ('Blockly.IDragg @@ -444,29 +444,30 @@ lockly.IDrag -gable +Target ');%0A%0A%0A/**%0A * @@ -573,24 +573,16 @@ xtends %7B -Blockly. IDragTar @@ -871,24 +871,16 @@ param %7B! -Blockly. IDraggab
21353d529178558c176f48f305fd7290153132bf
Fix broken spec.
spec/google/lastresortwebkitfontwatchrunner_spec.js
spec/google/lastresortwebkitfontwatchrunner_spec.js
describe('LastResortWebKitFontWatchRunner', function () { var LastResortWebKitFontWatchRunner = webfont.LastResortWebKitFontWatchRunner, BrowserInfo = webfont.BrowserInfo, Size = webfont.Size, DomHelper = webfont.DomHelper, FontRuler = webfont.FontRuler, Font = webfont.Font, FontVariationDescription = webfont.FontVariationDescription, domHelper = new DomHelper(window), font = new Font('My Family', new FontVariationDescription('n4')); var TARGET_SIZE = new Size(3, 3), FALLBACK_SIZE_A = new Size(1, 1), FALLBACK_SIZE_B = new Size(2, 2), LAST_RESORT_SIZE = new Size(4, 4), browserInfo = new BrowserInfo(true, true, false), setupSizes = [FALLBACK_SIZE_A, FALLBACK_SIZE_B, LAST_RESORT_SIZE], actualSizes = [], timesToGetTimeBeforeTimeout = 10, activeCallback = null, inactiveCallback = null; beforeEach(function () { jasmine.Clock.useMock(); actualSizes = []; activeCallback = jasmine.createSpy('activeCallback'); inactiveCallback = jasmine.createSpy('inactiveCallback'); timesToGetTimeBeforeTimeout = 10; var setupFinished = false, fakeGetSizeCount = 0; spyOn(FontRuler.prototype, 'getSize').andCallFake(function () { var result = null; if (setupFinished) { // If you are getting an exception here your tests does not specify enough // size data to run properly. if (fakeGetSizeCount >= actualSizes.length) { throw 'Invalid test data'; } result = actualSizes[fakeGetSizeCount]; fakeGetSizeCount += 1; } else { result = setupSizes[Math.min(fakeGetSizeCount, setupSizes.length - 1)]; fakeGetSizeCount += 1; } return result; }); spyOn(goog, 'now').andCallFake(function () { if (timesToGetTimeBeforeTimeout <= 0) { return 6000; } else { timesToGetTimeBeforeTimeout -= 1; return 1; } }); var originalStart = LastResortWebKitFontWatchRunner.prototype.start; spyOn(LastResortWebKitFontWatchRunner.prototype, 'start').andCallFake(function () { setupFinished = true; fakeGetSizeCount = 0; originalStart.apply(this); }); }); it('should ignore fallback size and call active', function () { actualSizes = [ LAST_RESORT_SIZE, LAST_RESORT_SIZE, TARGET_SIZE, TARGET_SIZE ]; var fontWatchRunner = new LastResortWebKitFontWatchRunner(activeCallback, inactiveCallback, domHelper, font, browserInfo); fontWatchRunner.start(); jasmine.Clock.tick(1 * 25); expect(activeCallback).toHaveBeenCalledWith(fontFamily); }); it('should consider last resort font as having identical metrics and call active', function () { actualSizes = [ LAST_RESORT_SIZE, LAST_RESORT_SIZE, LAST_RESORT_SIZE, LAST_RESORT_SIZE ]; timesToGetTimeBeforeTimeout = 2; var arimo = new Font('Arimo'); var fontWatchRunner = new LastResortWebKitFontWatchRunner(activeCallback, inactiveCallback, domHelper, arimo, browserInfo); fontWatchRunner.start(); jasmine.Clock.tick(1 * 25); expect(activeCallback).toHaveBeenCalledWith(arimo); }); it('should fail to load font and call inactive', function () { actualSizes = [ LAST_RESORT_SIZE, LAST_RESORT_SIZE, LAST_RESORT_SIZE, LAST_RESORT_SIZE, FALLBACK_SIZE_A, FALLBACK_SIZE_B ]; timesToGetTimeBeforeTimeout = 3; var fontWatchRunner = new LastResortWebKitFontWatchRunner(activeCallback, inactiveCallback, domHelper, font, browserInfo); fontWatchRunner.start(); jasmine.Clock.tick(2 * 25); expect(inactiveCallback).toHaveBeenCalledWith(font); }); it('should call inactive when we are loading a metric incompatible font', function () { actualSizes = [ LAST_RESORT_SIZE, LAST_RESORT_SIZE, LAST_RESORT_SIZE, LAST_RESORT_SIZE ]; timesToGetTimeBeforeTimeout = 2; var fontWatchRunner = new LastResortWebKitFontWatchRunner(activeCallback, inactiveCallback, domHelper, font, browserInfo); fontWatchRunner.start(); jasmine.Clock.tick(1 * 25); expect(inactiveCallback).toHaveBeenCalledWith(font); }); });
JavaScript
0
@@ -2672,22 +2672,16 @@ ith(font -Family );%0A %7D);
13e280911fdde2057364d97c87f303318dc3fd3e
Fix a few bugs in the bindableEnum decorator
src/decorators.js
src/decorators.js
/* -*- javascript -*- */ "use strict"; import {constants} from './constants'; import {bindable, customAttribute, customElement} from 'aurelia-framework'; export function uiElement( component ) { let customElementFn = customElement( `${constants.elementPrefix}${component}` ); let metadata = { component }; return function( target, name, descriptor ) { Reflect.defineProperty( target, constants.metadataProperty, {value: metadata} ); return customElementFn( target, name, descriptor ); }; } export function uiAttribute( component, defaultBindingMode=null ) { let customAttributeFn = customAttribute( `${constants.attributePrefix}${component}`, defaultBindingMode ); let metadata = { component }; return function( target, name, descriptor ) { Reflect.defineProperty( target, constants.metadataProperty, {value: metadata} ); return customAttributeFn( target, name, descriptor ); }; } const DEFAULT_ENUM_OPTIONS = { includeName: true, cssClass: null }; export function bindableEnum( validValues, options={} ) { options = Object.assign( {}, DEFAULT_ENUM_OPTIONS, options ); // console.debug( "Bindable enum decorator called with: ", validValues ); return function( target, name, descriptor ) { let changedMethodName = `${name}Changed`; target[ changedMethodName ] = function( newValue, oldValue ) { this.logger.debug( `Changing ${name} to ${newValue} from ${oldValue}` ); this.removeCssClasses( oldValue ); this.addCssClasses( newValue ); if ( options.includeName ) { if ( newValue ) { this.addCssClasses( name ); } else { this.removeCssClases( name ); } } }; let originalBind = target.bind; target.bind = function( ...args ) { if ( originalBind ) { Reflect.apply( originalBind, this, args ); } if ( this[name] ) { this.addCssClasses( this[name] ); if ( options.includeName ) { let cssClass = options.cssClass || name; this.addCssClasses( cssClass ); } } }; return bindable( target, name, descriptor ); }; } export function bindableToggle( target, name, descriptor ) { let changedMethodName = `${name}Changed`; target[ changedMethodName ] = function( newValue ) { if ( newValue ) { this.addCssClasses(name); } else { this.removeCssClasses(name); } }; let originalBind = target.bind; target.bind = function( ...args ) { if ( originalBind ) { Reflect.apply( originalBind, this, args ); } // Treat an empty-string value as true for boolean attributes // (e.g., <ui-form inverted>) if ( this[name] !== null && this[name] !== false ) { this.addCssClasses( name ); } }; return bindable( target, name, descriptor ); }
JavaScript
0.000002
@@ -1512,29 +1512,94 @@ ) %7B%0A%09%09%09%09 -if ( newValue +let cssClass = options.cssClass %7C%7C name;%0A%0A%09%09%09%09if ( newValue %7C%7C newValue === '' ) %7B%0A%09%09%09 @@ -1616,28 +1616,32 @@ CssClasses( -name +cssClass );%0A%09%09%09%09%7D el @@ -1668,28 +1668,32 @@ eCssClases( -name +cssClass );%0A%09%09%09%09%7D%0A%09%09 @@ -1868,16 +1868,37 @@ is%5Bname%5D + %7C%7C this%5Bname%5D === '' ) %7B%0A%09%09%09
c5a0da9b49010de2c61439d00b8756ac636353d6
fix DOM.format
src/dom/format.js
src/dom/format.js
import { DOM } from "../types"; var reVar = /\{([\w\-]+)\}/g; /** * Formats template using a variables map * @memberof DOM * @alias DOM.format * @param {String} tmpl template string * @param {Object} varMap key/value map of variables * @return {String} a resulting string * @example * DOM.format("foo {name}", {name: "bar"}); // => "foo bar" * DOM.format("your {0}", ["title"]); // => "your title" */ DOM.format = function(tmpl, varMap) { if (typeof tmpl !== "string") tmpl = String(tmpl); if (!varMap || typeof varMap !== "object") varMap = {}; return tmpl.replace(reVar, (x, name, index) => { if (name in varMap) { x = varMap[name]; if (typeof x === "function") x = x(index); } return x; }); };
JavaScript
0.000406
@@ -738,16 +738,44 @@ (index); +%0A%0A x = String(x); %0A
0826095bff574578333c86a48d087b4d43ef1716
disable unicorn/no-fn-reference-in-iterator
plugins/unicorn.js
plugins/unicorn.js
'use strict'; module.exports = { plugins: ['unicorn'], rules: { // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/catch-error-name.md 'unicorn/catch-error-name': ['error', { name: 'err' }], // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/explicit-length-check.md 'unicorn/explicit-length-check': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/filename-case.md 'unicorn/filename-case': 'off', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/no-abusive-eslint-disable.md 'unicorn/no-abusive-eslint-disable': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/no-process-exit.md 'unicorn/no-process-exit': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/throw-new-error.md 'unicorn/throw-new-error': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/number-literal-case.md 'unicorn/number-literal-case': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/escape-case.md 'unicorn/escape-case': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/no-array-instanceof.md 'unicorn/no-array-instanceof': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/no-new-buffer.md 'unicorn/no-new-buffer': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/no-hex-escape.md 'unicorn/no-hex-escape': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/custom-error-definition.md 'unicorn/custom-error-definition': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/prefer-starts-ends-with.md 'unicorn/prefer-starts-ends-with': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/prefer-type-error.md 'unicorn/prefer-type-error': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/no-fn-reference-in-iterator.md 'unicorn/no-fn-reference-in-iterator': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/import-index.md 'unicorn/import-index': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/new-for-builtins.md 'unicorn/new-for-builtins': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/regex-shorthand.md 'unicorn/regex-shorthand': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/prefer-spread.md 'unicorn/prefer-spread': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/error-message.md 'unicorn/error-message': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/no-unsafe-regex.md 'unicorn/no-unsafe-regex': 'error', // https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/prefer-add-event-listener.md 'unicorn/prefer-add-event-listener': 'error', }, };
JavaScript
0.000015
@@ -2316,29 +2316,27 @@ iterator': ' -error +off ',%0A%0A // h
4d34c94edb493d1dc40f33171b97a54473f92c61
update the toggle.js work to add/remove the hidden selector
assets/javascripts/modules/toggle.js
assets/javascripts/modules/toggle.js
require('jquery'); /* Helper to enable elements to toggle other elements on the page specified by data attribute Attach event to parent as delegate, open close dependant on triggers id. Toggle markup example: <fieldset class="form-field-group visible-javascript-on js-aria-show js-toggle" id="uk-number" data-target="uk-phone-number-toggle-target" data-trigger="js-toggle-trigger" data-open="uk-phone-number-toggle-open" data-close="uk-phone-number-toggle-close"> <label class="block-label block-label--inline" for="uk-phone-number-toggle-close">Yes <input type="radio" id="uk-phone-number-toggle-close" class="js-toggle-trigger" value="yes" name="uk-number" required /> </label> <label class="block-label block-label--inline" for="uk-phone-number-toggle-open">No <input type="radio" id="uk-phone-number-toggle-open" class="js-toggle-trigger" value="no" name="uk-number" required aria-controls="uk-phone-number-toggle-target"/> </label> </fieldset> Target markup example: <div id="uk-phone-number-toggle-target" class="toggle-target"> ...... </div> */ var $toggleElems; /** * Controls for triggering toggle * 1 (left mouse click) * 32 (space bar) * @param $elem */ var toggleEvent = function ($elem) { var $triggerElemSelector = $($elem.data('trigger')); var $targetElem = $('#' + $elem.data('target')); var openId = $elem.data('open'); var closeId = $elem.data('close'); var target; $elem.on('click', $triggerElemSelector, function (event) { if (event.which === 1 || 32) { //limit to left mouse click and space bar target = event.target; if (target.id === openId) { $targetElem.show().attr('aria-expanded', 'true').attr('aria-visible', 'true'); } else if (target.id === closeId) { $targetElem.hide().attr('aria-expanded', 'false').attr('aria-visible', 'false'); } } }); }; var addListeners = function () { $toggleElems.each(function (index, elem) { toggleEvent($(elem)); }); }; var setup = function () { $toggleElems = $('.js-toggle'); }; module.exports = function () { setup(); if ($toggleElems.length) { addListeners(); } };
JavaScript
0
@@ -1265,29 +1265,22 @@ class=%22 -toggle-target +hidden %22%3E%0A..... @@ -1868,13 +1868,28 @@ lem. -show( +removeClass('hidden' ).at @@ -2012,13 +2012,25 @@ lem. +addClass(' hid -e( +den' ).at
4819419156ae75e6d6dec4e19efa8058279c34b0
add comment
_tools/createDataFiles.js
_tools/createDataFiles.js
#!/usr/bin/env node /* Writes files for JSON representation of all individuals on tracks with a given individual */ var EventEmitter = require("events").EventEmitter; var argv = require("minimist")(process.argv.slice(2)); var fs = require("graceful-fs"); var logger = new EventEmitter(); if (! argv.q) { logger.on("log", function (msg) { console.log(msg); }); } var sourceDataDir = __dirname + "/../node_modules/music-routes-data/data"; var individuals = require(sourceDataDir + "/individuals.json"); var individualIds = individuals.map(function(elem) { return elem._id; }); var individual_track = require(sourceDataDir + "/individual_track.json"); var tracks = require(sourceDataDir + "/tracks.json"); var getName = function (id) { return individuals.filter(function(elem) { return elem._id === id; })[0].names[0]; }; var generateJson = function (individualId) { logger.emit("log", "Generating JSON data for individual with ID of " + individualId + "..."); var sourceLabel = getName(individualId); var tracksWithIndividual = individual_track.filter(function (elem) { return elem.individual_id === individualId; }).map(function (elem) { return elem.track_id; }); var tracksDetailsForIndividual = tracks.filter(function (elem) { return tracksWithIndividual.indexOf(elem._id) > -1; }); var trackCounts = {}; var connectedIndividuals = individual_track.filter(function (elem) { if (tracksWithIndividual.indexOf(elem.track_id) > -1) { if (elem.individual_id != individualId) { if (trackCounts[elem.individual_id]) { trackCounts[elem.individual_id]++; return false; } trackCounts[elem.individual_id] = 1; return true; } } return false; }).map(function (elem) { return { name: getName(elem.individual_id), targetId: elem.individual_id, trackCount: trackCounts[elem.individual_id] }; }); var file = individualId + ".json"; var formattedOutput = JSON.stringify({ source: sourceLabel, trackCount: tracksWithIndividual.length, tracks: tracksDetailsForIndividual, targets: connectedIndividuals }, null, 2); fs.writeFile(__dirname + "/../data/" + file, formattedOutput, function (err) { if (err) { throw err; } logger.emit("log", "Wrote JSON file for individual with ID of " + individualId); } ); }; individualIds.forEach(function (individualId) { generateJson(individualId); });
JavaScript
0
@@ -1192,32 +1192,63 @@ rack_id;%0A %7D);%0A%0A + //TODO: get release info too%0A var tracksDeta
e618c72f49fa806ba4b79c2236ca25365069088f
use eventName when available for a gesture
addon/event_dispatcher.js
addon/event_dispatcher.js
import Ember from 'ember'; import defaultHammerEvents from './hammer-events'; import dasherizedToCamel from 'ember-allpurpose/string/dasherized-to-camel'; import jQuery from 'jquery'; import mobileDetection from './utils/is-mobile'; let ROOT_ELEMENT_CLASS = 'ember-application'; let ROOT_ELEMENT_SELECTOR = '.' + ROOT_ELEMENT_CLASS; const eventEndings = { pan: ['Start','Move', 'End', 'Cancel', 'Left', 'Right', 'Up', 'Down'], pinch: ['Start','Move', 'End', 'Cancel', 'In', 'Out'], press: ['Up'], rotate: ['Start','Move', 'End', 'Cancel'], swipe: ['Left', 'Right', 'Up', 'Down'], tap: [] }; const { assert, EventDispatcher, merge, isNone, set, get } = Ember; const assign = Ember.assign || merge; export default EventDispatcher.extend({ /** Whether or not to cache handler paths on the element when `useCapture` is also true. This needs to be replaced by a feature flag. @private @type {boolean} */ useFastPaths: false, useCapture: false, canDispatchToEventManager: false, _gestures: null, _initializeGestures() { const list = getModuleList(); const events = assign({}, defaultHammerEvents); list.forEach((name) => { const recognizer = this.container.lookupFactory('ember-gesture:recognizers/' + name); if (recognizer && !recognizer.ignoreEvents) { addEvent(events, recognizer.recognizer, name); } }); // add them to the event dispatcher this.set('_gestures', events); }, _fastFocus() { let $root = jQuery(this.get('rootElement')); $root.on('click.ember-gestures, touchend.ember-gestures', function (e) { /* Implements fastfocus mechanisms on mobile web/Cordova */ if (mobileDetection.is()) { var $element = jQuery(e.currentTarget); var $target = jQuery(e.target); /* If the click was on an input element that needs to be able to focus, recast the click as a "focus" event. This fixes tap events on mobile where keyboardShrinksView or similar is true. Such devices depend on the ghost click to trigger focus, but the ghost click will never reach the element. */ var notFocusableTypes = ['submit', 'file', 'button', 'hidden', 'reset', 'range', 'radio', 'image', 'checkbox']; //fastfocus if ($element.is('textarea') || ($element.is('input') && notFocusableTypes.indexOf($element.attr('type')) === -1)) { $element.focus(); } else if ($target.is('textarea') || ($target.is('input') && notFocusableTypes.indexOf($target.attr('type')) === -1)) { $target.focus(); } } }); }, willDestroy() { jQuery(this.get('rootElement')).off('.ember-gestures'); this._super(...arguments); }, _finalEvents: null, setup(addedEvents, rootElement) { this._initializeGestures(); const events = this._finalEvents = assign({}, get(this, 'events')); let event; // remove undesirable events from Ember's Eventing if (this.get('removeTracking')) { events.touchstart = null; events.touchmove = null; events.touchcancel = null; events.touchend = null; events.mousedown = null; events.mouseenter = null; events.mousemove = null; events.mouseleave = null; events.mouseup = null; events.drag = null; events.dragend = null; events.dragenter = null; events.dragleave = null; events.dragover = null; events.dragstart = null; events.drop = null; events.dblclick = null; } // assign custom events into Ember's Eventing assign(events, addedEvents || {}); // delete unwanted events for (event in events) { if (events.hasOwnProperty(event)) { if (!events[event]) { delete events[event]; } } } // assign our events into Ember's Eventing assign(events, this.get('_gestures')); if (!isNone(rootElement)) { set(this, 'rootElement', rootElement); } this._fastFocus(); rootElement = jQuery(get(this, 'rootElement')); assert(`You cannot use the same root element (${rootElement.selector || rootElement[0].tagName}) multiple times in an Ember.Application`, !rootElement.is(ROOT_ELEMENT_SELECTOR)); assert('You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application', !rootElement.closest(ROOT_ELEMENT_SELECTOR).length); assert('You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application', !rootElement.find(ROOT_ELEMENT_SELECTOR).length); rootElement.addClass(ROOT_ELEMENT_CLASS); assert(`Unable to add '${ROOT_ELEMENT_CLASS}' class to rootElement. Make sure you set rootElement to the body or an element in the body.`, rootElement.is(ROOT_ELEMENT_SELECTOR)); for (event in events) { if (events.hasOwnProperty(event)) { this.setupHandler(rootElement, event, events[event]); } } } }); function addEvent(hash, gesture, name) { const eventName = dasherizedToCamel(name); const eventBase = eventName.toLowerCase(); const endings = eventEndings[gesture]; hash[eventBase] = eventName; endings.forEach((ending) => { const event = eventName + ending; hash[event.toLowerCase()] = event; }); } // this function can be replaced in ember 1.13 with a private api // and in ember 2.0 with a potentially public api matching 1.13's // private api. This is a stop gap for pre-ember 1.13 function getModuleList() { /* global requirejs */ const list = []; for(var moduleName in requirejs.entries) { if (requirejs.entries.hasOwnProperty(moduleName)) { const parts = moduleName.match(/ember-gestures\/recognizers\/(.*)/); if (parts && parts[1].indexOf('jshint') === -1) { list.push(parts[1]); } } } return list; }
JavaScript
0.000001
@@ -1304,36 +1304,8 @@ izer - && !recognizer.ignoreEvents ) %7B%0A @@ -1351,16 +1351,40 @@ ognizer, + recognizer.eventName %7C%7C name);%0A
1bb6dc4432e6407244ae9a8171a4bbe917adfbe9
Fix list-form route create & apply filters predicate
addon/routes/list-form.js
addon/routes/list-form.js
/** @module ember-flexberry */ import Ember from 'ember'; import LimitedRouteMixin from '../mixins/limited-route'; import SortableRouteMixin from '../mixins/sortable-route'; import PaginatedRouteMixin from '../mixins/paginated-route'; import ProjectedModelFormRoute from '../routes/projected-model-form'; import FlexberryObjectlistviewRouteMixin from '../mixins/flexberry-objectlistview-route'; import FlexberryObjectlistviewHierarchicalRouteMixin from '../mixins/flexberry-objectlistview-hierarchical-route'; import ReloadListMixin from '../mixins/reload-list-mixin'; /** Base route for the List Forms. This class re-exports to the application as `/routes/list-form`. So, you can inherit from `./list-form`, even if file `app/routes/list-form.js` is not presented in the application. Example: ```javascript // app/routes/employees.js import ListFormRoute from './list-form'; export default ListFormRoute.extend({ }); ``` If you want to add some common logic on all List Forms, you can override `app/routes/list-form.js` as follows: ```javascript // app/routes/list-form.js import ListFormRoute from 'ember-flexberry/routes/list-form'; export default ListFormRoute.extend({ }); ``` @class ListFormRoute @extends ProjectedModelFormRoute @uses PaginatedRouteMixin @uses SortableRouteMixin @uses LimitedRouteMixin @uses ReloadListMixin @uses FlexberryObjectlistviewRouteMixin */ export default ProjectedModelFormRoute.extend( PaginatedRouteMixin, SortableRouteMixin, LimitedRouteMixin, ReloadListMixin, FlexberryObjectlistviewRouteMixin, FlexberryObjectlistviewHierarchicalRouteMixin, { /** Current sorting. @property sorting @type Array @default [] */ sorting: [], /** A hook you can implement to convert the URL into the model for this route. [More info](http://emberjs.com/api/classes/Ember.Route.html#method_model). @method model @param {Object} params @param {Object} transition */ model: function(params, transition) { let modelName = this.get('modelName'); let webPage = transition.targetName; let projectionName = this.get('modelProjection'); let limitPredicate = this.objectListViewLimitPredicate({ modelName: modelName, projectionName: projectionName, params: params }); let userSettingsService = this.get('userSettingsService'); userSettingsService.setCurrentWebPage(webPage); let developerUserSettings = this.get('developerUserSettings'); Ember.assert('Property developerUserSettings is not defined in /app/routes/' + transition.targetName + '.js', developerUserSettings); let nComponents = 0; let componentName; for (componentName in developerUserSettings) { let componentDesc = developerUserSettings[componentName]; switch (typeof componentDesc) { case 'string': developerUserSettings[componentName] = JSON.parse(componentDesc); break; case 'object': break; default: Ember.assert('Component description ' + 'developerUserSettings.' + componentName + 'in /app/routes/' + transition.targetName + '.js must have types object or string', false); } nComponents += 1; } if (nComponents === 0) { Ember.assert('Developer MUST DEFINE component settings in /app/routes/' + transition.targetName + '.js', false); } Ember.assert('Developer MUST DEFINE SINGLE components settings in /app/routes/' + transition.targetName + '.js' + nComponents + ' defined.', nComponents === 1); let userSettingPromise = userSettingsService.setDeveloperUserSettings(developerUserSettings); let listComponentNames = userSettingsService.getListComponentNames(); componentName = listComponentNames[0]; let ret = userSettingPromise .then(currectPageUserSettings => { if (params) { userSettingsService.setCurrentParams(componentName, params); } let hierarchicalAttribute; let controller = this.controllerFor(this.routeName); if (controller.get('inHierarchicalMode')) { hierarchicalAttribute = controller.get('hierarchicalAttribute'); } this.sorting = userSettingsService.getCurrentSorting(componentName); let queryParameters = { modelName: modelName, projectionName: projectionName, perPage: params.perPage, page: params.page, sorting: this.sorting, filter: params.filter, predicate: limitPredicate, hierarchicalAttribute: hierarchicalAttribute, }; // Find by query is always fetching. // TODO: support getting from cache with "store.all->filterByProjection". // TODO: move includeSorting to setupController mixins? return this.reloadList(queryParameters); }).then((records) => { this.includeSorting(records, this.sorting); return records; }); return ret; }, /** A hook you can use to setup the controller for the current route. [More info](http://emberjs.com/api/classes/Ember.Route.html#method_setupController). @method setupController @param {<a href="http://emberjs.com/api/classes/Ember.Controller.html">Ember.Controller</a>} controller @param {Object} model */ setupController: function(controller, model) { this._super(...arguments); // Define 'modelProjection' for controller instance. // TODO: remove that when list-form controller will be moved to this route. let modelClass = this.store.modelFor(this.get('modelName')); let proj = modelClass.projections.get(this.get('modelProjection')); controller.set('userSettings', this.userSettings); controller.set('modelProjection', proj); }, });
JavaScript
0.000003
@@ -2168,24 +2168,77 @@ ojection');%0A + let filtersPredicate = this._filtersPredicate();%0A let limi @@ -4562,16 +4562,53 @@ filter,%0A + filters: filtersPredicate,%0A
09f8da67284f940d5c4cfa8fde27a99a9751aea6
Fix fertilizer
src/fertilizer.js
src/fertilizer.js
'use strict'; var MineralFertilizer = function (name, carbamid, no3, nh4) { var _name = name.toLowerCase() , _vo_Carbamid = carbamid || 0 // [kg (N) kg-1 (N)] , _vo_NO3 = no3 || 0 // [kg (N) kg-1 (N)] , _vo_NH4 = nh4 || 0 // [kg (N) kg-1 (N)] ; if (_name === 'ammonium nitrate') { _vo_NO3 = 0.5; _vo_NH4 = 0.5; _vo_Carbamid = 0; } else if (_name === 'ammonium phosphate') { _vo_NO3 = 0; _vo_NH4 = 1; _vo_Carbamid = 0; } else if (_name === 'ammonium sulphate') { _vo_NO3 = 0; _vo_NH4 = 1; _vo_Carbamid = 0; } else if (_name === 'potassium nitrate') { _vo_NO3 = 1; _vo_NH4 = 0; _vo_Carbamid = 0; } else if (_name === 'compound fertiliser (0 no3, 100 nh4)') { _vo_NO3 = 0; _vo_NH4 = 1; _vo_Carbamid = 0; } else if (_name === 'compound fertiliser (35 no3, 65 nh4)') { _vo_NO3 = 0.35; _vo_NH4 = 0.65; _vo_Carbamid = 0; } else if (_name === 'compound fertiliser (43 no3, 57 nh4)') { _vo_NO3 = 0.435; _vo_NH4 = 0.565; _vo_Carbamid = 0; } else if (_name === 'compound fertiliser (50 no3, 50 nh4)') { _vo_NO3 = 0.5; _vo_NH4 = 0.5; _vo_Carbamid = 0; } else if (_name === 'urea') { _vo_NO3 = 0; _vo_NH4 = 0; _vo_Carbamid = 1; } else if (_name === 'urea ammonium nitrate') { _vo_NO3 = 0.25; _vo_NH4 = 0.25; _vo_Carbamid = 0.5; } else if (_name === 'urea ammonium sulphate') { _vo_NO3 = 0; _vo_NH4 = 0.18; _vo_Carbamid = 0.82; } return { getName: function () { return _name; }, getCarbamid: function () { return _vo_Carbamid; }, getNH4: function () { return _vo_NH4; }, getNO3: function () { return _vo_NO3; } }; }; var OrganicFertilizer = function (omp) { this.name = ""; this.vo_AOM_DryMatterContent = omp.vo_AOM_DryMatterContent | 0.0; this.vo_AOM_NH4Content = omp.vo_AOM_NH4Content | 0.0; this.vo_AOM_NO3Content = omp.vo_AOM_NO3Content | 0.0; this.vo_AOM_CarbamidContent = omp.vo_AOM_CarbamidContent | 0.0; this.vo_AOM_SlowDecCoeffStandard = omp.vo_AOM_SlowDecCoeffStandard | 0.0; this.vo_AOM_FastDecCoeffStandard = omp.vo_AOM_FastDecCoeffStandard | 0.0; this.vo_PartAOM_to_AOM_Slow = omp.vo_PartAOM_to_AOM_Slow | 0.0; this.vo_PartAOM_to_AOM_Fast = omp.vo_PartAOM_to_AOM_Fast | 0.0; this.vo_CN_Ratio_AOM_Slow = omp.vo_CN_Ratio_AOM_Slow | 0.0; this.vo_CN_Ratio_AOM_Fast = omp.vo_CN_Ratio_AOM_Fast | 0.0; this.vo_PartAOM_Slow_to_SMB_Slow = omp.vo_PartAOM_Slow_to_SMB_Slow | 0.0; this.vo_PartAOM_Slow_to_SMB_Fast = omp.vo_PartAOM_Slow_to_SMB_Fast | 0.0; this.vo_NConcentration = 0.0; };
JavaScript
0.000256
@@ -1805,19 +1805,20 @@ nction ( -omp +name ) %7B%0A%0A t @@ -1832,10 +1832,26 @@ e = -%22%22 +name.toLowerCase() ;%0A @@ -1884,38 +1884,8 @@ nt = - omp.vo_AOM_DryMatterContent %7C 0.0 @@ -1916,32 +1916,8 @@ nt = - omp.vo_AOM_NH4Content %7C 0.0 @@ -1948,32 +1948,8 @@ nt = - omp.vo_AOM_NO3Content %7C 0.0 @@ -1985,37 +1985,8 @@ nt = - omp.vo_AOM_CarbamidContent %7C 0.0 @@ -2027,42 +2027,8 @@ rd = - omp.vo_AOM_SlowDecCoeffStandard %7C 0.0 @@ -2069,42 +2069,8 @@ rd = - omp.vo_AOM_FastDecCoeffStandard %7C 0.0 @@ -2106,37 +2106,8 @@ ow = - omp.vo_PartAOM_to_AOM_Slow %7C 0.0 @@ -2143,37 +2143,8 @@ st = - omp.vo_PartAOM_to_AOM_Fast %7C 0.0 @@ -2178,35 +2178,8 @@ ow = - omp.vo_CN_Ratio_AOM_Slow %7C 0.0 @@ -2213,35 +2213,8 @@ st = - omp.vo_CN_Ratio_AOM_Fast %7C 0.0 @@ -2255,42 +2255,8 @@ ow = - omp.vo_PartAOM_Slow_to_SMB_Slow %7C 0.0 @@ -2297,42 +2297,8 @@ st = - omp.vo_PartAOM_Slow_to_SMB_Fast %7C 0.0 @@ -2332,11 +2332,15 @@ = 0.0;%0A%0A + %0A%0A %7D;%0A
e073a5bd9e06da67608332a74ea56f7b95078bf9
add comments
src/file-store.js
src/file-store.js
var fs = require( 'fs' ); var path = require( 'path' ); var mkdirp = require( 'mkdirp' ); var Promise = require( 'promise' ); module.exports = function ( filepath ) { filepath = path.resolve( filepath ); var fileObj = { read: function () { var data; var json; try { data = fs.readFileSync( filepath ); json = JSON.parse( data ); } catch ( err ) { console.error( 'Error while trying to read file:', filepath, '\n' + 'Ensure file has correctly formatted JSON and try again.' ); throw err; } return json; }, write: function( data ) { var json = JSON.stringify( data ); return new Promise(function (resolve, reject) { mkdirp( path.dirname(filepath), function ( err ) { if ( err ) { console.error( err ); return reject( err ); } fs.writeFile( filepath, json, function (err) { if ( err ) reject( err ); else { fileObj.exists = true; resolve(); } }); }); }); }, exists: fs.existsSync( filepath ) }; return fileObj; };
JavaScript
0
@@ -219,16 +219,171 @@ Obj = %7B%0A + /**%0A * Synchronously tries to read and parse JSON from the enclosed filepath.%0A * @returns %7BObject%7D - The JSON parsed from the file.%0A */%0A read @@ -770,24 +770,310 @@ on;%0A %7D,%0A%0A + /**%0A * Writes the given data to the enclosed filepath.%0A * @param %7BObject%7D - An object that is easily convertible to JSON.%0A * @returns %7BPromise%7D - A promise that is resolved upon completion of %0A * the write to disk, it is rejected if any errors occur.%0A */%0A write: f
c6be20438fa0856c21dedab975528d68a1bcb8fb
remove use strict
generators/app/templates/webpack.config.js
generators/app/templates/webpack.config.js
'use strict'; var path = require('path'); var webpack = require('webpack'); module.exports = { entry: { index: './js/index.js' }, output: { path: path.resolve(__dirname, 'build', 'js'), filename: '[hash].[name].bundle.js', chunkFilename: '[hash].[id].bundle.js', publicPath: 'js/' }, module: { loaders: [ { test: /\.css$/, loader: 'style!css!autoprefixer?browsers=last 5 version!' }, { test: /\.less$/, loader: 'style!css!autoprefixer?browsers=last 5 version!less!' }, { test: /\.js$/, loader: 'babel', exclude: /(node_modules|bower_components)/ }, { test: /\.(eot|svg|ttf|woff|woff2)\w*/, loader: 'file' }, { test: /\.html$/, loader: 'raw' } ] }, resolve: { root: [ path.resolve(__dirname), path.resolve(__dirname, 'js/'), path.resolve(__dirname, 'js/fw/'), path.resolve(__dirname, 'etc/') ] }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.optimize.CommonsChunkPlugin('[hash].common.bundle.js') ] };
JavaScript
0.000007
@@ -1,19 +1,4 @@ -'use strict';%0A%0A var
9223205d329b182905c733a78addf91aed1383b9
Remove "smart" hex numbering. Improve world gen speed by removing console.log() calls.
src/game/world.js
src/game/world.js
var LandType = { GRASS: 'grass', SAND: 'sand', WATER: 'water' }; var World = { hexes: [], hexCount: 0, hexSize: { HEIGHT: 50, WIDTH: 65, SIDE: 35 }, idGenLetters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'], widthPx: 0, heightPx: 0, generate: function (width, height) { this.hexes = []; this.hexCount = 0; var widthPx = width * this.hexSize.WIDTH; var heightPx = height * this.hexSize.HEIGHT; this.widthPx = widthPx; this.heightPx = heightPx; var row = 0; var y = 0.0; while (y + this.hexSize.HEIGHT <= heightPx) { var col = 0; var offset = 0.0; if (row % 2 == 1) { offset = ((this.hexSize.WIDTH - this.hexSize.SIDE) / 2) + this.hexSize.SIDE; col = 1; } var x = offset; while (x + this.hexSize.WIDTH <= widthPx) { var hex = new Hex(this.generateHexId(row, col), x, y); console.log('Created Hex ' + hex.id + ' at ' + hex.x + ',' + hex.y, hex); this.hexes.push(hex); this.hexCount++; col += 2; x += this.hexSize.WIDTH + this.hexSize.SIDE; } row++; y += this.hexSize.HEIGHT / 2; } Camera.centerToMap(); }, generateHexId: function (row, col) { var result = ''; var idx = row; while (idx > 25) { result = this.idGenLetters[idx] + result; idx -= 26; } return this.idGenLetters[idx] + result + (col + 1); }, update: function () { Camera.update(); }, draw: function (ctx) { this.drawHexes(ctx); this.drawFog(ctx); }, drawHexes: function (ctx) { ctx.save(); ctx.translate(Camera.translateX(0), Camera.translateY(0)); for (var i = 0; i < this.hexCount; i++) { var hex = this.hexes[i]; hex.draw(ctx); } ctx.restore(); }, drawFog: function (ctx) { var grd = ctx.createRadialGradient(Canvas.canvas.width / 2, Canvas.canvas.height / 2, Canvas.canvas.height / 4, Canvas.canvas.width / 2, Canvas.canvas.height / 2, Canvas.canvas.height / 2); grd.addColorStop(0, "rgba(0, 0, 0, 0)"); grd.addColorStop(1, "rgba(150, 150, 200, 0.25)"); ctx.fillStyle = grd; ctx.fillRect(0, 0, Canvas.canvas.width, Canvas.canvas.height); } };
JavaScript
0
@@ -201,159 +201,8 @@ %7D,%0A%0A - idGenLetters: %5B'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'%5D,%0A%0A @@ -213,16 +213,16 @@ hPx: 0,%0A + heig @@ -942,127 +942,24 @@ his. -generateHexId(row, col), x, y);%0A console.log('Created Hex ' + hex.id + ' at ' + hex.x + ',' + hex.y, hex +hexCount++, x, y );%0A @@ -1000,42 +1000,8 @@ );%0A%0A - this.hexCount++;%0A%0A @@ -1162,32 +1162,32 @@ / 2;%0A %7D%0A%0A + Camera.c @@ -1212,281 +1212,8 @@ %7D,%0A%0A - generateHexId: function (row, col) %7B%0A var result = '';%0A var idx = row;%0A%0A while (idx %3E 25) %7B%0A result = this.idGenLetters%5Bidx%5D + result;%0A idx -= 26;%0A %7D%0A%0A return this.idGenLetters%5Bidx%5D + result + (col + 1);%0A %7D,%0A%0A
06e5c46c8df784ab8f6e7713ada68bbb011dbb68
Fix typo in option validation.
packages/babel-preset-typescript/src/index.js
packages/babel-preset-typescript/src/index.js
import { declare } from "@babel/helper-plugin-utils"; import transformTypeScript from "@babel/plugin-transform-typescript"; export default declare( (api, { jsxPragma, allExtensions = false, isTSX = false }) => { api.assertVersion(7); if (typeof allExtensions !== "boolean") { throw new Error(".allExtensions must be a boolean, or undefined"); } if (typeof isTSX !== "boolean") { throw new Error(".allExtensions must be a boolean, or undefined"); } if (isTSX && !allExtensions) { throw new Error("isTSX:true requires allExtensions:true"); } return { overrides: allExtensions ? [ { plugins: [[transformTypeScript, { jsxPragma, isTSX }]], }, ] : [ { // Only set 'test' if explicitly requested, since it requires that // Babel is being called` test: /\.ts$/, plugins: [[transformTypeScript, { jsxPragma }]], }, { // Only set 'test' if explicitly requested, since it requires that // Babel is being called` test: /\.tsx$/, plugins: [[transformTypeScript, { jsxPragma, isTSX: true }]], }, ], }; }, );
JavaScript
0.000001
@@ -418,37 +418,29 @@ new Error(%22. -allExtensions +isTSX must be a b
47eb0b5c6b55805b9cf3ef2932b9d315aa0c3129
Fix deprecation warning
kolibri/core/assets/test/progress-bar.spec.js
kolibri/core/assets/test/progress-bar.spec.js
/* eslint-env mocha */ import Vue from 'vue-test'; // eslint-disable-line import assert from 'assert'; import { shallow } from '@vue/test-utils'; import ProgressBar from '../src/views/progress-bar'; function testProgressBar(wrapper, expected) { const { text, width } = expected; assert.equal(wrapper.find('.progress-bar-text').text(), text); assert(wrapper.find('.progress-bar-complete').hasStyle('width', width)); } describe('ProgressBar Component', () => { it('should give 0 percent for progress of < 0', () => { const wrapper = shallow(ProgressBar, { propsData: { progress: -0.0000001, }, }); // The negative still shows up... testProgressBar(wrapper, { text: '-0%', width: '0%' }); }); it('should give 10 percent for progress of 0.1', () => { const wrapper = shallow(ProgressBar, { propsData: { progress: 0.1, }, }); testProgressBar(wrapper, { text: '10%', width: '10%' }); }); it('should give 100 percent for progress of 1.0', () => { const wrapper = shallow(ProgressBar, { propsData: { progress: 1.0, }, }); testProgressBar(wrapper, { text: '100%', width: '100%' }); }); it('should give 100 percent for progress of > 1.0', () => { const wrapper = shallow(ProgressBar, { propsData: { progress: 1.0000001, }, }); testProgressBar(wrapper, { text: '100%', width: '100%' }); }); });
JavaScript
0.000099
@@ -96,16 +96,47 @@ ssert';%0A +import %7B expect %7D from 'chai';%0A import %7B @@ -373,21 +373,21 @@ ext);%0A -asser +expec t(wrappe @@ -423,33 +423,44 @@ e'). -hasS +element.s tyle -(' +. width -', +).to.equal( width) -) ;%0A%7D%0A
e4cb9d860b561b6973400eaca210ea60ef38aa74
add sample service to about core services
src/client/modules/applets/about/modules/reactComponents/AboutCoreServices.js
src/client/modules/applets/about/modules/reactComponents/AboutCoreServices.js
define([ 'preact', 'htm', './AboutService/AboutServiceMain', 'bootstrap' ], ( preact, htm, AboutService ) => { const {h, Component} = preact; const html = htm.bind(h); const SERVICES = [ { title: 'Auth', type: 'rest', module: 'auth2', path: '/', versionKey: 'version' }, { title: 'Catalog', module: 'Catalog', type: 'jsonrpc11', versionMethod: 'version' }, { title: 'Execution Engine 2', type: 'jsonrpc11', module: 'execution_engine2', versionMethod: 'ver' }, { title: 'Feeds', type: 'rest', module: 'feeds', path: '/', versionKey: 'version' }, { title: 'Groups', type: 'rest', module: 'groups', path: '/', versionKey: 'version' }, { title: 'Search2', module: 'SearchAPI2', type: 'jsonrpc20', statusMethod: 'rpc.discover', versionKey: 'service_info.version' // statusKeys: [ // { // key: 'version', // label: 'Version' // }, // { // key: 'average', // label: '' // } // ] }, { title: 'Service Wizard', module: 'ServiceWizard', type: 'jsonrpc11', versionMethod: 'version' }, { title: 'User Profile', module: 'UserProfile', type: 'jsonrpc11', versionMethod: 'ver' }, { title: 'Workspace', module: 'Workspace', type: 'jsonrpc11', versionMethod: 'ver' }, ]; class AboutCoreServices extends Component { render() { const rows = SERVICES.map((service) => { return html` <tr> <td> ${service.title} </td> <${AboutService} service=${service} runtime=${this.props.runtime}/> </tr> `; }); return html` <table class="table table-striped"> <thead> <tr> <th style=${{width: '12em'}}> Service </th> <th> Version </th> <th> Perf (ms/call) </th> <th> Perf calls (ms/call) </th> </tr> </thead> <tbody> ${rows} </tbody> </table> `; } } return AboutCoreServices; });
JavaScript
0
@@ -145,16 +145,17 @@ const %7B + h, Compo @@ -158,16 +158,17 @@ omponent + %7D = prea @@ -1028,32 +1028,221 @@ %7D,%0A %7B%0A + title: 'Samples',%0A module: 'SampleService',%0A type: 'jsonrpc11',%0A statusMethod: 'status',%0A versionKey: 'version'%0A %7D,%0A %7B%0A titl @@ -2777,16 +2777,17 @@ tyle=$%7B%7B + width: ' @@ -2791,16 +2791,17 @@ : '12em' + %7D%7D%3E%0A
6d6aedb6b6848e5727d51808f13c76740d9d3161
Use single quotes
configurations/default.js
configurations/default.js
module.exports = { "rules": { "accessor-pairs": 2, "array-bracket-spacing": [2, "never"], "block-scoped-var": 2, "block-spacing": [2, "always"], "brace-style": [2, "1tbs"], "camelcase": 2, "comma-dangle": [2, "never"], "comma-spacing": 2, "comma-style": [2, "last"], "computed-property-spacing": [2, "never"], "consistent-return": 2, "consistent-this": [2, "that"], "curly": 2, "dot-location": [2, "object"], "dot-notation": 2, "eol-last": 2, "eqeqeq": 2, "func-style": [2, "declaration"], "guard-for-in": 2, "indent": [2, 2], "jsx-quotes": [2, "prefer-double"], "key-spacing": [2, {"beforeColon": false, "afterColon": true}], "linebreak-style": [2, "unix"], "lines-around-comment": [2, {"beforeBlockComment": true, "beforeLineComment": true}], "new-cap": [2, {"newIsCap": true, "capIsNew": true}], "new-parens": 2, "no-array-constructor": 2, "no-bitwise": 2, "no-caller": 2, "no-case-declarations": 2, "no-cond-assign": [2, "except-parens"], "no-constant-condition": 2, "no-control-regex": 2, "no-delete-var": 2, "no-dupe-args": 2, "no-dupe-keys": 2, "no-duplicate-case": 2, "no-empty": 2, "no-empty-character-class": 2, "no-empty-pattern": 2, "no-eq-null": 2, "no-eval": 2, "no-ex-assign": 2, "no-extend-native": 2, "no-extra-bind": 2, "no-extra-boolean-cast": 2, "no-extra-parens": 2, "no-extra-semi": 2, "no-floating-decimal": 2, "no-func-assign": 2, "no-implied-eval": 2, "no-inner-declarations": 2, "no-invalid-regexp": 2, "no-invalid-this": 2, "no-irregular-whitespace": 2, "no-labels": 2, "no-lone-blocks": 2, "no-lonely-if": 2, "no-loop-func": 2, "no-mixed-spaces-and-tabs": 2, "no-multi-spaces": 2, "no-multiple-empty-lines": [2, {"max": 1}], "no-native-reassign": 2, "no-negated-in-lhs": 2, "no-nested-ternary": 2, "no-new": 2, "no-new-func": 2, "no-new-object": 2, "no-new-wrappers": 2, "no-obj-calls": 2, "no-octal": 2, "no-octal-escape": 2, "no-param-reassign": 2, "no-proto": 2, "no-redeclare": 2, "no-regex-spaces": 2, "no-return-assign": 2, "no-self-compare": 2, "no-sequences": 2, "no-shadow": 2, "no-shadow-restricted-names": 2, "no-spaced-func": 2, "no-sparse-arrays": 2, "no-throw-literal": 2, "no-trailing-spaces": 2, "no-undef": 2, "no-undef-init": 2, "no-undefined": 2, "no-unexpected-multiline": 2, "no-unneeded-ternary": 2, "no-unreachable": 2, "no-unused-expressions": 2, "no-unused-vars": 2, "no-use-before-define": 2, "no-useless-concat": 2, "no-void": 2, "no-warning-comments": 1, "no-with": 2, "object-curly-spacing": [2, "never"], "operator-linebreak": [2, "after"], "quote-props": [2, "as-needed"], "quotes": [2, "double"], "radix": 2, "semi": [2, "always"], "semi-spacing": [2, {"before": false, "after": true}], "space-after-keywords": [2, "always"], "space-before-blocks": [2, "always"], "space-before-function-paren": [2, "never"], "space-before-keywords": [2, "always"], "space-in-parens": [2, "never"], "space-infix-ops": 2, "space-return-throw-case": 2, "space-unary-ops": [2, {"words": true, "nonwords": false}], "spaced-comment": [2, "always"], "use-isnan": 2, "valid-jsdoc": 2, "valid-typeof": 2, "wrap-iife": [2, "outside"] } };
JavaScript
0
@@ -2950,20 +2950,20 @@ %22: %5B2, %22 -doub +sing le%22%5D,%0A
d36623cf36fa742251ef1664527adeb05b46fbf6
Update Alert to respect v4 design
packages/components/components/alert/Alert.js
packages/components/components/alert/Alert.js
import React from 'react'; import PropTypes from 'prop-types'; import { LearnMore } from 'react-components'; const CLASSES = { info: 'mb1 block-info', standard: 'mb1 block-info-standard', warning: 'mb1 block-info-error', error: 'mb1 block-info-warning' }; const Alert = ({ type, children, learnMore, className }) => { return ( <div className={CLASSES[type].concat(` ${className || ''}`)}> <div>{children}</div> {learnMore ? ( <div> <LearnMore url={learnMore} /> </div> ) : null} </div> ); }; Alert.propTypes = { type: PropTypes.oneOf(['info', 'error', 'warning', 'standard']).isRequired, children: PropTypes.node.isRequired, className: PropTypes.string, learnMore: PropTypes.string }; Alert.defaultProps = { type: 'info' }; export default Alert;
JavaScript
0
@@ -134,40 +134,8 @@ nfo: - 'mb1 block-info',%0A standard: 'mb @@ -187,21 +187,32 @@ ck-info- -error +standard-warning ',%0A e @@ -233,23 +233,30 @@ ck-info- -warning +standard-error '%0A%7D;%0A%0Aco
d5b12798fb613ae89a73764becd46932d8a400c7
Add token refresh method.
org.opent2t.sample.hub.superpopular/com.nest.hub/js/thingTranslator.js
org.opent2t.sample.hub.superpopular/com.nest.hub/js/thingTranslator.js
// This code uses ES2015 syntax that requires at least Node.js v4. // For Node.js ES2015 support details, reference http://node.green/ "use strict"; var OpenT2T = require('opent2t').OpenT2T; var Firebase = require("firebase"); /** * This translator class implements the "Hub" interface. */ class Translator { constructor(accessToken) { this._accessToken = accessToken; this._baseUrl = "https://developer-api.nest.com"; this._devicesPath = 'devices/'; this._structPath = 'structures/'; this._name = "Nest Hub"; this._firebaseRef = new Firebase(this._baseUrl); this._firebaseRef.authWithCustomToken(this._accessToken.accessToken); } /** * Get the hub definition and devices */ get(expand, payload) { return this.getPlatforms(expand, payload); } /** * Get the list of devices discovered through the hub. */ getPlatforms(expand, payload) { if(payload !== undefined){ return this._providerSchemaToPlatformSchema( payload, expand ); } else { return this._firebaseRef.child(this._devicesPath).once('value').then((snapshot) => { return this._providerSchemaToPlatformSchema(snapshot.val(), expand); }); } } /* eslint no-unused-vars: "off" */ /** * Subscribe to notifications for a platform. * This function is intended to be called by the platform translator for initial subscription, * and on the hub translator (this) for verification. */ _subscribe(subscriptionInfo) { // Error case: waiting for design decision throw new Error("Not implemented"); } /** * Unsubscribe from a platform subscription. * This function is intended to be called by a platform translator */ _unsubscribe(subscriptionInfo) { // Error case: waiting for design decision throw new Error("Not implemented"); } /* eslint no-unused-vars: "warn" */ /** * Translates an array of provider schemas into an opent2t/OCF representations */ _providerSchemaToPlatformSchema(providerSchemas, expand) { var platformPromises = []; if(providerSchemas.thermostats !== undefined){ // get the opent2t schema and translator for Nest thermostat var opent2tInfo = { "schema": 'org.opent2t.sample.thermostat.superpopular', "translator": "opent2t-translator-com-nest-thermostat" }; var nestThermostatIds = Object.keys(providerSchemas.thermostats); nestThermostatIds.forEach((nestThermostatId) => { // set the opent2t info for the Nest Device var deviceInfo = {}; deviceInfo.opent2t = {}; deviceInfo.opent2t.controlId = nestThermostatId; // Create a translator for this device and get the platform information, possibly expanded platformPromises.push(OpenT2T.createTranslatorAsync(opent2tInfo.translator, { 'deviceInfo': deviceInfo, 'hub': this }) .then((translator) => { // Use get to translate the Nest formatted device that we already got in the previous request. // We already have this data, so no need to make an unnecesary request over the wire. var deviceSchema = providerSchemas.thermostats[nestThermostatId]; return this._getAwayStatus(deviceSchema['structure_id']).then((result) => { deviceSchema.away = result; return OpenT2T.invokeMethodAsync(translator, opent2tInfo.schema, 'get', [expand, deviceSchema ]) .then((platformResponse) => { return platformResponse; }); }); })); }); } return Promise.all(platformPromises) .then((platforms) => { var toReturn = {}; toReturn.schema = "opent2t.p.hub"; toReturn.platforms = platforms; return toReturn; }); } /** * Get the name of the hub. Ties to the n property from oic.core */ getN() { return this._name; } /** * Gets device details (all fields), response formatted per nest api */ getDeviceDetailsAsync(deviceType, deviceId) { return this._firebaseRef.child(this._devicesPath + deviceType + '/' +deviceId).once('value').then((snapshot) => { var deviceSchema = snapshot.val(); return this._getAwayStatus(deviceSchema['structure_id']).then((result) => { deviceSchema.away = result; return deviceSchema; }); }); } /** * Puts device details (all fields) payload formatted per nest api */ putDeviceDetailsAsync(deviceType, deviceId, putPayload) { var propertyName = Object.keys(putPayload); var path = this._devicesPath + deviceType + '/' + deviceId + '/' + propertyName[0]; return this._firebaseRef.child(path).set(putPayload[propertyName[0]]).then((response) => { if (response === undefined) { //success var result = { device_id:deviceId }; result[propertyName] = putPayload[propertyName[0]]; //get temperature scale if (propertyName[0].includes('_temperature_')) { result['temperature_scale'] = propertyName[0].charAt(propertyName[0].length -1); } return result; } }).catch(function (err) { var str = err.toString(); var startInd = str.indexOf('{'); var endInd = str.lastIndexOf('}'); var errorMsg = JSON.parse(str.substring(startInd, endInd + 1)); throw new Error(errorMsg.error); }); } /** * Internal Helper function to get the away status for structure with structureId */ _getAwayStatus(structureId) { return this._firebaseRef.child(this._structPath + structureId + '/away').once('value').then((snapshot) => { return snapshot.val(); }); } } module.exports = Translator;
JavaScript
0
@@ -1326,16 +1326,386 @@ %22off%22 */ +%0A%0A /**%0A * Refreshes the OAuth token for the hub by returning the existing access token. %0A * does not support refresh tokens, because Nest access tokens are effectively non-expiring (about 10 years)%0A * https://developers.nest.com/documentation/cloud/authorization-reference%0A */%0A refreshAuthToken(authInfo) %7B%0A return this._accessToken;%0A %7D%0A%0A %0A /**
2743ea84de99e02730149413674b928912a023d6
Changed angular 2 to angular
src/containers/home.js
src/containers/home.js
import React from 'react'; import { Link } from 'react-router'; import Card from '../components/card'; import Contact from '../components/contact'; function Home() { return ( <div className="container"> <p className="intro h3"> Hey there! I'm Renee Vrantsidis and I'm a JavaScript Developer in Toronto, Canada. I've worked across the stack using JavaScript, HTML, CSS and PHP, but I specialize in front-end JavaScript work. I believe the web is for everyone. Inclusivity and accessibility in tech are both important topics to me. I also love video games, narrative design, and talking about all of the above to anyone who will listen. Get in touch at renee@renvrant.com. </p> <div className="flex flex-wrap card-list py3"> <Card title="Technologies" color="1"> <ul> <li>Angular 2</li> <li>React</li> <li>React Native</li> <li>Redux</li> <li>Node</li> <li>Webpack</li> </ul> </Card> <Card title="Speaking" color="2"> <ul> <li><a href="https://youtu.be/_MrOw8iywC8?t=9500" target="_blank"> FormControl Freaks: Redux Edition</a> <cite>ng-conf 2017</cite></li> <li>Designing Choice in Narrative Games <cite>Gamercamp 2014</cite></li> <li> <a href="http://www.longstorygame.com/post/78854753270/our-sxsw-14-panel-building-empathic-games-for" target="_blank"> Building Empathic Games For Health Outcomes</a> <cite>SXSW 2014, Dames Making Games 2014</cite> </li> <li>Introduction to Web Design Workshop <cite>Centennial College 2012</cite></li> </ul> </Card> <Card title="Projects and Contributions" color="3"> <ul> <li> <a href="http://www.niftyfish.ca" target="_blank">NiftyFish</a> + <a href="http://tank.niftyfish.ca" target="_blank">NiftyFish Tank</a> @ <a href="http://www.tiff.net/exhibitions/nifty-fish">TIFF</a> </li> <li><a href="https://www.freshbooks.com" target="_blank">FreshBooks</a></li> <li><a href="https://mobile.drivetime.com" target="_blank">DriveTime</a></li> </ul> </Card> <Card title="Writing" color="4"> <ul> <li><a href="https://angular-2-training-book.rangle.io/handout/architect/functional_forms.html" target="_blank">Functional Forms in Angular</a></li> <li> <a href="https://angular-2-training-book.rangle.io/handout/a11y/" target="_blank"> Angular Accessibility</a> </li> {/*<li>*/} {/*<a href="https://medium.com/@renvrant/teach-determination-not-code-e383f5b65a90#.nfdypf6s0" target="_blank">*/} {/*Teach determination, not code</a>*/} {/*</li>*/} </ul> </Card> <Card title="Social" color="5"> <ul> <li><a href="https://www.github.com/renvrant/" target="_blank">Github</a></li> <li><a href="https://www.linkedin.com/in/renvrant" target="_blank">LinkedIn</a></li> <li><a href="http://codepen.io/renvrant/" target="_blank">CodePen</a></li> <li><a href="http://www.twitter.com/renvrant" target="_blank">Twitter</a></li> </ul> </Card> </div> <Contact /> </div> ); } export default Home;
JavaScript
0.99922
@@ -866,18 +866,16 @@ %3EAngular - 2 %3C/li%3E%0A
65cfe7d389c743d913051b2d95955f8de721772b
Fix eslint complaints
src/logger.js
src/logger.js
exports.log = (...args) => { if (!process.env.MIGSI_QUIET) { console.log(...args) } } exports.warn = (...args) => { if (!process.env.MIGSI_QUIET) { console.warn(...args) } } exports.error = (...args) => { if (!process.env.MIGSI_QUIET) { console.error(...args) } } exports.write = (...args) => { if (!process.env.MIGSI_QUIET) { process.stdout.write (...args) } }
JavaScript
0.000004
@@ -373,18 +373,16 @@ ut.write - (...args
0583fb9758ff5bdbe904c59a91e50dda8b91bad1
Update logger.js
src/logger.js
src/logger.js
import bunyan from 'bunyan'; import chalk from 'chalk'; import moment from 'moment'; import nconf from 'nconf'; import R from 'ramda'; const production = (nconf.get('NODE_ENV') === 'production'); const config = {name: 'furbot'}; if (nconf.get('SHARDING') && nconf.get('SHARD_NUMBER')) config.shard_number = nconf.get('SHARD_NUMBER'); const logger = bunyan.createLogger(config); function _submitToLogger(type, msg) { if (R.is(Object, msg)) return logger[type](msg, msg.message || ''); return logger[type](msg); } function cmd(cmd, evt, suffix) { if (production) return logger.info({cmd, evt, suffix}, 'cmd'); console.log(chalk.magenta.bold(`[FurBot]`), chalk.blue(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), chalk.bold.green(`[${evt.message.author.username}]`), chalk.green(`!${cmd}`), suffix); } function info(msg) { if (production) return _submitToLogger('info', msg); console.log(chalk.magenta.bold(`[FurBot]`), chalk.blue(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), msg); } function blank(msg) { if (production) return _submitToLogger('blank', msg); console.log(`==============================================================================`); } function success(msg) { if (production) return _submitToLogger('success', msg); console.log(chalk.magenta.bold(`[FurBot]`), chalk.blue(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), chalk.green(`${msg}`)); } function warn(msg) { if (production) return _submitToLogger('warn', msg); console.log(chalk.magenta.bold(`[FurBot]`), chalk.blue(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), chalk.yellow(`[WARN] ${msg}`)); } function error(msg) { if (production) return _submitToLogger('error', msg); console.log(chalk.magenta.bold(`[FurBot]`), chalk.blue(`[${moment().format('YYYY-MM-DD HH:mm:ss')}]`), chalk.red(`[ERROR] ${msg}`)); console.log(`[ERROR]: %j`, msg); } export default {cmd, info, blank, success, warn, error};
JavaScript
0.000001
@@ -1816,45 +1816,66 @@ msg%7D + ++ %60));%0A -console.log(%60%5BERROR%5D: %25j%60, msg +var str = JSON.stringify(msg);%0A console.log(str );%0A%7D
6f293d806351782c7c63dd537592be6c9c4b6d44
Set level=error on uncaughExceptions logger.
src/logger.js
src/logger.js
'use strict'; const winston = require('winston'); const dailyRotateFile = require('winston-daily-rotate-file'); const logger = new winston.Logger({ transports: [ new (dailyRotateFile)({ name: 'exception-file-daily', handleExceptions: true, humanReadableUnhandledException: true, filename: '../logs/exception.log', datePattern: '.yyyy-MM-dd', prepend: false }), new (dailyRotateFile)({ name: 'error-file-daily', level: 'error', filename: '../logs/error.log', datePattern: '.yyyy-MM-dd', prepend: false }), new (dailyRotateFile)({ name: 'info-file-daily', level: 'info', filename: '../logs/info.log', datePattern: '.yyyy-MM-dd', prepend: false }), new (dailyRotateFile)({ name: 'debug-file-daily', level: 'debug', filename: '../logs/debug.log', datePattern: '.yyyy-MM-dd', prepend: false }) ] }); module.exports = logger;
JavaScript
0
@@ -228,32 +228,60 @@ on-file-daily',%0A + level: 'error',%0A hand
673c74971eec8dc7f1ba040a54788f035d576a5a
Fix roleslug to have single double-quotes
app/scripts/controllers/main.js
app/scripts/controllers/main.js
'use strict'; /* * Controller for view Modal * * displays various instance information * depending on which view button the user * selects from the instance table * */ var ModalInstanceCtrl = function ($scope, $modalInstance, items) { $scope.items = items; $scope.selected = { item: $scope.items[0] }; $scope.ok = function () { $modalInstance.close($scope.selected.item); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }; angular.module('ancorDashboardApp') .controller('MainCtrl', function ($scope, $rootScope, $http, $window, $modal, $log, $route) { $http.get($rootScope.ancorIPAddress+'/v1').success(function(data) { $scope.version = data.version; }); $http.get($rootScope.ancorIPAddress+'/v1/goals').success(function(data) { $scope.goalName = data[0].name; }); $http.get($rootScope.ancorIPAddress+'/v1/roles').success(function(data) { $scope.fullRoles = data; $scope.roles = []; angular.forEach(data, function(value) { $scope.roles.push(value.slug); }); }); // retrieve instances from ANCOR $http.get($rootScope.ancorIPAddress+'/v1/instances').success(function(data) { $scope.instances = data; var numDeployed = 0, numUndeployed = 0, numErrored = 0, numUndefined = 0, numPlanDeployed = 0, numPlanUndeployed = 0, numPlanErrored = 0, numPlanUndefined = 0; // display different label color depending on // what stage the instance is at angular.forEach($scope.instances, function(value){ angular.forEach(value, function(v, k){ // console.log('k: ' + k + '| v: ' + v); if (v === 'deploy' && k === 'stage') { numDeployed++; } else if (v === 'undefined' && k === 'stage') { numUndefined++; } else if (v === 'undeployed' && k === 'stage') { numUndeployed++; } else if (v === 'error' && k === 'stage') { numErrored++; } // do checks for planned_stage here // if (v === 'deploy' && k === 'planned_stage') { numPlanDeployed++; } else if (v === 'undefined' && k === 'planned_stage') { numPlanUndefined++; } else if (v === 'undeployed' && k === 'planned_stage') { numPlanUndeployed++; } else if (v === 'error' && k === 'planned_stage') { numPlanErrored++; } }); }); $scope.totalDeployed = numDeployed; $scope.totalUndefined = numUndefined; $scope.totalUndeployed = numUndeployed; $scope.totalErrored = numErrored; $scope.totalPlanDeployed = numPlanDeployed; $scope.totalPlanUndefined = numPlanUndefined; $scope.totalPlanUndeployed = numPlanUndeployed; $scope.totalPlanErrored = numPlanErrored; $scope.totalInstances = $scope.instances.length; }); // Define custom entries for instance table view $scope.instanceColumnEntries = [ 'Name', 'Interface', 'Stage', 'Planned Stage', 'More Info', 'Operations' ]; // sortable functions $scope.orderByField = 'name'; $scope.reverseSort = false; // GET api/instances/x // Query ancor for specific instance for detailed view // Will be invoked when instance is clicked on the table // Will be able to take id from given msg to do // http get call on specific instance for more info // // $scope.sendAlert = function (msg) { // var str = 'id: ' + msg.id + '\nname:' + msg.name + '\ninterface: ' + msg.interfaces + '\nstage: ' + msg.stage + '\nplanned_stage: ' + msg.planned_stage; // $window.alert(str); // }; $scope.replaceInstance = function (id) { var url = $rootScope.ancorIPAddress+'/v1/instances/' + id, data = { 'replace': true }; console.log('replace ' + id); $window.alert('Replaced ' + id + '!'); $http.post(url, data).success(); $route.reload(); }; $scope.deleteInstance = function (id) { var url = $rootScope.ancorIPAddress+'/v1/instances/' + id; console.log('delete ' + id); $window.alert('Deleted ' + id + '!'); $http.delete(url); $route.reload(); }; $scope.addNewRole = function (roleSlug) { var url = $rootScope.ancorIPAddress+'/v1/instances', newRole = { 'role': '"' + roleSlug + '"' }; console.log(newRole); $http.post(url, newRole).success(); $route.reload(); }; // Modal view of a given instance $scope.open = function (instance) { $scope.items = instance; // console.log(instance); var modalInstance = $modal.open({ templateUrl: 'myModalContent.html', controller: ModalInstanceCtrl, resolve: { items: function () { return $scope.items; } } }); modalInstance.result.then(function (selectedItem) { $scope.selected = selectedItem; }, function () { $log.info('Modal dismissed at: ' + new Date()); }); }; // Page Data $scope.title = 'ANCOR Index'; // $scope.version = 'v0.0.1'; // will be replaced by HTTP GET /api/version $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma', 'SitePoint' ]; // $scope.instances = [{name: 'Test Name', interfaces: 'Test Interface', stage: 'Success'}, {name: 'Test 2', interfaces: '2Int 2Face', stage: 'Success'}]; });
JavaScript
0
@@ -4480,14 +4480,8 @@ le': - '%22' + rol @@ -4489,14 +4489,8 @@ Slug - + '%22' %7D;%0A
da4f5e3f4e7ba0b832224df3fc48a377a1e83802
remove trailing whitespace
app/scripts/directives/clock.js
app/scripts/directives/clock.js
angular.module('fivefifteenApp.directives', []) .directive('clock', function ($timeout, Data) { return function (scope, element, attrs) { var timeoutId; // timeoutId, so that we can cancel the time updates if (!Data.initTime) { Data.initTime = new Date(); } var init = Data.initTime; var current = new Date(); var elapsed = new Date(); elapsed.setTime(current.getTime() - init.getTime()); element.text("Minute/s elapsed: " + elapsed.getMinutes()); // schedule update in one second function updateLater() { // save the timeoutId for canceling timeoutId = $timeout(function() { var current = new Date(); var elapsed = new Date(); elapsed.setTime(current.getTime() - init.getTime()); element.text("Minute/s elapsed: " + elapsed.getMinutes()); updateLater(); // schedule another update }, 1000); } // listen on DOM destroy (removal) event, and cancel the next UI update // to prevent updating time ofter the DOM element was removed. element.bind('$destroy', function() { $timeout.cancel(timeoutId); }); updateLater(); // kick off the UI update process. } });
JavaScript
0.999996
@@ -1,8 +1,22 @@ +'use strict'%0A%0A angular. @@ -288,18 +288,16 @@ Date(); - %0A %7D
bd27ccdadb81e5170b7d1a137a1b9ca55cfc1e11
Revert "Choose random column as default"
app/scripts/models/ai-player.js
app/scripts/models/ai-player.js
'use strict'; var Grid = require('./grid'); var Player = require('./player'); var Chip = require('./chip'); // An AI player that can think for itself function AIPlayer(args) { Player.call(this, args); } AIPlayer.prototype = Object.create(Player.prototype); AIPlayer.prototype.type = 'ai'; // The duration to wait (in ms) for the user to process the AI player's actions AIPlayer.waitDelay = 100; // The maximum number of grid moves to look ahead (this determine's the AI's // intelligence) AIPlayer.maxComputeDepth = 3; // Wait for a short moment to give the user time to see and process the AI // player's actions AIPlayer.prototype.wait = function (callback) { setTimeout(function () { callback(); }, AIPlayer.waitDelay); }; // Compute the column where the AI player should place its next chip AIPlayer.prototype.computeNextMove = function (game) { var bestMove = this.maximizeMove( game.grid, game.getOtherPlayer(this), AIPlayer.maxComputeDepth, Grid.minScore, Grid.maxScore); // If no particular column yields an advantage or disadvantage, choose a // column at random if (bestMove.column === 0 && bestMove.score === 0) { bestMove.column = Math.floor(Math.random() * game.grid.columnCount); } // Choose next available column if original pick is full while (game.grid.getNextAvailableSlot({column: bestMove.column}) === null) { bestMove.column += 1; // Wrap around if needed if (bestMove.column === game.grid.columnCount) { bestMove.column = 0; } } game.emitter.emit('ai-player:compute-next-move', this, bestMove); return bestMove.column; }; // Choose a column that will maximize the AI player's chances of winning AIPlayer.prototype.maximizeMove = function (grid, minPlayer, depth, alpha, beta) { var gridScore = grid.getScore({ currentPlayer: this, currentPlayerIsMaxPlayer: true }); // If max search depth was reached or if winning grid was found if (depth === 0 || Math.abs(gridScore) === Grid.maxScore) { return {column: null, score: gridScore}; } var maxMove = {column: null, score: Grid.minScore}; for (var c = 0; c < grid.columnCount; c += 1) { // Continue to next possible move if this column is full if (grid.columns[c].length === grid.rowCount) { continue; } // Clone the current grid and place a chip to generate a new permutation var nextGrid = new Grid(grid); nextGrid.placeChip({column: c, chip: new Chip({player: this})}); // Minimize the opponent human player's chances of winning var minMove = this.minimizeMove(nextGrid, minPlayer, depth - 1, alpha, beta); // If a move yields a lower opponent score, make it the tentative max move if (minMove.score > maxMove.score) { maxMove.column = c; maxMove.score = minMove.score; alpha = minMove.score; } else if (maxMove.column === null || minMove.score === Grid.minScore) { // Ensure that obvious column choices are not forgotten maxMove.column = minMove.column; maxMove.score = minMove.score; } // Stop if there are no moves better than the current max move if (alpha >= beta) { break; } } return maxMove; }; // Choose a column that will minimize the human player's chances of winning AIPlayer.prototype.minimizeMove = function (grid, minPlayer, depth, alpha, beta) { var gridScore = grid.getScore({ currentPlayer: minPlayer, currentPlayerIsMaxPlayer: false }); // If max search depth was reached or if winning grid was found if (depth === 0 || Math.abs(gridScore) === Grid.maxScore) { return {column: null, score: gridScore}; } var minMove = {column: null, score: Grid.maxScore}; for (var c = 0; c < grid.columnCount; c += 1) { // Continue to next possible move if this column is full if (grid.columns[c].length === grid.rowCount) { continue; } var nextGrid = new Grid(grid); // The human playing against the AI is always the first player nextGrid.placeChip({column: c, chip: new Chip({player: minPlayer})}); // Maximize the AI player's chances of winning var maxMove = this.maximizeMove(nextGrid, minPlayer, depth - 1, alpha, beta); // If a move yields a higher AI score, make it the tentative max move if (maxMove.score < minMove.score) { minMove.column = c; minMove.score = maxMove.score; beta = maxMove.score; } else if (minMove.column === null || maxMove.score === Grid.minScore) { // Ensure that obvious column choices are not forgotten minMove.column = maxMove.column; minMove.score = maxMove.score; } // Stop if there are no moves better than the current min move if (alpha >= beta) { break; } } return minMove; }; module.exports = AIPlayer;
JavaScript
0
@@ -1066,38 +1066,41 @@ ge, -choose a%0A // column at random +default to the%0A // center column %0A i @@ -1177,57 +1177,9 @@ n = -Math.floor(Math.random() * game.grid.columnCount) +3 ;%0A
27929a554d1b2c94d84e130fc07f15108dad2eb4
Fix unhappy PhantomJS with fn.bind(fn)
src/identifier.js
src/identifier.js
import Node from './node'; import Arguments from './arguments'; import { isWriteableObservable, isObservable } from 'tko.observable'; export default function Identifier(parser, token, dereferences) { this.token = token; this.dereferences = dereferences; this.parser = parser; } /** * Return the value of the given * * @param {Object} parent (optional) source of the identifier e.g. for * membership. e.g. `a.b`, one would pass `a` in as * the parent when calling lookup_value for `b`. * @return {Mixed} The value of the token for this Identifier. */ Identifier.prototype.lookup_value = function (parent) { var token = this.token, parser = this.parser, $context = parser.context, $data = $context.$data || {}, globals = parser.globals || {}; if (parent) { return Node.value_of(parent)[token]; } // short circuits switch (token) { case '$element': return parser.node; case '$context': return $context; case '$data': return $context.$data; default: } // instanceof Object covers 1. {}, 2. [], 3. function() {}, 4. new *; it excludes undefined, null, primitives. if ($data instanceof Object && token in $data) { return $data[token]; } if (token in $context) { return $context[token]; } if (token in globals) { return globals[token]; } throw new Error("The variable \"" + token + "\" was not found on $data, $context, or knockout options.bindingGlobals."); }; /** * Apply all () and [] functions on the identifier to the lhs value e.g. * a()[3] has deref functions that are essentially this: * [_deref_call, _deref_this where this=3] * * @param {mixed} value Should be an object. * @return {mixed} The dereferenced value. */ Identifier.prototype.dereference = function (value) { var member, refs = this.dereferences || [], parser = this.parser, $context = parser.context || {}, $data = $context.$data || {}, self = { // top-level `this` in function calls $context: $context, $data: $data, globals: parser.globals || {}, $element: parser.node }, last_value, // becomes `this` in function calls to object properties. i, n; for (i = 0, n = refs.length; i < n; ++i) { member = Node.value_of(refs[i]); if (typeof value === 'function' && refs[i] instanceof Arguments) { // fn(args) value = value.apply(last_value || self, member); last_value = value; } else { // obj[x] or obj.x dereference. Note that obj may be a function. last_value = value; value = Node.value_of(value[member]); } } // With obj.x, make `obj = this` if (typeof value === 'function' && n > 0) { return value.bind(last_value); } return value; }; /** * Return the value as one would get it from the top-level i.e. * $data.token/$context.token/globals.token; this does not return intermediate * values on a chain of members i.e. $data.hello.there -- requesting the * Identifier('there').value will return $data/$context/globals.there. * * This will dereference using () or [arg] member. * @param {object | Identifier | Expression} parent * @return {mixed} Return the primitive or an accessor. */ Identifier.prototype.get_value = function (parent) { return this.dereference(this.lookup_value(parent)); }; Identifier.prototype.assign = function assign(object, property, value) { if (isWriteableObservable(object[property])) { object[property](value); } else if (!isObservable(object[property])) { object[property] = value; } }; /** * Set the value of the Identifier. * * @param {Mixed} new_value The value that Identifier is to be set to. */ Identifier.prototype.set_value = function (new_value) { var parser = this.parser, $context = parser.context, $data = $context.$data || {}, globals = parser.globals || {}, refs = this.dereferences || [], leaf = this.token, i, n, root; if (Object.hasOwnProperty.call($data, leaf)) { root = $data; } else if (Object.hasOwnProperty.call($context, leaf)) { root = $context; } else if (Object.hasOwnProperty.call(globals, leaf)) { root = globals; } else { throw new Error("Identifier::set_value -- " + "The property '" + leaf + "' does not exist " + "on the $data, $context, or globals."); } // Degenerate case. {$data|$context|global}[leaf] = something; n = refs.length; if (n === 0) { this.assign(root, leaf, new_value); return; } // First dereference is {$data|$context|global}[token]. root = root[leaf]; // We cannot use this.dereference because that gives the leaf; to evoke // the ES5 setter we have to call `obj[leaf] = new_value` for (i = 0; i < n - 1; ++i) { leaf = refs[i]; if (leaf instanceof Arguments) { root = root(); } else { root = root[Node.value_of(leaf)]; } } // We indicate that a dereference is a function when it is `true`. if (refs[i] === true) { throw new Error("Cannot assign a value to a function."); } // Call the setter for the leaf. if (refs[i]) { this.assign(root, Node.value_of(refs[i]), new_value); } }; Identifier.prototype[Node.isExpressionOrIdentifierSymbol] = true;
JavaScript
0.000002
@@ -2723,16 +2723,40 @@ && n %3E 0 + && last_value !== value ) %7B%0A
8738d271d2942a5c0c9f1ffe903a3c123d67366f
clean up
src/image-zoom.js
src/image-zoom.js
+function() { /** * The main service. */ function ImageZoomService() { this._scaleBase = 0.9 this._image = null this._overlay = null this._window = window this._document = document this._body = document.body } ImageZoomService.prototype.init = function() { // Add listener for click event this._body.addEventListener('click', this._handleClick.bind(this)) // Create overlay this._overlay = new Overlay() } ImageZoomService.prototype._handleClick = function(event) { var target = event.target if (!target) return if (target.tagName === 'IMG' && target.hasAttribute('data-action')) { this._image = new Zoomable(target) var action = target.getAttribute('data-action') switch (action) { case 'zoom': this._zoom() break; case 'close': this._close() break; default: break; } } else if (this._image.isActive()) { this._close() } } ImageZoomService.prototype._handleKeyDown = function(event) { if (event.keyCode === 27) this._close() } ImageZoomService.prototype._zoom = function() { var imgRect = this._image.getRect() var centerX = this._window.innerWidth / 2 var centerY = this._window.innerHeight / 2 var imgRectHalfWidth = imgRect.width / 2 var imgRectHalfHeight = imgRect.height / 2 var imgX = imgRect.left + imgRectHalfWidth var imgY = imgRect.top + imgRectHalfHeight var translate = { x: centerX - imgX, y: centerY - imgY } var distX = centerX - imgRectHalfWidth var distY = centerY - imgRectHalfHeight var scale = this._scaleBase + Math.min(distX / imgRectHalfWidth, distY / imgRectHalfHeight) this._overlay.show() this._image.zoomIn() this._image.transform(translate, scale) this._document.addEventListener('keydown', this._handleKeyDown.bind(this)) } ImageZoomService.prototype._close = function() { if (!this._image) return this._overlay.hide() this._image.zoomOut() this._document.removeEventListener('keydown', this._handleKeyDown.bind(this)) this._image = null } /** * An overlay that hide/show DOM body. */ function Overlay() { this._body = document.body this._element = document.createElement('div') this._element.classList.add('image-zoom-overlay') } Overlay.prototype.show = function() { this._body.classList.add('image-zoom-overlay-show') this._body.appendChild(this._element) } Overlay.prototype.hide = function() { this._body.classList.remove('image-zoom-overlay-show') this._body.removeChild(this._element) } /** * The target image. */ function Zoomable(img) { this._targetImg = img this._rect = this._targetImg.getBoundingClientRect() this._body = document.body } Zoomable.prototype.isActive = function() { return this._targetImg != null } Zoomable.prototype.zoomIn = function() { this._targetImg.setAttribute('data-action', 'close') this._targetImg.classList.add('image-zoom-transition', 'image-zoom-img') } Zoomable.prototype.zoomOut = function() { this._targetImg.setAttribute('data-action', 'zoom') this._targetImg.classList.remove('image-zoom-img') setStyles(this._targetImg, { '-webkit-transform': '', '-ms-transform': '', 'transform': '', }) this._targetImg = null } Zoomable.prototype.getRect = function() { return this._rect } Zoomable.prototype.transform = function(translate, scale) { var transform = 'translate(' + translate.x + 'px,' + translate.y + 'px) ' + 'scale(' + scale + ',' + scale + ')' setStyles(this._targetImg, { '-webkit-transform': transform, '-ms-transform': transform, 'transform': transform, }) } /** * Set css styles. */ function setStyles(element, styles) { for (var prop in styles) { element.style[prop] = styles[prop] } } document.addEventListener('DOMContentLoaded', function() { new ImageZoomService().init() }) }()
JavaScript
0.000001
@@ -12,43 +12,8 @@ %7B%0A%0A - /**%0A * The main service.%0A */%0A fu @@ -36,24 +36,24 @@ Service() %7B%0A + this._sc @@ -259,44 +259,8 @@ ) %7B%0A - // Add listener for click event%0A @@ -329,31 +329,8 @@ is)) -%0A%0A // Create overlay %0A @@ -976,24 +976,49 @@ on(event) %7B%0A + // Esc =%3E close zoom%0A if (even @@ -1100,24 +1100,304 @@ unction() %7B%0A + this._calculateZoom(function(translate, scale) %7B%0A this._image.zoomIn(translate, scale)%0A %7D)%0A%0A this._overlay.show()%0A this._document.addEventListener('keydown', this._handleKeyDown.bind(this))%0A %7D%0A%0A ImageZoomService.prototype._calculateZoom = function(callback) %7B%0A var imgR @@ -1978,176 +1978,33 @@ -this._overlay.show()%0A this._image.zoomIn()%0A this._image.transform(translate, scale)%0A%0A this._document.addEventListener('keydown', this._handleKeyDown.bind(this) +callback(translate, scale )%0A @@ -2263,10 +2263,11 @@ * -An +The ove @@ -3051,32 +3051,48 @@ omIn = function( +translate, scale ) %7B%0A this._ta @@ -3212,16 +3212,281 @@ om-img') +%0A%0A var transform = 'translate(' + translate.x + 'px,' + translate.y + 'px) ' +%0A 'scale(' + scale + ',' + scale + ')'%0A%0A setStyles(this._targetImg, %7B%0A '-webkit-transform': transform,%0A '-ms-transform': transform,%0A 'transform': transform,%0A %7D) %0A %7D%0A%0A @@ -3829,32 +3829,32 @@ = function() %7B%0A + return this. @@ -3868,339 +3868,8 @@ %7D%0A%0A - Zoomable.prototype.transform = function(translate, scale) %7B%0A var transform = 'translate(' + translate.x + 'px,' + translate.y + 'px) ' +%0A 'scale(' + scale + ',' + scale + ')'%0A%0A setStyles(this._targetImg, %7B%0A '-webkit-transform': transform,%0A '-ms-transform': transform,%0A 'transform': transform,%0A %7D)%0A %7D%0A%0A /*
66e19baf548ae8ecc216bbc878d85d9d5766d3bf
Update default Docker image for 12.3.1
src/itk-js-cli.js
src/itk-js-cli.js
#!/usr/bin/env node const fs = require('fs-extra') const path = require('path') const spawnSync = require('child_process').spawnSync const program = require('commander') const build = (sourceDir) => { // Check that the source directory exists and chdir to it. if (!fs.existsSync(sourceDir)) { console.error('The source directory: ' + sourceDir + ' does not exist!') process.exit(1) } process.chdir(sourceDir) // Make the 'web-build' directory to hold the dockcross script and the CMake // build. try { fs.mkdirSync('web-build') } catch (err) { if (err.code !== 'EEXIST') throw err } // Check that we have docker and can run it. const dockerVersion = spawnSync('docker', ['--version'], { env: process.env, stdio: [ 'ignore', 'ignore', 'ignore' ] }) if (dockerVersion.status !== 0) { console.error("Could not run the 'docker' command.") console.error('This tool requires Docker.') console.error('') console.error('Please find installation instructions at:') console.error('') console.error(' https://docs.docker.com/install/') console.error('') process.exit(dockerVersion.status) } let dockerImage = 'insighttoolkit/itk-js:20200415-fb44ec4' if (program.commands[0].image) { dockerImage = program.commands[0].image } // Ensure we have the 'dockcross' Docker build environment driver script const dockcrossScript = 'web-build/itk-js-build-env' try { fs.statSync(dockcrossScript) } catch (err) { if (err.code === 'ENOENT') { const output = fs.openSync(dockcrossScript, 'w') const dockerCall = spawnSync('docker', ['run', '--rm', dockerImage], { env: process.env, stdio: [ 'ignore', output, null ] }) if (dockerCall.status !== 0) { process.exit(dockerCall.status) } fs.closeSync(output) fs.chmodSync(dockcrossScript, '755') } else { throw err } } const hypenIndex = program.rawArgs.findIndex((arg) => arg === '--') let cmakeArgs = [] if (hypenIndex !== -1) { cmakeArgs = program.rawArgs.slice(hypenIndex + 1) } if(process.platform === "win32"){ var dockerBuild = spawnSync('"C:\\Program Files\\Git\\bin\\sh.exe"', ["--login", "-i", "-c", '"web-build/itk-js-build-env web-build ' + cmakeArgs + '"'], { env: process.env, stdio: 'inherit', shell: true }); if (dockerBuild.status !== 0) { console.error(dockerBuild.error); } process.exit(dockerBuild.status); } else { const dockerBuild = spawnSync('bash', [dockcrossScript, 'web-build'].concat(cmakeArgs), { env: process.env, stdio: 'inherit' }) if (dockerBuild.status !== 0) { console.error(dockerBuild.error); } process.exit(dockerBuild.status) } } const test = (sourceDir) => { // Check that the source directory exists and chdir to it. if (!fs.existsSync(sourceDir)) { console.error('The source directory: ' + sourceDir + ' does not exist!') process.exit(1) } process.chdir(sourceDir) const dockcrossScript = path.join('web-build/itk-js-build-env') try { fs.statSync(dockcrossScript) } catch (err) { console.error('Could not find ' + sourceDir + '/web-build/itk-js-build-env') console.error('') console.error('Has') console.error('') console.error(' itk-js build ' + sourceDir) console.error('') console.error('been executed?') process.exit(1) } const hypenIndex = program.rawArgs.findIndex((arg) => arg === '--') let ctestArgs = '' if (hypenIndex !== -1) { ctestArgs = program.rawArgs.slice(hypenIndex + 1).join(' ') } if(process.platform === "win32"){ var dockerBuild = spawnSync('"C:\\Program Files\\Git\\bin\\sh.exe"', ["--login", "-i", "-c", '"web-build/itk-js-build-env bash -c cd web-build && ctest ' + cmakeArgs + '"'], { env: process.env, stdio: 'inherit', shell: true }); if (dockerBuild.status !== 0) { console.error(dockerBuild.error); } process.exit(dockerBuild.status); } else { const dockerBuild = spawnSync('bash', [dockcrossScript, 'bash', '-c', 'cd web-build && ctest ' + ctestArgs], { env: process.env, stdio: 'inherit' }) process.exit(dockerBuild.status) } } program .command('build <sourceDir>') .usage('[options] <sourceDir> [-- <cmake arguments>]') .description('build the CMake project found in the given source directory') .action(build) .option('-i, --image <image>', 'build environment Docker image, defaults to insighttoolkit/itk-js') // todo: needs a wrapper in web_add_test that 1) mount /work into the emscripten filesystem // and 2) invokes the runtime // program // .command('test <sourceDir>') // .usage('[options] <sourceDir> [-- <ctest arguments>]') // .description('run ctest on the project previously built from the given source directory') // .action(test) program .parse(process.argv) program.help()
JavaScript
0
@@ -1218,17 +1218,17 @@ 0041 -5-fb44ec4 +6-e17aafa '%0A
939119c08be866dfe76f39869821c902d996fe46
Drop likert scale #1 labels below anchors
public/js/settings.js
public/js/settings.js
/** * Settings configuration for jsPASAT */ var jsPASAT = { // Pace of PASAT trial presentation 'TIMING_STIM_DISPLAY': 1000, 'TIMING_POST_STIM': 3000, // Practice block stimuli 'PRACTICE_BLOCK_1_STIMULI': [9, 1, 3, 5, 2, 6], 'PRACTICE_BLOCK_2_STIMULI': [6, 4, 5, 7, 2, 8, 4, 5, 9, 3, 6, 9, 2, 7, 3, 8], // Re-useable Likert scale labels 'LIKERT_SCALE_1': ["1 - None", "2", "3", "4", "5", "6", "7 - A Lot"], 'LIKERT_SCALE_2': [ "1<br>Significantly<br>Below Average", "2", "3", "4<br>Average", "5", "6", "7<br>Significantly<br>Above Average" ], };
JavaScript
0
@@ -373,19 +373,20 @@ _1': %5B%221 - - +%3Cbr%3E None%22, %22 @@ -415,11 +415,12 @@ , %227 - - +%3Cbr%3E A Lo
ec7a3f08bcd0872baaacafb86ce717720dea26c5
Add support for shiftKey in key events
public/src/js/keys.js
public/src/js/keys.js
/* * debugger.io: An interactive web scripting sandbox * * keys.js: key-command handlers */ define(function(require) { 'use strict'; var $ = require('jquery'); var _ = require('underscore'); var bus = require('bus'); var config = require('config'); var utils = require('utils'); // --- var keys = utils.module('keys'); var handlers = {}; var last_hid = 0; var key_map = { 'enter': 13, 'esc': 27, 'left': 37, 'up': 38, 'right': 39, 'down': 40, '/': 191 }; bus.init(function(av) { keys.console.log('init keys module'); $(document).on('keyup', function(e) { // hey, I just met you ... var keyHandlers = _.filter(handlers, function(h) { return !h.paused && h.ctrl === e.ctrlKey && h.alt === e.altKey && h.key === e.which; }); // and this is crazy ... if (keyHandlers.length) { e.preventDefault(); e.stopPropagation(); } _.each(keyHandlers, function(handler) { // but here's my number ... var callback = handler ? handler.callback : null; // so call me maybe. if (_.isFunction(callback)) { keys.console.log('executing callback for handler', handler.hid); callback(e); } }); }); }); /** * Get a char code from a single-char * * @param {String} key - single-char or key description * @return {Integer | null} char code if found, null otherwise */ keys.key_code_for = function(key) { if (!_.isString(key)) { return null; } if (_.has(key_map, key)) { return key_map[key]; } if (key.length === 1) { return key.toUpperCase().charCodeAt(0); } return null; }; /** * Register a new key callback function * * @param {Object} opts - { ctrl: Boolean, alt: Boolean, key: String } * @param {Function} callback - callback function, passed up event * @return {Integer} unique handler id, null if opts.key is undefined */ keys.register_handler = function(opts, callback) { var opts = opts || {}; var hid = last_hid++; if (_.isUndefined(opts.key)) { return null; } keys.console.log('registering key handler', hid); handlers[hid] = { hid: hid, ctrl: !!opts.ctrl, alt: !!opts.alt, key: keys.key_code_for(opts.key), callback: callback }; return hid; }; /** * Unregister a key hander by id * * @param {Integer} hid - handler id */ keys.unregister_handler = function(hid) { if (_.has(handlers, hid)) { keys.console.log('unregistering key handler', hid); delete handlers[hid]; } }; /** * Pause a key hander by id * * @param {Integer} hid - handler id */ keys.pause_handler = function(hid) { if (_.has(handlers, hid)) { keys.console.log('pausing key handler', hid); handlers[hid].paused = true; } }; /** * Resume a paused a key hander by id * * @param {Integer} hid - handler id */ keys.resume_handler = function(hid) { if (_.has(handlers, hid)) { keys.console.log('resuming key handler', hid); handlers[hid].paused = false; } }; /** * Toggle a key hander by id * * @param {Integer} hid - handler id */ keys.toggle_handler = function(hid) { if (_.has(handlers, hid)) { keys.console.log('toggling key handler', hid); handlers[hid].paused = !handlers[hid].paused; } }; return keys; });
JavaScript
0
@@ -628,18 +628,20 @@ .on('key -up +down ', funct @@ -822,16 +822,42 @@ + h.shift === e.shiftKey && h.key = @@ -1312,16 +1312,41 @@ back(e); +%0A%0A return false; %0A @@ -1864,16 +1864,23 @@ opts - %7B +%0A * ctrl: B @@ -1900,16 +1900,32 @@ Boolean, + shift: Boolean, key: St @@ -1928,16 +1928,21 @@ : String +%0A * %7D%0A * @@ -2358,16 +2358,16 @@ s.ctrl,%0A - al @@ -2381,16 +2381,43 @@ ts.alt,%0A + shift: !!opts.shift,%0A ke
30e3359d1d0433544707ec3a50757cef3b2f5714
Split PaperScope#remove() into #clear() and #remove(), so scopes can be reused.
src/core/PaperScope.js
src/core/PaperScope.js
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Distributed under the MIT license. See LICENSE file for details. * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * All rights reserved. */ /** * Define internal PaperScope class that handles all the fields available on the * global paper object, which simply is a pointer to the currently active scope. */ var PaperScope = this.PaperScope = Base.extend({ initialize: function(id) { this.document = null; this.documents = []; this.tools = []; this.id = id; PaperScope.scopes[id] = this; }, /** * Installs the paper scope into any other given scope. Can be used for * examle to inject the currently active PaperScope into the window's global * scope, to emulate PaperScript-style globally accessible Paper classes: * * paper.install(window); */ install: function(scope) { // Use scope as side-car (= 'this' inside iterator), and have it // returned at the end. return Base.each(this, function(value, key) { this[key] = value; }, scope); }, remove: function() { // Remove all documents and tools. for (var i = this.documents.length - 1; i >= 0; i--) this.documents[i].remove(); for (var i = this.tools.length - 1; i >= 0; i--) this.tools[i].remove(); }, statics: { scopes: {}, get: function(id) { return this.scopes[id] || null; } } });
JavaScript
0
@@ -1262,22 +1262,21 @@ ;%0A%09%7D,%0A%0A%09 -remove +clear : functi @@ -1488,16 +1488,96 @@ );%0A%09%7D,%0A%0A +%09remove: function() %7B%0A%09%09this.clear();%0A%09%09delete PaperScope.scopes%5Bthis.id%5D;%0A%09%7D,%0A%0A %09statics
77b9276f9411186b203cc1e26f7d3be44bf272b1
Change all const to var.
spec/providers/coreIntegration/udpsocket.integration.src.js
spec/providers/coreIntegration/udpsocket.integration.src.js
module.exports = function(provider, setup) { var socket, serverDispatchEvent; const listenPort = 8082, sendPort = 8083; beforeEach(function () { setup(); serverDispatchEvent = jasmine.createSpy("dispatchEvent"); socket = new provider.provider(undefined, serverDispatchEvent); }); it("Connects, has state, and sends/receives data", function (done) { const todo = []; // Pending tasks to complete before calling |done()|. const markTask = function(name) { var tag = { name: name }; todo.push(tag); return tag; } const did = function(task) { var i = todo.indexOf(task); expect(i).not.toEqual(-1); // A task must not be done twice. todo.splice(i, 1); // Remove |task| from the list. if (todo.length == 0) { done(); // This is the only call to |done()|. } }; // callPoint returns a function that must be called exactly once. const callPoint = function(name) { return did.bind(null, markTask(name)); }; const LOCALHOST = '127.0.0.1'; const checkSocketInfo = function(socketToCheck, port) { const getInfoTask = markTask('getInfo'); socketToCheck.getInfo(function(state) { expect(state).toEqual(jasmine.objectContaining({ 'localAddress': LOCALHOST, 'localPort': port })); did(getInfoTask); }); }; const sendString = "Hello World", sendBuffer = str2ab(sendString), clientDispatchEvent = jasmine.createSpy("dispatchEvent"), sendingSocket = new provider.provider(undefined, clientDispatchEvent); // Don't finish this test until a packet is received. const receivePacketTask = markTask('receive packet'); // Set up connections socket.bind(LOCALHOST, listenPort, function(returnCode) { expect(returnCode).toEqual(0); checkSocketInfo(socket, listenPort); sendingSocket.bind(LOCALHOST, sendPort, function(returnCode) { expect(returnCode).toEqual(0); checkSocketInfo(sendingSocket, sendPort); // Check data sending serverDispatchEvent.and.callFake(function(event, data) { expect(event).toEqual("onData"); expect(data.resultCode).toEqual(0); expect(data.port).toEqual(sendPort); expect(data.data).toEqual(sendBuffer); sendingSocket.destroy(callPoint('destroy sending socket')); socket.destroy(callPoint('destroy receiving socket')); did(receivePacketTask); }); sendingSocket.sendTo(sendBuffer, "127.0.0.1", listenPort, callPoint('send continuation')); }); }); }); function str2ab(str) { var buf = new ArrayBuffer(str.length); var bufView = new Uint8Array(buf); for (var i=0, strLen=str.length; i<strLen; i++) { bufView[i] = str.charCodeAt(i); } return buf; } };
JavaScript
0
@@ -75,21 +75,19 @@ vent;%0A -const +var listenP @@ -367,21 +367,19 @@ ) %7B%0A -const +var todo = @@ -441,21 +441,19 @@ )%7C.%0A -const +var markTas @@ -555,21 +555,19 @@ %7D%0A -const +var did = f @@ -916,21 +916,19 @@ ce.%0A -const +var callPoi @@ -1006,21 +1006,19 @@ %7D;%0A%0A -const +var LOCALHO @@ -1039,21 +1039,19 @@ 1';%0A -const +var checkSo @@ -1099,21 +1099,19 @@ %7B%0A -const +var getInfo @@ -1367,21 +1367,19 @@ %7D;%0A%0A -const +var sendStr @@ -1658,13 +1658,11 @@ -const +var rec
a78e6ffc5a1a31e293b62cc67a95e529a61fbf4a
fix missing tailing comma
src/js/helpers.js
src/js/helpers.js
import { CLASS_PICKED, NAMESPACE, } from './constants'; import { addClass, addLeadingZero, getDaysInMonth, isFinite, isFunction, isNumber, setData, tokenToType, } from './utilities'; export default { render(type) { if (!type) { this.format.tokens.forEach(token => this.render(tokenToType(token))); return; } const { options } = this; const data = this.data[type]; const current = this.current(type); const max = isFunction(data.max) ? data.max() : data.max; const min = isFunction(data.min) ? data.min() : data.min; let base = 0; if (isFinite(max)) { base = min > 0 ? max : max + 1; } data.list.innerHTML = ''; data.current = current; for (let i = 0; i < options.rows + 2; i += 1) { const item = document.createElement('li'); const position = i - data.index; let newValue = current + (position * data.increment); if (base) { newValue %= base; if (newValue < min) { newValue += base; } } item.textContent = options.translate(type, data.aliases ? data.aliases[newValue] : addLeadingZero(newValue + data.offset, data.digit)); setData(item, 'name', type); setData(item, 'value', newValue); addClass(item, `${NAMESPACE}-item`); if (position === 0) { addClass(item, CLASS_PICKED); data.item = item; } data.list.appendChild(item); } }, current(type, value) { const { date } = this; const { format } = this; const token = format[type]; switch (token.charAt(0)) { case 'Y': if (isNumber(value)) { date.setFullYear(token.length === 2 ? (2000 + value) : value); if (format.month) { this.render(tokenToType(format.month)); } if (format.day) { this.render(tokenToType(format.day)); } } return date.getFullYear(); case 'M': if (isNumber(value)) { date.setMonth( value, // The current day should not exceed its maximum day in current month Math.min(date.getDate(), getDaysInMonth(date.getFullYear(), value)) ); if (format.day) { this.render(tokenToType(format.day)); } } return date.getMonth(); case 'D': if (isNumber(value)) { date.setDate(value); } return date.getDate(); case 'H': if (isNumber(value)) { date.setHours(value); } return date.getHours(); case 'm': if (isNumber(value)) { date.setMinutes(value); } return date.getMinutes(); case 's': if (isNumber(value)) { date.setSeconds(value); } return date.getSeconds(); case 'S': if (isNumber(value)) { date.setMilliseconds(value); } return date.getMilliseconds(); default: } return date; }, getValue() { const { element } = this; return this.isInput ? element.value : element.textContent; }, setValue(value) { const { element } = this; if (this.isInput) { element.value = value; } else if (this.options.container) { element.textContent = value; } }, open() { const { body } = this; body.style.overflow = 'hidden'; body.style.paddingRight = `${this.scrollBarWidth + (parseFloat(this.initialBodyPaddingRight) || 0)}px`; }, close() { const { body } = this; body.style.overflow = ''; body.style.paddingRight = this.initialBodyPaddingRight; }, };
JavaScript
0.000453
@@ -2213,16 +2213,17 @@ value)) +, %0A
94f8dea8312b52b9c7c51e58d48f3a4f51390b89
fix incorrect quality url
src/js/options.js
src/js/options.js
/* global DPLAYER_VERSION */ import defaultApiBackend from './api.js'; export default (options) => { // default options const defaultOption = { container: options.element || document.getElementsByClassName('dplayer')[0], live: false, autoplay: false, theme: '#b7daff', loop: false, lang: (navigator.language || navigator.browserLanguage).toLowerCase(), screenshot: false, hotkey: true, preload: 'auto', volume: 0.7, apiBackend: defaultApiBackend, video: {}, contextmenu: [], mutex: true }; for (const defaultKey in defaultOption) { if (defaultOption.hasOwnProperty(defaultKey) && !options.hasOwnProperty(defaultKey)) { options[defaultKey] = defaultOption[defaultKey]; } } if (options.video) { !options.video.type && (options.video.type = 'auto'); } if (typeof options.danmaku === 'object' && options.danmaku) { !options.danmaku.user && (options.danmaku.user = 'DIYgod'); } if (options.subtitle) { !options.subtitle.type && (options.subtitle.type = 'webvtt'); !options.subtitle.fontSize && (options.subtitle.fontSize = '20px'); !options.subtitle.bottom && (options.subtitle.bottom = '40px'); !options.subtitle.color && (options.subtitle.color = '#fff'); } if (options.video.quality) { options.video.url = [ options.video.quality[options.video.defaultQuality].url ]; } if (options.lang) { options.lang = options.lang.toLowerCase(); } options.contextmenu = options.contextmenu.concat([ { text: 'Video info', click: (player) => { player.infoPanel.triggle(); } }, { text: 'About author', link: 'https://diygod.me' }, { text: `DPlayer v${DPLAYER_VERSION}`, link: 'https://github.com/MoePlayer/DPlayer' } ]); return options; };
JavaScript
0.99844
@@ -1447,22 +1447,8 @@ rl = - %5B%0A opt @@ -1503,18 +1503,8 @@ .url -%0A %5D ;%0A
1cb25dda211a02ded7a34d9acc4cab47fcf8ff04
Fix proto lang handler to work minified and to use the type style for types like uint32.
src/lang-proto.js
src/lang-proto.js
// Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * Registers a language handler for Protocol Buffers as described at * http://code.google.com/p/protobuf/. * * Based on the lexical grammar at * http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715 * * @author mikesamuel@gmail.com */ PR['registerLangHandler'](PR['sourceDecorator']({ keywords: ( 'bool bytes default double enum extend extensions false fixed32 ' + 'fixed64 float group import int32 int64 max message option ' + 'optional package repeated required returns rpc service ' + 'sfixed32 sfixed64 sint32 sint64 string syntax to true uint32 ' + 'uint64'), cStyleComments: true }), ['proto']);
JavaScript
0
@@ -929,16 +929,17 @@ +' keywords : (%0A @@ -934,16 +934,17 @@ keywords +' : (%0A @@ -956,46 +956,41 @@ ' -bool bytes - +, default - +, double - +, enum - +, extend - +, exte @@ -999,23 +999,15 @@ ions - +, false - fixed32 +, '%0A @@ -1023,66 +1023,40 @@ + ' -fixed64 float group - +, import - int32 int64 max +,max, message - +, option - +, '%0A @@ -1080,25 +1080,25 @@ onal - +, package - +, repeated req @@ -1093,25 +1093,25 @@ repeated - +, required returns @@ -1106,29 +1106,29 @@ ired - +, returns - rpc +,rpc, service - +, '%0A @@ -1144,94 +1144,100 @@ + ' -sfixed32 sfixed64 sint32 sint64 string syntax - to +,to, true - uint32 '%0A + 'uint64') +'),%0A 'types': /%5E(bool%7C(double%7Cs?fixed%7C%5Bsu%5D?int)(32%7C64)%7Cfloat%7Cstring)%5Cb/ ,%0A @@ -1242,16 +1242,17 @@ +' cStyleCo @@ -1257,16 +1257,17 @@ Comments +' : true%0A
8f9abea4199dcd09736fa5fbac46c239469338d2
fix lint
src/lang/index.js
src/lang/index.js
const savedLang = window.localStorage && window.localStorage.getItem('localization'); const lang = require(`./${savedLang || 'en-US'}.json`); export const langs = [ { value: 'en-US', translated: lang.language_en_us, native: 'English (US)', }, { value: 'bg-BG', translated: lang.language_bg, native: 'български bǎlgarski', }, { value: 'cs-CZ', translated: lang.language_cs, native: 'Čeština', }, { value: 'de-DE', translated: lang.language_de, native: 'Deutsch', }, { value: 'es-ES', translated: lang.language_es_419, native: 'Español (América Latina)', }, { value: 'es-PE', translated: lang.language_es_419, native: 'Español (América Latina)', }, { value: 'fi-FI', translated: lang.language_fi, native: 'Suomi', }, { value: 'fr-FR', translated: lang.language_fr, native: 'Français', }, { value: 'it-IT', translated: lang.language_it, native: 'Italiano', }, { value: 'ja-JP', translated: lang.language_ja, native: '日本語', }, { value: 'ko-KR', translated: lang.language_ko, native: '한국어', }, { value: 'ms-MY', translated: lang.language_ms, native: 'Bahasa Melayu', }, { value: 'nl-NL', translated: lang.language_nl, native: 'Nederlands', }, { value: 'pl_PL', translated: lang.language_pl, native: 'Polszczyzna', }, { value: 'pt_BR', translated: lang.language_pt_br, native: 'Português Brasileiro', }, { value: 'ru-RU', translated: lang.language_ru, native: 'Русский', }, { value: 'sv-SE', translated: lang.language_sv, native: 'Svenska', }, { value: 'tr-TR', translated: lang.language_tr, native: 'Türkçe', }, { value: 'uk-UA', translated: lang.language_uk, native: 'Українська', }, { value: 'vi-VN', translated: lang.language_vi, native: 'Tiếng Việt', },{ value: 'zh-CN', translated: lang.language_zh_cn, native: '简化字', }, { value: 'zh-TW', translated: lang.language_zh_tw, native: '繁體字', }, ]; export default lang;
JavaScript
0.000013
@@ -1928,16 +1928,17 @@ t',%0A %7D, + %7B%0A va
b4f75fd7a6f859affac61eaa97732543cc76a930
Add min:0 to templates of Bookshelf DBs. Issue #8436 (#9155)
packages/strapi-connector-bookshelf/lib/knex.js
packages/strapi-connector-bookshelf/lib/knex.js
'use strict'; /** * Module dependencies */ // Node.js core. const fs = require('fs'); const path = require('path'); // Public node modules. const _ = require('lodash'); /* eslint-disable prefer-template */ // Array of supported clients. const CLIENTS = [ 'pg', 'mysql', 'mysql2', 'sqlite3', 'mariasql', 'oracle', 'strong-oracle', 'mssql', ]; const defaultConfig = { host: 'localhost', charset: 'utf8', }; /** * Knex hook */ module.exports = strapi => { // For each connection in the config register a new Knex connection. _.forEach( _.pickBy(strapi.config.connections, { connector: 'bookshelf', }), (connection, name) => { // Make sure we use the client even if the typo is not the exact one. switch (connection.settings.client) { case 'postgre': case 'postgres': case 'postgresql': connection.settings.client = 'pg'; break; case 'sqlite': connection.settings.client = 'sqlite3'; break; case 'maria': case 'mariadb': connection.settings.client = 'mariasql'; break; case 'ms': connection.settings.client = 'mssql'; break; } // Make sure the client is supported. if (!_.includes(CLIENTS, connection.settings.client)) { strapi.log.error( 'The client `' + connection.settings.client + '` for the `' + name + '` connection is not supported.' ); strapi.stop(); } // Make sure the client is installed in the application // `node_modules` directory. let client; try { client = require(connection.settings.client); } catch (err) { strapi.log.error('The client `' + connection.settings.client + '` is not installed.'); strapi.log.error( 'You can install it with `$ npm install ' + connection.settings.client + ' --save`.' ); strapi.stop(); } const options = _.defaultsDeep( { client: connection.settings.client, connection: { host: _.get(connection.settings, 'host'), user: _.get(connection.settings, 'username') || _.get(connection.settings, 'user'), password: _.get(connection.settings, 'password'), database: _.get(connection.settings, 'database'), charset: _.get(connection.settings, 'charset'), schema: _.get(connection.settings, 'schema', 'public'), port: _.get(connection.settings, 'port'), socketPath: _.get(connection.settings, 'socketPath'), ssl: _.get(connection.settings, 'ssl', false), timezone: _.get(connection.settings, 'timezone', 'utc'), filename: _.get(connection.settings, 'filename', '.tmp/data.db'), }, ...connection.options, debug: _.get(connection.options, 'debug', false), }, strapi.config.hook.settings.knex, defaultConfig ); // Resolve path to the directory containing the database file. const fileDirectory = options.connection.filename ? path.dirname(path.resolve(strapi.config.appPath, options.connection.filename)) : ''; switch (options.client) { case 'mysql': options.connection.supportBigNumbers = true; options.connection.bigNumberStrings = true; options.connection.typeCast = (field, next) => { if (field.type == 'DECIMAL' || field.type === 'NEWDECIMAL') { var value = field.string(); return value === null ? null : Number(value); } if (field.type == 'TINY' && field.length == 1) { let value = field.string(); return value ? value == '1' : null; } return next(); }; break; case 'pg': client.types.setTypeParser(1700, 'text', parseFloat); if (_.isString(_.get(options.connection, 'schema'))) { options.pool = { ...options.pool, afterCreate: (conn, cb) => { conn.query(`SET SESSION SCHEMA '${options.connection.schema}';`, err => { cb(err, conn); }); }, }; } else { delete options.connection.schema; } break; case 'sqlite3': // Create the directory if it does not exist. try { fs.statSync(fileDirectory); } catch (err) { fs.mkdirSync(fileDirectory); } // Force base directory. // Note: it removes the warning logs when starting the administration in development mode. options.connection.filename = path.resolve( strapi.config.appPath, options.connection.filename ); // Disable warn log // .returning() is not supported by sqlite3 and will not have any effect. options.log = { warn: () => {}, }; break; } // Finally, use the client via `knex`. // If anyone has a solution to use different paths for `knex` and clients // please drop us an email at support@strapi.io-- it would avoid the Strapi // applications to have `knex` as a dependency. try { // Try to require from local dependency. const connection = require('knex')(options); _.set(strapi, `connections.${name}`, connection); } catch (err) { strapi.log.error('Impossible to use the `' + name + '` connection...'); strapi.log.warn( 'Be sure that your client `' + name + '` are in the same node_modules directory' ); strapi.log.error(err); strapi.stop(); } } ); };
JavaScript
0
@@ -2964,32 +2964,122 @@ debug', false),%0A + pool: %7B%0A min: _.get(connection.options.pool, 'min', 0),%0A %7D,%0A %7D,%0A
c48d70c30ada817865fc7f62d7d08b9bca2caae9
Add test for cancel option
src/domain/reservation/manage/action/__tests__/ManageReservationsDropdown.test.js
src/domain/reservation/manage/action/__tests__/ManageReservationsDropdown.test.js
import React from 'react'; import toJSON from 'enzyme-to-json'; import { UntranslatedManageReservationsDropdown as ManageReservationsDropdown } from '../ManageReservationsDropdown'; import { shallowWithIntl } from '../../../../../../app/utils/testUtils'; import reservation from '../../../../../common/data/fixtures/reservation'; const findButtonByLabel = (wrapper, label) => wrapper.find({ children: `ManageReservationsList.actionLabel.${label}` }); describe('ManageReservationsDropdown', () => { const defaultProps = { reservation: reservation.build({ state: null }), t: path => path, userCanModify: true, }; const getWrapper = props => shallowWithIntl( <ManageReservationsDropdown {...defaultProps} {...props} />, ); test('renders correctly', () => { expect(toJSON(getWrapper())).toMatchSnapshot(); }); test('show information, edit and cancel buttons', () => { const wrapper = getWrapper(); expect(findButtonByLabel(wrapper, 'information').length).toEqual(1); expect(findButtonByLabel(wrapper, 'edit').length).toEqual(1); }); test('do not show approve, deny and cancel buttons', () => { const wrapper = getWrapper(); expect(findButtonByLabel(wrapper, 'approve').length).toEqual(0); expect(findButtonByLabel(wrapper, 'deny').length).toEqual(0); expect(findButtonByLabel(wrapper, 'cancel').length).toEqual(0); }); describe('when state is requested', () => { const getWrapperInRequestedState = props => getWrapper({ reservation: { ...defaultProps.reservation, state: 'requested' }, ...props, }); test('show approve and deny button', () => { const wrapper = getWrapperInRequestedState(); expect(findButtonByLabel(wrapper, 'approve').length).toEqual(1); expect(findButtonByLabel(wrapper, 'deny').length).toEqual(1); }); }); });
JavaScript
0.000001
@@ -864,25 +864,17 @@ tion -, edit and cancel + and edit but @@ -1835,13 +1835,252 @@ );%0A %7D); +%0A%0A describe('when props.userCanCancel is true', () =%3E %7B%0A test('show cancel button', () =%3E %7B%0A const wrapper = getWrapper(%7B userCanCancel: true %7D);%0A%0A expect(findButtonByLabel(wrapper, 'cancel').length).toEqual(1);%0A %7D);%0A %7D); %0A%7D);%0A
43412f088ab6ef1676eedc2b8770dde79f585f1e
update all examples to gatsby-plugin-mdx; remove old katex patch
packages/gatsby-plugin-mdx/utils/babel-plugin-html-attr-to-jsx-attr.js
packages/gatsby-plugin-mdx/utils/babel-plugin-html-attr-to-jsx-attr.js
const { camelCase } = require("change-case"); const toStyleObject = require("to-style").object; const t = require("@babel/types"); const generate = require("@babel/generator"); var TRANSLATIONS = { class: "className", for: "htmlFor", srcset: "srcSet" }; const valueFromType = value => { switch (typeof value) { case "string": return t.stringLiteral(value); case "number": return t.numericLiteral(value); case "boolean": return t.booleanLiteral(value); default: throw new Error("gatsby-mdx needs to include a new type"); } }; const propsKeysVisitor = { ObjectProperty(node) { if (node.node.key.extra.rawValue in TRANSLATIONS) { node.node.key.value = TRANSLATIONS[node.node.key.value] || node.node.key.value; } } }; var jsxAttributeFromHTMLAttributeVisitor = { JSXAttribute: function(node) { if (node.node.name.name in TRANSLATIONS) { node.node.name.name = TRANSLATIONS[node.node.name.name]; } else if (node.node.name.name === "props") { node.traverse(propsKeysVisitor); } else if ( node.node.name.name.includes("-") && !node.node.name.name.startsWith("data") && !node.node.name.name.startsWith("aria") ) { node.node.name.name = camelCase(node.node.name.name); } if ( node.node.name.name === "style" && node.node.value.type === "StringLiteral" // node.node.value.type !== "JSXExpressionContainer" ) { const styleObject = toStyleObject(node.node.value.extra.rawValue, { camelize: true }); // node.node.value.value = `{${JSON.stringify(styleObject)}}`; node.node.value = t.jSXExpressionContainer( t.objectExpression( Object.entries(styleObject).map(([key, value]) => t.objectProperty(t.StringLiteral(key), valueFromType(value)) ) ) ); } } }; module.exports = function attrs() { return { visitor: { JSXElement: function(path) { path.traverse(jsxAttributeFromHTMLAttributeVisitor); if ( path.node.openingElement.name.name === "annotation" /* && if gatsby-remark-katex is enabled*/ ) { const genCode = path.node.children.map( ast => generate.default(ast).code ); path.node.children = [ t.jSXText( genCode .join("") .replace("{", "&#123;") .replace("}", "&#125;") ) ]; } } } }; };
JavaScript
0
@@ -127,54 +127,8 @@ s%22); -%0Aconst generate = require(%22@babel/generator%22); %0A%0Ava @@ -2012,478 +2012,8 @@ or); -%0A%0A if (%0A path.node.openingElement.name.name ===%0A %22annotation%22 /* && if gatsby-remark-katex is enabled*/%0A ) %7B%0A const genCode = path.node.children.map(%0A ast =%3E generate.default(ast).code%0A );%0A path.node.children = %5B%0A t.jSXText(%0A genCode%0A .join(%22%22)%0A .replace(%22%7B%22, %22&#123;%22)%0A .replace(%22%7D%22, %22&#125;%22)%0A )%0A %5D;%0A %7D %0A
9c753f33b035810a14e73f298836f6caca91f50e
add includeXHRQueryString to config
src/lib/config.js
src/lib/config.js
var utils = require('./utils') var Subscription = require('../common/subscription') function Config () { this.config = {} this.defaults = { opbeatAgentName: 'opbeat-js', VERSION: '%%VERSION%%', apiHost: 'intake.opbeat.com', isInstalled: false, debug: false, logLevel: 'warn', orgId: null, appId: null, angularAppName: null, performance: { browserResponsivenessInterval: 500, browserResponsivenessBuffer: 3, checkBrowserResponsiveness: true, enable: true, enableStackFrames: false, groupSimilarTraces: true, similarTraceThreshold: 0.05, captureInteractions: false, sendVerboseDebugInfo: false }, libraryPathPattern: '(node_modules|bower_components|webpack)', context: {}, platform: {} } this._changeSubscription = new Subscription() } Config.prototype.init = function () { var scriptData = _getConfigFromScript() this.setConfig(scriptData) } Config.prototype.get = function (key) { return utils.arrayReduce(key.split('.'), function (obj, i) { return obj && obj[i] }, this.config) } Config.prototype.set = function (key, value) { var levels = key.split('.') var max_level = levels.length - 1 var target = this.config utils.arraySome(levels, function (level, i) { if (typeof level === 'undefined') { return true } if (i === max_level) { target[level] = value } else { var obj = target[level] || {} target[level] = obj target = obj } }) } Config.prototype.getAgentName = function () { var version = this.config['VERSION'] if (!version || version.indexOf('%%VERSION') >= 0) { version = 'dev' } return this.get('opbeatAgentName') + '/' + version } Config.prototype.setConfig = function (properties) { properties = properties || {} this.config = utils.merge({}, this.defaults, this.config, properties) this._changeSubscription.applyAll(this, [this.config]) } Config.prototype.subscribeToChange = function (fn) { return this._changeSubscription.subscribe(fn) } Config.prototype.isValid = function () { var requiredKeys = ['appId', 'orgId'] var values = utils.arrayMap(requiredKeys, utils.functionBind(function (key) { return (this.config[key] === null) || (this.config[key] === undefined) }, this)) return utils.arrayIndexOf(values, true) === -1 } var _getConfigFromScript = function () { var script = utils.getCurrentScript() var config = _getDataAttributesFromNode(script) return config } function _getDataAttributesFromNode (node) { var dataAttrs = {} var dataRegex = /^data\-([\w\-]+)$/ if (node) { var attrs = node.attributes for (var i = 0; i < attrs.length; i++) { var attr = attrs[i] if (dataRegex.test(attr.nodeName)) { var key = attr.nodeName.match(dataRegex)[1] // camelCase key key = utils.arrayMap(key.split('-'), function (group, index) { return index > 0 ? group.charAt(0).toUpperCase() + group.substring(1) : group }).join('') dataAttrs[key] = attr.value || attr.nodeValue } } } return dataAttrs } Config.prototype.VERSION = '%%VERSION%%' Config.prototype.isPlatformSupported = function () { return typeof Array.prototype.forEach === 'function' && typeof JSON.stringify === 'function' && typeof Function.bind === 'function' && window.performance && typeof window.performance.now === 'function' && utils.isCORSSupported() } module.exports = new Config()
JavaScript
0
@@ -683,16 +683,53 @@ o: false +,%0A includeXHRQueryString: false, %0A %7D,%0A
9af73a5924d5483e40b885555f0f144ec619a91a
Make prettify work if goog for some reason exists but doesn't export provide.
prettify.js
prettify.js
// Copyright 2010 Steven Dee. 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. if (typeof goog != 'undefined') { goog.provide('jsprettify.entities'); goog.provide('jsprettify.prettifyHtml'); goog.provide('jsprettify.prettifyStr'); } var jsprettify = jsprettify || {}; /** * This object contains some common typographical HTML entities. * @type {Object.<string,string>} */ jsprettify.entities = { endash: '\u2013', emdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019', ldquo: '\u201c', rdquo: '\u201d', hellip: '\u2026' }; /** * Prettifies strings by replacing ASCII shorthand with proper typographical * symbols. * @param {string} text Text to prettify. * @return {string} Prettified text. */ jsprettify.prettifyStr = function(text) { var e = jsprettify.entities; /** * This array-of-arrays holds entries consisting of patterns and * substitutions in the order that they are to be applied. We need to * preserve order, since e.g. if -- were replaced before ---, disaster * would ensue. * @type {Array.<Array.<string>>} */ var subs = [ ['\\.\\.\\.', e.hellip], ["(^|[\\s\"])'", '$1' + e.lsquo], ['(^|[\\s-])"', '$1' + e.ldquo], ['---', e.emdash], ['--', e.endash], ["'($|[\\s\"])?", e.rsquo + '$1'], ['"($|[\\s.,;:?!])', e.rdquo + '$1'] ]; for (var i = 0; i < subs.length; i++) { var arr = subs[i]; var re = new RegExp(arr[0], 'g'); var sub = arr[1]; text = text.replace(re, sub); }; return text; }; /** * Prettifies HTML Nodes by recursively prettifying their child text nodes. * This function operates nondestructively -- a prettified HTML fragment is * returned, and can replace the existing one to prettify a document. * @param {Node|null} e Node to start prettifying. * @param {{uglyTags: Array.<string>, uglyClass: string}} opt_args Optional * arguments to customize the behavior of the function. 'uglyTags' is an * array of tagnames not to prettify. 'uglyClass' is a string consisting * of the class not to prettify. * @return {Node|null} Prettified version of the passed node. */ jsprettify.prettifyHtml = function(e, opt_args) { var args = opt_args || {}; var uglyTags = args['uglyTags'] || []; var uglyClass = args['uglyClass'] || ""; var contains = function(arr, obj) { for (var i = 0; i < arr.length; i++) { if (arr[i] == obj) { return true; } } return false; }; if (e == null) { return null; } var ret = e.cloneNode(true); if (e.nodeType == Node.TEXT_NODE) { ret.textContent = jsprettify.prettifyStr(ret.textContent); } else if (! contains(uglyTags, e.nodeName.toLowerCase()) && ! (e.className && e.className == uglyClass)) { var curChildren = ret.childNodes; for (var i = 0; i < curChildren.length; i++) { ret.replaceChild(jsprettify.prettifyHtml(curChildren[i], opt_args), curChildren[i]); } } return ret; }; /** * Auto-prettify everything with classname 'prettify' in a document. This can * be used in e.g. a window.onload function to automatically prettify all text * when the window has loaded. */ window['prettify'] = function() { var es = document.getElementsByClassName('prettify'); var opts = {'uglyTags': ['code', 'pre'], 'uglyClass': 'keepugly'}; for (var i = 0; i < es.length; i++) { var parentNode = es[i].parentNode; parentNode.replaceChild(jsprettify.prettifyHtml(es[i], opts), es[i]); } };
JavaScript
0
@@ -621,16 +621,54 @@ goog != + 'undefined' && typeof goog.provide != 'undefi
b37604166a75fdddad18e0fa60a198b60df7d4a8
use env variable flag for refreshing models from apis
src/models.js
src/models.js
import mongoose from 'mongoose'; import timestamps from 'mongoose-timestamp'; import riotDataLoader from './utils/riotDataLoader'; import lolproDataLoader from './utils/lolproDataLoader'; const db = mongoose.connection; var models = {}; const uristring = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/lolpacks_dev'; db.on('error', console.error); db.once('open', function() { let ChampionSchema = new mongoose.Schema({ riotId: Number, key: String, name: String, image: { w: Number, full: String, sprite: String, group: String, h: Number, y: Number, x: Number }, lolproUri: String }); ChampionSchema.plugin(timestamps); ChampionSchema.index({key: 1}); ChampionSchema.index({name: 1}); let ItemSchema = new mongoose.Schema({ riotId: Number, name: String, description: String, image: { w: Number, full: String, sprite: String, group: String, h: Number, y: Number, x: Number }, gold: { total: Number, purchaseable: Boolean, sell: Number, base: Number }, from: [Number] }); ItemSchema.plugin(timestamps); ItemSchema.index({riotId: 1}); ItemSchema.index({name: 1}); let ChampionGuideSchema = new mongoose.Schema({ name: String, lolproUri: String, views: Number, votes: Number, _championId: mongoose.Schema.Types.ObjectId }); ChampionGuideSchema.plugin(timestamps); ChampionGuideSchema.index({_championId: 1}); ChampionGuideSchema.index({name: 1}); let ItemSetSchema = new mongoose.Schema({ name: String, index: Number, itemNames: [String], _championGuideId: mongoose.Schema.Types.ObjectId }); ItemSetSchema.plugin(timestamps); ItemSetSchema.index({name: 1}); ItemSetSchema.index({_championGuideId: 1}); models.Champion = mongoose.model('Champion', ChampionSchema); models.Item = mongoose.model('Item', ItemSchema); models.ChampionGuide = mongoose.model('ChampionGuide', ChampionGuideSchema); models.ItemSet = mongoose.model('ItemSet', ItemSetSchema); //riotDataLoader.loadChampions().then(lolproDataLoader.updateChampions) //riotDataLoader.loadItems(); // Create your schemas and models here. }); mongoose.connect(uristring); export default models;
JavaScript
0
@@ -2131,18 +2131,65 @@ ma);%0A%0A -// +if (process.env.REFRESH_MODELS === 'true') %7B%0A riotData @@ -2211,16 +2211,23 @@ pions(). +%0A then(lol @@ -2259,14 +2259,329 @@ ions -)%0A // +()).%0A then(lolproDataLoader.updateChampionGuides()).%0A then(() =%3E %7B%0A models.ChampionGuide.find((err, guides) =%3E %7B%0A guides.forEach((guide) =%3E %7B%0A setTimeout(() =%3E %7B%0A lolproDataLoader.updateChampionBuild(guide);%0A %7D, 2000);%0A %7D);%0A %7D);%0A %7D);%0A%0A riot @@ -2604,16 +2604,21 @@ tems();%0A + %7D%0A%0A // Cre
c229f31e1936a8ab675e58b603d0cd69f917f078
check for log directory prior to adding rolling log appender
lib/controllers/AbstractApplicationFactory.js
lib/controllers/AbstractApplicationFactory.js
/** * @class AbstractApplicationFactory * * @author: darryl.west@roundpeg.com * @created: 8/10/14 4:12 PM */ var dash = require('lodash' ), CommonValidator = require( '../delegates/CommonValidator' ), MiddlewareDelegate = require( '../delegates/MiddlewareDelegate' ), bodyParser = require('body-parser' ), AbstractServiceFactory = require( './AbstractServiceFactory' ); var AbstractApplicationFactory = function(options) { 'use strict'; if (!options) options = {}; var factory = this, config = options, logManager = options.logManager, log = options.log, services = [], middlewareDelegate = options.middlewareDelegate, validator = options.validator; /** * create a logger for the specific category, i.e., class * * @param name - the category name, usually the class name * @param level - the designated log level, defaults to info * @returns the logger */ this.createLogger = function(name, level) { if (!logManager) { var Manager = require('simple-node-logger'); if (typeof config.readLoggerConfig === 'function') { var opts = config.readLoggerConfig(); logManager = new Manager( opts ); logManager.createRollingAppender( opts ); } else { logManager = new Manager( config ); logManager.createConsoleAppender( config ); } } return logManager.createLogger( name, level ); }; /** * create and return the middleware delegate; will only create a single instance * * @returns the delegate */ this.createMiddlewareDelegate = function() { if (!middlewareDelegate) { log.info('create MiddlewareDelegate'); var opts = dash.clone( config ); opts.log = factory.createLogger( 'MiddlewareDelegate' ); middlewareDelegate = new MiddlewareDelegate( opts ); } return middlewareDelegate; }; /** * create and return the common validator */ this.createCommonValidator = function() { if (!validator) { log.info("create common validator"); var opts = dash.clone( config ); opts.log = factory.createLogger( 'CommonValidator' ); validator = new CommonValidator( opts ); } return validator; }; /** * add the service */ this.addService = function(service) { if (!service.hasOwnProperty( 'serviceName' )) { throw new Error('Attempt to add a service without a serviceName property'); } var svc = factory.findService( service.serviceName ); if (!svc) { services.push( service ); } }; /** * find the service by name * * @param name the service name as defined by service.serviceName * @returns if found, the service, else null */ this.findService = function(name) { var list = services.filter(function(svc) { return svc.serviceName === name; }); if (list.length === 1) { return list[0]; } else { return null; } }; /** * return the services collection * @returns services */ this.getServices = function() { return services; }; /** * return the configuration */ this.getConfiguration = function() { return config; }; this.createWebServices = function(serviceFactory, list) { if (!serviceFactory) serviceFactory = factory; list.forEach(function(name) { var service = factory.findService( name ); if (!service) { var closure = 'create' + name; log.info('invoking: ', closure); if (factory.hasOwnProperty( closure )) { service = factory[ closure ].call(); } else { service = serviceFactory[ closure ].call(); } factory.addService( service ); } }); log.info('service count: ', factory.getServices().length); return factory.getServices(); }; /** * initialize the app defaults * * @param app - an express or express like object */ this.initAppDefaults = function(app) { log.info('init default trust and x-powered-by values'); app.enable('trust proxy'); app.disable('x-powered-by'); }; /** * initialize the standard middleware. if the delegate is missing, then create; if * the list is missing then pull the list from the middleware public methods * * @param app - an express or express like object * @param middleware - the optional middleware delegate * @param list - an optional list of middleware functions */ this.initMiddleware = function(app, middleware, list) { log.info('create the standard middleware'); if (!middleware) { middleware = factory.createMiddlewareDelegate(); } if (!list) { list = dash.methods( middleware ); } list.forEach(function(method) { // add the middleware, or die trying app.use( middleware[ method ] ); }); // always enable the json body parser app.use( bodyParser.json() ); }; /** * iterate over all services and add all routes to the app object * * @param app - an express or compatible app */ this.assignRoutes = function(app) { log.info('assign routes to the application'); services.forEach(function(service) { log.info('add routes for ', service.serviceName); service.routes.forEach(function(route) { var fullPath = factory.createRoutePath( config.baseURI, route.path ); log.info('route path: ', fullPath, ', method: ', route.method ); app[ route.method ]( fullPath, route.fn ); }); }); }; /** * create a full route path given base and service paths * * @param basePath - the path for the primary service, e.g. MyPrimaryService or /MyPrimaryService/ (no scheme) * @param servicePath - the path for the specific service, e.g, /user or /admin */ this.createRoutePath = function(basePath, servicePath) { // check for base and service return [ basePath.replace(/\/+$/, ''), servicePath.replace(/^\/+/, '') ].join('/'); }; // create the factory log log = factory.createLogger('AbstractApplicationFactory'); }; /** * extend the public methods of this abstract class to a child class. create the * parent object using options passed from the child class. * * Typical use: * * var parent = AbstractApplicationFactory.extend( this, options ); * * @param child * @param options * @returns parent object */ AbstractApplicationFactory.extend = function(child, options) { 'use strict'; var parent = new AbstractApplicationFactory( options ); dash.extend( child, parent ); return parent; }; module.exports = AbstractApplicationFactory;
JavaScript
0
@@ -1268,24 +1268,146 @@ r( opts );%0A%0A + // auto-config with rolling appender%0A if (opts.logDirectory && opts.fileNamePattern) %7B%0A @@ -1444,32 +1444,50 @@ pender( opts );%0A + %7D%0A %7D el
6c8e75c0fdd9ebb48b0e874abc89e0032cc762cd
Update namespace
lib/node_modules/@stdlib/ndarray/lib/index.js
lib/node_modules/@stdlib/ndarray/lib/index.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'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace ns */ var ns = {}; /** * @name array * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/array} */ setReadOnly( ns, 'array', require( '@stdlib/ndarray/array' ) ); /** * @name base * @memberof ns * @readonly * @type {Namespace} * @see {@link module:@stdlib/ndarray/base} */ setReadOnly( ns, 'base', require( '@stdlib/ndarray/base' ) ); /** * @name ndarrayCastingModes * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/casting-modes} */ setReadOnly( ns, 'ndarrayCastingModes', require( '@stdlib/ndarray/casting-modes' ) ); /** * @name ndarray * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/ctor} */ setReadOnly( ns, 'ndarray', require( '@stdlib/ndarray/ctor' ) ); /** * @name ndarrayDataTypes * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/dtypes} */ setReadOnly( ns, 'ndarrayDataTypes', require( '@stdlib/ndarray/dtypes' ) ); /** * @name ind2sub * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/ind2sub} */ setReadOnly( ns, 'ind2sub', require( '@stdlib/ndarray/ind2sub' ) ); /** * @name ndarrayIndexModes * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/index-modes} */ setReadOnly( ns, 'ndarrayIndexModes', require( '@stdlib/ndarray/index-modes' ) ); /** * @name ndarrayMinDataType * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/min-dtype} */ setReadOnly( ns, 'ndarrayMinDataType', require( '@stdlib/ndarray/min-dtype' ) ); /** * @name ndarrayNextDataType * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/next-dtype} */ setReadOnly( ns, 'ndarrayNextDataType', require( '@stdlib/ndarray/next-dtype' ) ); /** * @name ndarrayOrders * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/orders} */ setReadOnly( ns, 'ndarrayOrders', require( '@stdlib/ndarray/orders' ) ); /** * @name ndarrayPromotionRules * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/promotion-rules} */ setReadOnly( ns, 'ndarrayPromotionRules', require( '@stdlib/ndarray/promotion-rules' ) ); /** * @name ndarraySafeCasts * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/safe-casts} */ setReadOnly( ns, 'ndarraySafeCasts', require( '@stdlib/ndarray/safe-casts' ) ); /** * @name ndarraySameKindCasts * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/same-kind-casts} */ setReadOnly( ns, 'ndarraySameKindCasts', require( '@stdlib/ndarray/same-kind-casts' ) ); /** * @name sub2ind * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/sub2ind} */ setReadOnly( ns, 'sub2ind', require( '@stdlib/ndarray/sub2ind' ) ); /** * @name ndzeros * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/zeros} */ setReadOnly( ns, 'ndzeros', require( '@stdlib/ndarray/zeros' ) ); /** * @name ndzerosLike * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/ndarray/zeros-like} */ setReadOnly( ns, 'ndzerosLike', require( '@stdlib/ndarray/zeros-like' ) ); // EXPORTS // module.exports = ns;
JavaScript
0.000001
@@ -1850,32 +1850,238 @@ y/dtypes' ) );%0A%0A +/**%0A* @name scalar2ndarray%0A* @memberof ns%0A* @readonly%0A* @type %7BFunction%7D%0A* @see %7B@link module:@stdlib/ndarray/from-scalar%7D%0A*/%0AsetReadOnly( ns, 'scalar2ndarray', require( '@stdlib/ndarray/from-scalar' ) );%0A%0A /**%0A* @name ind2
bba1a1d0bd1bee6c213a22c51ddeafdc14955b6a
Use of _routerMicrolib.currentRouteInfos if available (#88)
addon/helpers/route-action.js
addon/helpers/route-action.js
import { A as emberArray } from '@ember/array'; import Helper from '@ember/component/helper'; import { get, computed } from '@ember/object'; import { getOwner } from '@ember/application'; import { run } from '@ember/runloop'; import { runInDebug, assert } from '@ember/debug'; import { ACTION } from '../-private/internals'; function getCurrentHandlerInfos(router) { let routerLib = router._routerMicrolib || router.router; return routerLib.currentHandlerInfos; } function getRoutes(router) { return emberArray(getCurrentHandlerInfos(router)) .mapBy('handler') .reverse(); } function getRouteWithAction(router, actionName) { let action; let handler = emberArray(getRoutes(router)).find((route) => { let actions = route.actions || route._actions; action = actions[actionName]; return typeof(action) === 'function'; }); return { action, handler }; } export default Helper.extend({ router: computed(function() { return getOwner(this).lookup('router:main'); }).readOnly(), compute([actionName, ...params]) { let router = get(this, 'router'); assert('[ember-route-action-helper] Unable to lookup router', router); runInDebug(() => { let { handler } = getRouteWithAction(router, actionName); assert(`[ember-route-action-helper] Unable to find action ${actionName}`, handler); }); let routeAction = function(...invocationArgs) { let { action, handler } = getRouteWithAction(router, actionName); let args = params.concat(invocationArgs); return run.join(handler, action, ...args); }; routeAction[ACTION] = true; return routeAction; } });
JavaScript
0
@@ -330,39 +330,32 @@ ction getCurrent -Handler Infos(router) %7B%0A @@ -427,38 +427,156 @@ urn -routerLib.currentHandlerInfos; +%7B%0A currentInfos: routerLib.currentRouteInfos %7C%7C routerLib.currentHandlerInfos,%0A mapBy: routerLib.currentRouteInfos && 'route' %7C%7C 'handler'%0A %7D %0A%7D%0A%0A @@ -610,26 +610,40 @@ %7B%0A -return emberArray( +const %7B currentInfos, mapBy %7D = getC @@ -644,31 +644,24 @@ = getCurrent -Handler Infos(router @@ -661,16 +661,50 @@ (router) +;%0A return emberArray(currentInfos )%0A .m @@ -708,25 +708,21 @@ .mapBy( -'handler' +mapBy )%0A .r
afa4decb6591e4292e0c979156c7fc4c4f866592
Fix JSCS
addon/mixins/offline-model.js
addon/mixins/offline-model.js
/** @module ember-flexberry-data */ import Ember from 'ember'; import DS from 'ember-data'; import AuditModelMixin from './audit-model'; /** Mixin for Ember models. Adds metadata properties that can be used to resolve synchronization conflicts. Creation and changing date and time of record will be filled with current date and time on model saving. It's recommended to use this mixin when model class extends subclass of [DS.Model](http://emberjs.com/api/data/classes/DS.Model.html) or includes other mixins, i.e. it's not inherited directly from [DS.Model](http://emberjs.com/api/data/classes/DS.Model.html). Also it can be used explicitly when it is not necessary to use projections for particular model in application. If model class inherited directly from [DS.Model](http://emberjs.com/api/data/classes/DS.Model.html) and it's planned to use projections, then it's recommended to extend model class from {{#crossLink "Offline.Model"}}{{/crossLink}}. @class ModelMixin @namespace Offline @extends <a href="http://emberjs.com/api/classes/Ember.Mixin.html">Ember.Mixin</a> @public */ export default Ember.Mixin.create({ /** Date and time of last sync down of model. @property syncDownTime @type Date */ syncDownTime: DS.attr('date'), /** Flag to indicate that model synchronized in readonly mode. Readonly mode allows to prevent any modifications of model on client side or server side. @property readOnly @type Boolean @readOnly */ readOnly: DS.attr('boolean'), /** Global instance of Syncer that contains methods to sync model up and down. @property syncer @type Syncer @readOnly */ syncer: Ember.inject.service('syncer'), /** Save the record and persist any changes to the record to an external source via the adapter. [More info](http://emberjs.com/api/data/classes/DS.Model.html#method_save). @method save @param {Object} [options] @return {Promise} */ save() { let _this = this; let __super = _this._super; return new Ember.RSVP.Promise((resolve, reject) => { if (_this.get('readOnly')) { reject(new Error('Attempt to save readonly model instance.')); } else if (_this.get('hasDirtyAttributes') && !_this.get('offlineGlobals.isOnline')) { _this.get('syncer').createJob(_this).then((auditEntity) => { __super.call(_this, ...arguments).then((record) => { if (!auditEntity.get('objectPrimaryKey')) { auditEntity.set('objectPrimaryKey', record.get('id')); auditEntity.save().then(() => { resolve(record); }); } else { resolve(record); } }).catch((reason) => { auditEntity.destroyRecord().then(() => { reject(reason); }) }); }).catch((reason) => { reject(reason); }); } else { resolve(__super.call(_this, ...arguments)); } }); }, }, AuditModelMixin);
JavaScript
0.000223
@@ -2851,16 +2851,17 @@ %7D) +; %0A
c82058ad57dfdab0e8e2505b6f44d7e33398ffb2
add the word "safely" to clarify
src/ng/log.js
src/ng/log.js
'use strict'; /** * @ngdoc object * @name ng.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * The default is not to log `debug` messages. You can use * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. * * @example <example> <file name="script.js"> function LogCtrl($scope, $log) { $scope.$log = $log; $scope.message = 'Hello World!'; } </file> <file name="index.html"> <div ng-controller="LogCtrl"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> </div> </file> </example> */ /** * @ngdoc object * @name ng.$logProvider * @description * Use the `$logProvider` to configure how the application logs messages */ function $LogProvider(){ var debug = true, self = this; /** * @ngdoc property * @name ng.$logProvider#debugEnabled * @methodOf ng.$logProvider * @description * @param {string=} flag enable or disable debug level messages * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.debugEnabled = function(flag) { if (isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = ['$window', function($window){ return { /** * @ngdoc method * @name ng.$log#log * @methodOf ng.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name ng.$log#info * @methodOf ng.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name ng.$log#warn * @methodOf ng.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name ng.$log#error * @methodOf ng.$log * * @description * Write an error message */ error: consoleLog('error'), /** * @ngdoc method * @name ng.$log#debug * @methodOf ng.$log * * @description * Write a debug message */ debug: (function () { var fn = consoleLog('debug'); return function() { if (debug) { fn.apply(self, arguments); } }; }()) }; function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } function consoleLog(type) { var console = $window.console || {}, logFn = console[type] || console.log || noop; if (logFn.apply) { return function() { var args = []; forEach(arguments, function(arg) { args.push(formatError(arg)); }); return logFn.apply(console, args); }; } // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { logFn(arg1, arg2 == null ? '' : arg2); }; } }]; }
JavaScript
0.999463
@@ -140,16 +140,23 @@ ntation +safely writes t
7610e55781b541498407ee64bd45921ed29e3d98
Support no model
logology-v12/src/www/js/app/views/MenuView.js
logology-v12/src/www/js/app/views/MenuView.js
/* @flow */ "use strict"; import scrollContainer from "$WIDGETS/scrollContainer"; import View from "$LIB/View"; import glyph from "$WIDGETS/glyph"; import list from "$WIDGETS/list"; import listItem from "$WIDGETS/listItem"; import listItemContents from "$WIDGETS/listItemContents"; import listItemActions from "$WIDGETS/listItemActions"; import listItemSpacer from "$WIDGETS/listItemSpacer"; import listHeading from "$WIDGETS/listHeading"; import listIndicator from "$WIDGETS/listIndicator"; import h from "yasmf-h"; import L from "$APP/localization/localization"; import GCS from "$LIB/grandCentralStation"; import dictionariesList from "./dictionariesList"; const kp = require("keypather")(); export default class MenuView extends View { get TARGET_SELECTORS() { return [ {selector: "tap:ul li > button:not([value^='APP:'])", emit: "dictionaryItemTapped"}, {selector: "tap:ul li > button[value^='APP:']", emit: "navItemTapped"} ]; } get MENU_ITEMS() { return [ {label: "nav:get-more-dictionaries", emit: "APP:DO:moreDictionaries"}, {label: "nav:readability", emit:"APP:DO:readability"}, {label: "nav:settings", emit:"APP:DO:settings"}, {label: "nav:about", emit:"APP:DO:about"}]; } template() { const model = kp.get(this, "controller.model"); // get the dictionary list model // return a list of all the available dictionaries along with options for downloading // more and changing settings. return scrollContainer({contents: list({ contents: dictionariesList(model).concat( listItemSpacer(), this.MENU_ITEMS.map(item => { return listItem({ contents: listItemContents({ props: { value: item.emit }, contents: [ h.el("div.y-flex",L.T(item.label) ) ] }) }); })) }) }); } onDictionaryItemTapped(sender: Object, notice: string, listItem: Node) { GCS.emit("APP:DO:viewDictionary",listItem.value); // select another dictionary GCS.emit("APP:DO:menu"); // close the sidebar } onNavItemTapped(sender: Object, notice: string, listItem: Node) { GCS.emit(listItem.value); // notify the app that it needs to navigate GCS.emit("APP:DO:menu"); // close the sidebar } } export function createMenuView(options = {}) { return new MenuView(options); }
JavaScript
0
@@ -1322,20 +1322,18 @@ -cons +le t model @@ -1401,16 +1401,66 @@ t model%0A + if (!model) %7Bmodel = %7Bdictionaries: %5B%5D%7D%7D;%0A @@ -2598,32 +2598,34 @@ avigate%0A +// GCS.emit(%22APP:DO
d019e3c39d84dcb9037ad804a2c87fddcbb5c972
Fix LiveQuery#willDestroy
addon/-private/live-query.js
addon/-private/live-query.js
import Ember from 'ember'; import ReadOnlyArrayProxy from './system/read-only-array-proxy'; const { get, set, computed, isArray } = Ember; export default ReadOnlyArrayProxy.extend({ _sourceCache: null, _query: null, _identityMap: null, _content: null, init(...args) { this._super(...args); this._sourceCache.on('patch', this.invalidate, this); this._sourceCache.on('reset', this.invalidate, this); }, willDestroy() { this._super(...args); this._sourceCache.off('patch', this.invalidate, this); this._sourceCache.off('reset', this.invalidate, this); }, invalidate() { set(this, '_content', null); }, content: computed('_content', { get() { if (get(this, '_content') === null) { let results = this._sourceCache.query(this._query); let content; if (isArray(results)) { content = results.map(r => this._identityMap.lookup(r)) } else if (typeof results === 'object') { content = Object.keys(results).map(r => this._identityMap.lookup(results[r])) } set(this, '_content', content); } return this._content; } }) });
JavaScript
0
@@ -436,16 +436,23 @@ Destroy( +...args ) %7B%0A
630089d54920bf6c6d40e3349ec1efe902ac213a
Remove useless import
addon/utils/truth-convert.js
addon/utils/truth-convert.js
import { isArray } from '@ember/array'; import { get } from '@ember/object'; export default function truthConvert(result) { const truthy = result && result.isTruthy; if (typeof truthy === 'boolean') { return truthy; } if (isArray(result)) { return result.length !== 0; } else { return !!result; } }
JavaScript
0.000004
@@ -36,45 +36,8 @@ ay'; -%0Aimport %7B get %7D from '@ember/object'; %0A%0Aex
aebebb66a674a86ff0a481848e8caf5cc2439f9b
Update store_shard_info_MOD.js (#627)
actions/store_shard_info_MOD.js
actions/store_shard_info_MOD.js
module.exports = { name: 'Store Shard Info', section: 'Bot Client Control', subtitle (data) { const info = ['Total Count of Servers (in All Shards)', 'Total Count of Members (in All Shards)', 'Shard\'s Ping (On The Current Server)', 'Shard\'s ID (On The Current Server)', 'Total Number of Servers (in Current Server\'s Shard)', 'Total Count of Members (in Current Server\'s Shard)', 'Total Server\'s List (On The Current Server\'s Shard)'] return `Shard - ${info[parseInt(data.info)]}` }, variableStorage (data, varType) { if (parseInt(data.storage) !== varType) return return ([data.varName2, 'Number']) }, fields: ['info', 'storage', 'varName2'], html (isEvent, data) { return ` <div style="float: left; width: 80%; padding-top: 8px;"> Source Info:<br> <select id="info" class="round"> <option value="0">Total Count of Servers (in All Shards)</option> <option value="1">Total Count of Members (in All Shards)</option> <option value="2">Shard's Ping (On The Current Server)</option> <option value="3">Shard's ID (On The Current Server)</option> <option value="4">Total Number of Servers (in Current Server's Shard)</option> <option value="5">Total Count of Members (in Current Server's Shard)</option> <option value="6">Total Server's List (On The Current Server's Shard)</option> </select> </div><br><br><br> <div> <div style="float: left; width: 35%; padding-top: 8px;"> Store In:<br> <select id="storage" class="round"> ${data.variables[1]} </select> </div> <div id="varNameContainer2" style="float: right; width: 60%; padding-top: 8px;"> Variable Name:<br> <input id="varName2" class="round" type="text"><br> </div> </div>` }, init () {}, action (cache) { const client = this.getDBM().Bot.bot const data = cache.actions[cache.index] const info = parseInt(data.info) client.shard.fetchClientValues('guilds.cache.size') .then((r) => { const shardGuildCount = r.reduce((p, c) => p + c, 0) client.shard.broadcastEval('this.guilds.cache.reduce((p, g) => prev + g.memberCount, 0)') .then((r) => { const shardMemberCount = r.reduce((p, c) => p + c, 0) const shardIDs = client.shard.ids const shardID = Number(shardIDs) + 1 if (!client) { this.callNextAction(cache) return } let result switch (info) { case 0: // Total Count of Servers in All Shards result = shardGuildCount break case 1: // Total Count of Members in All Shards result = shardMemberCount break case 2: // Shard's Ping On The Current Server result = client.shard.client.ws.ping break case 3: // Shard's ID On The Current Server result = shardID break case 4: // Total Count of Servers in Current Server's Shard result = client.guilds.cache.size break case 5: // Total Count of Members in Current Server's Shard result = client.guilds.cache.array()[0].memberCount break case 6: // Total Server's List On The Current Server's Shard result = client.shard.client.guilds.cache.array() break default: break } if (result !== undefined) { const storage = parseInt(data.storage) const varName2 = this.evalMessage(data.varName2, cache) this.storeValue(result, storage, varName2, cache) } this.callNextAction(cache) }) }) }, mod () {} }
JavaScript
0
@@ -2163,11 +2163,8 @@ =%3E p -rev + g
40d591a2aa057a6ad8121aa0019282d81f1b00a0
fix win devtools and async ready Inspired in https://github.com/electron-react-boilerplate/electron-react-boilerplate/blob/cd786e4580e52cfd596dfb9d36be7e23f6ce88df/app/main.dev.js , fixes errors on win
src/main/index.js
src/main/index.js
import path from 'path'; import { app, Menu } from 'electron'; import { autoUpdater } from 'electron-updater'; import electronDebug from 'electron-debug'; import createWindow from './helpers/window'; import { migrateSettings } from './migrate-settings'; import tray from './tray'; import getMenu from './get-menu'; import installExtension, { REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS } from 'electron-devtools-installer'; const settings = require('electron-settings'); require('electron-dl')({saveAs: true}); migrateSettings(); if (process.env.NAME === 'development') { electronDebug({enabled: true}); } if (!process.env.NAME) { autoUpdater.checkForUpdatesAndNotify(); } require('electron-context-menu')(); let mainWindow; let isQuitting = false; const isAlreadyRunning = app.makeSingleInstance(() => { if (mainWindow) { if (mainWindow.isMinimized()) { mainWindow.restore(); } mainWindow.show(); } }); if (isAlreadyRunning) { app.exit(); } function createMainWindow() { if (process.argv.indexOf('test') !== -1) { try { settings.deleteAll(); } catch (error) { // eslint-disable-next-line no-console console.log(error); } } const isDarkMode = settings.get('darkMode'); const win = new createWindow('main', { title: app.getName(), show: false, width: 1300, height: 850, icon: process.platform === 'linux' && path.join(__dirname, 'images/Icon.png'), minWidth: 1000, minHeight: 700, alwaysOnTop: settings.get('alwaysOnTop'), titleBarStyle: 'hiddenInset', autoHideMenuBar: true, darkTheme: isDarkMode, // GTK+3 //backgroundColor: isDarkMode ? '#192633' : '#fff', webPreferences: { preload: './renderer.js', nodeIntegration: true, plugins: true } }); if (process.platform === 'darwin') { win.setSheetOffset(40); } const url = process.env.NAME === 'development' ? 'http://localhost:8080' : 'file://'.concat(__dirname, '/index.html'); win.loadURL(url); win.on('close', e => { if (!isQuitting) { e.preventDefault(); if (process.platform === 'darwin') { app.hide(); } else { win.hide(); } } }); return win; } app.on('ready', () => { if (process.env.NAME === 'development') { /* eslint-disable no-console */ [REDUX_DEVTOOLS, REACT_DEVELOPER_TOOLS] .forEach(extension => installExtension(extension) .then((name) => console.log(`Added Extension: ${name}`)) .catch((err) => console.log('An error occurred: ', err)) ); /* eslint-enable no-console */ } Menu.setApplicationMenu(getMenu()); mainWindow = createMainWindow(); tray.create(mainWindow); const page = mainWindow.webContents; const argv = require('minimist')(process.argv.slice(1)); page.on('dom-ready', () => { if (argv.minimize) { mainWindow.minimize(); } else { mainWindow.show(); } if (process.env.NAME === 'development') { mainWindow.openDevTools(); } }); }); app.on('activate', () => { mainWindow.show(); }); app.on('before-quit', () => { isQuitting = true; });
JavaScript
0.000001
@@ -312,80 +312,165 @@ u';%0A -import installExtension, %7B REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS %7D from +%0Aconst settings = require('electron-settings');%0Arequire('electron-dl')(%7BsaveAs: true%7D);%0A%0Aconst installExtensions = async () =%3E %7B%0A const installer = require( 'ele @@ -498,97 +498,242 @@ ler' +) ;%0A -%0A + const -settings = require('electron-settings');%0A%0Arequire('electron-dl')(%7BsaveAs: true%7D) +forceDownload = !!process.env.UPGRADE_EXTENSIONS;%0A const extensions = %5B'REACT_DEVELOPER_TOOLS', 'REDUX_DEVTOOLS'%5D;%0A%0A return Promise.all(%0A extensions.map(name =%3E installer.default(installer%5Bname%5D, forceDownload))%0A );%0A%7D ;%0A%0Am @@ -2455,24 +2455,30 @@ .on('ready', + async () =%3E %7B%0A i @@ -2470,24 +2470,24 @@ ync () =%3E %7B%0A - if (proces @@ -2562,253 +2562,32 @@ -%5BREDUX_DEVTOOLS, REACT_DEVELOPER_TOOLS%5D%0A .forEach(extension =%3E%0A installExtension(extension)%0A .then((name) =%3E console.log(%60Added Extension: $%7Bname%7D%60))%0A .catch((err) =%3E console.log('An error occurred: ', err))%0A +await installExtensions( );%0A
9ee5e4c70e347492d248bcdb3588d2d7b97bd23a
Optional change encode and decode functions
angular-cookie.js
angular-cookie.js
/* * Copyright 2013 Ivan Pusic * Contributors: * Matjaz Lipus */ angular.module('ivpusic.cookie', ['ipCookie']); angular.module('ipCookie', ['ng']). factory('ipCookie', ['$document', function ($document) { 'use strict'; function tryDecodeURIComponent(value) { try { return decodeURIComponent(value); } catch(e) { // Ignore any invalid uri component } } return (function () { function cookieFun(key, value, options) { var cookies, list, i, cookie, pos, name, hasCookies, all, expiresFor; options = options || {}; if (value !== undefined) { // we are setting value value = typeof value === 'object' ? JSON.stringify(value) : String(value); if (typeof options.expires === 'number') { expiresFor = options.expires; options.expires = new Date(); // Trying to delete a cookie; set a date far in the past if (expiresFor === -1) { options.expires = new Date('Thu, 01 Jan 1970 00:00:00 GMT'); // A new } else if (options.expirationUnit !== undefined) { if (options.expirationUnit === 'hours') { options.expires.setHours(options.expires.getHours() + expiresFor); } else if (options.expirationUnit === 'minutes') { options.expires.setMinutes(options.expires.getMinutes() + expiresFor); } else if (options.expirationUnit === 'seconds') { options.expires.setSeconds(options.expires.getSeconds() + expiresFor); } else { options.expires.setDate(options.expires.getDate() + expiresFor); } } else { options.expires.setDate(options.expires.getDate() + expiresFor); } } return ($document[0].cookie = [ encodeURIComponent(key), '=', encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } list = []; all = $document[0].cookie; if (all) { list = all.split('; '); } cookies = {}; hasCookies = false; for (i = 0; i < list.length; ++i) { if (list[i]) { cookie = list[i]; pos = cookie.indexOf('='); name = cookie.substring(0, pos); value = tryDecodeURIComponent(cookie.substring(pos + 1)); if(angular.isUndefined(value)) continue; if (key === undefined || key === name) { try { cookies[name] = JSON.parse(value); } catch (e) { cookies[name] = value; } if (key === name) { return cookies[name]; } hasCookies = true; } } } if (hasCookies && key === undefined) { return cookies; } } cookieFun.remove = function (key, options) { var hasCookie = cookieFun(key) !== undefined; if (hasCookie) { if (!options) { options = {}; } options.expires = -1; cookieFun(key, '', options); } return hasCookie; }; return cookieFun; }()); } ]);
JavaScript
0.999999
@@ -690,16 +690,131 @@ s %7C%7C %7B%7D; +%0A var dec = options.decode %7C%7C tryDecodeURIComponent;%0A var enc = options.encode %7C%7C encodeURIComponent; %0A%0A @@ -2113,31 +2113,16 @@ enc -odeURIComponent (key),%0A @@ -2152,31 +2152,16 @@ enc -odeURIComponent (value), @@ -2815,37 +2815,19 @@ value = -tryDecodeURIComponent +dec (cookie.
9eb2b5de7e79ba2e255bb9f221b6107c34728176
Remove old fix
angular.hammer.js
angular.hammer.js
(function (window, angular, Hammer) { 'use strict'; // ---- Default Hammer Directive Definitions ---- var gestureTypes = [ 'hmPan:pan', 'hmPanstart:panstart', 'hmPanmove:panmove', 'hmPanend:panend', 'hmPancancel:pancancel', 'hmPanleft:panleft', 'hmPanright:panright', 'hmPanup:panup', 'hmPandown:pandown', 'hmPinch:pinch', 'hmPinchstart:pinchstart', 'hmPinchmove:pinchmove', 'hmPinchend:pinchend', 'hmPinchcancel:pinchcancel', 'hmPinchin:pinchin', 'hmPinchout:pinchout', 'hmPress:press', 'hmRotate:rotate', 'hmRotatestart:rotatestart', 'hmRotatemove:rotatemove', 'hmRotateend:rotateend', 'hmRotatecancel:rotatecancel', 'hmSwipe:swipe', 'hmSwipeleft:swipeleft', 'hmSwiperight:swiperight', 'hmSwipeup:swipeup', 'hmSwipedown:swipedown', 'hmTap:tap', 'hmDoubletap:doubletap' ]; // ---- Module Definition ---- /** * @ngInject */ angular.module('hmTouchEvents', []) .directive('hmCustom', hammerCustomDirective); angular.forEach(gestureTypes, function (type) { var directive = type.split(':'), directiveName = directive[0], eventName = directive[1]; /** * @ngInject */ angular.module('hmTouchEvents') .directive(directiveName, ['$parse', '$window', function ($parse, $window) { return { 'restrict' : 'A', 'link' : function (scope, element, attrs) { var handlerName = attrs[directiveName], handlerExpr = $parse(handlerName), handler = function (event) { var phase = scope.$root.$$phase, fn = function () { handlerExpr(scope, {$event: event}); }; if (scope[handlerName]) { scope[handlerName](event); } else { if (phase === '$apply' || phase === '$digest') { fn(); } else { scope.$apply(fn); } } }, opts = angular.fromJson(attrs.hmOptions), hammer = element.data('hammer'); if (!Hammer || !$window.addEventListener) { if (directiveName === 'hmTap') { element.bind('click', handler); } if (directiveName === 'hmDoubleTap') { element.bind('dblclick', handler); } return; } if (!hammer) { hammer = new Hammer(element[0], opts); element.data('hammer', hammer); } hammer.on(eventName, handler); scope.$on('$destroy', function () { hammer.off(eventName, handler); }); } }; }]); }); // ---- Hammer Custom Recognizer Directive Implementation ---- function hammerCustomDirective ($parse) { return { 'restrict' : 'A', 'link' : function (scope, element, attrs) { var apply = scope.safeApply || scope.$apply, hammer = element.data('hammer'), opts = angular.fromJson(attrs.hmOptions), recognizerList = angular.fromJson(attrs.hmCustom); if (!hammer) { hammer = new Hammer.Manager(element[0], opts); element.data('hammer', hammer); } angular.forEach(recognizerList, function (options) { var expression, handler, recognizer; if (options.directions) { options.directions = parseDirections(options.directions); } recognizer = hammer.get(options.event); if (recognizer) { recognizer.set(options); } else { addRecognizer(hammer, options); } if (options.recognizeWith) { recognizer.recognizeWith(options.recognizeWith); } if (options.requireFailure) { recognizer.requireFailure(options.requireFailure); } expression = $parse(options.val); handler = function (event) { var phase = scope.$root.$$phase, fn = function () { expression(scope, {$event: event}); }; if (scope[options.val]) { scope[options.val](event); } else { if (phase === '$apply' || phase === '$digest') { fn(); } else { scope.$apply(fn); } } }; hammer.on(options.event, handler); scope.$on('$destroy', function () { hammer.off(options.event, handler); }); }); } }; } hammerCustomDirective.$inject = ['$parse']; // ---- Private Functions ----- function addRecognizer (manager, options) { var recognizer; if (options && options.type && options.event) { if (options.type === 'pan') { recognizer = new Hammer.Pan(options); } if (options.type === 'pinch') { recognizer = new Hammer.Pinch(options); } if (options.type === 'press') { recognizer = new Hammer.Press(options); } if (options.type === 'rotate') { recognizer = new Hammer.Rotate(options); } if (options.type === 'swipe') { recognizer = new Hammer.Swipe(options); } if (options.type === 'tap') { recognizer = new Hammer.Tap(options); } } if (manager && recognizer) { manager.add(recognizer); } } function parseDirections (dirs) { var directions = 0; angular.forEach(dirs.split('|'), function (direction) { if (Hammer.hasOwnProperty(direction)) { directions = directions | Hammer[direction]; } }); return directions; } })(window, window.angular, window.Hammer);
JavaScript
0
@@ -4830,54 +4830,8 @@ %0A %7D -%0A hammerCustomDirective.$inject = %5B'$parse'%5D; %0A%0A
ca3b12538c4e98a7368b6f39a69987ed9dc62d95
Extend default options to include parameters needed for the API
src/opbeat.js
src/opbeat.js
require('TraceKit') var exceptionist = require('./lib/exceptionist') var logger = require('./lib/logger') var defaultOptions = { apiHost: 'https://opbeat.com', logger: 'javascript', } function Opbeat () { this.VERSION = '0.0.1' this.isInstalled = false this.options = defaultOptions this.isPlatformSupport = function () { // TODO: Add some platform checks return true } this.onTraceKitReport = function (stackInfo, options) { logger.log('onTraceKitReport', stackInfo, options) var exception = exceptionist.traceKitStackToOpbeatException(stackInfo, options) exceptionist.processException(exception, options) } } /* * Configure Opbeat with Opbeat.com credentials and other options * * @param {object} options Optional set of of global options * @return {Opbeat} */ Opbeat.prototype.config = function (options) { return this } /* * Installs a global window.onerror error handler * to capture and report uncaught exceptions. * At this point, install() is required to be called due * to the way TraceKit is set up. * * @return {Opbeat} */ Opbeat.prototype.install = function () { if (this.isPlatformSupport() && !this.isInstalled) { TraceKit.report.subscribe(this.onTraceKitReport.bind(this)) this.isInstalled = true } return this } /* * Uninstalls the global error handler. * * @return {Opbeat} */ Opbeat.prototype.uninstall = function () { TraceKit.report.uninstall() this.isInstalled = false return this } /* * Manually capture an exception and send it over to Opbeat.com * * @param {error} ex An exception to be logged * @param {object} options A specific set of options for this error [optional] * @return {Opbeat} */ Opbeat.prototype.captureException = function (ex, options) { if (!(ex instanceof Error)) { throw 'Passed exception needs to be an instanceof Error' } // TraceKit.report will re-raise any exception passed to it, // which means you have to wrap it in try/catch. Instead, we // can wrap it here and only re-raise if TraceKit.report // raises an exception different from the one we asked to // report on. try { TraceKit.report(ex, options) } catch(ex1) { if (ex !== ex1) { throw ex1 } } return this } /* * Set/clear a user to be sent along with the payload. * * @param {object} user An object representing user data [optional] * @return {Opbeat} */ Opbeat.prototype.setUserContext = function (user) { return this } /* * Set extra attributes to be sent along with the payload. * * @param {object} extra An object representing extra data [optional] * @return {Opbeat} */ Opbeat.prototype.setExtraContext = function (extra) { return this } module.exports = new Opbeat()
JavaScript
0
@@ -180,16 +180,78 @@ cript',%0A + organizationId: 123,%0A appId: 123,%0A clientToken: 'kenneth'%0A %7D%0A%0Afunct
43336a550a01b76bafe7a302d5024db2c4f8bc7b
Fix rollup
packages/veritone-json-schemas/rollup.config.js
packages/veritone-json-schemas/rollup.config.js
import commonjs from 'rollup-plugin-commonjs'; import resolve from 'rollup-plugin-node-resolve'; import babel from 'rollup-plugin-babel'; import json from 'rollup-plugin-json'; import pkg from './package.json'; const extensions = [ '.js' ]; export default { input: './src/index.js', external: [], plugins: [ json({ include: ['schemas/**', 'node_modules/ajv/**/*'], preferConst: true, indent: ' ', compact: true, namedExports: true }), resolve({ extensions }), commonjs(), babel({ extensions, include: ['src/**/*'] }), ], output: [{ file: pkg.main, format: 'cjs', }, { file: pkg.module, format: 'es', }] };
JavaScript
0.000001
@@ -567,16 +567,38 @@ c/**/*'%5D +, runtimeHelpers: true %7D),%0A %5D
3d2dabb273f306a06dabd2a55944029467f35525
Update RenderNotification particle to skip standard template&model rendering (#3752)
particles/PipeApps/source/RenderNotification.js
particles/PipeApps/source/RenderNotification.js
/** * @license * Copyright (c) 2019 Google Inc. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * Code distributed by Google as part of this project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */ 'use strict'; defineParticle(({UiParticle, html, log}) => { return class extends UiParticle { setHandles(handles) { this.output({ modality: 'notification', title: `Hello`, text: `I'm a notification.`, handler: `onNotificationClick` }); } onNotificationClick(event) { this.output({ modality: 'notification', title: `Hello`, text: `Notification was clicked` }); } }; });
JavaScript
0
@@ -399,92 +399,31 @@ %0A%0A -return class extends UiParticle %7B%0A setHandles(handles) %7B%0A this.output(%7B%0A +const notification = %7B%0A @@ -444,36 +444,32 @@ ification',%0A - - title: %60Hello%60,%0A @@ -460,36 +460,32 @@ title: %60Hello%60,%0A - text: %60I'm a @@ -505,20 +505,16 @@ .%60,%0A - - handler: @@ -542,94 +542,285 @@ %60%0A - %7D);%0A %7D%0A onNotificationClick(event) %7B%0A this.output(%7B%0A modality: ' +%7D;%0A%0A const clickNotification = %7B%0A modality: 'notification',%0A title: %60Hello%60,%0A text: %60Notification was clicked%60%0A %7D;%0A%0A return class extends UiParticle %7B%0A renderOutput(inputs, state) %7B%0A if (!state.notified) %7B%0A state.notified = true;%0A this.output( noti @@ -831,84 +831,198 @@ tion -', +); %0A - title: %60Hello%60,%0A text: %60Notification was clicked%60%0A %7D) +%7D%0A if (state.clicked) %7B%0A state.clicked = false;%0A this.output(clickNotification);%0A %7D%0A %7D%0A onNotificationClick(event) %7B%0A this.state = %7Bclicked: true%7D ;%0A