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
f3dfda01a6ba89cf689c3f240ed7b5931e225df6
Fix address iteration
beacon.js
beacon.js
var config = require('./config') var engine = require('./engine') var hooks = require('./hooks') var log = require('./log').logger('beacon') var request = require('request') var Q = require('q'); var Beacon = function(options) { var options = options || {} this.url = options.url if(!this.url) { throw new Error('Beacon needs a URL.'); } this.interval = options.interval || 1*60*60*1000; this._timer = null; this.running = false; this.consent_for_beacon = "false"; this.localAddresses = [] } function setURL(url) { this.set('url', url); } function setInterval(interval) { this.set('interval', interval); } // Changing any of the options provokes a new beacon report Beacon.prototype.set = function(key, value) { this[key] = value; var wasRunning = this.running; this.stop(); if(wasRunning) { this.run('config'); } } // Start reporting with the beacon Beacon.prototype.start = function(reason) { this.running = true; this.run(reason); } // Function called at intervals to report to the beacon Beacon.prototype.run = function(reason) { if (this.consent_for_beacon === "true"){ this.report(reason) .catch(function(err) { log.warn('Could not send a beacon message: ' + err); }) .finally(function() { this._timer = setTimeout(this.run.bind(this), this.interval); }.bind(this)); } else { log.warn('Beacon is not enabled'); } } // Stops further beacon reports. Reports can be restarted with start() Beacon.prototype.stop = function() { this.running = false; if(this._timer) { clearTimeout(this._timer); } } Beacon.prototype.once = function(reason) { var wasRunning = this.running; this.stop(); this.start(reason); } // Return a promise that fulfills with the beacon message to be sent Beacon.prototype.createMessage = function(reason) { var msg = { id : config.updater.get('id'), name : config.updater.get('name'), os : config.platform, platform : config.updater.get('platform'), os_version : config.updater.get('os_version'), reason : reason || 'interval', local_ips : [] } this.localAddresses.forEach(function(idx, addr) { msg.local_ips.push({'address':addr}); }); var deferred = Q.defer() try { engine.getVersion(function(err, version) { if(err) { msg.engine_version = {}; log.warn("Engine version could not be determined"); log.warn(err); } else { msg.engine_version = version; } require('./updater').getVersion(function(err, version) { if(err) { msg.updater_version = {}; log.warn("Updater version could not be determined"); log.warn(err); } else { msg.updater_version = version } deferred.resolve(msg); }) }) } catch(e) { deferred.reject(e) } return deferred.promise } // Return a promise that resolves when the beacon server has been contacted Beacon.prototype.report = function(reason) { deferred = Q.defer() if(this.url) { log.info('Sending beacon report (' + (reason || 'interval') + ') to ' + this.url); return this.createMessage(reason) .then(function(message) { request({uri : this.url, json : true,body : message, method : 'POST'}, function(err, response, body) { if(err) { log.warn('Could not send message to beacon server: ' + err); deferred.reject(err); } else if(response.statusCode != 200) { if(response.statusCode === 301) { if(response.headers.location) { log.warn('Beacon URL has changed. Updating configuration to new URL: ' + response.headers.location) config.updater.set('beacon_url', response.headers.location); deferred.resolve(); return; } } var err = new Error("Beacon server responded with status code " + response.statusCode); log.warn(err); deferred.reject(err); } else { //log.debug('Beacon response code: ' + response.statusCode) //log.debug('Beacon response body: ' + body); log.info('Post to beacon server successful.'); deferred.resolve(); } }); }.bind(this)).catch(function(err){ log.error(err) deferred.reject(err); }.bind(this)) } else { deferred.resolve(); } return deferred.promise() } Beacon.prototype.setLocalAddresses = function(localAddresses) { this.localAddresses = localAddresses; } module.exports = Beacon
JavaScript
0.000004
@@ -2080,17 +2080,17 @@ ion( -idx, addr +addr, idx ) %7B%0A @@ -3039,16 +3039,42 @@ sage) %7B%0A +%09%09%09//console.log(message)%0A %09%09%09reque
9d33bab900967cf8fe2e9ecb97d608e98c2d36e0
Index correctly
blotpw.js
blotpw.js
/*global chrome queue*/ (function(){ function getHostname(url) { var a = document.createElement('a'); a.href = url; return a.hostname; } // Returns whether or not a URL is either HTTP or HTTPS. function urlIsHttp(url) { var a = document.createElement('a'); a.href = url; return a.protocol == 'http:' || a.protocol == 'https:' ; } function getHostnameFromUrl(url) { return urlIsHttp(url) ? getHostname(url) : null; } function getDomainProfiles(cb) { var xhr = new XMLHttpRequest(); xhr.onload = function() { return cb(null, JSON.parse(xhr.responseText)); }; xhr.open("GET", "/domainprofiles.json", true); xhr.send(); } function blotString(info) { var base = info.domain; if (info.email) base = info.email + ' ' + base; if (info.salt) base = base + ' ' + info.salt; return base; } function getLocalNamespaces(namespaces,cb) { return chrome.storage.local.get(null, function(items) { var results = {}; namespaces.forEach(function(namespace) { results[namespace] = {}; }); Object.keys(items).forEach(function (key) { namespaces.forEach(function(namespace) { var prefix = namespace + '.'; if (key.slice(0,prefix.length) == prefix) { results[namespace][key.slice(prefix.length)] = items.key; } }); }); return cb(null, results); }); } function getDefaults(cb){ getLocalNamespaces(['defaults'], function(err,res) { return cb(err,res.defaults); }); } function getDomainAndInfo(hostname, cb) { var components = hostname.split('.'); queue() .defer(getDomainProfiles) .defer(getLocalNamespaces, ['records', 'defaults']) .await(function(err, profiles, local) { var records = local.records; var i = 0; // For every level of the domain by specificity while (i < components.length) { var domain = components.slice(i, components.length).join('.'); // If there is a profile or record for this domain if (profiles[domain] || records[domain]) { return cb(null,{ domain: domain, profile: profiles[domain], record: records[domain], defaults: local.defaults }); } ++i; } // if no profile or record found return cb(null,{ domain: // strip 'www' prefix, if present // check lastIndexOf because if www appears multiple times in // the components, something freaky is going on, and we're not // going to touch that components.lastIndexOf('www') == 0 ? components.slice(1).join('.') : hostname, defaults: local.defaults }); }); } window.blotpw = { blotString: blotString, getHostnameFromUrl: getHostnameFromUrl, getDomainAndInfo: getDomainAndInfo, getDefaults: getDefaults }; })();
JavaScript
0.000001
@@ -1269,20 +1269,21 @@ = items -. +%5B key +%5D ;%0A
c575eae813cd018c4027ca3ba8b31647f9569923
Replace ok with created response
app/templates/api/controllers/AuthController.js
app/templates/api/controllers/AuthController.js
/** * AuthController * @description :: Server-side logic for manage user's authorization */ var passport = require('passport'); module.exports = { /** * Sign in by local strategy in passport */ signin: function (req, res) { passport.authenticate('local', function (error, user, info) { if (error) { sails.log.error(error); res.serverError(error); } else if (info) { res.unauthorized(null, info.code, info.message); } else { res.ok({ token: CipherService.create('jwt', {id: user.id}).hashSync(), user: user }); } })(req, res); }, /** * Sign up in system */ signup: function (req, res) { // TODO: think about model duplicate User .create(req.allParams()) .exec(function (error, user) { if (error) { sails.log.error(error); res.serverError(error); } else { res.ok({ token: CipherService.create('jwt', {id: user.id}).hashSync(), user: user }); } }); }, /** * Facebook authorization\linking */ facebook: function (req, res) { passport.authenticate('jwt', function (error, user) { req.user = user; passport.authenticate('facebook-token', function (error, user, info) { if (error) { sails.log.error(error); res.serverError(error); } else if (info) { res.unauthorized(null, info.code, info.message); } else { res.ok({ token: CipherService.create('jwt', {id: user.id}).hashSync(), user: user }); } })(req, res); })(req, res); }, /** * Twitter authorization\linking */ twitter: function (req, res) { passport.authenticate('jwt', function (error, user) { req.user = user; passport.authenticate('twitter-token', function (error, user, info) { if (error) { sails.log.error(error); res.serverError(error); } else if (info) { res.unauthorized(null, info.code, info.message); } else { res.ok({ token: CipherService.create('jwt', {id: user.id}).hashSync(), user: user }); } })(req, res); })(req, res); } };
JavaScript
0.000007
@@ -1106,34 +1106,39 @@ res. -ok +created (%7B%0A
37dfeb6614b5acec47f518f212102464fb724274
Teste de build com js
modulo-client/src/components/input.js
modulo-client/src/components/input.js
/** * Number-Field */ function initNumberField(){ var targets = $('.number-field input'); jQuery.each(targets, function(i, target) { if(target !== undefined) { var jQueryTarget = $(target); $(jQueryTarget).on('change', function() { var jQuerySelf = $(this); var functionName = jQuerySelf.attr('data-onchange'); if(jQuerySelf.val() !== jQuerySelf.attr('data-previousValue')) { var f = new Function(functionName); f.call(); jQuerySelf.attr('data-previousValue', jQuerySelf.val()); } }); } }); } function fncUppercase() { $("input").keyup(function() { var textUpperCase = $(this).val().toUpperCase(); if(window.getSelection().toString() === $(this).val()) { $(this).val(textUpperCase); $(this).select(); } else { $(this).val(textUpperCase); } }); $("textarea").keyup(function() { var textUpperCase = $(this).val().toUpperCase(); if(window.getSelection().toString() === $(this).val()) { $(this).val(textUpperCase); $(this).select(); } else { $(this).val(textUpperCase); } }); } function numbersOnly() { jQuery('.numbersOnly').keyup(function () { this.value = this.value.replace(/[^0-9\.]/g,''); }); } function formatMask() { $('.cns').mask('999.9999.9999.9999'); $(".cpf").mask("999.999.999-99"); $(".cep").mask("99999-999"); $(".rg").mask("99.999.999-9"); }
JavaScript
0
@@ -1309,24 +1309,64 @@ 9.999-99%22);%0A +%09$(%22.cnpj%22).mask(%2299.999.999/9999-99%22);%0A %09$(%22.cep%22).m
9c52787c7e70489d5f5737dad99525031b9cb7bd
add user collection
src/client/lib/horizon.js
src/client/lib/horizon.js
import Horizon from '@horizon/client'; import { API_BASE, COLLECTIONS } from '../constants'; export const hz = Horizon({ authType: 'token', host: API_BASE, secure: true }); export const hzRooms = hz(COLLECTIONS.ROOMS);
JavaScript
0
@@ -213,8 +213,54 @@ ROOMS);%0A +export const hzUsers = hz(COLLECTIONS.USERS);%0A
166365fd38f51f79e69e028a1c11e2620eddcb99
Remove navigation order hijacking. Earlier, we move the selected kind and stories to the top. It's kind a weird and discussed on #21
src/client/ui/controls.js
src/client/ui/controls.js
import React from 'react'; export default class StorybookControls extends React.Component { getKindNames() { const { storyStore, selectedKind } = this.props; if (!storyStore) { return []; } const kinds = storyStore.map(({ kind }) => kind); const selectedKindIndex = kinds.indexOf(selectedKind); // add the selected kind to the top of the list kinds.splice(selectedKindIndex, 1); kinds.unshift(selectedKind); return kinds; } getStories(kind) { const { storyStore } = this.props; const storiesInfo = storyStore.find(item => item.kind === kind); if (!storiesInfo) { return []; } return storiesInfo.stories; } fireOnKind(kind) { const { onKind } = this.props; if (onKind) onKind(kind); } fireOnStory(story) { const { onStory } = this.props; if (onStory) onStory(story); } renderStory(story) { const { selectedStory } = this.props; const storyStyle = { fontSize: 13, padding: '8px 0px 8px 10px', cursor: 'pointer', }; if (story === selectedStory) { storyStyle.fontWeight = 'bold'; } return ( <div key={story} style={storyStyle} onClick={this.fireOnStory.bind(this, story)} > {story} </div> ); } renderKind(kind) { const kindStyle = { fontSize: 15, padding: '10px 0px', cursor: 'pointer', borderBottom: '1px solid #EEE', }; const { selectedKind } = this.props; if (kind === selectedKind) { const stories = this.getStories(selectedKind); kindStyle.fontWeight = 'bold'; return ( <div key={kind}> <div style={kindStyle} onClick={this.fireOnKind.bind(this, kind)} > {kind} </div> <div> {stories.map(this.renderStory.bind(this))} </div> </div> ); } return ( <div key={kind} style={kindStyle} onClick={this.fireOnKind.bind(this, kind)} > {kind} </div> ); } render() { const kindNames = this.getKindNames(); const mainStyle = { fontFamily: ` -apple-system, ".SFNSText-Regular", "San Francisco", "Roboto", "Segoe UI", "Helvetica Neue", "Lucida Grande", sans-serif `, padding: '20px 10px 10px 10px', color: '#444', }; const h1Style = { textTransform: 'uppercase', letterSpacing: '3.5px', fontSize: '12px', fontWeight: 'bolder', color: '#828282', border: '1px solid #C1C1C1', textAlign: 'center', borderRadius: '2px', padding: '5px', margin: '0 0 20px 0', cursor: 'default', }; return ( <div style={mainStyle}> <h3 style={h1Style}>React Storybook</h3> <div> {kindNames.map(this.renderKind.bind(this))} </div> </div> ); } } StorybookControls.propTypes = { storyStore: React.PropTypes.array, selectedKind: React.PropTypes.string, selectedStory: React.PropTypes.string, onKind: React.PropTypes.func, onStory: React.PropTypes.func, };
JavaScript
0
@@ -131,22 +131,8 @@ tore -, selectedKind %7D = @@ -136,32 +136,32 @@ %7D = this.props;%0A + if (!storySt @@ -199,21 +199,14 @@ -const kinds = +return sto @@ -242,212 +242,8 @@ d);%0A - const selectedKindIndex = kinds.indexOf(selectedKind);%0A%0A // add the selected kind to the top of the list%0A kinds.splice(selectedKindIndex, 1);%0A kinds.unshift(selectedKind);%0A%0A return kinds;%0A %7D%0A
890dfd207776934d23e746dfd5077a23a1f67182
Remove unused declaration
src/components/AboutUs.js
src/components/AboutUs.js
// Page to create/About Us import React from 'react'; import { Link } from 'react-router-dom'; import links from '../constants/links'; const AboutUs = (props) => { return ( <div> <h1>AboutUs page</h1> Check us out on <a href={links.github}>Github</a>! </div> ); }; export default AboutUs;
JavaScript
0.000001
@@ -52,49 +52,8 @@ t';%0A -import %7B Link %7D from 'react-router-dom';%0A impo
687747f1205597f41510375159bedd8b4888ddb9
Correct wrong invariant checks
src/components/ngRedux.js
src/components/ngRedux.js
import Connector from './connector'; import invariant from 'invariant'; import isFunction from '../utils/isFunction'; import {createStore, applyMiddleware} from 'redux'; export default function ngReduxProvider() { let _reducer = undefined; let _middlewares = []; let _storeEnhancer = undefined; this.createStoreWith = (reducer, middlewares, storeEnhancer) => { invariant( isFunction(reducer), 'The reducer parameter passed to createStoreWith must be a Function. Instead received %s.', typeof selector ); invariant( !storeEnhancer || isFunction(storeEnhancer), 'The storeEnhancer parameter passed to createStoreWith must be a Function. Instead received %s.', typeof selector ); _reducer = reducer; _storeEnhancer = storeEnhancer || createStore; _middlewares = middlewares; }; this.$get = ($injector) => { let resolvedMiddleware = []; for(let middleware of _middlewares) { if(_.isString(middleware)) { resolvedMiddleware.push($injector.get(middleware)); } else { resolvedMiddleware.push(middleware); } } return Connector(applyMiddleware(...resolvedMiddleware)(_storeEnhancer)(_reducer)); } }
JavaScript
0.000141
@@ -516,39 +516,38 @@ %0A typeof -selecto +reduce r%0A );%0A%0A @@ -738,14 +738,19 @@ of s -electo +toreEnhance r%0A
bc7cacc92a1cce5497be9a5f54edca5dc3eeae8a
fix duplicated search entries
packages/admin/src/components/MenuTree/MenuTree.js
packages/admin/src/components/MenuTree/MenuTree.js
import React from 'react' import PropTypes from 'prop-types' import {StyledMenuEntryWrapper} from './StyledComponents' import MenuItem from './MenuItem' import {prepareMenuTree} from '../../utils/navigationUtils' const MenuTree = ({ items, searchFilter, typeMapping, requireSearch }) => { if (requireSearch && !searchFilter) { return null } if (!items || items.length === 0) { return null } const actualItems = prepareMenuTree(items, searchFilter, typeMapping) const MenuItems = actualItems.map(item => ( <MenuItem key={item.name} item={item} typeMapping={typeMapping} menuTreePath={item.name} /> )) return ( <StyledMenuEntryWrapper> {MenuItems} </StyledMenuEntryWrapper> ) } MenuTree.propTypes = { items: PropTypes.array, searchFilter: PropTypes.string, typeMapping: PropTypes.objectOf( PropTypes.shape({ component: PropTypes.elementType.isRequired, childrenWrapperComponent: PropTypes.elementType.isRequired, filterAttribute: PropTypes.arrayOf(PropTypes.string), props: PropTypes.object }) ), requireSearch: PropTypes.bool } export default React.memo(MenuTree)
JavaScript
0.000001
@@ -521,20 +521,29 @@ ems.map( +( item +, index) =%3E (%0A @@ -566,24 +566,20 @@ key=%7Bi -tem.name +ndex %7D%0A
55785bf43268c88bde20c28e88c26685d79ff11c
fix links on install page
public/landing/application.client.js
public/landing/application.client.js
/* globals angular */ 'use strict'; angular.module('betterfriendsLanding', ['ionic']); // routes angular.module('betterfriendsLanding').config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $stateProvider .state('respond', { url: '/r/:eid/:inviteCode', templateUrl: '/landing/respond.client.view.html', controller: 'RespondController' }) .state('accepted', { url: '/accepted/:eid/:inviteCode', templateUrl: '/landing/accepted.client.view.html', controller: 'AcceptedController' }); } ]); angular.module('betterfriendsLanding').controller('RespondController', ['$scope', '$stateParams', '$state', '$http', function ($scope, $stateParams, $state, $http) { $scope.accept = function() { var data = {newStatus:'accepted'}; $http.post('/event/updateStatus/'+$stateParams.eid+'/'+$stateParams.inviteCode, data).then(function (res) { $state.go('accepted', {eid:$stateParams.eid, inviteCode:$stateParams.inviteCode}); }); }; $http.get('/event/get/'+$stateParams.eid+'/'+$stateParams.inviteCode).then(function (res) { $scope.event = res.data.event; $scope.invitee = res.data.invitee; }); } ]); angular.module('betterfriendsLanding').controller('AcceptedController', ['$scope', '$stateParams', '$window', '$timeout', '$http', function ($scope, $stateParams, $window, $timeout, $http) { $scope.invite = function() { var clickedAt = new Date(); $timeout(function () { if (new Date() - clickedAt < 2000) { $window.location.href = 'http://www.testflightapp.com/install/ba99bd94a202a6c4b4142ee99b83eac7-MTM3NDk0NTQ/'; //itms-apps://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6'; } }, 500); var data = { eid:$stateParams.eid, inviteCode:$stateParams.inviteCode }; var dataString = encodeURIComponent('j:'+JSON.stringify(data)); $window.location.href = 'betterfriends://cookiedata?data='+dataString; }; $http.get('/event/get/'+$stateParams.eid+'/'+$stateParams.inviteCode).then(function (res) { $scope.event = res.data.event; $scope.invitee = res.data.invitee; }); } ]);
JavaScript
0
@@ -1672,54 +1672,64 @@ ll/b -a99bd94a202a6c4b4142ee99b83eac7-MTM3NDk0NTQ/'; +0917ddaaf8336dda336598c7613a26e-MTM3NDk5Nzk/';%0A //i @@ -1994,24 +1994,70 @@ ta));%0A +//TODO: off for now to force upgrade.%0A // $window.loca
6e7bd136a7bfbd7aa055f79d7c783f95481afd74
make selectedfilters accessible (#1132)
packages/web/src/components/basic/SelectedFilters.js
packages/web/src/components/basic/SelectedFilters.js
import React, { Component } from 'react'; import { withTheme } from 'emotion-theming'; import { setValue, clearValues } from '@appbaseio/reactivecore/lib/actions'; import types from '@appbaseio/reactivecore/lib/utils/types'; import { getClassName } from '@appbaseio/reactivecore/lib/utils/helper'; import Button, { filters } from '../../styles/Button'; import Container from '../../styles/Container'; import Title from '../../styles/Title'; import { connect } from '../../utils'; class SelectedFilters extends Component { componentDidUpdate = () => { if (this.props.onChange) { this.props.onChange(this.props.selectedValues); } }; remove = (component, value = null) => { const { onClear } = this.props; this.props.setValue(component, null); if (onClear) { onClear(component, value); } }; clearValues = () => { const { onClear } = this.props; this.props.clearValues(); if (onClear) { onClear(null); } }; renderValue = (value, isArray) => { if (isArray && value.length) { const arrayToRender = value.map(item => this.renderValue(item)); return arrayToRender.join(', '); } else if (value && typeof value === 'object') { // TODO: support for NestedList let label = (typeof value.label === 'string' ? value.label : value.value) || value.key || value.distance || null; if (value.location) { label = `${value.location} - ${label}`; } return label; } return value; }; renderFilters = () => { const { selectedValues } = this.props; return Object.keys(selectedValues) .filter(id => this.props.components.includes(id) && selectedValues[id].showFilter) .map((component, index) => { const { label, value, category } = selectedValues[component]; const isArray = Array.isArray(value); if (label && ((isArray && value.length) || (!isArray && value))) { const valueToRender = category ? this.renderValue(`${value} in ${category} category`, isArray) : this.renderValue(value, isArray); return ( <Button className={getClassName(this.props.innerClass, 'button') || null} key={`${component}-${index + 1}`} onClick={() => this.remove(component, value)} > <span> {selectedValues[component].label}: {valueToRender} </span> <span>&#x2715;</span> </Button> ); } return null; }) .filter(Boolean); }; render() { if (this.props.render) { return this.props.render(this.props); } const { theme } = this.props; const filtersToRender = this.renderFilters(); const hasValues = !!filtersToRender.length; return ( <Container style={this.props.style} className={`${filters(theme)} ${this.props.className || ''}`} > {this.props.title && hasValues && ( <Title className={getClassName(this.props.innerClass, 'title') || null}> {this.props.title} </Title> )} {filtersToRender} {this.props.showClearAll && hasValues ? ( <Button className={getClassName(this.props.innerClass, 'button') || null} onClick={this.clearValues} > {this.props.clearAllLabel} </Button> ) : null} </Container> ); } } SelectedFilters.propTypes = { clearValues: types.func, setValue: types.func, components: types.components, selectedValues: types.selectedValues, className: types.string, clearAllLabel: types.title, innerClass: types.style, showClearAll: types.bool, style: types.style, theme: types.style, onClear: types.func, render: types.func, title: types.title, onChange: types.func, }; SelectedFilters.defaultProps = { className: null, clearAllLabel: 'Clear All', showClearAll: true, style: {}, }; const mapStateToProps = state => ({ components: state.components, selectedValues: state.selectedValues, }); const mapDispatchtoProps = dispatch => ({ clearValues: () => dispatch(clearValues()), setValue: (component, value) => dispatch(setValue(component, value)), }); const ConnectedComponent = connect( mapStateToProps, mapDispatchtoProps, )(withTheme(props => <SelectedFilters ref={props.myForwardedRef} {...props} />)); // eslint-disable-next-line export default React.forwardRef((props, ref) => ( <ConnectedComponent {...props} myForwardedRef={ref} /> ));
JavaScript
0
@@ -240,16 +240,34 @@ lassName +, handleA11yAction %7D from @@ -2154,16 +2154,126 @@ + 1%7D%60%7D%0A +%09%09%09%09%09%09%09tabIndex=%220%22%0A%09%09%09%09%09%09%09onKeyPress=%7Bevent =%3E handleA11yAction(event, () =%3E this.remove(component, value))%7D%0A %09%09%09%09%09%09%09o @@ -3212,16 +3212,105 @@ Values%7D%0A +%09%09%09%09%09%09tabIndex=%220%22%0A%09%09%09%09%09%09onKeyPress=%7Bevent =%3E handleA11yAction(event, this.clearValues)%7D%0A %09%09%09%09%09%3E%0A%09
9af823152517282d82d4cc823b419322a25efe77
Add function to get user score from user table
server/db/models.js
server/db/models.js
var db = require('./modelAdapters'); var util = require('../core/utilities'); var validate = require('../core/routeValidations.js'); //exports.createMessage({message: 'Excellant, it works!', x: 10, y: 10, z: 10, userToken: 'live'}); exports.createMessage = function(userData) { if (!validate.validateCoordinates(userData)) { return new Promise(function(resolve, reject) { reject('Validations failed. Please enter valid coordinates'); }); } return db.insert('messages', { userToken: userData.userToken, messageString: userData.message, image: util.saveImage(userData.image), imageH: userData.imageH, imageW: userData.imageW, score: userData.score || 0 }).then(function(messageSuccess) { return db.insert('marks', { x: userData.x, y: userData.y, z: userData.z, userToken: userData.userToken, messageId: messageSuccess.insertId }).then(function(markSuccess) { return {markSuccess: markSuccess, messageSuccess: messageSuccess}; }); }); }; //exports.createComment({messageId: 1, message: 'works', x: 10, y: 10, z: 10}); exports.createComment = function(userData) { if (!validate.validateCoordinates(userData)) { return new Promise(function(resolve, reject) { reject('Validations failed. Please enter valid coordinates'); }); } return db.insert('comments',{ messageId: userData.messageId, commentString: userData.commentString }).then(function(commentSuccess) { return db.insert('marks', { x: userData.x, y: userData.y, z: userData.z, userToken: userData.userToken, commentId: commentSuccess.insertId }).then(function(markSuccess) { return {markSuccess: markSuccess, commentSuccess: commentSuccess}; }); }); }; //exports.createUser('grgrdg'); exports.createUser = function(token) { return db.insert('users', {token: token}); }; //exports.createVote({messageId: string, userToken: string}); exports.createVote = function(userData) { var voteObject = {userToken: userData.userToken}; if (userData.hasOwnProperty('messageId')) { voteObject.messageId = userData.messageId; } else { voteObject.commentId = userData.commentId; } var voteParams = util.createQueryParams(voteObject); return db.whereParams('votes', voteParams) .then(function(vote) { if (vote.length === 0) { return db.insert('votes', voteObject); } else { return db.deleteRowWhere('votes', voteParams); } }); }; //exports.retrieveVotesByUser(userToken string) exports.retrieveVotesByUser = function(userToken) { return db.where('votes', ['userToken', userToken]); }; //exports.retrieveMarks({x: float, y: float, z: float, userToken: string}) exports.retrieveMarks = function(userData) { if (validate.validateCoordinates(userData)) { return db.retrieveMarks(userData) .then(function(marks) { return exports.retrieveVotesByUser(userData.userToken) .then(function(votes) { return new Promise(function(resolve) { resolve(util.decorateMarksWithVoteStatus(marks, votes)); }); }); }); } else { return new Promise(function(resolve, reject) { reject('Validations failed. Please enter valid coordinates'); }); } }; //exports.retrieveScore(3).then(callback(success)); exports.retrieveScore = function(messageId, objectToFill) { return new Promise(function(resolve, reject) { db.where('messages', ['id', messageId]) .then(function(success) { resolve(success[0].score); }, function(err) { reject(err); }); }); }; //exports.updateScore(3, 9001); exports.updateScore = function(messageId, amount) { return db.update('messages', ['score', amount, 'id', messageId]); }; //exports.retrieveVotes(10).then(function(success){console.log(success)}); exports.retrieveVotes = function(messageId) { return db.retrieveCount('votes', ['messageId', messageId]); }; //exports.retrieveComments({x: float, y: float, z: float, messageId: string, userToken: string}) exports.retrieveComments = function(userData) { return db.retrieveComments(userData) .then(function(comments) { return exports.retrieveVotesByUser(userData.userToken) .then(function(votes) { return new Promise(function(resolve) { resolve(util.decorateCommentsWithVoteStatus(comments, votes)); }); }); }); }; //delete(string tableName, [string key, string value]); exports.deleteRow = db.deleteRow; //deleteUser(string userToken) exports.deleteUser = function(userToken) { return db.deleteRow('users', ['token', userToken]); }; //deleteMessage(string messageId) exports.deleteMessage = function(messageId) { return db.deleteRow('messages', ['id', messageId]); }; //deleteMark(string markId) exports.deleteMark = function(markId) { return db.deleteRow('marks', ['id', markId]); }; //deleteVote(string voteId) exports.deleteVote = function(voteId) { return db.deleteRow('votes', ['id', voteId]); }; //deleteVotesByUserToken(string userToken) exports.deleteVotesByUserToken = function(userToken) { return db.deleteRow('votes', ['userToken', userToken]); }; //deleteMarkByUserToken(string userToken); exports.deleteMarkByUserToken = function(userToken) { return db.deleteRow('marks', ['userToken', userToken]); }; //deleteMessagesByScore(string score); exports.deleteMessagesByScore = function(score) { return db.deleteRow('messages', ['score', score]); };
JavaScript
0.000002
@@ -2689,32 +2689,136 @@ serToken%5D);%0A%7D;%0A%0A +exports.retrieveUserScore = function(userToken) %7B%0A return db.where('users', %5B'token', userToken%5D);%0A%7D;%0A%0A //exports.retrie
c79843091a485501601704a7d47924bebdbca695
Change default name
src/web/config/settings.js
src/web/config/settings.js
const root = window.root; console.assert(typeof root.app.config === 'object', 'root.app.config is not an object'); const settings = { version: root.app.config.version, webroot: root.app.config.webroot, cdn: root.app.config.cdn, name: 'CNC.js', log: { level: 'warn', // trace, debug, info, warn, error logger: 'console', // console prefix: '' }, i18next: { lowerCaseLng: true, // logs out more info (console) debug: false, // language to lookup key if not found on set language fallbackLng: 'en', // string or array of namespaces ns: [ 'locale', // locale: language, timezone, ... 'resource' // default ], // default namespace used if not passed to translation function defaultNS: 'resource', whitelist: [ 'en', // default language 'de', 'es', 'fr', 'it', 'ja', 'zh-cn', 'zh-tw' ], // array of languages to preload preload: [], // language codes to lookup, given set language is 'en-US': // 'all' --> ['en-US', 'en', 'dev'] // 'currentOnly' --> 'en-US' // 'languageOnly' --> 'en' load: 'currentOnly', // char to separate keys keySeparator: '.', // char to split namespace from key nsSeparator: ':', interpolation: { prefix: '{{', suffix: '}}' }, // options for language detection // https://github.com/i18next/i18next-browser-languageDetector detection: { // order and from where user language should be detected order: ['querystring', 'cookie', 'localStorage'], // keys or params to lookup language from lookupQuerystring: 'lang', lookupCookie: 'lang', lookupLocalStorage: 'lang', // cache user language on caches: ['localStorage', 'cookie'] }, // options for backend // https://github.com/i18next/i18next-xhr-backend backend: { // path where resources get loaded from loadPath: root.app.config.webroot + 'i18n/{{lng}}/{{ns}}.json', // path to post missing resources addPath: 'api/i18n/sendMissing/{{lng}}/{{ns}}', // your backend server supports multiloading // /locales/resources.json?lng=de+en&ns=ns1+ns2 allowMultiLoading: false, // allow cross domain requests crossDomain: false } } }; export default settings;
JavaScript
0.000005
@@ -249,19 +249,16 @@ me: 'CNC -.js ',%0A l
b5843e0ebb451a1e47d14c3aed9574914070e52e
disable save button when ajax is loading
public/assets/js/app/user.js
public/assets/js/app/user.js
$(function(){ /** * all response will be in below format * { * success : boolean, * data : {resource_object} or null, * message : string, * code : integer * } */ /** * reset the form and show it! */ $('#btn-user-add').click(function(e){ e.preventDefault(); $('#user-form-data').each(function(){ this.reset(); }); $('#btn-user-save').attr('data-method', 'POST'); $('#user-modal').modal('show'); }); /** * sen GET request to display resource with specific id, and display it in modal form */ $('#user-table').on('click', '.btn-user-edit', function(e){ var $userid = $(this).attr('data-id'); $.get(global.baseUrl+'admin/user/'+$userid, function(resp){ if(resp.success){ $('#user-form-data').each(function(){ this.reset(); }); var $user = resp.data; for(var a in $user){ $('#user_'+a).val($user[a]); } $('#btn-user-save').attr('data-method', 'PUT'); $('#user-modal').modal('show'); }else{ alert(resp.message); if(resp.code == 401){ location.reload(); } } }); }); /** * send DELETE request to the resouce server */ $('#user-table').on('click', '.btn-user-delete', function(e){ e.preventDefault(); var $userid = $(this).attr('data-id'); if(confirm('Are you sure to delete this user?')){ $.ajax({ url : global.baseUrl+'admin/user/'+$userid, method : 'DELETE', data : { id : $userid }, success : function(resp){ if(resp.success){ $('#user-row-'+$userid).remove(); }else{ alert(resp.message); if(resp.code == 401){ location.reload(); } } } }); } }); /** * send POST request to save data to resource server * or send PUT request to update data on resource server * based on data-method value */ $('#btn-user-save').click(function(e){ e.preventDefault(); var $button = $(this); var $userdata = $('#user-form-data').serialize(); var $method = $(this).attr('data-method'); var $url = ($method == 'POST') ? global.baseUrl+'admin/user' : global.baseUrl+'admin/user/'+$('#user_id').val(); $button.prop('disabled', true); $button.html('saving...'); $.ajax({ url: $url, data: $userdata, method : $method, success: function(resp){ if(resp.success){ user = resp.data; $button.prop('disabled', false); $button.html('save'); if($method == 'POST'){ /** append user to new row */ $('#user-table').append( '<tr id="user-row-'+resp.data.id+'">'+ '<td>'+user.id+'</td>'+ '<td>'+user.first_name+'</td>'+ '<td>'+user.last_name+'</td>'+ '<td>'+user.email+'</td>'+ '<td>'+ '<div class="dropdown text-center">'+ '<a class="btn btn-primary btn-sm" href="#" data-toggle="dropdown">Action <b class="caret"></b></a>'+ '<ul aria-labelledby="dLabel" role="menu" class="dropdown-menu pull-right">'+ '<li class="text-left"><a data-id="'+user.id+'" class="btn-user-edit" href="#">Edit</a></li>'+ '<li class="text-left"><a data-id="'+user.id+'" class="btn-user-delete" href="#">Remove</a></li>'+ '</ul>'+ '</div>'+ '</td>'+ '</tr>' ); }else{ var $fields = $('#user-row-'+resp.data.id+' td'); $($fields[1]).html(user.first_name); $($fields[2]).html(user.last_name); $($fields[3]).html(user.email); } /** reset the form and hide modal form */ $('#user-form-data').each(function(){ this.reset(); }); $('#user-modal').modal('hide'); }else{ alert(resp.message); if(resp.code == 401){ location.reload(); } } } }); }); });
JavaScript
0.000001
@@ -2967,32 +2967,33 @@ function(resp)%7B%0A +%0A @@ -2996,63 +2996,77 @@ -if(resp.success)%7B%0A%0A user = resp.data +$button.prop('disabled', false);%0A $button.html('save') ;%0A @@ -3083,44 +3083,43 @@ +%0A -$button.prop('disabled', false); + if(resp.success)%7B%0A %0A @@ -3135,36 +3135,32 @@ -$button.html('save') +user = resp.data ;%0A%0A
04d0eced2546d289d8d70b7d1404b7c519bc6874
Remove _emit on client, wasn't much of a use anyway
public/javascripts/client.js
public/javascripts/client.js
(function(d) { "use strict"; var SpotifyRemoteClient = function(host) { this.host = host || window.location.hostname; this.elements = []; this._canTouchThis = 'ontouchstart' in window || 'createTouch' in d; this._volumeRangeBlocked = false; this._positionRangeBlocked = false; }; SpotifyRemoteClient.prototype.init = function(io, container) { this.socket = io.connect(this.host); this.container = container; this.socket.on('currentTrack', this.showCurrentTrack.bind(this)); this.socket.on('currentState', this.showCurrentState.bind(this)); this.socket.on('currentArtwork', this.showCurrentArtwork.bind(this)); var body = d.getElementsByTagName('body')[0]; body.addEventListener( 'click', function(event) { var command = { 'previous': 'previous', 'next': 'next', 'current-play-state': 'playPause' }[event.target.id]; if (command) this._emit(command); event.preventDefault(); }.bind(this) ); body.addEventListener( 'keyup', function(event) { var command = { 32: 'playPause', // space 78: 'next', // n 80: 'previous', // p 107: 'volumeUp', // + on numpad 109: 'volumeDown', // - on numpad 187: 'volumeUp', // + 189: 'volumeDown' // - }[event.keyCode]; if (command) this._emit(command); }.bind(this) ); // volume control this.$('current-volume').addEventListener( 'change', function(event) { this.socket.emit('setVolume', event.target.value); }.bind(this) ); this.$('current-volume').addEventListener( this._canTouchThis ? 'touchstart' : 'mousedown', function() { this._volumeRangeBlocked = true; }.bind(this) ); this.$('current-volume').addEventListener( this._canTouchThis ? 'touchend' : 'mouseup', function() { this._volumeRangeBlocked = false; }.bind(this) ); // position control this.$('position').addEventListener( this._canTouchThis ? 'touchstart' : 'mousedown', function() { this._positionRangeBlocked = true; }.bind(this) ); this.$('position').addEventListener( this._canTouchThis ? 'touchend' : 'mouseup', function(event) { this.socket.emit('jumpTo', event.target.value); this._positionRangeBlocked = false; }.bind(this) ); }; SpotifyRemoteClient.prototype.showCurrentTrack = function(track) { // don't rerender stuff when nothing has changed if (this.currentTrack && this.currentTrack.id == track.id) { return; } this.$('artist').textContent = track.artist; this.$('name').textContent = track.name; this.$('duration').textContent = formatTime(track.duration); this.$('position').setAttribute('max', track.duration); this.currentTrack = track; }; SpotifyRemoteClient.prototype.showCurrentState = function(state) { if (!this.currentState || this.currentState.position !== state.position) { this.$('played-time').textContent = formatTime(parseInt(state.position, 10)); if (!this._positionRangeBlocked) { this.$('position').value = state.position.replace(',', '.'); } } if (!this.currentState || this.currentState.state !== state.state) { this.$('current-play-state').textContent = state.state == 'paused' ? 'Play' : 'Pause'; } if (!this._volumeRangeBlocked && (!this.currentState || this.currentState.volume !== state.volume)) { this.$('current-volume').value = state.volume; } this.currentState = state; }; SpotifyRemoteClient.prototype.showCurrentArtwork = function(artwork) { this.$('artwork').src = 'data:image/png;base64,' + artwork; }; SpotifyRemoteClient.prototype._emit = function(command) { this.socket.emit(command); }; // jQuery. SpotifyRemoteClient.prototype.$ = function(id) { this.elements[id] = this.elements[id] || d.getElementById(id); return this.elements[id]; }; function formatTime(totalSeconds) { var minutes = Math.floor(totalSeconds / 60); var seconds = totalSeconds % 60; minutes = minutes < 10 ? '0' + minutes : minutes; seconds = seconds < 10 ? '0' + seconds : seconds; return minutes + ":" + seconds; }; var client = new SpotifyRemoteClient(); client.init(io, d.getElementById('remote-control')); })(document);
JavaScript
0.000001
@@ -990,33 +990,39 @@ (command) this. -_ +socket. emit(command);%0A%0A @@ -1485,17 +1485,23 @@ d) this. -_ +socket. emit(com @@ -3913,105 +3913,8 @@ %7D;%0A%0A - SpotifyRemoteClient.prototype._emit = function(command) %7B%0A this.socket.emit(command);%0A %7D;%0A%0A //
d8b5577c891f18497d32bd998f2158389dd77470
Use touchstart instead of click for touch devices
public/javascripts/client.js
public/javascripts/client.js
(function(d) { "use strict"; var SpotifyRemoteClient = function(host) { this.host = host || window.location.hostname; this.elements = []; this._canTouchThis = 'ontouchstart' in window || 'createTouch' in d; this._volumeRangeBlocked = false; this._positionRangeBlocked = false; }; SpotifyRemoteClient.prototype.init = function(io, container) { this.socket = io.connect(this.host); this.container = container; this.socket.on('currentTrack', this.showCurrentTrack.bind(this)); this.socket.on('currentState', this.showCurrentState.bind(this)); this.socket.on('currentArtwork', this.showCurrentArtwork.bind(this)); var body = d.getElementsByTagName('body')[0]; body.addEventListener( 'click', function(event) { var command = { 'previous': 'previous', 'next': 'next', 'current-play-state': 'playPause' }[event.target.id]; if (command) this.socket.emit(command); event.preventDefault(); }.bind(this) ); body.addEventListener( 'keyup', function(event) { var command = { 32: 'playPause', // space 78: 'next', // n 80: 'previous', // p 107: 'volumeUp', // + on numpad 109: 'volumeDown', // - on numpad 187: 'volumeUp', // + 189: 'volumeDown' // - }[event.keyCode]; if (command) this.socket.emit(command); }.bind(this) ); // volume control this.$('current-volume').addEventListener( 'change', function(event) { this.socket.emit('setVolume', event.target.value); }.bind(this) ); this.$('current-volume').addEventListener( this._canTouchThis ? 'touchstart' : 'mousedown', function() { this._volumeRangeBlocked = true; }.bind(this) ); this.$('current-volume').addEventListener( this._canTouchThis ? 'touchend' : 'mouseup', function() { this._volumeRangeBlocked = false; }.bind(this) ); // position control this.$('position').addEventListener( this._canTouchThis ? 'touchstart' : 'mousedown', function() { this._positionRangeBlocked = true; }.bind(this) ); this.$('position').addEventListener( this._canTouchThis ? 'touchend' : 'mouseup', function(event) { this.socket.emit('jumpTo', event.target.value); this._positionRangeBlocked = false; }.bind(this) ); }; SpotifyRemoteClient.prototype.showCurrentTrack = function(track) { // don't rerender stuff when nothing has changed if (this.currentTrack && this.currentTrack.id == track.id) { return; } this.$('artist').textContent = track.artist; this.$('name').textContent = track.name; this.$('duration').textContent = formatTime(track.duration); this.$('position').setAttribute('max', track.duration); this.currentTrack = track; }; SpotifyRemoteClient.prototype.showCurrentState = function(state) { if (!this.currentState || this.currentState.position !== state.position) { this.$('played-time').textContent = formatTime(parseInt(state.position, 10)); if (!this._positionRangeBlocked) { this.$('position').value = state.position.replace(',', '.'); } } if (!this.currentState || this.currentState.state !== state.state) { this.$('current-play-state').textContent = state.state == 'paused' ? 'Play' : 'Pause'; } if (!this._volumeRangeBlocked && (!this.currentState || this.currentState.volume !== state.volume)) { this.$('current-volume').value = state.volume; } this.currentState = state; }; SpotifyRemoteClient.prototype.showCurrentArtwork = function(artwork) { this.$('artwork').src = 'data:image/png;base64,' + artwork; }; // jQuery. SpotifyRemoteClient.prototype.$ = function(id) { this.elements[id] = this.elements[id] || d.getElementById(id); return this.elements[id]; }; function formatTime(totalSeconds) { var minutes = Math.floor(totalSeconds / 60); var seconds = totalSeconds % 60; minutes = minutes < 10 ? '0' + minutes : minutes; seconds = seconds < 10 ? '0' + seconds : seconds; return minutes + ":" + seconds; }; var client = new SpotifyRemoteClient(); client.init(io, d.getElementById('remote-control')); })(document);
JavaScript
0
@@ -781,16 +781,52 @@ r(%0A + this._canTouchThis ? 'touchstart' : 'click'
a6c84a27758fce3b9d2ec1cf0f14aeed7f7af50d
remove mrender event
public/js/views/trackView.js
public/js/views/trackView.js
var WO = WO || {}; WO.TrackView = Backbone.View.extend({ events: { 'click .delete-track-button' : 'deleteTrack', 'change .track-volume-slider' : 'setTrackVolume', 'click .mute-track-button' : 'muteTrack', 'change .instrument-selector' : 'changeInstrument', 'click .track-container' : 'setActiveTrack' }, template: _.template( '<div class="track-container active-track <%= cid %>">' + '<div class="track-controls">' + '<p class="track-title"> <%= attributes.title %> </p>' + '<button class="delete-track-button" id="delete"><i class="fa fa-trash-o"></i></button><br>' + '<form action="#">' + // '<fieldset>' + '<label for="instrument">Select instrument </label>' + '<select name="instrument-selector" class="instrument-selector">' + '<option selected="selected" value="Acoustic Piano">Acoustic Piano</option>'+ '<option value="Synth">Synth</option>'+ '<option value="Drums">Drums</option>' + '</select>' + // '</fieldset>' + '</form><br>' + '<button class="solo-track-button" id="solo">S</button>' + '<button class="mute-track-button" id="mute">M</button>' + '<div class="track-volume-slider-group">' + '<i class="fa fa-volume-down"></i>' + '<input class="track-volume-slider" type="range" min="0.00" max="1.00" step="0.01" value="0.75">' + '<i class="fa fa-volume-up"></i>' + '</div>' + '</div>' + '<div class="track-notes" style="overflow:scroll"></div>' + '</div>' ), initialize: function(){ $(document).ready((function(){ this.model.set('mRender', new WO.MidiRender(this.model.cid+ ' .track-notes')); }).bind(this)); }, render: function(){ this.$el.html( this.template(this.model)); return this.$el; }, deleteTrack: function(){ this.model.collection.remove(this.model); }, setTrackVolume: function(){ var volume = this.$el.find('.track-volume-slider').val(); this.model.set('volume', volume); this.model.get('instrument').setVolume(volume*20); }, muteTrack: function(){ var volume, color; if( this.model.get('isMuted') ){ volume = 0; this.model.set('isMuted', false); color = "rgb(255,255,255)"; }else{ volume = -50; this.model.set('isMuted', true); color = "rgb(255,0,0)"; } // console.log(color); $('.mute-track-button').toggleClass('muted'); this.model.set('volume', volume); this.model.get('instrument').setVolume(volume); }, changeInstrument : function(e){ console.log($(e.currentTarget)[0].value); this.model.set('instrument'); //get number of track //use that number in variable - "WO.instrumentTrack" + number //set the instrument name using the instrument from the dropdown }, setActiveTrack: function(){ //know current active $('.active-track').removeClass('active-track'); //remove active-track class console.log("collection", this.model.collection); console.log("model", this.model); this.model.collection.settings.activeTrack = this.model; //add active-track class this.$el.find('.track-container').addClass('active-track'); console.log(this.$el); } });
JavaScript
0.000002
@@ -1624,148 +1624,8 @@ ()%7B%0A - $(document).ready((function()%7B%0A this.model.set('mRender', new WO.MidiRender(this.model.cid+ ' .track-notes'));%0A %7D).bind(this));%0A %7D, @@ -3142,16 +3142,111 @@ s.$el);%0A + WO.instrumentKeyHandler(this.model.collection.settings.activeTrack.attributes.instrument);%0A %7D%0A%0A%7D);
5897a3d7bdadbaa57a24c14a2d02c287540452fc
Remove misplaced comma that breaks IE8
packages/ember-data/lib/system/debug/debug_info.js
packages/ember-data/lib/system/debug/debug_info.js
require("ember-data/system/model/model"); DS.Model.reopen({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function() { var attributes = ['id'], relationships = { belongsTo: [], hasMany: [] }, expensiveProperties = []; this.eachAttribute(function(name, meta) { attributes.push(name); }, this); this.eachRelationship(function(name, relationship) { relationships[relationship.kind].push(name); expensiveProperties.push(name); }); var groups = [ { name: 'Attributes', properties: attributes, expand: true, }, { name: 'Belongs To', properties: relationships.belongsTo, expand: true }, { name: 'Has Many', properties: relationships.hasMany, expand: true }, { name: 'Flags', properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] } ]; return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; } });
JavaScript
0.999761
@@ -1079,25 +1079,24 @@ expand: true -, %0A %7D,%0A
c0e76b05ec9a69325a325acbf10b3b52dac6f268
tweak error messages
packages/eslint-config-tester/lib/error-compare.js
packages/eslint-config-tester/lib/error-compare.js
/** * @fileoverview Compare expected errors with those from ESLint. */ goog.module('googlejs.configTester.errorCompare'); const googObject = goog.require('goog.object'); const types = goog.require('googlejs.configTester.types'); /** * Compares all ESLint results to the expected results for a list of files. * @param {!Object<string, !types.ExpectedErrors>} expectedErrorsByFile A map of * an absolute filepath to the expected errors for the file. */ function compareEslintToExpected(expectedErrorsByFile) { googObject.forEach(expectedErrorsByFile, (expectedErrors, filePath) => { compareErrorsForFile(expectedErrors); }); } /** * Compares errors between ESLint and the expected errors for one file. * @param {!types.ExpectedErrors} expectedErrors A map of an absolute filepath * to the expected errors for the file. */ function compareErrorsForFile(expectedErrors) { googObject.forEach(expectedErrors.errorsByLineNumber, (lineErrors, line) => { verifyExpectedErrors(lineErrors); verifyEslintErrors(lineErrors); }); } /** * Creates an error string from an ESLint message. * @param {!types.LineErrors} lineErrors * @param {string} explanation * @return {string} */ function makeErrorMessage(lineErrors, explanation) { return `${lineErrors.filePath}:${lineErrors.line} - ${explanation}`; } /** * Verifies that all ESLint messages match with an expected error message. * @param {!types.LineErrors} lineErrors */ function verifyEslintErrors(lineErrors) { const {eslintRules, expectedRules} = lineErrors; if (eslintRules.isSubsetOf(expectedRules)) { return; } const unmatched = eslintRules.difference(expectedRules); const ruleList = unmatched.getValues(); const message = `These ESLint errors (${ruleList.join(', ')}) ` + `did not have a corresponding expected error.`; throw new Error(makeErrorMessage(lineErrors, message)); } /** * Verifies that each expected error was also found by ESLint. * @param {!types.LineErrors} lineErrors */ function verifyExpectedErrors(lineErrors) { const {eslintRules, expectedRules} = lineErrors; if (expectedRules.isSubsetOf(eslintRules)) { return; } const unmatched = expectedRules.difference(eslintRules); const ruleList = unmatched.getValues(); const message = `These expected errors (${ruleList.join(', ')}) ` + `were not found by ESLint.`; throw new Error(makeErrorMessage(lineErrors, message)); } exports = { compareEslintToExpected, compareErrorsForFile, makeErrorMessage, verifyEslintErrors, verifyExpectedErrors, };
JavaScript
0.000001
@@ -1735,18 +1735,26 @@ e = %60The -se + following ESLint @@ -2299,18 +2299,26 @@ e = %60The -se + following expecte
6c919ee4ad667670ed5d565d18090dd6cb56ee5b
Fix dependencyin model
packages/isomorphic-core/src/models/transaction.js
packages/isomorphic-core/src/models/transaction.js
const {DatabaseTypes: {JSONARRAYType}} = require('isomorphic-core'); module.exports = (sequelize, Sequelize) => { return sequelize.define('transaction', { event: Sequelize.STRING, object: Sequelize.STRING, objectId: Sequelize.STRING, changedFields: JSONARRAYType('changedFields'), }, { instanceMethods: { toJSON: function toJSON() { return { id: `${this.id}`, event: this.event, object: this.object, objectId: this.objectId, changedFields: this.changedFields, } }, }, }); }
JavaScript
0
@@ -2,24 +2,8 @@ onst - %7BDatabaseTypes: %7BJS @@ -14,17 +14,16 @@ RAYType%7D -%7D = requi @@ -30,23 +30,25 @@ re(' -isomorphic-core +../database-types ');%0A
8163be8e5ffd873e1953520d0a9ea7804900a876
remove extra closing bracket
public/navigation.js
public/navigation.js
var app = angular.module('myApp', []); app.controller("Ctrl1",function($scope){ $scope.contents = { name : 'Work Experience', isDropdown: true, dropdownValues: ['HubSpot | June 2016 - Dec 2016', 'HubSpot | May 2015 - Dec 2015', 'Goldman Sachs | July 2014 - Dec 2014'] }; $scope.navBarData = [ { name : 'Work Experience', isDropdown: true, dropdownValues: ['HubSpot | June 2016 - Dec 2016', 'HubSpot | May 2015 - Dec 2015', 'Goldman Sachs | July 2014 - Dec 2014'] }, { name : 'Education', isDropdown: false, dropdownValues: [] }, { name : 'Mentorship', isDropdown: true, dropdownValues: ['Fellow | Jan 2016 - April 2016', 'Tutor | Jan 2014 - April 2014 Surfing'] }, { name : 'Hobbies', isDropdown: true, dropdownValues: ['Performing', 'Kite Surfing', 'Running'] } ]; }); app.directive('navbar', function() { return { restrict: 'AE', replace: 'true', templateUrl: '/navigation.html', scope: false }; }); });
JavaScript
0.000001
@@ -995,17 +995,13 @@ lse%0A %7D; -%0A%7D); %0A%0A%7D);
544a32414e33cee5e69eebbb0ddcfdac0f9ffa35
(refactor) add the last line
home/home.js
home/home.js
var dbConnection = require('../databaseSetup.js'); //checks if the user has received any friend requests and any contents to vote. module.exports.checkUpdates = function(req, res){ //take the userId information from the request. var userId = req.body.userId; //prepare the data object to send back with the properties. var data = { friendRequestCount: undefined, pendingCount: undefined }; //define the mysql query to use var countFriendRequestQuery = "SELECT * FROM friendRequests WHERE confirmerId = ?"; var countPendingQuery = "SELECT contentId FROM receivers WHERE receiversId = ?"; //first, check friendRequests database to check if there is any friend requests dbConnection.query(countFriendRequestQuery, userId, function(error, rows){ if(error){ res.send(error); }else{ //store the number of the requests in the data object data.friendRequestCount = rows.length; //second, check receivers datbase to check if there is any pending contents dbConnection.query(countPendingQuery, userId, function(error, rows){ if(error){ //if there is any error, send back the friend request count at least. res.send(data); }else{ //store the number of the pending contents in the data object data.pendingCount = rows.length; //send back the data to client res.send(data); } }); } }); };
JavaScript
0.999982
@@ -1440,8 +1440,9 @@ );%0A %0A%7D; +%0A
e1ed0981ea780a4006738cf844908ba6b16b3c72
Update Tooltip onClick fallback
src/atoms/Tooltip/index.js
src/atoms/Tooltip/index.js
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import Icon from 'atoms/Icon'; import Modal from 'molecules/Modal'; import styles from './tooltip.module.scss'; class Tooltip extends React.Component { constructor(props) { super(props); this.state = { modalIsOpen: false, visible: false }; } componentDidMount() { document.addEventListener('mousedown', this.hide); } componentWillUnmount() { document.removeEventListener('mousedown', this.hide); } setWrapperRef = (node) => { this.ref = node; } openModal = () => { (window.innerWidth <= 768) && this.setState({ modalIsOpen: true }); } closeModal = () => { this.setState({ modalIsOpen: false }); } toggleVisibility = (e) => { e.stopPropagation(); this.setState({ visible: !this.state.visible }); this.props.onClick && this.props.onClick(e); }; hide = (e) => { if (this.ref && !this.ref.contains(e.target)) { e.stopPropagation(); this.setState({ visible: false }); } }; handleClick = e => window.innerWidth <= 768 ? this.openModal() : this.toggleVisibility(e); render() { const { children, className, left, right, text, hoverMessageClassName, inline, tooltipIconSize, revealOnClick } = this.props; return ( <span> <span onClick={revealOnClick ? this.handleClick : this.openModal} className={classnames( !revealOnClick && styles['tooltip-wrapper'], this.state.visible && styles.reveal, inline && styles[`inline-${inline}`], className )} ref={this.setWrapperRef} > { text || <Icon icon='tooltip' className={styles['tooltip']} inline={inline} height={`${tooltipIconSize}px`} width={`${tooltipIconSize}px`} /> } <span className={classnames( children && styles['hover-message'], left && styles['left'], right && styles['right'], hoverMessageClassName )} > { children } </span> </span> <Modal header='Learn more' onRequestClose={this.closeModal} isOpen={this.state.modalIsOpen} contentLabel='' > {children} </Modal> </span> ); } } Tooltip.propTypes = { /** * This prop will add a new className to any inherent classNames * provided in the component's index.js file. */ className: PropTypes.string, /** * render left-side variant */ left: PropTypes.bool, /** * render right-side variant */ right: PropTypes.bool, /** * onClick will override the default `openModal` click handler */ onClick: PropTypes.func, /** * defaults to a question mark Icon */ text: PropTypes.node, /** * className for the hover message */ hoverMessageClassName: PropTypes.string, /** * adds margin to left or right when Tooltip is inline */ inline: PropTypes.oneOf([ 'left', 'right', ]), /** * Changes height and width of default Tooltip icon. Provide a pixel amount as a number (without the units) */ tooltipIconSize: PropTypes.number, /** * When viewport is not mobile and revealOnClick prop is present, reveals tooltip message on click only */ revealOnClick: PropTypes.bool }; Tooltip.defaultProps = { tooltipIconSize: 12, }; export default Tooltip;
JavaScript
0
@@ -607,31 +607,32 @@ penModal = ( +e ) =%3E %7B%0A - (window. @@ -697,24 +697,79 @@ rue%0A %7D);%0A + this.props.onClick && this.props.onClick(e, true);%0A %7D%0A%0A close @@ -996,16 +996,37 @@ nClick(e +, !this.state.visible );%0A %7D;%0A @@ -1176,16 +1176,16 @@ %7D%0A %7D;%0A%0A - handle @@ -1239,16 +1239,17 @@ enModal( +e ) : this
6afd96d5b6f59b9d61b15fb08ec36b936d1f90b3
fix linting in circler tank
packages/jsbattle-engine/src/tanks/circler.tank.js
packages/jsbattle-engine/src/tanks/circler.tank.js
// Author: Jonathan Cross importScripts('lib/tank.js'); tank.init(function(settings, info) { settings.SKIN = "forest" wander_turn_counter = 0; circle_dir = 1.0; boost_counter = 0; prev_energy = 100; }); function controlGun(state, control) { if (!state.radar.enemy) { // Fire randomly in the hope to hit something by luck. control.GUN_TURN = 1; control.SHOOT = 0.1; return; } // Predict where the enemy will be to adjust the gun angle. let enemy = state.radar.enemy; let bullet_speed = 4; let distance = Math.distance(state.x, state.y, enemy.x, enemy.y) let bullet_time = distance / bullet_speed; let target = {x: enemy.x + bullet_time * enemy.speed * Math.cos(Math.deg2rad(enemy.angle)), y: enemy.y + bullet_time * enemy.speed * Math.sin(Math.deg2rad(enemy.angle))}; let enemy_angle = Math.deg.atan2(target.y - state.y, target.x - state.x); let gun_angle_diff = Math.deg.normalize(enemy_angle - state.gun.angle - state.angle); control.GUN_TURN = 0.3 * gun_angle_diff; control.SHOOT = 0.1; } function controlRadar(state, control) { if (!state.radar.enemy) { control.RADAR_TURN = 1; return; } // Try to keep the radar fixed on the enemy. let dx = state.radar.enemy.x - state.x; let dy = state.radar.enemy.y - state.y; let enemy_angle = Math.deg.atan2(dy, dx); let radar_angle_diff = Math.deg.normalize(enemy_angle - state.radar.angle - state.angle); control.RADAR_TURN = 0.3 * radar_angle_diff; } // Just go in straight lines; if we hit a wall then turn randomly. function wander(state, control) { if (wander_turn_counter > 0) { wander_turn_counter--; control.TURN = -1.0; control.THROTTLE = 0.0; return; } control.TURN = 0.0; control.THROTTLE = 1.0; if (state.collisions.wall) { wander_turn_counter = Math.round(Math.randomRange(40, 70)); } } // Circle around an enemy, changing direction if we // hit something to avoid getting stuck. function circleEnemy(state, control) { if (state.collisions.wall || state.collisions.enemy) { circle_dir *= -1; } let enemy = state.radar.enemy; // Get the unit vector from us to the enemy. let r = Math.distance(state.x, state.y, enemy.x, enemy.y) let u = {x: (enemy.x - state.x) / r, y: (enemy.y - state.y) / r}; // Find the target point to move toward. In the coordinate system // where our tank is to the west and the enemy is to the east, // the target point is 150 units west of the enemy, and // either 100 north or 100 south, depending on circle_dir. let target = {x: enemy.x - 150*u.x - 100*circle_dir*u.y, y: enemy.y - 150*u.y + 100*circle_dir*u.x}; let target_angle = Math.deg.atan2(target.y - state.y, target.x - state.x); let target_angle_diff = Math.deg.normalize(target_angle - state.angle); // Move toward target_angle. If we need to turn more than 90 degrees, // then reverse direction and turn the opposite way. let forwards = Math.abs(target_angle_diff) > 90 ? -1.0 : 1.0; control.TURN = forwards * 0.5 * target_angle_diff; control.THROTTLE = forwards * 1.0; } function controlBoost(state, control) { if (boost_counter > 0) { control.BOOST = 1; boost_counter--; } else { control.BOOST = 0; } // If we took damage, then enable boost for a short time to get away. if (prev_energy != state.energy) { boost_counter = 10; } prev_energy = state.energy; } function controlMovement(state, control) { if (!state.radar.enemy) { wander(state, control); } else { circleEnemy(state, control); } } tank.loop(function(state, control) { controlRadar(state, control); controlGun(state, control); controlMovement(state, control); controlBoost(state, control); });
JavaScript
0.000001
@@ -113,16 +113,17 @@ %22forest%22 +; %0A%0A wand @@ -584,24 +584,25 @@ .x, enemy.y) +; %0A let bulle @@ -2226,16 +2226,17 @@ enemy.y) +; %0A let u
b79827e737fce4dfabe45964b86e82ee36d5241e
Add logging to Algolia index cleaning
packages/lesswrong/server/scripts/algoliaExport.js
packages/lesswrong/server/scripts/algoliaExport.js
/* global Vulcan */ import { Posts } from '../../lib/collections/posts' import { Comments } from '../../lib/collections/comments' import Users from 'meteor/vulcan:users' import { getCollection } from 'meteor/vulcan:lib'; import Sequences from '../../lib/collections/sequences/collection.js' import { wrapVulcanAsyncScript } from './utils' import { getAlgoliaAdminClient, algoliaIndexDocumentBatch, algoliaDeleteIds, algoliaDoSearch, subsetOfIdsAlgoliaShouldntIndex } from '../search/utils'; import { forEachDocumentBatchInCollection } from '../queryUtil'; import keyBy from 'lodash/keyBy'; import { algoliaIndexNames } from '../../lib/algoliaIndexNames'; async function algoliaExport(collection, selector = {}, updateFunction) { let client = getAlgoliaAdminClient(); if (!client) return; const indexName = algoliaIndexNames[collection.collectionName]; // eslint-disable-next-line no-console console.log(`Exporting ${indexName}...`) let algoliaIndex = client.initIndex(indexName) // eslint-disable-next-line no-console console.log("Initiated Index connection") let totalErrors = []; const totalItems = collection.find(selector).count(); let exportedSoFar = 0; await forEachDocumentBatchInCollection({collection, batchSize: 100, loadFactor: 0.5, callback: async (documents) => { await algoliaIndexDocumentBatch({ documents, collection, algoliaIndex, errors: totalErrors, updateFunction }); exportedSoFar += documents.length; // eslint-disable-next-line no-console console.log(`Exported ${exportedSoFar}/${totalItems} entries to Algolia`); }}); if (totalErrors.length) { // eslint-disable-next-line no-console console.log(`${collection._name} indexing encountered the following errors:`, totalErrors) } else { // eslint-disable-next-line no-console console.log('No errors found when indexing', collection._name) } } async function algoliaExportByCollectionName(collectionName) { switch (collectionName) { case 'Posts': await algoliaExport(Posts, {baseScore: {$gte: 0}, draft: {$ne: true}, status: 2}) break case 'Comments': await algoliaExport(Comments, {baseScore: {$gt: 0}, isDeleted: {$ne: true}}) break case 'Users': await algoliaExport(Users, {deleted: {$ne: true}}) break case 'Sequences': await algoliaExport(Sequences) break default: throw new Error(`Did not recognize collectionName: ${collectionName}`) } } export async function algoliaExportAll() { for (let collectionName in algoliaIndexNames) await algoliaExportByCollectionName(collectionName); } Vulcan.runAlgoliaExport = wrapVulcanAsyncScript('runAlgoliaExport', algoliaExportByCollectionName) Vulcan.runAlgoliaExportAll = wrapVulcanAsyncScript('runAlgoliaExportAll', algoliaExportAll) Vulcan.algoliaExportAll = algoliaExportAll // Go through the Algolia index for a collection, removing any documents which // don't exist in mongodb or which exist but shouldn't be indexed. This plus // algoliaExport together should result in a fully up to date Algolia index, // regardless of the starting state. async function algoliaCleanIndex(collection) { let client = getAlgoliaAdminClient(); if (!client) return; // eslint-disable-next-line no-console console.log(`Deleting spurious documents from Algolia index for ${collection.collectionName}`); let algoliaIndex = client.initIndex(algoliaIndexNames[collection.collectionName]); let currentPage = 0; let pageResults; do { // FIXME: If rows actually get deleted, then this shifts the pagination // boundaries, so deleting n documents means skipping the check on the // first n results on the next page. // Unfortunately we can't just naively skip advancing the page whenever // something is deleted, because that has the potential to be // catastrophically slow; if the index consists of (pagesize-1) valid // documents followed by many invalid documents, then we handle the invalid // documents only one at a time. pageResults = await algoliaDoSearch(algoliaIndex, { query: "", attributesToRetrieve: ['objectID', '_id'], hitsPerPage: 1000, page: currentPage, }); currentPage++; const ids = _.map(pageResults.hits, hit=>hit._id); const mongoIdsToDelete = await subsetOfIdsAlgoliaShouldntIndex(collection, ids); const mongoIdsToDeleteDict = keyBy(mongoIdsToDelete, id=>id); if (mongoIdsToDelete.length > 0) { const hitsToDelete = _.filter(pageResults.hits, hit=>hit._id in mongoIdsToDeleteDict); const objectIdsToDelete = _.map(hitsToDelete, hit=>hit.objectID); await algoliaDeleteIds(algoliaIndex, objectIdsToDelete); } } while(pageResults.hits.length > 0) } export async function algoliaCleanAll() { for (let collectionName in algoliaIndexNames) await algoliaCleanIndex(getCollection(collectionName)); } Vulcan.algoliaCleanIndex = wrapVulcanAsyncScript('algoliaCleanIndex', algoliaCleanIndex); Vulcan.algoliaCleanAll = wrapVulcanAsyncScript('algoliaCleanAll', algoliaCleanAll); Vulcan.algoliaCleanAll = algoliaCleanAll
JavaScript
0
@@ -4234,27 +4234,8 @@ %7D);%0A - currentPage++;%0A @@ -4655,75 +4655,395 @@ -await algoliaDeleteIds(algoliaIndex, objectIdsToDelete);%0A %7D%0A +// eslint-disable-next-line no-console%0A console.log(%60Deleting $%7BobjectIdsToDelete.length%7D object IDs for $%7BmongoIdsToDelete.length%7D mongo IDs%60);%0A await algoliaDeleteIds(algoliaIndex, objectIdsToDelete);%0A %7D else %7B%0A // eslint-disable-next-line no-console%0A console.log(%60Nothing to delete in page $%7BcurrentPage%7D with $%7Bids.length%7D hits%60);%0A %7D%0A %0A currentPage++; %0A %7D
c6e653a1f15ff6349650168f22bd5c73c90d6709
Update dict.tw.js
proxy_module/dict.tw/dict.tw.js
proxy_module/dict.tw/dict.tw.js
/** * 查詢 www.moedict.tw * 成功查詢的頁面:https://www.moedict.tw/%E5%8B%BE%E8%90%8C * http://localhost:3000/moedict/勾萌 * * 成功查詢的頁面:https://www.moedict.tw/%E5%AE%8B * http://localhost:3000/moedict/宋 * * 失敗查詢的頁面:https://www.moedict.tw/%E4%B8%8D%E8%90%8C * http://localhost:3000/moedict/不萌 * */ CONFIG.module_alias["dict.tw"] = "dict.tw"; launch_proxy["dict.tw"] = function (_output, _query, _mode) { var _options = { module: "dict.tw", query: _query, // 正式查詢 url: "http://dict.tw/dict/" + encodeURI(_query), encoding: "utf8", // -------------------------------------------------- /** * 沒找到資料的選擇器 */ //content_not_found_selector: "body", content_not_found_string: '<body itemscope="itemscope" itemtype="http://schema.org/ItemList">', /** * 取出指定元素的HTML程式碼 */ //html_selector: ".syllable:first-of-type", /** * 取出指定元素的純文字 * 取出音節(斷句) */ //text_selector: ".syllable:first-of-type", /** * 指定處理元素的方法 */ process: function (_content) { // var _d = $(_content).find(".db_info").find(".def"); var _s = $(_content).find(".syllable:first"); var _syllable =_s[0].text; var _d = $(_content).find(".db_info").next(".def").find(".syllable"); var _def = _d[0].value; var _removePhone = $(_d[0]).find("a").remove(); var _removeSyllable = $(_removePhone).find("span").remove(); var _removeBr = $(_removeSyllable).find("br").remove(); var _t = _removeBr.text; _content =_syllable + " def:"+ _def + " phone:" + _t; return _content; }, // ------------------------ /** * 指定use_agnet (可省略) */ //user_agent: "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10", /** * 指定來源網頁 referer (可省略) */ //referer: "https://zh.wikipedia.org/wiki/Wikipedia:%E9%A6%96%E9%A1%B5", // ------------------------ /** * 參考來源網頁的名稱 */ //referer_name: "dict.tw線上字典", /** * 參考來源網頁 */ //referer_source: "https://zh.wikipedia.org/w/index.php?title=" + encodeURI(_query) + "&oldformat=true" }; web_crawler(_output, _options, _mode); //_res.send(_query); // ---------------------------------------- }; // launch_proxy = function (_output, _query) {
JavaScript
0.000001
@@ -844,18 +844,16 @@ */%0A -// html_sel @@ -857,32 +857,36 @@ selector: %22. -syllable +db_info .def :first-of-ty @@ -1035,16 +1035,18 @@ */%0A +/* process: @@ -1690,16 +1690,18 @@ ;%0A %7D, +*/ %0A
64a733f8e1da5c302e1424e2ff7930b2da43198b
remove parent form submit on enter
enterKey.js
enterKey.js
/** * @copyright Urucas * @license MIT License * @version Release: 1.0.0 * @link http://urucas.com * @developers Bruno Alassia, Pamela Prosperi */ Element.prototype.enterKey = function(callback) { if(!(this instanceof HTMLInputElement && this.getAttribute("type") == "text")) { return; } // remove parent form default submit on enter var parent = this.parentNode; while(!(parent instanceof HTMLDocument) && parent != null) { if(parent instanceof HTMLFormElement) { parent.setAttribute("onsubmit","return false"); break; } parent = parent.parentNode; } this.addEventListener("keyup", function(e){ var keyCode = e.keyCode; if(keyCode == 13) { callback(this.value); e.stopPropagation(); } }, false); } NodeList.prototype.enterKey = function(callback, preventDefault) { for(var i=0;i<this.length;i++){ if(this.item(i) instanceof Element) { this.item(i).enterKey(callback); } } }; // jQuery extension try { jQuery.fn.enterKey = function(callback) { for(var i=0; i<this.length;i++) { var el = this[i]; el.enterKey(callback); } return this; } }catch(e) {} // prevent submit default event try { }catch(e) { }
JavaScript
0
@@ -1124,60 +1124,4 @@ %7B%7D%0A -%0A// prevent submit default event%0Atry %7B%0A%09%0A%7Dcatch(e) %7B %7D%0A%0A
1aa77efc5126b29a3401242cb4e46f8174863cac
Add call to super in constructor because it is required
entities.js
entities.js
/* entities.js * Stuff that moves and reacts to physics */ 'use strict'; /* Point * * public: * - x * - y * - step(gravity) * * private: * - vx * - vy * - dx * - dy */ class Point { constructor(x, y, friction = 0, airFriction = 1) { // TODO: should I use point IDs??? // this.id = id++; // debug // position this.x = x; this.y = y; // velocity this.dx = 0; this.dy = 0; // previous position for inertia this.vx = x; this.vy = y; this.friction = friction; this.airFriction = airFriction; } step(gravity) { this.dx = (this.x - this.vx) * this.airFriction + gravity.x; this.dy = (this.y - this.vy) * this.airFriction + gravity.y; this.vx = this.x; this.vy = this.y; this.x += this.dx; this.y += this.dy; } } class Constraint { shouldCrash(crashed) { return crashed; } shouldResolve() { return true; } doResolve() { throw new Error('Not implemented'); } resolve(crashed) { if (this.shouldResolve(crashed)) { this.doResolve(); } return this.shouldCrash(crashed); } } /* Stick * * public: * - resolve() * * private: * - p * - q * - restLength */ class Stick extends Constraint { constructor (p, q) { this.p = p; this.q = q; this.restLength = this.length; } get dx() { return this.p.x - this.q.x; } get dy() { return this.p.y - this.q.y; } get length() { let dx = this.dx; let dy = this.dy; return Math.sqrt(dx * dx + dy * dy); } get diff() { // prevent division by zero // this will allow interesting behavior but w/e if (this.length === 0) { return 0; } return (this.length - this.restLength) / this.length * 0.5; } // set dx(x) {}, set dy(x) {}, set length(x) {}, set diff(x) {}, doResolve() { let dx = this.dx * this.diff; let dy = this.dy * this.diff; this.p.x -= dx; this.p.y -= dy; this.q.x += dx; this.q.y += dy; } } /* BindStick * * public: * - resolve() * * private: * - p * - q * - restLength * - endurance */ class BindStick extends Stick { constructor(p, q, endurance) { super(p, q); this.endurance = endurance * this.restLength * 0.5; } shouldCrash(crashed) { return crashed || this.diff > this.endurance; } shouldResolve(crashed) { return !this.shouldCrash(crashed); } } /* RepelStick * * public: * - resolve() * * private: * - p * - q * - restLength */ class RepelStick extends Stick { shouldResolve() { return this.length < this.restLength; } } /* Stick * * public: * - resolve() * * private: * - p * - q * - restLength */ class ScarfStick extends Stick { doResolve() { this.q.x += this.dx * this.diff * 2; this.q.y += this.dy * this.diff * 2; } } class Joint extends Constraint { constructor(s, t, p = null) { this.s = s; this.t = t; this.p = p; } } // allow kramuals class ClockwiseCrashJoint extends Joint { constructor(s, t) { super(s, t); } isClockwise() { return this.s.dx * this.t.dy - this.s.dy * this.t.dx >= 0; } shouldResolve() { return false; } shouldCrash(crashed) { return crashed || !this.isClockwise(); } } module.exports = { Point, Stick, BindStick, RepelStick, ScarfStick, ClockwiseCrashJoint };
JavaScript
0.000001
@@ -1253,24 +1253,38 @@ or (p, q) %7B%0A + super();%0A%0A this.p = @@ -2898,24 +2898,38 @@ p = null) %7B%0A + super();%0A%0A this.s =
d7f6cf31b28e2f245afa71a27da24e090f4c0992
formatted the help output
knoxfs.js
knoxfs.js
var HDFSRequest = require('./hdfsmod'); var readline = require('readline'), rl = readline.createInterface(process.stdin, process.stdout); var user = "guest"; var pwd = "guest-password"; var hostport = "localhost:8443"; var cluster = "sandbox"; var wd = "/"; rl.setPrompt('knoxfs> '); rl.prompt(); if (typeof String.prototype.startsWith != 'function') { // see below for better implementation! String.prototype.startsWith = function (str){ return this.indexOf(str) == 0; }; } function callback(error, response, body) { if (!error && response.statusCode == 200) { console.log(body); } else { console.log(error); } } console.log(""); console.log("KKKKKKKKK KKKKKKK FFFFFFFFFFFFFFFFFFFFFF "); console.log("K:::::::K K:::::K F::::::::::::::::::::F "); console.log("K:::::::K K:::::K F::::::::::::::::::::F "); console.log("K:::::::K K::::::K FF::::::FFFFFFFFF::::F "); console.log("KK::::::K K:::::KKKnnnn nnnnnnnn ooooooooooo xxxxxxx xxxxxxx F:::::F FFFFFF ssssssssss "); console.log(" K:::::K K:::::K n:::nn::::::::nn oo:::::::::::oox:::::x x:::::x F:::::F ss::::::::::s "); console.log(" K::::::K:::::K n::::::::::::::nn o:::::::::::::::ox:::::x x:::::x F::::::FFFFFFFFFFss:::::::::::::s "); console.log(" K:::::::::::K nn:::::::::::::::no:::::ooooo:::::o x:::::xx:::::x F:::::::::::::::Fs::::::ssss:::::s"); console.log(" K:::::::::::K n:::::nnnn:::::no::::o o::::o x::::::::::x F:::::::::::::::F s:::::s ssssss "); console.log(" K::::::K:::::K n::::n n::::no::::o o::::o x::::::::x F::::::FFFFFFFFFF s::::::s "); console.log(" K:::::K K:::::K n::::n n::::no::::o o::::o x::::::::x F:::::F s::::::s "); console.log("KK::::::K K:::::KKK n::::n n::::no::::o o::::o x::::::::::x F:::::F ssssss s:::::s "); console.log("K:::::::K K::::::K n::::n n::::no:::::ooooo:::::o x:::::xx:::::x FF:::::::FF s:::::ssss::::::s"); console.log("K:::::::K K:::::K n::::n n::::no:::::::::::::::ox:::::x x:::::x F::::::::FF s::::::::::::::s "); console.log("K:::::::K K:::::K n::::n n::::n oo:::::::::::oox:::::x x:::::x F::::::::FF s:::::::::::ss "); console.log("KKKKKKKKK KKKKKKK nnnnnn nnnnnn ooooooooooo xxxxxxx xxxxxxxFFFFFFFFFFF sssssssssss "); console.log(""); rl.on('line', function(line) { switch(line.trim()) { case '?': case 'help': console.log(''); console.log('Available KnoxFs Commands and Usage ---------------'); console.log('ls - Usage: ls <path> '); console.log('open - Usage: open <path> '); console.log('create - Usage: create <local-file-path> <dest-path> '); console.log('rm - Usage: rm <path> '); console.log('cd - Usage: cd <path> '); console.log('pwd - Usage: pwd '); console.log('---------------------------------------------------'); break; default: var knox = new HDFSRequest('https://' + hostport + '/gateway', cluster, user, pwd); if (line.startsWith('ls ') || line == "ls") { var array = line.split(" "); if (array.length > 1 && !array[1].startsWith("/")) array[1] = this.wd + array[1]; var path = ""; if (array.length == 1) { path = this.wd; } else { path = array[1]; } var status = knox.listStatus({path: path}, callback); } else if (line.startsWith('open ')) { var array = line.split(" "); if (array.length > 1 && !array[1].startsWith("/")) array[1] = this.wd + array[1]; var path = ""; if (array.length == 1) { path = this.wd; } else { path = array[1]; } var status = knox.open({path: path}, callback); } else if (line.startsWith('create ')) { // var array = line.split(" "); // knox.create(array[1], {path: array[2]}, callback); console.log("Not available yet.") } else if (line.startsWith('rm ')) { var array = line.split(" "); knox.rm({path: array[1]}, callback); } else if (line.startsWith('cd ')) { var array = line.split(" "); if (typeof this.wd == 'undefined') this.wd = "/"; if (array[1].startsWith("/")) { this.wd = array[1]; } else { this.wd += array[1]; } if (this.wd != "/") { this.wd += "/"; } console.log("set working dir to: " + this.wd); } else if (line.startsWith('pwd')) { console.log("current working dir is: " + this.wd); } } rl.prompt(); }).on('close', function() { console.log('Have a great day!'); process.exit(0); });
JavaScript
0.999999
@@ -3074,16 +3074,20 @@ log('rm + - Usage: @@ -3123,16 +3123,20 @@ log('cd + - Usage: @@ -3173,16 +3173,19 @@ og('pwd + - Usage:
ee218756db38e3e5c7b04fc5aaf0ac6d07f6574d
Disable keyboard shortcuts when modal windows is visible
public/app/keyboardShortcuts.js
public/app/keyboardShortcuts.js
/******************************************************************************* * Copyright (C) 2012 eBay 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. ******************************************************************************/ define([ "jquery", "app" ], function($, app) { var aPressed = false; var lastKey = ''; var isCtrl = false; $(document) .keydown(function(e) { if (e.ctrlKey) { isCtrl = true; } if (e.key === 'a') { aPressed = true; } if ((e.key === 'f' && isCtrl) || (aPressed || lastKey === 'a') && e.key === 's') { app.vent.trigger('focus-search-field'); return false; } if ((aPressed || lastKey === 'a') && e.key === 'c') { app.vent.trigger('units:collapse'); } if ((aPressed || lastKey === 'a') && e.key === 'e') { app.vent.trigger('units:expand'); } }) .keyup(function(e) { if (e.ctrlKey) { isCtrl = false; } if (e.key === 'a') { aPressed = false; } lastKey = e.key; }); });
JavaScript
0
@@ -874,32 +874,125 @@ n(function(e) %7B%0A +%09%09%09/*jshint maxcomplexity:7 */%0A%09%09%09if ($('#asimov-modal').is(%22:visible%22)) %7B%0A%09%09%09%09return;%0A%09%09%09%7D%0A%0A %09%09%09if (e.ctrlKey @@ -1460,16 +1460,78 @@ on(e) %7B%0A +%09%09%09if ($('#asimov-modal').is(%22:visible%22)) %7B%0A%09%09%09%09return;%0A%09%09%09%7D%0A%0A %09%09%09if (e
b1d707dc0fefe71f4d649322fa72f39f502482b1
save the model attributes, not the model's JSON representation
public/backbone.localStorage.js
public/backbone.localStorage.js
/** * Backbone localStorage Adapter * Version 1.1.7 * * https://github.com/jeromegn/Backbone.localStorage */ (function (root, factory) { if (typeof exports === 'object' && typeof require === 'function') { module.exports = factory(require("underscore"), require("backbone")); } else if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["underscore","backbone"], function(_, Backbone) { // Use global variables if the locals are undefined. return factory(_ || root._, Backbone || root.Backbone); }); } else { // RequireJS isn't being used. Assume underscore and backbone are loaded in <script> tags factory(_, Backbone); } }(this, function(_, Backbone) { // A simple module to replace `Backbone.sync` with *localStorage*-based // persistence. Models are given GUIDS, and saved into a JSON object. Simple // as that. // Hold reference to Underscore.js and Backbone.js in the closure in order // to make things work even if they are removed from the global namespace // Generate four random hex digits. function S4() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; // Generate a pseudo-GUID by concatenating random hexadecimal. function guid() { return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); }; // Our Store is represented by a single JS object in *localStorage*. Create it // with a meaningful name, like the name you'd give a table. // window.Store is deprectated, use Backbone.LocalStorage instead Backbone.LocalStorage = window.Store = function(name) { if( !this.localStorage ) { throw "Backbone.localStorage: Environment does not support localStorage." } this.name = name; var store = this.localStorage().getItem(this.name); this.records = (store && store.split(",")) || []; }; _.extend(Backbone.LocalStorage.prototype, { // Save the current state of the **Store** to *localStorage*. save: function() { this.localStorage().setItem(this.name, this.records.join(",")); }, // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already // have an id of it's own. create: function(model) { if (!model.id) { model.id = guid(); model.set(model.idAttribute, model.id); } this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model)); this.records.push(model.id.toString()); this.save(); return this.find(model); }, // Update a model by replacing its copy in `this.data`. update: function(model) { this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model)); if (!_.include(this.records, model.id.toString())) this.records.push(model.id.toString()); this.save(); return this.find(model); }, // Retrieve a model from `this.data` by id. find: function(model) { return this.jsonData(this.localStorage().getItem(this.name+"-"+model.id)); }, // Return the array of all models currently in storage. findAll: function() { // Lodash removed _#chain in v1.0.0-rc.1 return (_.chain || _)(this.records) .map(function(id){ return this.jsonData(this.localStorage().getItem(this.name+"-"+id)); }, this) .compact() .value(); }, // Delete a model from `this.data`, returning it. destroy: function(model) { if (model.isNew()) return false this.localStorage().removeItem(this.name+"-"+model.id); this.records = _.reject(this.records, function(id){ return id === model.id.toString(); }); this.save(); return model; }, localStorage: function() { return localStorage; }, // fix for "illegal access" error on Android when JSON.parse is passed null jsonData: function (data) { return data && JSON.parse(data); }, // Clear localStorage for specific collection. _clear: function() { var local = this.localStorage(), itemRe = new RegExp("^" + this.name + "-"); // Remove id-tracking item (e.g., "foo"). local.removeItem(this.name); // Lodash removed _#chain in v1.0.0-rc.1 // Match all data items (e.g., "foo-ID") and remove. (_.chain || _)(local).keys() .filter(function (k) { return itemRe.test(k); }) .each(function (k) { local.removeItem(k); }); this.records.length = 0; }, // Size of localStorage. _storageSize: function() { return this.localStorage().length; } }); // localSync delegate to the model or collection's // *localStorage* property, which should be an instance of `Store`. // window.Store.sync and Backbone.localSync is deprecated, use Backbone.LocalStorage.sync instead Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options) { var store = model.localStorage || model.collection.localStorage; var resp, errorMessage, syncDfd = Backbone.$.Deferred && Backbone.$.Deferred(); //If $ is having Deferred - use it. try { switch (method) { case "read": resp = model.id != undefined ? store.find(model) : store.findAll(); break; case "create": resp = store.create(model); break; case "update": resp = store.update(model); break; case "delete": resp = store.destroy(model); break; } } catch(error) { if (error.code === 22 && store._storageSize() === 0) errorMessage = "Private browsing is unsupported"; else errorMessage = error.message; } if (resp) { if (options && options.success) { if (Backbone.VERSION === "0.9.10") { options.success(model, resp, options); } else { options.success(resp); } } if (syncDfd) { syncDfd.resolve(resp); } } else { errorMessage = errorMessage ? errorMessage : "Record Not Found"; if (options && options.error) if (Backbone.VERSION === "0.9.10") { options.error(model, errorMessage, options); } else { options.error(errorMessage); } if (syncDfd) syncDfd.reject(errorMessage); } // add compatibility with $.ajax // always execute callback for success and error if (options && options.complete) options.complete(resp); return syncDfd && syncDfd.promise(); }; Backbone.ajaxSync = Backbone.sync; Backbone.getSyncMethod = function(model) { if(model.localStorage || (model.collection && model.collection.localStorage)) { return Backbone.localSync; } return Backbone.ajaxSync; }; // Override 'Backbone.sync' to default to localSync, // the original 'Backbone.sync' is still available in 'Backbone.ajaxSync' Backbone.sync = function(method, model, options) { return Backbone.getSyncMethod(model).apply(this, [method, model, options]); }; return Backbone.LocalStorage; }));
JavaScript
0.000002
@@ -2358,32 +2358,43 @@ .stringify(model +.attributes ));%0A this.rec @@ -2639,16 +2639,27 @@ fy(model +.attributes ));%0A
49555daed5c6943860eb307b98c615891c04f2ee
Update myCtrl.js
public/js/controllers/myCtrl.js
public/js/controllers/myCtrl.js
/*global angular*/ /*global controller*/ var myApp=angular.module("myApp",[]); myApp.controller("myCtrl",function($scope,$http){ $http.get("/api/name").then(function(response){ $scope.names=response.data; }); $scope.create=function(){ $http.post("/api/name",$scope.name).then(function(response){ $scope.names=response.data; }) $scope.name=""; }; $scope.remove=function(id){ $http.delete("/api/name/"+id).then(function(response){ $scope.names=response.data; }) }; })
JavaScript
0.000003
@@ -375,16 +375,18 @@ ope.name +.n =%22%22;%0A
05d90965187038ccfcc51e61081ea9f1c8a901dc
Fix clear method in board layer.
src/board/layer.service.js
src/board/layer.service.js
/** * BoardLayer :: This class represents a layer on the board and is the base class for all board * layers. Each layer can contain it's own objects on a grid with coordinates and is responsible * for drawing itself as well as its objects onto the canvas. */ /** * Module definition and dependencies */ angular.module('ngGo.Board.Layer.Service', [ 'ngGo', 'ngGo.Board.Grid.Service' ]) /** * Factory definition */ .factory('BoardLayer', function(BoardGrid) { /** * Constructor */ function BoardLayer(board, context) { //Remember board reference and 2d canvas context this.board = board; this.context = context; //Initialize grid for board objects this.grid = new BoardGrid(); } /***************************************************************************** * Generic grid and object handling ***/ /** * Set grid size */ BoardLayer.prototype.setSize = function(width, height) { //Note: since this method is usually only called upon a global board resize, //which also triggers the redraw method for layers, the layer is not cleared //here, as it will happen anyway during the redraw cycle. //Set it in the grid (removing all objects in the process) this.grid.setSize(width, height); }; /** * Get all items */ BoardLayer.prototype.getAll = function() { return this.grid.clone(); }; /** * Set all items at once */ BoardLayer.prototype.setAll = function(grid) { this.grid = grid.clone(); }; /** * Remove all (clear layer and empty grid) */ BoardLayer.prototype.removeAll = function() { this.clear(); this.grid.empty(); }; /** * Add a single item */ BoardLayer.prototype.add = function(x, y, value) { this.clearCell(x, y); this.grid.set(x, y, value); this.drawCell(x, y); }; /** * Remove a single item */ BoardLayer.prototype.remove = function(x, y) { this.clearCell(x, y); this.grid.unset(x, y); }; /** * Get an item */ BoardLayer.prototype.get = function(x, y) { return this.grid.get(x, y); }; /** * Check if there is an item */ BoardLayer.prototype.has = function(x, y) { return this.grid.has(x, y); }; /***************************************************************************** * Generic drawing methods ***/ /** * Draw layer */ BoardLayer.prototype.draw = function() { //Drawing method to be implemented in specific layer class }; /** * Clear layer (this method doesn't clear objects, as the canvas wipe clears the entire canvas) */ BoardLayer.prototype.clear = function() { if (this.context) { this.context.clearRect( 0, 0, this.context.canvas.clientWidth, this.context.canvas.clientHeight ); } }; /** * Redraw layer */ BoardLayer.prototype.redraw = function() { this.clear(); this.draw(); }; /** * Draw cell */ BoardLayer.prototype.drawCell = function(/*x, y*/) { //Drawing method to be implemented in specific layer class }; /** * Clear cell */ BoardLayer.prototype.clearCell = function(/*x, y*/) { //Clearing method to be implemented in specific layer class }; /** * Redraw cell */ BoardLayer.prototype.redrawCell = function(x, y) { this.clearCell(x, y); this.drawCell(x, y); }; /** * Set the canvas2d context */ BoardLayer.prototype.setContext = function(context) { this.context = context; }; /** * Get the canvas2d context */ BoardLayer.prototype.getContext = function() { return this.context; }; //Return return BoardLayer; });
JavaScript
0
@@ -2670,118 +2670,233 @@ -this.context.clearRect(%0A 0, 0, this.context.canvas.clientWidth, this.context.canvas.clientHeight%0A +var pixelRatio = window.devicePixelRatio %7C%7C 1;%0A var width = this.context.canvas.clientWidth * pixelRatio;%0A var height = this.context.canvas.clientHeight * pixelRatio;%0A this.context.clearRect(0, 0, width, height );%0A
809ef19ce5e42b48a15e5fe79c3be4cd0e5359aa
Remove unnecessary comment
es6/main.js
es6/main.js
require('jquery'); require('jquery-mobile'); require('jquery.cookie'); // for flat-ui require('jquery-ui'); require('jquery-ui-touch-punch'); require('../bower_components/bootstrap/dist/js/bootstrap.js'); require('bootstrap-switch'); require('bootstrap-tagsinput'); // require('holderjs'); // require('typeahead.js'); require('select2'); require('../bower_components/flat-ui/js/radiocheck.js'); import * as shiren4 from '../es6/model/shiren4.js'; $(() => { // alert(shiren4.data[0].name) $(':checkbox').checkboxradio(); $('a.reset-checkboxes').click(() => { if(window.confirm('リセットしますか?')) clearCheckboxes(); }); loadFromCookie(); $(':checkbox').change(() => saveToCookie()); }); // Clear CheckBoxes "{{{1 var clearCheckboxes = () => { $(':checkbox') .prop('checked', false) .checkboxradio('refresh'); saveToCookie(); }; // Save/Load Cookie Data "{{{1 var loadFromCookie = () => { if (typeof getCookie() === "undefined") return; var cookieData = JSON.parse(getCookie()); Object.keys(cookieData) .forEach((key) => { $(`#${key} :checkbox`) .each((index, elem) => $(elem) .prop('checked', cookieData[key][$(elem).data('id')]) .checkboxradio('refresh') ); }); }; var saveToCookie = () => { var ary = {}; $(':checkbox') .each((index, val) => { var t = $(val).data('type'); if (!(t in ary)) ary[t] = {}; ary[t][$(val).data('id')] = $(val).prop('checked'); }); var json = JSON.stringify(ary); setCookie(json); }; var setCookie = (data) => { var thirtyDaysLater = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); document.cookie = `data=${encodeURIComponent(data)};path=${location.pathname};expires=${thirtyDaysLater.toGMTString()}`; } var getCookie = () => { if (!document.cookie) return; var targetCookie = document.cookie .split("; ") .map((elem) => { var str = elem.split('='); return {key: str[0], value: str[1]}; }) .filter((cookie) => cookie.key == 'data'); if (!targetCookie.some((cookie) => cookie.key == 'data')) return; return decodeURIComponent(targetCookie[0].value); } // __END__ "{{{1 // vim: expandtab softtabstop=2 shiftwidth=2 // vim: foldmethod=marker
JavaScript
0
@@ -457,41 +457,8 @@ %3E %7B%0A - // alert(shiren4.data%5B0%5D.name)%0A $(
a75ce162aafba8a3fe7a753892c4588cf8197bb3
Fix volume list item quirk
src/templates/volume.js
src/templates/volume.js
import React from "react"; import { Link } from "gatsby"; import { prepareTitle } from "../common.js"; import Layout from "../components/layout"; import styled from "@emotion/styled"; import SEO from "../components/seo"; const VolumeWrapper = styled.div` border-top: 1px solid #faf9f3; `; const Volume = styled.div` max-width: 960px; margin: 0 auto; font-size: 0.92rem; `; const VolumeTitle = styled.h2` padding-left: 24px; padding-right: 24px; `; const DiscourseList = styled.div` -moz-border-radius: 2px; -webkit-border-radius: 2px; border-bottom: 1px solid #e3e1ce; border-left: 1px solid #e3e1ce; border-spacing: 0; border-top: 1px solid #e3e1ce; clear: both; max-width: 100%; background-color: white; margin-bottom: 16px; @media (max-width: 640px) { padding: 12px; } `; const DiscourseListItem = styled.div` display: flex; @media (max-width: 640px) { flex-direction: column; margin-top: 24px; margin-bottom: 24px; } @media (min-width: 641px) { margin-top: 8px; margin-bottom: 8px; } &:first-of-type { margin-top: 8px; } &:last-of-type { margin-bottom: 8px; } &:hover { background-color: #f8f8f8; } `; const Pages = styled.div` width: 80px; padding: 4px 8px; @media (max-width: 640px) { order: 4; padding-left: 24px; } @media (min-width: 641px) { padding-left: 12px; } `; const DateComponent = styled.div` width: 145px; padding: 4px 8px; @media (max-width: 640px) { padding-left: 24px; order: 3; } `; const Speaker = styled.div` width: 130px; padding: 4px 8px; @media (max-width: 640px) { order: 2; padding-left: 24px; } `; const Title = styled.div` flex: 1; @media (max-width: 640px) { order: 1; } padding: 4px 8px; padding-right: 12px; `; export default ({ pageContext: { volumeNumbers, volumeNumber, discourses } }) => { return ( <Layout volumeNumbers={volumeNumbers} volumeNumber={volumeNumber}> <SEO title={`Journal of Discourses, vol. ${volumeNumber}`} /> <VolumeWrapper> <Volume> <VolumeTitle>Volume {volumeNumber}</VolumeTitle> <DiscourseList> {discourses.map(discourse => { const event = new Date(); if (discourse.date) { event.setFullYear(parseInt(discourse.date.substr(0, 4), 10)); event.setMonth(parseInt(discourse.date.substr(5, 7), 10) - 1); event.setDate(parseInt(discourse.date.substr(8, 10), 10)); event.setUTCHours(0); } const dateOptions = { year: "numeric", month: "long", day: "numeric" }; return ( <DiscourseListItem key={discourse.id}> <Pages> pp. {discourse.start_page}-{discourse.end_page} </Pages> <DateComponent title={discourse.date}> {discourse.date && event.toLocaleDateString("default", dateOptions)} </DateComponent> <Speaker>{discourse.speaker}</Speaker> <Title> <Link to={`/${discourse.volume}/${discourse.start_page}`} dangerouslySetInnerHTML={{ __html: prepareTitle(discourse.title) }} /> </Title> </DiscourseListItem> ); })} </DiscourseList> </Volume> </VolumeWrapper> </Layout> ); };
JavaScript
0.00001
@@ -868,16 +868,31 @@ : flex;%0A + width: 100%25;%0A @media @@ -1589,22 +1589,72 @@ %60%0A +padding: 4px 8px;%0A @media (max- width: -13 +64 0px +) %7B%0A order: 2 ;%0A + pa @@ -1654,34 +1654,40 @@ %0A padding +-left : +2 4px - 8px; +;%0A %7D %0A @media (m @@ -1678,34 +1678,34 @@ %0A %7D%0A @media (m -ax +in -width: 640px) %7B @@ -1690,39 +1690,57 @@ a (min-width: 64 -0 +1 px) %7B%0A + width: 130px;%0A order: 2;%0A
9bfc53e355800310b18c32d802243ed1cfc23d29
Update jquery.responsiveImage.js
src/jquery.responsiveImage.js
src/jquery.responsiveImage.js
/*! jquery-responsive-image * Copyright (c) 2015 Jan Rembold <janrembold@gmail.com>; License: MIT */ (function ( $, window, document, undefined ) { 'use strict'; // Create the defaults var pluginName = 'responsiveImage', defaults = { source: '> span', sourcePrefix: '', container: null, minWidthDefault: 0, maxWidthDefault: Number.MAX_VALUE, minDprDefault: 1, attributes: ['title', 'alt', 'class', 'width', 'height'], resizeEvent: 'resize', preload: false, autoDpr: false, onGetWidth: null, onLoadSources: null }; // The actual plugin constructor function Plugin ( element, options ) { var self = this; self.$element = $(element); self.options = $.extend( {}, defaults, options ); self.sources = []; self.dpr = self.getDpr(); self.attributeCount = self.options.attributes.length; if( typeof( self.$element.data('source-prefix') ) !== 'undefined' ) { self.options.sourcePrefix = self.$element.data('source-prefix'); } self.init(); } // Avoid Plugin.prototype conflicts $.extend(Plugin.prototype, { init: function () { var self = this; // load sources self.sources = self.loadSources(); if(self.sources.length === 0) { return; } // check container or viewport support - data-container overrides default setting var containerSelector = self.$element.attr('data-container') || self.options.container; if(containerSelector) { self.$container = self.$element.parents(containerSelector); } // load responsive image self.loadResponsiveImage(); // init resize event with jquery-debouncedwidth support: https://github.com/janrembold/jquery-debouncedwidth self.initResizeEvent(); }, loadSources: function(){ var self = this; var sources = []; if( $.isFunction( self.options.onLoadSources ) ) { // use injected source loader sources = self.options.onLoadSources( self ); } else { // prepare all necessary image data self.$element.find(self.options.source).each(function(){ var $source = $(this); // only use images with source if($source.data('src')) { var data = { 'src': self.options.sourcePrefix + $source.data('src'), 'minWidth': $source.data('min-width') || self.options.minWidthDefault, 'maxWidth': $source.data('max-width') || self.options.maxWidthDefault, 'minDpr': $source.data('min-dpr') || self.options.minDprDefault }; // prepare all attributes for(var i=0; i<self.attributeCount; i++) { var attribute = self.options.attributes[i]; data[attribute] = $source.data(attribute) || self.$element.data(attribute); } sources.push(data); } }); } // sort sources desc by minWidth, maxWidth and minDpr -> largest files first sources.sort(function(a, b) { if(b.minWidth === a.minWidth) { if(b.maxWidth === a.maxWidth) { return b.minDpr - a.minDpr; } return b.maxWidth - a.maxWidth; } return b.minWidth - a.minWidth; }); return sources; }, loadResponsiveImage: function () { var self = this; var newSource; var targetWidth = self.getWidth(); var sourceCount = self.sources.length; // search for best image source for (var i=0; i<sourceCount; i++) { if( self.sources[i].minWidth <= targetWidth && self.sources[i].maxWidth > targetWidth && self.sources[i].minDpr <= self.dpr ) { newSource = self.sources[i]; break; } } // check if image is already loaded if(newSource === self.$currentSource) { return; } // set new source self.$currentSource = newSource; // create new image var $image = self.createImageWithAttributes(newSource); // append responsive image immediately to target element if( !self.options.preload ) { self.setNewSource( $image ); } }, setNewSource: function( $image ) { var self = this; // set new image to html self.$element.html( $image ); // trigger new source event self.$element.trigger('new.source.'+pluginName); }, getWidth: function(){ var self = this; var width; if($.isFunction(self.options.onGetWidth)) { // get width from custom function width = self.options.onGetWidth.call(this); } else if(self.$container) { // get width from container width = self.$container.width(); } else { // get window width width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; } // multiply width with dpr if( self.options.autoDpr ) { width *= self.dpr; } return width; }, getDpr: function(){ var dpr = 1; if (window.screen.systemXDPI !== undefined && window.screen.logicalXDPI !== undefined && window.screen.systemXDPI > window.screen.logicalXDPI) { dpr = window.screen.systemXDPI / window.screen.logicalXDPI; } if (window.devicePixelRatio !== undefined) { dpr = window.devicePixelRatio; } // return only dpr >= 1, because zoomed pages (>100%) return dpr values smaller than 1 return dpr >= 1 ? dpr : 1; }, createImageWithAttributes: function(source){ // create default image var self = this; var $image = $('<img/>'); // append all given attributes for(var i=0; i<self.attributeCount; i++) { var attribute = self.options.attributes[i]; if(typeof(source[attribute]) !== 'undefined' && source[attribute] !== '') { $image.attr(attribute, source[attribute]); } } // add load event listener and set image source $image.one('load', function() { self.$element.trigger('load.source.responsiveImage'); // append responsive image to target element after preload if( self.options.preload ) { self.setNewSource( $image ); } }) .attr('src', source.src); // check if image is already completed, maybe from browser cache if( $image.get(0).complete ) { $image.trigger('load'); } return $image; }, initResizeEvent: function(){ var self = this; // attach resize event handler if( self.options.resizeEvent !== '' ) { $(window).on(self.options.resizeEvent, $.proxy(self.loadResponsiveImage, self)); } } }); $.fn[ pluginName ] = function ( options ) { return this.each(function() { if ( !$.data( this, 'plugin_' + pluginName ) ) { $.data( this, 'plugin_' + pluginName, new Plugin( this, options ) ); $(this).trigger('ready.'+pluginName); } $(window).trigger('all.ready.'+pluginName); }); }; })( jQuery, window, document );
JavaScript
0.000002
@@ -6451,29 +6451,21 @@ %7D -%0A%0A + else if (win @@ -8546,8 +8546,9 @@ ument ); +%0A
ceb3717ba936cec753d25f1fac049e5640110ce4
Convert to Glimmer component
ember/app/components/fullscreen-button.js
ember/app/components/fullscreen-button.js
/* global BigScreen */ import Component from '@ember/component'; import { action } from '@ember/object'; export default Component.extend({ tagName: '', toggle: action(function () { let element = this.fullscreenElement; BigScreen.toggle(document.querySelector(element)); }), });
JavaScript
0.999793
@@ -24,25 +24,26 @@ %0Aimport -Component +%7B action %7D from '@ @@ -52,137 +52,137 @@ ber/ -componen +objec t';%0A +%0A import -%7B action %7D from '@ember/object';%0A%0Aexport default Component.extend(%7B%0A tagName: '',%0A%0A toggle: action(function +Component from '@glimmer/component';%0A%0Aexport default class FullscreenButton extends Component %7B%0A @action toggle () %7B @@ -205,16 +205,21 @@ = this. +args. fullscre @@ -291,11 +291,7 @@ %0A %7D -),%0A%7D); +%0A%7D %0A
baa902602fbe058d150c20baa2862e962888b4ce
update jsdoc.js (#110)
packages/grafeas/.jsdoc.js
packages/grafeas/.jsdoc.js
// Copyright 2019 Google LLC // // 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 // // https://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'; module.exports = { opts: { readme: './README.md', package: './package.json', template: './node_modules/jsdoc-fresh', recurse: true, verbose: true, destination: './docs/' }, plugins: [ 'plugins/markdown', 'jsdoc-region-tag' ], source: { excludePattern: '(^|\\/|\\\\)[._]', include: [ 'build/src' ], includePattern: '\\.js$' }, templates: { copyright: 'Copyright 2018 Google, LLC.', includeDate: false, sourceFiles: false, systemName: '@google-cloud/grafeas', theme: 'lumen' }, markdown: { idInHeadings: true } };
JavaScript
0
@@ -1040,9 +1040,9 @@ 201 -8 +9 Goo @@ -1160,16 +1160,71 @@ 'lumen' +,%0A default: %7B%0A %22outputSourceFiles%22: false%0A %7D %0A %7D,%0A
a59f921d4efcc473dd1b90d4e6c3ff73af8d52f5
Convert to Glimmer component
ember/app/components/phase-icons-layer.js
ember/app/components/phase-icons-layer.js
import Component from '@ember/component'; import { action } from '@ember/object'; import Feature from 'ol/Feature'; import Point from 'ol/geom/Point'; import VectorLayer from 'ol/layer/Vector'; import VectorSource from 'ol/source/Vector'; import Icon from 'ol/style/Icon'; import Style from 'ol/style/Style'; const START_ICON = new Icon({ anchor: [0.5, 1], src: '/images/marker-green.png', }); const END_ICON = new Icon({ anchor: [0.5, 1], src: '/images/marker.png', }); START_ICON.load(); END_ICON.load(); const START_STYLE = new Style({ image: START_ICON }); const END_STYLE = new Style({ image: END_ICON }); export default Component.extend({ tagName: '', map: null, coordinates: null, init() { this._super(...arguments); this.layer = new VectorLayer({ source: new VectorSource({ useSpatialIndex: false, }), style(feature) { return feature.get('type') === 'end' ? END_STYLE : START_STYLE; }, zIndex: 100, }); this.map.addLayer(this.layer); this.updateSource(); }, willDestroy() { this._super(...arguments); this.map.removeLayer(this.layer); }, @action updateSource() { let source = this.layer.getSource(); source.clear(); if (this.coordinates) { let startPoint = new Point(this.coordinates[0]); let endPoint = new Point(this.coordinates[this.coordinates.length - 1]); let startFeature = new Feature({ geometry: startPoint, type: 'start' }); let endFeature = new Feature({ geometry: endPoint, type: 'end' }); source.addFeature(startFeature); source.addFeature(endFeature); } }, });
JavaScript
0.999518
@@ -1,24 +1,25 @@ import -Component +%7B action %7D from '@ @@ -28,16 +28,13 @@ ber/ -componen +objec t';%0A @@ -44,37 +44,41 @@ ort -%7B action %7D from '@ember/objec +Component from '@glimmer/componen t';%0A @@ -639,130 +639,52 @@ ult -Component.extend(%7B%0A tagName: '',%0A%0A map: null,%0A coordinates: null,%0A%0A init() %7B%0A this._super(...arguments);%0A%0A this. +class PhaseIconsLayer extends Component %7B%0A laye @@ -705,18 +705,16 @@ Layer(%7B%0A - sour @@ -742,18 +742,16 @@ %7B%0A - useSpati @@ -774,16 +774,12 @@ - %7D),%0A - @@ -801,18 +801,16 @@ %7B%0A - return f @@ -873,15 +873,11 @@ - %7D,%0A - @@ -895,14 +895,55 @@ ,%0A - %7D);%0A +%0A constructor() %7B%0A super(...arguments); %0A @@ -944,24 +944,29 @@ );%0A this. +args. map.addLayer @@ -979,17 +979,16 @@ layer);%0A -%0A this @@ -1003,25 +1003,24 @@ ource();%0A %7D -, %0A%0A willDest @@ -1035,19 +1035,25 @@ -this._super +super.willDestroy (... @@ -1073,16 +1073,21 @@ this. +args. map.remo @@ -1110,17 +1110,16 @@ er);%0A %7D -, %0A%0A @act @@ -1212,17 +1212,49 @@ -if (this. +let %7B coordinates %7D = this.args;%0A if ( coor @@ -1289,37 +1289,32 @@ int = new Point( -this. coordinates%5B0%5D); @@ -1345,21 +1345,16 @@ w Point( -this. coordina @@ -1357,21 +1357,16 @@ dinates%5B -this. coordina @@ -1622,14 +1622,11 @@ %7D%0A %7D -, %0A%7D -); %0A
eb9ebc9bf00bf9a1e3ed1ad2716ab35863e0a892
add graphqlUri to browser whitelist
packages/graphql/preset.js
packages/graphql/preset.js
module.exports = { mixins: [__dirname], fragmentsFile: '<rootDir>/fragmentTypes.json', graphqlMockServerPath: '/graphql', shouldPrefetchOnServer: true, configSchema: { fragmentsFile: { type: 'string', absolutePath: true, }, graphqlUri: { type: 'string', format: 'uri', }, graphqlSchemaFile: { type: 'string', absolutePath: true, }, graphqlMockSchemaFile: { type: 'string', }, graphqlMockServerPath: { type: 'string', }, shouldPrefetchOnServer: { type: 'boolean', }, }, };
JavaScript
0
@@ -153,16 +153,65 @@ : true,%0A + browserWhitelist: %7B%0A graphqlUri: true,%0A %7D,%0A config
b51687ebe876ef55d1598fc57c8f3ed6df03693d
fix location home page stats
src/js/pages/locations/app.js
src/js/pages/locations/app.js
/* global alert */ // Common modules import '../../common' import htmlEncode from 'htmlencode' const api = require('../../get-api-data') const browser = require('../../browser') const endpoints = require('../../api') const location = require('../../location/locationSelector') const templating = require('../../template-render') const wp = require('../../wordpress') const MapBuilder = require('../../models/accommodation/MapBuilder') const initLocations = function (currentLocationId) { const ui = { form: document.querySelector('.js-change-location-form'), select: document.querySelector('.js-change-location-select') } ui.form.addEventListener('submit', function (e) { e.preventDefault() const reqLocation = ui.select.value if (reqLocation) { location.setCurrent(reqLocation) browser.redirect(`/${reqLocation}`) } }) const redirectToHubPage = function (locationId) { location.setCurrent(locationId) browser.redirect(`/${locationId}`) } Array.from(document.querySelector('.js-change-location-select')) .filter((t) => t.tagName === 'OPTION') .find((o) => o.value === currentLocationId) .setAttribute('selected', 'selected') location.handler((result) => { if (result.length) { redirectToHubPage(result) } }, '.js-change-location-select') } const initNews = function (currentLocationId) { const reqPosts = 3 wp .getPostsByLocation(currentLocationId, reqPosts, 0, true) .then((result) => { if (result.posts.length === reqPosts) { templating.renderTemplate('js-news-tpl', result, 'js-news-output') } }) } const initFindHelp = function (currentLocation) { const ui = { form: document.querySelector('.js-find-help-form'), postcode: document.querySelector('.js-find-help-postcode') } ui.postcode.setAttribute('placeholder', `your postcode: eg ${currentLocation.postcode}`) ui.postcode.value = currentLocation.postcode ui.form.addEventListener('submit', function (e) { e.preventDefault() const reqLocation = ui.postcode.value location.setPostcode(reqLocation, () => { browser.redirect('/find-help/all-service-providers/') }, () => alert('We could not find your postcode, please try a nearby one')) }) } const initStatistics = function (currentLocation) { const stats = [ { field: 'totalServiceProviders', link: '/find-help/all-service-providers/', label: 'Organisations' }, { field: 'totalPledges', link: 'https://charter.streetsupport.net/progress/', label: 'Pledges' }, { field: 'totalVolunteers', link: '/give-help/volunteer/', label: 'Volunteers' }, { field: 'totalNeeds', link: '/give-help/help/', label: 'Needs' } ] const requiredStats = currentLocation.homePageStats.length ? currentLocation.homePageStats : ['totalServiceProviders', 'totalNeeds', 'totalVolunteers'] api .data(endpoints.statistics + currentLocation.id + '/latest') .then((result) => { const theData = { statistics: requiredStats .map((rs) => { const reqStat = stats.find((s) => s.field === rs) return { total: result.data[rs], link: reqStat.link, label: reqStat.label } }) } templating.renderTemplate('js-statistics-tpl', theData, 'js-statistics-output') }, (_) => { }) } window.initMap = () => { } const initMap = function (currentLocation) { const endpoint = `${endpoints.serviceProviderLocations}?latitude=${currentLocation.latitude}&longitude=${currentLocation.longitude}&range=20000&pageSize=1000` const buildInfoWindowMarkup = (p) => { return `<div class="card card--brand-h card--gmaps"> <div class="card__title"> <button class="card__close js-popup-close" title="close">&#10799;</button> <h1 class="h2">${htmlEncode.htmlDecode(p.serviceProviderName)}</h1> <p>${htmlEncode.htmlDecode(p.serviceProviderSynopsis)}</p> </div> <div class="card__details"> <a href="/find-help/organisation/?organisation=${p.serviceProviderKey}">View details</a> </div> </div>` } const getLocation = (p) => { return { latitude: p.latitude, longitude: p.longitude } } const map = new MapBuilder() api .data(endpoint) .then((result) => { const zoom = currentLocation.id === 'bournemouth' ? 11 // stinky : 12 map.init(result.data.items, currentLocation, null, buildInfoWindowMarkup, getLocation, { zoom }) }, (_) => { }) } const initSwep = function (currentLocationId) { api .data(endpoints.cities) .then((result) => { const city = result.data.find((c) => c.id === currentLocationId) if (city.swepIsAvailable) { templating.renderTemplate('js-swep-tpl', city, 'js-swep-output') } }, (_) => {}) } const currentLocation = location.getCurrentHub() initLocations(currentLocation.id) initNews(currentLocation.id) initFindHelp(currentLocation) initStatistics(currentLocation) initMap(currentLocation) initSwep(currentLocation.id)
JavaScript
0.000001
@@ -2754,23 +2754,16 @@ ageStats -.length %0A ? c
e891bd6fb370294bb9c57b97f2ea98aa9fed2e9b
Remove comments
src/chart/chart-grouped.js
src/chart/chart-grouped.js
import * as array from 'd3-array' // import * as scale from 'd3-scale' // import * as shape from 'd3-shape' import PropTypes from 'prop-types' import React, { PureComponent } from 'react' import { View } from 'react-native' import Svg from 'react-native-svg' import Path from '../animated-path' import Chart from './chart' class ChartGrouped extends PureComponent { state = { width: 0, height: 0, } _onLayout(event) { const { nativeEvent: { layout: { height, width } } } = event this.setState({ height, width }) } createPaths() { throw 'Extending "ChartGrouped" requires you to override "createPaths' } render() { const { data, xAccessor, yAccessor, yScale, xScale, style, animate, animationDuration, numberOfTicks, contentInset: { top = 0, bottom = 0, left = 0, right = 0, }, gridMax, gridMin, clampX, clampY, svg, children, } = this.props const { width, height } = this.state if (data.length === 0) { return <View style={ style } /> } const mappedData = data.map((dataArray) => dataArray.data.map((item, index) => ({ y: yAccessor({ item, index }), x: xAccessor({ item, index }), }))) const yValues = array.merge(mappedData).map(item => item.y) const xValues = array.merge(mappedData).map(item => item.x) const yExtent = array.extent([ ...yValues, gridMin, gridMax ]) const xExtent = array.extent([ ...xValues ]) const { yMin = yExtent[0], yMax = yExtent[1], xMin = xExtent[0], xMax = xExtent[1], } = this.props //invert range to support svg coordinate system const y = yScale() .domain([ yMin, yMax ]) .range([ height - bottom, top ]) .clamp(clampY) const x = xScale() .domain([ xMin, xMax ]) .range([ left, width - right ]) .clamp(clampX) const paths = this.createPaths({ data: mappedData, x, y, }) const ticks = y.ticks(numberOfTicks) const extraProps = { x, y, data, ticks, width, height, ...paths, } return ( <View style={ style }> <View style={{ flex: 1 }} onLayout={ event => this._onLayout(event) }> { height > 0 && width > 0 && <Svg style={{ height, width }}> { React.Children.map(children, child => { if (child && child.props.belowChart) { return React.cloneElement(child, extraProps) } return null }) } {paths.path.map((path, index) => { const { svg: pathSvg } = data[index] return ( <Path key={ path } fill={ 'none' } { ...svg } { ...pathSvg } d={ path } animate={ animate } animationDuration={ animationDuration } />) })} { React.Children.map(children, child => { if (child && !child.props.belowChart) { return React.cloneElement(child, extraProps) } return null }) } </Svg> } </View> </View> ) } } ChartGrouped.propTypes = { ...Chart.propTypes, data: PropTypes.arrayOf(PropTypes.shape({ data: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.object), PropTypes.arrayOf(PropTypes.number), PropTypes.arrayOf(PropTypes.array), ]), svg: PropTypes.object, })).isRequired, } ChartGrouped.defaultProps = { ...Chart.defaultProps, } export default ChartGrouped
JavaScript
0
@@ -31,82 +31,8 @@ ay'%0A -// import * as scale from 'd3-scale'%0A// import * as shape from 'd3-shape'%0A impo
50c87cfda8472d84ffb22c086dbad95382b161af
Resolve line height style in Divider component
src/lib/components/Divider.js
src/lib/components/Divider.js
"use strict"; /*eslint no-unused-vars: 0*/ var React = require("react"); var classNames = require("classnames"); var Container = require("./layout/Container"); var mixin = require("../util/mixin"); var Divider = React.createClass({ // Component API propTypes: { width: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), thickness: React.PropTypes.number, color: React.PropTypes.string, className: React.PropTypes.string, wrapper: React.PropTypes.shape({ className: React.PropTypes.string, style: React.PropTypes.object }) }, getDefaultProps: function () { return { thickness: 1, color: "#eaeaea", width: "100%", wrapper: {} }; }, render: function () { var containerProps = this.getContainerProps(); return ( <Container {...containerProps} /> ); }, // Private API getContainerProps: function () { return { cssPrefix: "divider", width: this.props.width, align: "center", className: this.props.className, wrapper: { align: "center", width: this.props.width, height: this.props.thickness, bgColor: this.props.color, className: classNames(this.props.wrapper.className), style: mixin({}, this.props.wrapper.style || {}, { fontSize: 1, lineHeight: 1, msoLineHeightRule: "exactly" }) } }; } // Public API }); module.exports = Divider;
JavaScript
0
@@ -1280,17 +1280,21 @@ Height: -1 +'1px' ,%0A%09%09%09%09%09m
6ff79f2d543997563e001349f3fe8737468e6f30
Update example
examples/NotificationExample/index.ios.js
examples/NotificationExample/index.ios.js
/** * Sample React Native App * https://github.com/facebook/react-native */ import React, { AppRegistry, StyleSheet, Component Text, View, } from 'react-native'; import Notification from 'react-native-notification'; class NotificationExample extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('NotificationExample', () => NotificationExample);
JavaScript
0.000001
@@ -128,16 +128,17 @@ omponent +, %0A Text, @@ -146,16 +146,36 @@ View,%0A + TouchableOpacity,%0A %7D from ' @@ -296,262 +296,422 @@ %7B%0A -render() %7B%0A return (%0A %3CView style=%7Bstyles.container%7D%3E%0A %3CText style=%7Bstyles.welcome%7D%3E%0A Welcome to React Native!%0A %3C/Text%3E%0A %3CText style=%7Bstyles.instructions%7D%3E%0A To get started, edit index.ios.js%0A %3C/Text%3E%0A +constructor(props) %7B%0A super(props);%0A%0A this.state = %7B%0A notificationVisible: false,%0A %7D%0A %7D%0A%0A onPress = () =%3E %7B%0A this.setState(%7B%0A notificationVisible: true,%0A %7D);%0A%0A setInterval(() =%3E %7B%0A this.setState(%7B%0A notificationVisible: false,%0A %7D);%0A %7D, 3000);%0A %7D;%0A%0A render() %7B%0A return (%0A %3CView style=%7Bstyles.container%7D%3E%0A %3CTouchableOpacity onPress=%7Bthis.onPress%7D%3E%0A @@ -734,28 +734,23 @@ %7Bstyles. -instructions +welcome %7D%3E%0A @@ -758,89 +758,170 @@ -Press Cmd+R to reload,%7B'%5Cn'%7D%0A Cmd+D or shake for dev menu%0A %3C/Text + Tap me!%0A %3C/Text%3E%0A %3C/TouchableOpacity%3E%0A %3CNotification visible=%7Bthis.state.notificationVisible%7D%3E%0A Hi there!%0A %3C/Notification %3E%0A
453a6b48e2deb1e3f20339ca22cd705f8761ca6a
Fix utils errors
app/lib/utils.js
app/lib/utils.js
/** * utils.js * * Common helper functions. */ var fs = require('fs-extra') var child_process = require('child_process') var path = require('path') /** * Uncompress the given src archive file to dst folder. * * Returns the name of the uncomressed file (caller is responsible * for cleaning it up eventually). */ module.exports.uncompress = function (src, dst, cb) { try { fs.ensureDirSync(dst) child_process.exec( 'dtrx -q -n -f ' + src, { cwd: dst }, function (err, stdout, stderr) { if (err) return cb(err) return cb(null, path.join(dst, path.basename(src).replace('.zip', ''))) }) } catch (err) { cb(err, undefined) } } /** Return max of the two dates. */ module.exports.datemax = function (a, b) { if (!b) return a if (!a) return b return (a.getTime() >= b.getTime() ? a : b) } /** Return max of the two dates. */ module.exports.datemin = function (a, b) { if (!b) return a if (!a) return b return (a.getTime() <= b.getTime() ? a : b) }
JavaScript
0.000179
@@ -78,26 +78,25 @@ ')%0Avar child -_p +P rocess = req @@ -408,26 +408,25 @@ )%0A%0A child -_p +P rocess.exec(
8ab7d06b995f370062b488448ef00c757e371d96
Update check_if_user_reacted_MOD.js (#406)
actions/check_if_user_reacted_MOD.js
actions/check_if_user_reacted_MOD.js
module.exports = { name: "Check If User Reacted", section: "Conditions", subtitle: function(data) { const results = ["Continue Actions", "Stop Action Sequence", "Jump To Action", "Jump Forward Actions"]; return `If True: ${results[parseInt(data.iftrue)]} ~ If False: ${results[parseInt(data.iffalse)]}`; }, fields: ["member", "varName", "reaction", "varName2", "iftrue", "iftrueVal", "iffalse", "iffalseVal"], html: function(isEvent, data) { return ` <div> <div style="float: left; width: 35%;"> Source Member:<br> <select id="member" class="round" onchange="glob.memberChange(this, 'varNameContainer')"> ${data.members[isEvent ? 1 : 0]} </select> </div> <div id="varNameContainer" style="display: none; float: right; width: 60%;"> Variable Name:<br> <input id="varName" class="round" type="text" list="variableList"><br> </div> </div><br><br><br><br> <div> <div style="float: left; width: 35%;"> Source Reaction:<br> <select id="reaction" class="round" onchange="glob.refreshVariableList(this)"> ${data.variables[1]} </select> </div> <div id="varNameContainer2" style="float: right; width: 60%;"> Variable Name:<br> <input id="varName2" class="round" type="text" list="variableList"><br> </div> </div><br><br><br> <div style="padding-top: 8px;"> ${data.conditions[0]} </div>`; }, init: function() { const { glob, document } = this; let option = document.createElement("OPTION"); option.value = "4"; option.text = "Jump to Anchor"; const iffalse = document.getElementById("iffalse"); if (iffalse.length == 4) { iffalse.add(option); } let option2 = document.createElement("OPTION"); option2.value = "4"; option2.text = "Jump to Anchor"; const iftrue = document.getElementById("iftrue"); if (iftrue.length == 4) { iftrue.add(option2); } glob.onChangeTrue = function(event) { switch (parseInt(event.value)) { case 0: case 1: document.getElementById("iftrueContainer").style.display = "none"; break; case 2: document.getElementById("iftrueName").innerHTML = "Action Number"; document.getElementById("iftrueContainer").style.display = null; break; case 3: document.getElementById("iftrueName").innerHTML = "Number of Actions to Skip"; document.getElementById("iftrueContainer").style.display = null; break; case 4: document.getElementById("iftrueName").innerHTML = "Anchor ID"; document.getElementById("iftrueContainer").style.display = null; break; } }; glob.onChangeFalse = function(event) { switch (parseInt(event.value)) { case 0: case 1: document.getElementById("iffalseContainer").style.display = "none"; break; case 2: document.getElementById("iffalseName").innerHTML = "Action Number"; document.getElementById("iffalseContainer").style.display = null; break; case 3: document.getElementById("iffalseName").innerHTML = "Number of Actions to Skip"; document.getElementById("iffalseContainer").style.display = null; break; case 4: document.getElementById("iffalseName").innerHTML = "Anchor ID"; document.getElementById("iffalseContainer").style.display = null; break; } }; glob.memberChange(document.getElementById("member"), "varNameContainer"); glob.refreshVariableList(document.getElementById("reaction")); glob.onChangeTrue(document.getElementById("iftrue")); glob.onChangeFalse(document.getElementById("iffalse")); }, action: function(cache) { const data = cache.actions[cache.index]; const type = parseInt(data.member); const varName = this.evalMessage(data.varName, cache); const member = this.getMember(type, varName, cache); const type2 = parseInt(data.reaction); const varName2 = this.evalMessage(data.varName2, cache); const reaction = this.getMods().getReaction(type2, varName2, cache); let result; if (Array.isArray(member)) { result = member.every(function(user) { if (this.dest(reaction, "users", "cache") && user) { return reaction.users.cache.has(user.id); } }); } else { if (this.dest(reaction, "users", "cache") && member) { result = reaction.users.cache.has(member.id); } } this.executeResults(result, data, cache); }, mod: function() {} };
JavaScript
0
@@ -200,16 +200,34 @@ Actions%22 +, %22Jump to Anchor%22 %5D;%0A%09%09ret
e87e1d7be36131b80d90ebee6f386e84f7492743
check if krypton supports opus
src/transcoders/Opus.js
src/transcoders/Opus.js
// Partly based on https://github.com/Rantanen/node-opus/blob/master/lib/Encoder.js const { Transform } = require('stream'); var BaseOpus, OpusEncoder, OpusEncoderName; const CTL = { BITRATE: 4002, FEC: 4012, PLP: 4014, }; for (const requireData of [ ['krypton', o => o.opus.OpusEncoder], ['node-opus', o => o.OpusEncoder], ['opusscript', o => o], ]) { const [name, fn] = requireData; try { BaseOpus = require(name); OpusEncoder = fn(BaseOpus); OpusEncoderName = name; break; } catch (e) { } } const charCode = x => x.charCodeAt(0); const OPUS_HEAD = Buffer.from([...'OpusHead'].map(charCode)); const OPUS_TAGS = Buffer.from([...'OpusTags'].map(charCode)); // frame size = (channels * rate * frame_duration) / 1000 /** * Takes a stream of Opus data and outputs a stream of PCM data, or the inverse. */ class OpusStream extends Transform { /** * Creates a new Opus transformer. * @param {Object} [options] options that you would pass to a regular Transform stream. */ constructor(options = {}) { if (!OpusEncoder) { throw Error('Could not find an Opus module! Please install node-opus or opusscript.'); } super(Object.assign({ readableObjectMode: true }, options)); if (OpusEncoderName === 'opusscript') { options.application = OpusEncoder.Application[options.application]; } this.encoder = new OpusEncoder(options.rate, options.channels, options.application); if (OpusEncoderName === 'krypton') { BaseOpus.count++; this._encode = async buffer => await BaseOpus.do(this.encoder.encode(buffer)).run(); this._decode = async buffer => await BaseOpus.do(this.encoder.decode(buffer)).run(); this.once('end', () => BaseOpus.count--); } this._options = options; this._required = this._options.frameSize * this._options.channels * 2; } _encode(buffer) { return this.encoder.encode(buffer, OpusEncoderName !== 'node-opus' ? this._options.frameSize : null); } _decode(buffer) { return this.encoder.decode(buffer, OpusEncoderName !== 'node-opus' ? this._options.frameSize : null); } /** * Returns the Opus module being used - `krypton`, `opusscript` or `node-opus`. * @type {string} */ static get type() { return OpusEncoderName; } /** * Sets the bitrate of the stream. * @param {number} bitrate the bitrate to use use, e.g. 48000 */ setBitrate(bitrate) { (this.encoder.applyEncoderCTL || this.encoder.encoderCTL) .apply(this.encoder, [CTL.BITRATE, Math.min(128e3, Math.max(16e3, bitrate))]); } /** * Enables or disables forward error correction. * @param {boolean} enabled whether or not to enable FEC. */ setFEC(enabled) { (this.encoder.applyEncoderCTL || this.encoder.encoderCTL) .apply(this.encoder, [CTL.FEC, enabled ? 1 : 0]); } /** * Sets the expected packet loss over network transmission. * @param {number} [percentage] a percentage (represented between 0 and 1) */ setPLP(percentage) { (this.encoder.applyEncoderCTL || this.encoder.encoderCTL) .apply(this.encoder, [CTL.FEC, Math.min(100, Math.max(0, percentage * 100))]); } } /** * Represents an Opus encoder stream. * @extends {OpusStream} */ class Encoder extends OpusStream { /** * Creates a new Opus encoder stream. * @param {Object} options options that you would pass to a regular OpusStream, plus a few more: * @param {number} options.frameSize the frame size to use (e.g. 960 for stereo audio at 48KHz with a frame * duration of 20ms) * @param {number} options.channels the number of channels to use */ constructor(options) { super(options); this._buffer = Buffer.alloc(0); } async _transform(chunk, encoding, done) { this._buffer = Buffer.concat([this._buffer, chunk]); let n = 0; while (this._buffer.length >= this._required * (n + 1)) { const buf = await this._encode(this._buffer.slice(n * this._required, (n + 1) * this._required)); this.push(buf); n++; } if (n > 0) this._buffer = this._buffer.slice(n * this._required); return done(); } _destroy(err, cb) { super._destroy(err, cb); this._buffer = null; } } /** * Represents an Opus decoder stream. * @extends {OpusStream} */ class Decoder extends OpusStream { _transform(chunk, encoding, done) { const signature = chunk.slice(0, 8); if (signature.equals(OPUS_HEAD)) { this.emit('format', { channels: this._options.channels, sampleRate: this._options.rate, bitDepth: 16, float: false, signed: true, version: chunk.readUInt8(8), preSkip: chunk.readUInt16LE(10), gain: chunk.readUInt16LE(16), }); return done(); } if (signature.equals(OPUS_TAGS)) { this.emit('tags', chunk); return done(); } this.push(this._decode(chunk)); return done(); } } module.exports = { Decoder, Encoder };
JavaScript
0.000001
@@ -272,16 +272,111 @@ n', o =%3E + %7B%0A if (!o.opus.version) throw Error('Krypton found, but Opus is not available');%0A return o.opus. @@ -382,24 +382,29 @@ .OpusEncoder +;%0A %7D %5D,%0A %5B'node- @@ -3330,32 +3330,47 @@ ds %7BOpusStream%7D%0A + * @inheritdoc%0A */%0Aclass Encode
5a7e357a990eb12ca3dc1f529af669ee6a639017
Add Websocket Send Error Handling
lib/webserver_client.js
lib/webserver_client.js
var WebSocket = require('ws'); var fs = require('fs'); var rl = require("readline").createInterface(process.stdin, process.stdout); var net = require("net"); var websocket_client = function(){ var th = this; var dir_home = process.env[process.platform == "win32" ? "USERPROFILE" : "HOME"]; var setting_file_path = require("path").join(dir_home,".setting.json"); /* ----- -----------------Websocket---------------- */ var ws_url = "ws://ec2-52-68-77-61.ap-northeast-1.compute.amazonaws.com:3000"; var ws_client = new WebSocket(ws_url); //接続時 ws_client.on('open',function(){ console.log("[WEBSERVER CLIENT] [WEBSOCKET CLIENT] Connect 2 WebServer"); choose_send(function(str){ create_send_message(str,function(message){ ws_client.send(message); }); }); }); //メッセージ受け取り時 ws_client.on('message',function(data){ console.log("[WEBSERVER CLIENT] [WEBSOCKET CLIENT] Message Recive : " + data); message_parse(data); }); ws_client.on('error',function(error){ console.log("[WEBSERVER CLIENT] [WEBSOCKET CLIENT] Error : " + error.stack); }); var send_to_webserver = function(str){ return ws_client.send(str); }; //-------------------------------------------------------------- /* ------------------ TCP Server And Client ----------------*/ // Client var tcp_client_port = 12000; var tcp_client = new net.Socket({readable:true,writable:true}); tcp_client.on('error',function(error){ tcp_client.connect({port:tcp_client_port}); }); var send_to_mpserver = function(str){ return tcp_client.write(str); }; var connect_to_mpserver = function(){ tcp_client.connect({port:tcp_client_port},function(){ console.log("[WEBSERVER CLIENT] [TCP CLIENT] CONNECT TO MPSERVER"); }); }; // Server var tcp_server_port = 10000; var tcp_server = new net.Server(function(socket){ console.log("[WEBSERVER CLIENT] [TCP SERVER] CLIENT CONECTED"); connect_to_mpserver(); socket.on('error',function(){ console.log("[WEBSERVER CLIENT] [TCP SERVER] SOCKET ERROR"); }); socket.on('data',function(str){ send_to_webserver(str); }); }); tcp_server.on('error',function(){ console.log("[WEBSERVER CLIENT] [TCP SERVER] SERVER ERROR"); }); var listen_tcp_server = function(){ tcp_server.listen(tcp_server_port,function(){ console.log("[WEBSERVER CLIENT] [TCP SERVER] SERVER LISTEN START]"); }); }; //-------------------------------------------------------------- //authかloginどちらを最初に送るか判定する var choose_send = function(callback){ fs.exists(setting_file_path,function(exists){ callback(exists ? "auth" : "login"); }); }; //送るメッセージを作成する var create_send_message = function(str,callback){ if(str == "auth"){ fs.readFile(setting_file_path,function(err,data){ obj = JSON.parse(data); json_obj = {"type":"auth","value":{"name":obj.name,"key":obj.raskey}}; callback(JSON.stringify(json_obj)); }); }else if(str == "login"){ var user_id,user_pass; rl.question("Your Account ID :",function(value){ user_id = value; rl.question("Your PassWord :",function(value){ user_pass = value; json_obj = { "type":"regist", "value":{ "name":user_id, "password":user_pass } }; text = JSON.stringify(json_obj); callback(text); }); }); } } //サーバー側から来たメッセージを解釈 var message_parse = function(str){ try{ obj = JSON.parse(str); switch(obj["type"]){ case "register": save_key(obj); break; case "login": check_login_result(obj); break; default: send_to_mpserver(JSON.stringify(obj)); break; } }catch(ex){ console.log("[WEBSERVER CLIENT] [WEBSOCKET CLIENT] Message Json Parse ERROR :" + ex.stack); } }; //鍵の保存 var save_key = function(obj){ if(obj.value.result != -1){ var save_str = JSON.stringify({"name":obj.value.user,"raskey":obj.value.key}); fs.writeFile(setting_file_path,save_str,function(err){ console.log(err); }); } }; //ログインチェック var check_login_result = function(obj){ result = obj.value.result == 0 ? "LOGIN OK" : "LOGIN BAD"; console.log("[WEBSERVER CLIENT] [WEBSOCKET CLIENT] Login Result : " + result); // TODO ログインに失敗した時の処理 }; this.start = function(){ listen_tcp_server(); }; }; module.exports = websocket_client;
JavaScript
0
@@ -1095,32 +1095,40 @@ function(str)%7B%0A +%09%09try%7B%0A%09 %09%09return ws_clie @@ -1137,24 +1137,119 @@ .send(str);%0A +%09%09%7Dcatch(ex)%7B%0A%09%09%09console.log(%22%5BWEBSERVER CLIENT%5D %5BWEBSOCKET CLIENT%5D Error %22 + ex.message);%0A%09%09%7D%0A %09%7D;%0A%0A%09//----
3c1d8582cd3da407cf6f2e49bf9435bd63399a54
disable electron task;
actor-apps/app-web/gulpfile.babel.js
actor-apps/app-web/gulpfile.babel.js
'use strict'; import path from 'path'; import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; import webpackConfig from './webpack.config.js'; import del from 'del'; import assign from 'lodash.assign'; import gulp from 'gulp'; import gutil from 'gulp-util'; import manifest from 'gulp-manifest'; import shell from 'gulp-shell'; import asar from 'asar' gulp.task('webpack:build', function(callback) { // modify some webpack config options var myConfig = Object.create(webpackConfig); myConfig.plugins = myConfig.plugins.concat( new webpack.DefinePlugin({ 'process.env': { // This has effect on the react lib size 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin() ); // run webpack webpack(myConfig, function(err, stats) { if (err) { throw new gutil.PluginError('webpack:build', err); } gutil.log('[webpack:build]', stats.toString({ colors: true })); callback(); }); }); gulp.task('webpack-dev-server', function(callback) { // modify some webpack config options var myConfig = Object.create(webpackConfig); myConfig.devtool = 'eval'; myConfig.debug = true; // Start a webpack-dev-server new WebpackDevServer(webpack(myConfig), { publicPath: myConfig.output.publicPath, contentBase: './dist', historyApiFallback: true, stats: { colors: true } }).listen(3000, 'localhost', function(err) { if (err) { throw new gutil.PluginError('webpack-dev-server', err); } gutil.log('[webpack-dev-server]', 'http://localhost:3000/webpack-dev-server/index.html'); }); }); gulp.task('emoji', () => { gulp.src(['./node_modules/emojify.js/dist/images/basic/*']) .pipe(gulp.dest('./dist/assets/img/emoji')); }); gulp.task('push', () => { gulp.src(['./push/*']) .pipe(gulp.dest('./dist/')); }); gulp.task('assets', () => { gulp.src(['src/assets/**/*']) .pipe(gulp.dest('./dist/assets/')); gulp.src(['src/fonts/**/*']) .pipe(gulp.dest('./dist/assets/fonts/')); }); gulp.task('html', () => { gulp.src('src/index.html') .pipe(gulp.dest('./dist/')); }); gulp.task('lib:build', shell.task(['cd ../ && ./gradlew :core-js:buildPackage'])); gulp.task('lib', ['lib:build'], () => { const stream = gulp.src('../core-js/build/package/*') .pipe(gulp.dest('./dist/actor/')); return stream; }); gulp.task( 'manifest:prod', ['html', 'static', 'webpack:build'], () => { gulp.src(['./dist/**/*']) .pipe(manifest({ hash: true, network: ['http://*', 'https://*', '*'], filename: 'app.appcache', exclude: 'app.appcache' })) .pipe(gulp.dest('./dist/')); }); gulp.task('electron:prepare', ['build'], () => { gulp.src(['dist/**/**']) .pipe(gulp.dest('./electron_dist/app')); }); gulp.task('electron:app', () => { gulp.src(['electron/**/**']) .pipe(gulp.dest('./electron_dist/app')); }); gulp.task('electron', ['electron:prepare', 'electron:app'], shell.task(['asar pack electron_dist/app electron_dist/app.asar'])) gulp.task('static', ['assets', 'lib', 'push', 'emoji']); gulp.task('dev', ['lib', 'html', 'static', 'webpack-dev-server']); gulp.task('build', ['html', 'static', 'webpack:build', 'manifest:prod']); gulp.task('build:gwt', ['html', 'static', 'webpack:build']); gulp.task('dist', ['build', 'electron']);
JavaScript
0.000001
@@ -3408,20 +3408,8 @@ ild' -, 'electron' %5D);%0A
b1d418628a5885ddbbade80a00cad52fcbd08c87
Fix for Collection index lookup since _.isNumber(NaN)==true
adaptors/backbone/context_adaptor.js
adaptors/backbone/context_adaptor.js
/** * Adaptor specific code for context lookups * * @author Matt DeGennaro <mdegennaro@wayfair.com> */ 'use strict'; var _ = require('underscore'); var Context = require('../../src/template/template_context'); var Backbone = require('backbone'); // List of properties that are allowed to be accessed from template var allowedModelProperties = _.invert(['validationError']); var allowedCollectionProperties = _.invert([]); // Use prototypeless objects to avoid unnecessary conflicts var blockedModelProperties = _.create(null); var blockedCollectionProperties = _.create(null); // Add properties that aren't on the prototype, but shouldn't be accessed anyways blockedModelProperties.attributes = true; blockedCollectionProperties.models = true; _.each(Backbone.Model.prototype, function(val, key) { if (allowedModelProperties[key] == null) { blockedModelProperties[key] = true; } }); _.each(Backbone.Collection.prototype, function(val, key) { if (allowedCollectionProperties[key] == null) { blockedCollectionProperties[key] = true; } }); /** * Set up parent context if the model has parents * @param {Any} view Value to wrap in context * @param {Context?} parentContext parentContext to use for lookups */ var initialize = function(view, parentContext) { if (view == null) { view = {}; } if (!parentContext && (view.parent || view.collection)) { this.parent = new Context(view.parent || view.collection); } else { this.parent = parentContext; } }; /** * Lookup value from given context view * @param {Object} view Context to lookup values from * @param {String} name String value to check * @return {Any?} Value from view or null */ var lookupValue = function(view, name) { var value = null; if (this.isModel(view) && view.has(name)) { value = view.get(name); } else if (this.isArray(view) && typeof view.at === 'function' && _.isNumber(parseInt(name, 10))) { value = view.at(name); } else if (view[name] != null) { if (view.tungstenCollection && blockedCollectionProperties[name]) { return null; } if (view.tungstenModel && blockedModelProperties[name]) { return null; } value = view[name]; } return value; }; module.exports = { initialize: initialize, lookupValue: lookupValue, ComponentWidget: require('./component_widget') };
JavaScript
0.000045
@@ -1921,37 +1921,25 @@ && -_.isNumber(parseIn +/%5E%5Cd+$/.tes t(name -, 10) )) %7B
741d3774aa8833166aecff6793a321e1191d8455
Update add-new-active-record-test
src/sagas/__tests__/add-new-active-record-test.js
src/sagas/__tests__/add-new-active-record-test.js
/** * Copyright 2017 Yuichiro Tsuchiya * * 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. */ /* eslint-env jest, jasmine */ jest.unmock('redux-thunk'); jest.unmock('redux-saga'); jest.unmock('redux-saga/effects'); jest.unmock('react-redux-form'); jest.unmock('mockdate'); jest.unmock('../../actions'); jest.unmock('../add-new-active-record'); jest.unmock('../../selectors'); import MockDate from 'mockdate'; import { delay } from 'redux-saga'; import { take, put, call, select } from 'redux-saga/effects'; import { ADD_NEW_ACTIVE_RECORD, changeActiveRecord, selectActiveRecord, } from '../../actions'; import { getActiveRecords, } from '../../selectors'; import { addNewActiveRecord, watchAddNewActiveRecord, } from '../add-new-active-record'; describe('ADD_NEW_ACTIVE_RECORD', () => { const mockCurrentTime = 1234567890123; beforeEach(() => { MockDate.set(mockCurrentTime); }); afterEach(() => { MockDate.reset(); }); it('calls actions.push() with new ID', () => { const saga = addNewActiveRecord('patient_foo'); expect(saga.next().value) .toEqual(select(getActiveRecords)); expect(saga.next([{}, {}]).value) .toEqual(put(changeActiveRecord(2, { _id: 'record_foo_1234567890123', type: 'record', $initialized_at: 1234567890123, }, { silent: true }))); expect(saga.next().value) .toEqual(put(selectActiveRecord('record_foo_1234567890123'))); expect(saga.next()) .toEqual({ done: true, value: undefined }); }); }); describe('watchAddNewActiveRecord', () => { it('calls addNewActiveRecord() with 1ms delay in blocking way', () => { const saga = watchAddNewActiveRecord(); expect(saga.next().value) .toEqual(take(ADD_NEW_ACTIVE_RECORD)); expect(saga.next({ patientId: 'patient_bar' }).value) .toEqual(call(addNewActiveRecord, 'patient_bar')); expect(saga.next().value) .toEqual(call(delay, 1)); }); });
JavaScript
0.000001
@@ -1497,16 +1497,39 @@ h new ID + and $meta.record_count ', () =%3E @@ -1523,32 +1523,32 @@ count', () =%3E %7B%0A - const saga = @@ -1580,24 +1580,138 @@ ent_foo');%0A%0A + const mockExistingActiveRecords = %5B%0A %7B _id: 'record_aaa_111' %7D,%0A %7B _id: 'record_aaa_222' %7D,%0A %5D;%0A%0A expect(s @@ -1796,16 +1796,33 @@ ext( -%5B%7B%7D, %7B%7D%5D +mockExistingActiveRecords ).va @@ -1910,16 +1910,16 @@ 90123',%0A - @@ -1934,16 +1934,173 @@ ecord',%0A + $meta: %7B%0A prev_record_ids: %5B%0A 'record_aaa_111',%0A 'record_aaa_222',%0A %5D,%0A record_count: 3,%0A %7D,%0A
369bc873f8e41ac29ec844bb4dee532cb086daa5
use an apostrophe rather than a prime (#566)
examples/nested-components/pages/index.js
examples/nested-components/pages/index.js
import P from '../components/paragraph' import Post from '../components/post' export default () => ( <div className='main'> <Post title='My first blog post'> <P>Hello there</P> <P>This is an example of a componentized blog post</P> </Post> <hr /> <Post title='My second blog post'> <P>Hello there</P> <P>This is another example.</P> <P>Wa-hoo!</P> </Post> <hr /> <Post title='The final blog post'> <P>C'est fin</P> </Post> <style jsx>{` .main { margin: auto; max-width: 420px; padding: 10px; } hr { width: 100px; border-width: 0; margin: 20px auto; text-align: center; } hr::before { content: "***"; color: #ccc; } `}</style> </div> )
JavaScript
0.000001
@@ -466,17 +466,17 @@ %3CP%3EC -' +%E2%80%99 est fin%3C
605bf7b60c4a7cc7b47f03840b96660b8f6f6124
Update schedule when user change the task status
app/actions/tasks.js
app/actions/tasks.js
import { ADD_TASK, DELETE_TASK, EDIT_TASK, CHANGE_TASK_STATUS, INVALIDATE_TASKS, REQUEST_TASKS, REQUEST_TASKS_SUCCESS, REQUEST_TASKS_FAILED, UPDATE_TASK_REQUEST, UPDATE_TASK_SUCCESS, UPDATE_TASK_FAILED, UPDATE_SCHEDULE, CALL_API } from '../constants/ActionTypes'; import { STATUS_COMPLETED } from '../constants/TaskStatuses'; import { doPut, doGet } from '../utils/apiUtils'; import { getTimeToSchedule } from '../utils/time'; import moment from 'moment-timezone'; import _ from 'lodash'; export function addTask(text) { return { type: ADD_TASK, text }; } export function deleteTask(id) { return { type: DELETE_TASK, id }; } export function editTask(id, text) { return { type: EDIT_TASK, id, text }; } export function changeStatus(id) { return { type: CHANGE_TASK_STATUS, id }; } export function toggleTaskStasus(id) { return (dispatch, getState) => { dispatch(changeStatus(id)); const task = getState().tasks.items.find(loopTask => loopTask.id === id); return dispatch(updateTask(task)); }; } export function invalidateTasks() { return { type: INVALIDATE_TASKS }; } export function scheduleTasks(tasks) { return (dispatch, getState) => { let taskScheduleMap = getState().tasks.schedule; // clear all timeout IDs _.forOwn(taskScheduleMap, (scheduleData) => { clearTimeout(scheduleData.timeoutId); }); taskScheduleMap = {}; tasks.forEach(function (task) { if (task.status === STATUS_COMPLETED) { return; } const time = getTimeToSchedule(task.text); if (time) { const deltaSeconds = moment(time, 'HH:mm').unix() - moment().unix(); if (deltaSeconds >= 0) { const timeoutId = setTimeout(() => dispatch({ type: 'SHOW_NOTIFICATION', payload: task.transformedText }), deltaSeconds * 1000); taskScheduleMap[task.id] = { timeoutId, scheduledFor: time }; } } }); return dispatch({ type: UPDATE_SCHEDULE, payload: taskScheduleMap }); }; } function fetchTasks() { return dispatch => { dispatch({ type: CALL_API, statuses: [REQUEST_TASKS, REQUEST_TASKS_SUCCESS, REQUEST_TASKS_FAILED], doApiCall: (accessToken) => { return doGet('/api/todos', { day: 'today' }, accessToken) .then((tasks) => { dispatch(scheduleTasks(tasks)); return tasks; }); } }); }; } export function shouldFetchTasks(state) { const fetchedAt = state.fetchedAt; if (!fetchedAt) { return true; } else if (state.isFetching) { return false; } return state.didInvalidate; } export function fetchTasksIfNeeded() { return (dispatch, getState) => { if (shouldFetchTasks(getState())) { return dispatch(fetchTasks()); } }; } export function updateTask(task) { return (dispatch, getState) => { dispatch({ type: CALL_API, statuses: [UPDATE_TASK_REQUEST, UPDATE_TASK_SUCCESS, UPDATE_TASK_FAILED], doApiCall: (accessToken) => { var url = `/api/todos/${ task.id }`; return doPut(url, task, accessToken). then(response => { dispatch(scheduleTasks(getState().tasks.items)); return response; }); } }); } }
JavaScript
0.000001
@@ -2923,17 +2923,16 @@ tate) =%3E - %7B%0A d @@ -3322,11 +3322,12 @@ %7D);%0A %7D +; %0A%7D%0A
a84246f1fefc03957e3bbbcc3f5bfa2f865bd64f
Fix dice command
commands.js
commands.js
const fs = require('fs'); // Commands are called with the following arguments: // commands[command](message, config, msg, ...parameters) // msg is the message content without the prefix or command module.exports = { 'ping': (message) => { message.reply("pong!"); }, // _ denotes arguments we don't care about 'echo': (message, _, msg) => { if (msg) { message.channel.send(msg); } }, 'prefix': (message, config, _, newPrefix) => { if (newPrefix) { config.prefix = newPrefix; fs.writeFile("./config.json", JSON.stringify(config, null, 4), err => console.error); message.channel.send(`Prefix successfully set to '${newPrefix}'`) } else { message.channel.send("Please provide a prefix."); } }, 'die': (message, config) => { if (message.author.id === config.ids.soupmaster) { message.channel.send("Emptying can...") .then(() => { console.log("Forced to disconnect."); process.exit(0); }); } }, 'factcheck': (message, _, msg) => { let bool1 = (Math.random() > 0.5), bool2 = (Math.random() > 0.5), str; if (msg) { str = `${message.author}'s claim, "${msg}",` str = bool1 ? `${str} is obviously ${bool2.toString()}.` : `${str} can't possibly be ${bool2.toString()}.`; } else { str = bool1 ? `${message.author} is always ${bool2 ? "right" : "wrong"}.` : `${message.author} is never ${bool2 ? "right" : "wrong"}.` } message.channel.send(str); }, 'coin': (message) => { let bool = (Math.random() > 0.5); message.channel.send(bool ? "Heads." : "Tails."); }, 'dice': (message, _, _, n) => { n = n || 6; message.channel.send(Math.floor(Math.random()*n) + 1); } }
JavaScript
0.006807
@@ -1896,16 +1896,17 @@ age, _, +_ _, n) =%3E @@ -1920,17 +1920,40 @@ n = -n +Math.max(parseInt(n), 0) %7C%7C 6;%0A
206267073bce21c913d2fbacc36b956ecd41ced2
Remove pause from music commands
commands.js
commands.js
const ytdl = require('ytdl-core'); function msToTime(s) { let ms = s % 1000; s = (s - ms) / 1000; let secs = s % 60; s = (s - secs) / 60; let mins = s % 60; s = (s - mins) / 60; let hrs = s % 24; let days = (s - hrs) / 24; let time_str = `${secs} seconds.`; if (mins) { time_str = `${mins} minutes and ` + time_str; } if (hrs) { time_str = `${hrs} hours ` + time_str; } if (days) { time_str = `${days} days ` + time_str; } return time_str; } let command_data = { "uptime": { doc: "How much time I have been online for", process: (client, message) => { return client.createMessage(message.channel_id, `I have been ruling this server for ${msToTime(client.uptime())}`); } }, "commands": { doc: "List all available commands", process: (client, message) => { let commands_str = ""; for (let c in module.exports) { let command = module.exports[c]; if (!command.private) { commands_str += `${command.usage}\n`; } } return client.createMessage(message.channel_id, commands_str); } }, "music": { args: [ { type: "subcommand", oneof: [ { name: "play", args: [ { name: "Youtube link" } ] }, { name: "stop" }, { name: "pause" } ]}, ], doc: "Music controls", process: (client, message, args) => { return new Promise((resolve, reject) => { switch(args[0]) { case "play": ytdl.getInfo(args[1], (err, info) => { if (err) { console.error("Error in !music:", err); } // `info` is a list of all possible formats this video exists in let audio_formats = info.formats.filter(i => i.type && i.type.indexOf('audio/') > -1); let selection = audio_formats.reduce((pv, cv) => pv.audioBitrate > cv.audioBitrate ? pv : cv); client.voice_connection.play(selection.url); }); break; case "stop": client.voice_connection.stop(); break; case "pause": break; } resolve(); }); } }, "hots": { args: [ { name: "hero" } ], doc: "View HotS build for <hero> on icy-veins.com and heroesfire.com", process: (client, message, args) => { return new Promise((resolve, reject) => { if (args[0].toLowerCase() === "murky") { client.createMessage(message.channel_id, "Fuck Murky", true); return; } let m1 = client.createMessage(message.channel_id, `http://www.icy-veins.com/heroes/${args.join('-')}-build-guide \n`); let m2 = client.createMessage(message.channel_id, `http://www.heroesfire.com/hots/wiki/heroes/${args.join('-')}`); return Promise.all([m1, m2]); }); } }, "heroesfire": { args: [ { name: "hero" } ], doc: "View HotS build for <hero> on heroesfire.com", process: (client, message, args) => { return client.createMessage(message.channel_id, `http://www.heroesfire.com/hots/wiki/heroes/${args.join('-')}`); } }, "icyveins": { args: [ { name: "hero" } ], doc: "View HotS build for <hero> on icy-veins.com", process: (client, message, args) => { return client.createMessage(message.channel_id, `http://www.icy-veins.com/heroes/${args.join('-')}-build-guide`); } }, "test": { private: true, process: (client, message) => { return client.createMessage(message.channel_id); } } }; function argsToString(args) { if (!args) return ""; let arg_str = ""; args.forEach(arg => { if (arg.type === "subcommand") { arg_str += `<${arg.oneof.reduce((pv, cv) => pv + cv.name + "|", "").slice(0,-1)}> `; arg.oneof.forEach(a => { if (a.args) { arg_str += argsToString(a.args); } }); } else { arg_str += `<${arg.name}>${arg.optional ? '?' : ""}`; } }); return arg_str; } class Command { constructor(name, data) { this.name = name; this.args = data.args || []; this.doc = data.doc || ""; this.private = data.private || false; this.process = data.process; } get usage() { return `**!${this.name}** ${argsToString(this.args)}\n _${this.doc}_`; } } let exprt = {}; for (var c in command_data) { if (command_data.hasOwnProperty(c)) { let command = new Command(c, command_data[c]); exprt[c] = command; } } module.exports = exprt;
JavaScript
0.000005
@@ -1449,43 +1449,8 @@ %7D,%0D%0A - %7B name: %22pause%22 %7D%0D%0A
b7fd64c2d8588097e2b4bf488a59d93d6daed83b
Change config command to edit config.js in the Shout home directory
src/command-line/config.js
src/command-line/config.js
var program = require("commander"); var child = require("child_process"); var CONFIG_PATH = process.cwd() + "/config.js"; program .command("config") .description("Edit config: '" + CONFIG_PATH + "'") .action(function() { child.spawn( "sudo", ["vi", CONFIG_PATH], {stdio: "inherit"} ); });
JavaScript
0
@@ -1,12 +1,64 @@ +var fs = require(%22fs%22);%0Avar path = require(%22path%22);%0A var program @@ -77,24 +77,56 @@ ommander%22);%0A +var mkdirp = require(%22mkdirp%22);%0A var child = @@ -155,45 +155,303 @@ %22);%0A -%0Avar CONFIG_PATH = process.cwd() + +var Helper = require(%22../helper%22);%0A%0Avar CONFIG_PATH = process.env.SHOUT_CONFIG;%0Aif(!CONFIG_PATH) %7B%0A%09CONFIG_PATH = Helper.resolveHomePath(%22config.js%22);%0A%7D%0Aif(!fs.exists(CONFIG_PATH)) %7B%0A%09mkdirp.sync(Helper.getHomeDirectory());%0A%09var configFile = fs.readFileSync(path.resolve(__dirname, %22..%22, %22..%22, %22 -/ conf @@ -456,17 +456,65 @@ nfig.js%22 -; +));%0A%09fs.writeFileSync(CONFIG_PATH, configFile);%0A%7D %0A%0Aprogra
85971be8f53ba4ea8443db46744f369d5fcf02b8
Move comments, remove commented code, and change concat
commands.js
commands.js
const static_commands = require('./static_commands.js') // Commands are called in the following manner: // commands[command](message, config, msg, ...parameters) // msg is the message content without the prefix or command module.exports = { 'ping': (message) => { message.edit("pong!"); }, // _ denotes arguments we don't care about 'selfbot_off': (message) => { message.edit("Selfbot logging off.").then(() => { console.log("Forced to disconnect."); process.exit(0); }); }, 'reply': (message, _, msg) => { let cb = '```', quotes = msg.split(/\.s\./g), reply = quotes.pop(); message.edit( quotes.map(q => `${cb}css\n> ${q}${cb}`) .join('') .concat(reply) ); }, // 'shrug': (message, _, msg) => { // message.edit(msg + "¯\\_(ツ)_\/¯"); // }, 'hideyourshame': (message, config, _, n=0) => { n = parseInt(n) + 1; message.channel.fetchMessages( {limit: 99} ) .then((messages) => { messages.array() .filter(m => m.author.id === config.soupmaster) .slice(0,n) .forEach(message => message.delete()); }); }, 'eval': (message, config, msg) => { try { message.channel.send(`Input\n\`\`\`js\n${msg}\`\`\`${'' }Output\n\`\`\`js\n${eval(msg)}\`\`\``) .catch(e => message.channel.send(e)) } catch (e) { message.channel.send(e) } } } for(let key in static_commands) { module.exports[key] = (message, _, msg) => { message.edit(`${msg} ${static_commands[key]}`); } }
JavaScript
0
@@ -306,55 +306,8 @@ %7D,%0A%0A - // _ denotes arguments we don't care about%0A @@ -328,32 +328,32 @@ (message) =%3E %7B%0A + message. @@ -489,24 +489,71 @@ %7D);%0A %7D,%0A%0A + // _ denotes arguments we don't care about%0A 'reply': @@ -833,104 +833,8 @@ %7D,%0A%0A - // 'shrug': (message, _, msg) =%3E %7B%0A // message.edit(msg + %22%C2%AF%5C%5C_(%E3%83%84)_%5C/%C2%AF%22);%0A // %7D,%0A%0A @@ -1299,16 +1299,45 @@ el.send( +%0A %60Input%5Cn @@ -1362,12 +1362,10 @@ %5C%60%5C%60 -$%7B'' +%60+ %0A @@ -1389,17 +1389,17 @@ -%7D +%60 Output%5Cn @@ -1427,16 +1427,45 @@ %7D%5C%60%5C%60%5C%60%60 +%0A )%0A
a45b4c36faf60cff85d473c5964ae5ce6b41cd8f
add type for file arg and return in docstring for checkStatusCol
bids-validator/validators/tsv/checkStatusCol.js
bids-validator/validators/tsv/checkStatusCol.js
const Issue = require('../../utils').issues.Issue /** * Checks status column in a electroencephalography _channels.tsv file to * ensure its values are only * 'good', 'bad', or 'n/a' * @param {string[]} rows - Each row of a tsv file to be checked. * @param file - File of rows being checked, used for error message if * problem is found. * @param {Object[]} issues - Array of issue objects to add to if problem is * found. */ const checkStatusCol = function(rows, file, issues) { const header = rows[0] const statusColumn = header.indexOf('status') if (statusColumn !== -1) { for (let i = 1; i < rows.length; i++) { const line = rows[i] const status = line[statusColumn] if (status !== 'good' && status !== 'bad' && status != 'n/a') { issues.push( new Issue({ file: file, evidence: line, line: i + 1, reason: 'the status column values should either be good, bad, or n/a', code: 125, }), ) } } } return } export default checkStatusCol
JavaScript
0
@@ -253,16 +253,25 @@ * @param + %7BObject%7D file - @@ -440,16 +440,82 @@ found.%0A + * @returns %7Bnull%7D Results of this function are stored in issues.%0A */%0Acons
f985297b28849f7439e2d600f375ae4f0c77d128
Tweak styles/add edit button to Activity
src/components/Activity.js
src/components/Activity.js
import React, { Component, PropTypes } from 'react'; import moment from 'moment'; class Activity extends Component { render() { const { timestamp, activity, deleteActivity } = this.props; return ( <div className="row row--middle"> <div className="col--4 col--start"> <div className="pv-"> {activity.description} <span className="cursor--pointer ml p- color-red--hover" onClick={() => deleteActivity(timestamp)} > &times; </span> </div> </div> </div> ); } } Activity.propTypes = { timestamp: PropTypes.string.isRequired, activity: PropTypes.object.isRequired, deleteActivity: PropTypes.func.isRequired, editActivity: PropTypes.func.isRequired, } export default Activity;
JavaScript
0
@@ -172,16 +172,30 @@ Activity +, editActivity %7D = thi @@ -254,16 +254,27 @@ --middle + row--start %22%3E%0A @@ -299,22 +299,33 @@ %22col ---4 col--start + flex align-items--center %22%3E%0A @@ -353,11 +353,12 @@ me=%22 -pv- +flex %22%3E%0A @@ -395,24 +395,37 @@ on%7D%0A + %3C/div%3E%0A %3Cspan%0A @@ -420,16 +420,16 @@ + %3Cspan%0A - @@ -447,16 +447,21 @@ ssName=%22 +flex cursor-- @@ -468,16 +468,25 @@ pointer +font--12 ml p- co @@ -493,22 +493,15 @@ lor- -red--hover%22%0A +-blue%22%0A @@ -523,22 +523,20 @@ =%7B() =%3E -delete +edit Activity @@ -562,69 +562,226 @@ - %3E%0A &times;%0A %3C/span%3E%0A %3C/div +%3E%0A edit%0A %3C/span%3E%0A %3Cspan%0A className=%22flex cursor--pointer ml-- p- color-red%22%0A onClick=%7B() =%3E deleteActivity(timestamp)%7D%0A %3E%0A &times;%0A %3C/span %3E%0A
58f2430a2ae9577fdc4406272442c0ef4db3df4e
Update content on bound value change #2
addon/components/content-editable.js
addon/components/content-editable.js
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['ember-content-editable'], classNameBindings: ['extraClass'], attributeBindings: ['contenteditable', 'placeholder'], contenteditable: true, setup: Ember.on('didInsertElement', function() { this.$().html(this.get('value')); }), stringInterpolator(s) { return s; }, updateValue: Ember.on('keyUp', function(event) { this.set('value', this.stringInterpolator(this.$().text())); this.handleKeyUp(event); }), handleKeyUp(event) { this.sendAction('keyUp', this.get('value'), event); if (event.keyCode === 27) { // Escape this.sendAction('escape-press', this, event); } else if (event.keyCode === 13) { // Enter this.sendAction('enter', this, event); this.sendAction('insert-newline', this, event); } }, /* Events */ keyDown(event) { this.sendAction('key-down', this.get('value'), event); }, keyPress(event) { this.sendAction('key-press', this, event); }, focusIn(event) { this.sendAction('focus-in', this, event); }, focusOut(event) { this.sendAction('focus-out', this, event); }, mouseEnter(event) { this.sendAction('mouse-enter', this, event); }, mouseLeave(event) { this.sendAction('mouse-leave', this, event); }, });
JavaScript
0
@@ -270,24 +270,174 @@ unction() %7B%0A + this.setValue();%0A %7D),%0A%0A valueChanged: Ember.observer('value', function() %7B%0A this.setValue();%0A %7D),%0A%0A setValue() %7B%0A if (this.element) %7B%0A this.$() @@ -460,26 +460,31 @@ value'));%0A + %7D%0A %7D -) ,%0A%0A stringI
53095ec8f993e726eec853327fd857c8af34af29
Update content inspection to use column-content
exporter.js
exporter.js
(function (maxWait,plstype){ var self = this, downloaded = false, playlistEntries={}, format = plstype, dialog; this.totalWait = 0; this.totalWaitSinceChange = 0; this.totalSongs = 0; this.quoteEscape = function(text) { return '"'+text.replace('"','""')+'"'; }; this.scrape = function() { var playlist = document.querySelectorAll('.song-table tr.song-row'); for (var i = 0; i < playlist.length; i++) { var l = playlist[i], title = l.querySelectorAll('td[data-col="title"] .content')[0].textContent, artist = l.querySelectorAll('td[data-col="artist"] .content')[0].textContent, album = l.querySelectorAll('td[data-col="album"] .content')[0].textContent, duration = l.querySelectorAll('td[data-col="duration"] span')[0].textContent, lineFormat; if (self.format == 'ivy') { lineFormat = artist.replace('-', ' ').trim() + ' - ' + title.replace(/(.+?)\s*[\(\[].+[\)\]]\s*$/, '$1').trim(); } else if (self.format == 'm3u') { var durationParts = duration.split(':'), totalSeconds; if (durationParts.length === 3) { totalSeconds = parseInt(durationParts[0],10) * 3600 + parseInt(durationParts[1],10) * 60 + parseInt(durationParts[2],10); } else if (durationParts.length == 2) { totalSeconds = parseInt(durationParts[0],10) * 60 + parseInt(durationParts[1],10); } else { totalSeconds = -1; } lineFormat = '#EXTINF:' + totalSeconds + ',' + artist.replace('-', ' ').trim() + ' - ' + title.replace(/(.+?)\s*[\(\[].+[\)\]]\s*$/, '$1').trim() + "\n" + album.trim() + '/' + artist.replace('-', ' ').trim() + ' - ' + title.replace(/(.+?)\s*[\(\[].+[\)\]]\s*$/, '$1').trim() + '.mp3' } else { lineFormat = quoteEscape(artist)+','+quoteEscape(title)+','+quoteEscape(album)+','+quoteEscape(duration); } if (!playlistEntries.hasOwnProperty(lineFormat)) { self.totalSongs++; self.totalWaitSinceChange = 0; playlistEntries[lineFormat] = { artist: artist, title: title, album: album, duration: duration } } } }; this.download = function() { if (downloaded) return; downloaded = true; var csvContent, downloadAnchor, downloadBlob, type, filename; csvContent = ''; for (var line in playlistEntries) { csvContent += line + "\n"; } if (self.format == 'ivy') { type = 'text'; filename = 'playlist.txt'; } else if (self.format == 'm3u') { csvContent = "#EXTM3U\n" + csvContent; type = 'text/m3u'; filename = 'playlist.m3u'; } else { type = 'text/csv'; filename = 'playlist.csv'; } downloadAnchor = document.createElement('a'); downloadBlob = new Blob([csvContent], {'type': type}); downloadAnchor.href = window.URL.createObjectURL(downloadBlob); downloadAnchor.download = filename; downloadAnchor.click(); }; this.scrollAll = function() { self.scrape(); if (downloaded) { return; } var timeUntilDownload = maxWait >= 0 ? maxWait*1000 - self.totalWait: 9000 - self.totalWaitSinceChange; if (timeUntilDownload > 0) { self.totalWait += 50; // close enough self.totalWaitSinceChange += 50; self.statusBox.innerHTML = 'Download in ' + Math.round(timeUntilDownload/1000) + ' seconds; Songs: ' + self.totalSongs; setTimeout(function(){self.scrollAll();}, 50); } else { download(); } }; this.begin = function() { self.dialog.close(); var playlistSelect = document.getElementById('playlist-format'); self.format = playlistSelect.options[playlistSelect.selectedIndex].value; self.scrape(); self.scrollAll(); return false; }; self.totalSongs = 0; self.statusBox = document.createElement('div'); self.statusBox.style.position = 'fixed'; self.statusBox.style.bottom = '0'; self.statusBox.style.right = '0'; self.statusBox.style.background = '#CCC'; self.statusBox.style.zIndex = 999999; self.statusBox.innerHTML = 'Songs: 0'; document.body.appendChild(self.statusBox); if (plstype === 'prompt') { self.dialog = document.createElement('dialog'); self.dialog.innerHTML = '<form onsubmit="return self.begin()"><strong>Select Format:</strong><select id="playlist-format">' +'<option value="m3u">M3U (Generic, soundiiz.com, etc.)</option>' +'<option value="csv">CSV (Generic CSV)</option>' +'<option value="ivy">IVY (ivyishere.org)</option>' +'</select> <input type="submit" value="Begin"/></dialog>'; document.body.appendChild(self.dialog); self.dialog.showModal(); } else { self.begin(); } })(-1,'prompt');
JavaScript
0
@@ -578,24 +578,31 @@ l=%22title%22%5D . +column- content')%5B0%5D @@ -679,24 +679,31 @@ =%22artist%22%5D . +column- content')%5B0%5D @@ -782,16 +782,23 @@ lbum%22%5D . +column- content' @@ -5120,16 +5120,17 @@ .begin() +; %22%3E%3Cstron @@ -5451,22 +5451,20 @@ gin%22/%3E%3C/ -dialog +form %3E';%0A
e97e724c440e18b2053f056948b18f17cea7d6f8
Add comments about variable names.
examples/federated/core_package/webpack.config.js
examples/federated/core_package/webpack.config.js
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. const path = require('path'); const fs = require('fs-extra'); const Handlebars = require('handlebars'); const Build = require('@jupyterlab/builder').Build; const webpack = require('webpack'); const merge = require('webpack-merge').default; const baseConfig = require('@jupyterlab/builder/lib/webpack.config.base'); const { ModuleFederationPlugin } = webpack.container; const packageData = require('./package.json'); // Handle the extensions. const jlab = packageData.jupyterlab; // Create a list of application extensions and mime extensions from // jlab.extensions const extensions = {}; const mimeExtensions = {}; for (const key of jlab.extensions) { const { jupyterlab: { extension, mimeExtension } } = require(`${key}/package.json`); if (extension !== undefined) { extensions[key] = extension === true ? '' : extension; } if (mimeExtension !== undefined) { mimeExtensions[key] = mimeExtension === true ? '' : mimeExtension; } } const extensionPackages = jlab.extensions; // Ensure a clean directory. function clean(dir) { if (fs.existsSync(dir)) { fs.removeSync(dir); } fs.ensureDirSync(dir); } const buildDir = path.resolve(jlab.buildDir); clean(buildDir); const outputDir = path.resolve(jlab.outputDir); clean(outputDir); const schemaDir = path.resolve(jlab.schemaDir); // ensureAssets puts schemas in the schemas subdirectory clean(path.join(schemaDir, 'schemas')); const themeDir = path.resolve(jlab.themeDir); // ensureAssets puts themes in the themes subdirectory clean(path.join(themeDir, 'themes')); // Configuration to handle extension assets const extensionAssetConfig = Build.ensureAssets({ packageNames: extensionPackages, output: buildDir, schemaOutput: schemaDir, themeOutput: themeDir }); // Create the entry point and other assets in build directory. const source = fs.readFileSync('index.template.js').toString(); const template = Handlebars.compile(source); const extData = { jupyterlab_extensions: extensions, jupyterlab_mime_extensions: mimeExtensions }; fs.writeFileSync(path.join(buildDir, 'index.js'), template(extData)); // Create the bootstrap file that loads federated extensions and calls the // initialization logic in index.js const entryPoint = path.join(buildDir, 'bootstrap.js'); fs.copySync('./bootstrap.js', entryPoint); function createShared(packageData) { // Set up module federation sharing config const shared = {}; const extensionPackages = packageData.jupyterlab.extensions; // Make sure any resolutions are shared for (let [pkg, requiredVersion] of Object.entries(packageData.resolutions)) { shared[pkg] = { requiredVersion }; } // Add any extension packages that are not in resolutions (i.e., installed from npm) for (let pkg of extensionPackages) { if (!shared[pkg]) { shared[pkg] = { requiredVersion: require(`${pkg}/package.json`).version }; } } // Add dependencies and sharedPackage config from extension packages if they // are not already in the shared config. This means that if there is a // conflict, the resolutions package version is the one that is shared. const extraShared = []; for (let pkg of extensionPackages) { let pkgShared = {}; let { dependencies = {}, jupyterlab: { sharedPackages = {} } = {} } = require(`${pkg}/package.json`); for (let [dep, requiredVersion] of Object.entries(dependencies)) { if (!shared[dep]) { pkgShared[dep] = { requiredVersion }; } } // Overwrite automatic dependency sharing with custom sharing config for (let [dep, config] of Object.entries(sharedPackages)) { if (config === false) { delete pkgShared[dep]; } else { if ('bundled' in config) { config.import = config.bundled; delete config.bundled; } pkgShared[dep] = config; } } extraShared.push(pkgShared); } // Now merge the extra shared config const mergedShare = {}; for (let sharedConfig of extraShared) { for (let [pkg, config] of Object.entries(sharedConfig)) { // Do not override the basic share config from resolutions if (shared[pkg]) { continue; } // Add if we haven't seen the config before if (!mergedShare[pkg]) { mergedShare[pkg] = config; continue; } // Choose between the existing config and this new config. We do not try // to merge configs, which may yield a config no one wants let oldConfig = mergedShare[pkg]; // if the old one has import: false, use the new one if (oldConfig.import === false) { mergedShare[pkg] = config; } } } Object.assign(shared, mergedShare); // Transform any file:// requiredVersion to the version number from the // imported package. This assumes (for simplicity) that the version we get // importing was installed from the file. for (let [pkg, { requiredVersion }] of Object.entries(shared)) { if (requiredVersion && requiredVersion.startsWith('file:')) { shared[pkg].requiredVersion = require(`${pkg}/package.json`).version; } } // Add singleton package information for (let pkg of packageData.jupyterlab.singletonPackages) { shared[pkg].singleton = true; } return shared; } const plugins = [ new ModuleFederationPlugin({ library: { type: 'var', name: ['_JUPYTERLAB', 'CORE_LIBRARY_FEDERATION'] }, name: 'CORE_FEDERATION', shared: createShared(packageData) }) ]; module.exports = [ merge(baseConfig, { mode: 'development', devtool: 'source-map', entry: ['./publicpath.js', entryPoint], output: { path: path.resolve(outputDir), library: { type: 'var', name: ['_JUPYTERLAB', 'CORE_OUTPUT'] }, filename: 'bundle.js' }, optimization: { splitChunks: { chunks: 'all', cacheGroups: { jlab_core: { test: /[\\/]node_modules[\\/]@(jupyterlab|lumino)[\\/]/, name: 'jlab_core' } } } }, plugins }) ].concat(extensionAssetConfig); // For debugging, write the config out const logPath = path.join(buildDir, 'build_log.json'); fs.writeFileSync(logPath, JSON.stringify(module.exports, null, ' '));
JavaScript
0
@@ -1233,24 +1233,102 @@ nc(dir);%0A%7D%0A%0A +// buildDir is a temporary directory where files are copied before the build.%0A const buildD @@ -1375,24 +1375,72 @@ buildDir);%0A%0A +// outputDir is where the final built assets go%0A const output @@ -1490,24 +1490,82 @@ utputDir);%0A%0A +// %3CschemaDir%3E/schemas is where the settings schemas live%0A const schema @@ -1597,16 +1597,29 @@ chemaDir + %7C%7C outputDir );%0A// en @@ -1711,16 +1711,64 @@ as'));%0A%0A +// %3CthemeDir%3E/themes is where theme assets live%0A const th @@ -1802,16 +1802,29 @@ themeDir + %7C%7C outputDir );%0A// en
290c2c409acebe7e623b406faa9a059cbc966b85
Fix empty language break
app/helpers/forms.js
app/helpers/forms.js
export const getBtnTextByType = (type) => { switch (type) { case 'text': return 'report.inputText'; case 'radio': return 'report.inputRadio'; case 'select': return 'report.inputSelect'; default: return 'report.input'; } }; export const parseQuestion = ({ question, form }, deviceLang) => { const lang = form.languages.includes(deviceLang) ? deviceLang : form.defaultLanguage; let parsedQuestion = { ...question }; const whitelist = ['defaultValue', 'label', 'values', 'name']; whitelist.forEach((key) => { if (typeof parsedQuestion[key] === 'object' && typeof parsedQuestion[key][lang] !== 'undefined') { parsedQuestion = { ...parsedQuestion, [key]: parsedQuestion[key][lang] }; } }); if (parsedQuestion.childQuestions) { parsedQuestion.childQuestions = parsedQuestion.childQuestions.map((child) => parseQuestion({ question: child, form }, deviceLang)); } return parsedQuestion; }; export const getAnswers = (forms, formName) => { if (!forms) return null; if (forms[formName] && forms[formName].values) return forms[formName].values; return {}; }; export const getTemplate = (reports, formName) => { const list = reports.list[formName]; const status = templateId => ( reports.templates[templateId] && reports.templates[templateId].status ); const templateId = list && list.area.templateId && status(list.area.templateId) !== 'unpublished' ? list.area.templateId : 'default'; return Object.assign({}, reports.templates[templateId]); }; export const getNextStep = ({ currentQuestion, questions, answers }) => { let next = 1; if (currentQuestion < questions.length - 1) { for (let i = currentQuestion + 1, qLength = questions.length; i < qLength; i++) { const nextConditions = questions[i].conditions; const nextHasConditions = nextConditions && nextConditions.length > 0; if (!nextHasConditions || (answers[nextConditions[0].name] === nextConditions[0].value)) { break; } next += 1; } return currentQuestion + next; } return null; }; export const getFormFields = (template, answers) => { const fields = [0]; template.questions.forEach((question, index) => { const nextStep = getNextStep({ currentQuestion: index, questions: template.questions, answers }); if (nextStep) fields.push(nextStep); }); return fields.map(field => template.questions[field].name); }; export const isQuestionAnswered = (question, answers) => { if (!question) return false; if (question.type !== 'blob') { return typeof answers[question.name] !== 'undefined'; } return answers[question.name] && !!answers[question.name].length; }; export default { getBtnTextByType, parseQuestion, getTemplate, getAnswers, getFormFields, getNextStep, isQuestionAnswered };
JavaScript
0.999999
@@ -600,19 +600,45 @@ 'object' - && +) %7B%0A const parsedValue = typeof @@ -678,19 +678,66 @@ defined' -) %7B +%0A ? parsedQuestion%5Bkey%5D%5Blang%5D%0A : ''; %0A p @@ -786,35 +786,21 @@ : parsed -Question%5Bkey%5D%5Blang%5D +Value %7D;%0A
5fb389375f64c63d995555f71825761886efd48a
Switch order
spec/assets/spec_helper.js
spec/assets/spec_helper.js
//= require support/third_party_for_specs //= require support/prop_types //= require support/test_utils //= require support/mock_react_router //= require support/magic_lamp //= require_self //= require support/utils /* global window*/ App = {}; expect = window.chai.expect; (function () { 'use strict'; MagicLamp.preload(); beforeEach(function () { this.sandbox = sinon.sandbox.create(); this.sandbox.stub(window.console, 'warn', function (message) { throw message; }); }); afterEach(function () { MagicLamp.clean(); this.sandbox.restore(); }); })();
JavaScript
0.000001
@@ -533,51 +533,51 @@ -MagicLamp.clean();%0A this.sandbox.restore +this.sandbox.restore();%0A MagicLamp.clean ();%0A
2dd04581b434285eea4a97841de07558087592d9
Fix input box component
src/components/InputBox.js
src/components/InputBox.js
import React, { PropTypes } from 'react'; export default function InputBox(props) { return ( <div key={props.key}> {props.msg}:&nbsp; <input ref={props.ref} type="text"/> </div> ); } InputBox.propTypes = { key: PropTypes.number, msg: PropTypes.string, ref: PropTypes.object };
JavaScript
0.000022
@@ -121,16 +121,23 @@ %3E%0A +%3Clabel%3E %7Bprops.m @@ -143,15 +143,16 @@ msg%7D -:&nbsp; +%3C/label%3E %0A @@ -160,16 +160,52 @@ %3Cinput + className=%22form-control theme-form%22 ref=%7Bpr
bdd48e7c425c2ddf44f6e93ba794fe33dd17966c
Allow scrolling in modal
src/components/MainMenu.js
src/components/MainMenu.js
import React from 'react'; import classnames from 'classnames'; import ScrollLock from 'react-scrolllock'; import IconBars from '../images/icon-bars.svg'; import IconTimes from '../images/icon-times.svg'; import IconTwitterSquare from '../images/icon-twitter-square.svg'; import IconFacebookSquare from '../images/icon-facebook-square.svg'; import HDOServices from './HDOServices'; export default class MainMenu extends React.Component { constructor(props) { super(props); this.state = { hidden: true }; } onClick = () => { this.setState({ hidden: !this.state.hidden }); }; render() { const { hidden } = this.state; const triggerClasses = classnames('main-menu__trigger', { hidden: !hidden }); const modalClasses = classnames('main-menu__modal', { hidden }); return ( <div className="main-menu"> <button className={triggerClasses} type="button" onClick={this.onClick}> <IconBars aria-hidden={!hidden} /> </button> <div id="main-menu" className={modalClasses} tabIndex="-1" role="dialog" aria-label="Main menu" aria-hidden={hidden} > {!hidden && <ScrollLock />} <button type="button" className="close main-menu__modal-close" data-dismiss="modal" aria-label="Close" onClick={this.onClick} > <IconTimes aria-hidden={hidden} /> </button> <div className="main-menu__nav-wrap"> <nav className="main-menu__nav"> <h2 className="hdo-nav-title">Holder de ord</h2> <ul className="nav flex-column"> <li className="nav-item"> <a className="nav-link main-menu__nav-link" href="https://www.holderdeord.no/portal/om-oss" > Om oss </a> </li> <li className="nav-item"> <a className="nav-link main-menu__nav-link" href="https://www.holderdeord.no/portal/stott-oss" > Støtt oss </a> </li> <li className="nav-item"> <a className="nav-link main-menu__nav-link main-menu__nav-social" href="https://twitter.com/holderdeord" > <IconTwitterSquare /> <span>Twitter</span> </a> </li> <li className="nav-item"> <a className="nav-link main-menu__nav-link main-menu__nav-social" href="https://www.facebook.com/holderdeord" > <IconFacebookSquare /> <span>Facebook</span> </a> </li> </ul> </nav> <nav className="main-menu__nav"> <h2 className="our-services-title">Våre tjenester</h2> <HDOServices /> </nav> </div> </div> </div> ); } }
JavaScript
0.000001
@@ -1169,16 +1169,84 @@ hidden%7D%0A + ref=%7Bel =%3E %7B%0A this.modalRef = el;%0A %7D%7D%0A @@ -1280,16 +1280,50 @@ rollLock + touchScrollTarget=%7Bthis.modalRef%7D /%3E%7D%0A
da1161407c00defc37ff8a5f81eb3630225550d6
check in L is Present in initializer
addon/initializers/leaflet-assets.js
addon/initializers/leaflet-assets.js
import { isNone } from '@ember/utils'; import config from 'ember-get-config'; /* global L */ export function initialize(/* container, application */) { if (typeof FastBoot === 'undefined') { let prefix = ''; if (!isNone(config.rootURL)) { prefix = config.rootURL; } else if (!isNone(config.baseURL)) { prefix = config.baseURL; } L.Icon.Default.imagePath = `${prefix}assets/images/`; } } export default { name: 'leaflet-assets', initialize };
JavaScript
0.000005
@@ -171,16 +171,44 @@ Boot === + 'undefined' && typeof L !== 'undefi
a3e6c408f9c452135e4f68772af5c7ef8a202f1b
Allow to add groups
extension/content/firebug/css/selectorPanel.js
extension/content/firebug/css/selectorPanel.js
/* See license.txt for terms of usage */ define([ "firebug/lib/trace", "firebug/lib/object", "firebug/lib/domplate", "firebug/lib/locale", "firebug/lib/dom", "firebug/lib/css", "firebug/lib/events", "firebug/css/selectorModule", "firebug/css/selectorEditor" ], function(FBTrace, Obj, Domplate, Locale, Dom, Css, Events, CSSSelectorsModule, SelectorEditor) { with (Domplate) { // ********************************************************************************************* // // CSS Computed panel (HTML side panel) function CSSSelectorsPanel() {} CSSSelectorsPanel.prototype = Obj.extend(Firebug.Panel, { template: domplate( { selectorsTag: DIV({"class": "selectorTrials a11yCSSView", role: "list", "aria-label": Locale.$STR("aria.labels.Elements")}, TAG("$selectorEditorRow"), DIV({"class": "elementsGroups"}, FOR("group", "$groups", TAG("$elementsGroupTag", {group: "$group", windows: "$windows"}) ) )), selectorEditorRow: DIV({"class": "selectorEditorContainer editorContainer a11yFocusNoTab", role: "button", "tabindex" : "0", "aria-label": Locale.$STR("a11y.labels.press enter to add new selector"), onclick: "$onClickEditor"}, Locale.$STR("css.selector.TryASelector") ), elementsGroupTag: DIV({"class": "elementsGroup foldableGroup", $opened: "$group.opened", role: "list", _repObject: "$group"}, H1({"class": "cssElementsHeader groupHeader focusRow", role: "listitem"}, DIV({"class": "twisty", role: "presentation"}), SPAN({"class": "cssElementsLabel groupLabel"}, "$group.selector") ), TAG("$elementsTag", {elements: "$windows,$group.selector|getElements"}) ), elementsTag: TABLE({"class": "cssElementsTable groupContent", role: "list"}, TBODY({role: "presentation"}, FOR("element", "$elements", TR({"class": "focusRow cssElementsRow cssElements", role: "listitem", _repObject: "$element"}, TD({"class": "cssElement", role: "presentation"}, TAG("$element|getElementTag", {object: "$element"}) ) ) ) ) ), getElementTag: function(value) { var rep = Firebug.getRep(value); var tag = rep.shortTag ? rep.shortTag : rep.tag; return tag; }, getElements: function(windows, selector) { return CSSSelectorsModule.matchElements(windows, selector); }, onClickEditor: function(event) { var target = event.currentTarget; var panel = Firebug.getElementPanel(target); Firebug.Editor.startEditing(target, ""); } }), getEditor: function(target, value) { if (!this.editor) this.editor = new CSSSelectorsPanelEditor(this.document); return this.editor; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Extends Panel name: "selectors", parentPanel: "stylesheet", order: 0, initialize: function() { this.groups = [ { selector: "div", opened: true }, { selector: "p > span", opened: true } ]; Firebug.Panel.initialize.apply(this, arguments); }, destroy: function(state) { Firebug.Panel.destroyNode.apply(this, arguments); }, initializeNode: function(oldPanelNode) { Firebug.Panel.initializeNode.apply(this, arguments); }, destroyNode: function() { Firebug.Panel.destroyNode.apply(this, arguments); }, supportsObject: function(object) { return 0; }, show: function(state) { this.refresh(); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // Groups refresh: function() { var parentNode = this.template.selectorsTag.replace( {groups: this.groups, windows: this.context.windows}, this.panelNode); } }); function CSSSelectorsPanelEditor(doc) { this.box = this.tag.replace({}, doc, this); this.input = this.box; Firebug.InlineEditor.prototype.initialize.call(this); this.tabNavigation = false; this.fixedWidth = true; } CSSSelectorsPanelEditor.prototype = domplate(SelectorEditor.prototype, { tag: INPUT({"class": "fixedWidthEditor a11yFocusNoTab", type: "text", title: Locale.$STR("Selector"), oninput: "$onInput", onkeypress: "$onKeyPress"} ) }); //********************************************************************************************* // //Registration Firebug.registerPanel(CSSSelectorsPanel); return CSSSelectorsPanel; //********************************************************************************************* // }});
JavaScript
0
@@ -3614,206 +3614,11 @@ = %5B -%0A %7B%0A selector: %22div%22,%0A opened: true%0A %7D,%0A %7B%0A selector: %22p %3E span%22,%0A opened: true%0A %7D%0A %5D;%0A + %0A @@ -4246,16 +4246,462 @@ Groups%0A%0A + addGroup: function(selector)%0A %7B%0A var group = %7B%0A selector: selector,%0A opened: true%0A %7D%0A this.groups.push(group);%0A%0A // Append element group to display%0A var elementsGroups = this.panelNode.getElementsByClassName(%22elementsGroups%22)%5B0%5D;%0A var elementsGroup = this.template.elementsGroupTag.replace(%0A %7Bgroup: group, windows: this.context.windows%7D, elementsGroups);%0A %7D,%0A%0A refr @@ -5401,16 +5401,16 @@ Press%22%7D%0A - @@ -5410,16 +5410,434 @@ ) +,%0A%0A endEditing: function(target, value, cancel)%0A %7B%0A if (cancel %7C%7C value == %22%22)%0A return;%0A%0A if (this.isValidSelector(value))%0A this.panel.addGroup(value);%0A %7D,%0A%0A isValidSelector: function(value)%0A %7B%0A try %7B%0A this.panel.panelNode.querySelector(value);%0A return true;%0A %7D%0A catch (e)%0A %7B%0A return false;%0A %7D%0A %7D %0A%7D);%0A%0A//
7caf2b88c8244248127c9cdab71cf5bb7d522bb1
Add a “system” property
addon/models/spacedog-schemafield.js
addon/models/spacedog-schemafield.js
import Ember from 'ember'; import Model from 'ember-data/model'; import attr from 'ember-data/attr'; const { computed, observer } = Ember; import { belongsTo } from 'ember-data/relationships'; import Constants from 'tsygan/constants'; const { types } = Constants; // This defines what a schema field is, using solely tsygan transforms // Ideally, this could be exoressed as a schema itself export default Model.extend({ // Name of the field - should be any string name: attr('tsygan@string'), // Type of the field (see typeOptions below for choises) type: attr('tsygan@enum', {'enum-set': Object.keys(types)}), // Whether the field is an array of things array: attr('tsygan@boolean', {defaultValue: false}), // In case the field type is a string, what language is that (see transforms) language: attr('tsygan@spacedog-language', {defaultValue: 'English'}), // If type is an enum, determines the list of allowed values enumSet: attr('tsygan@string', {array: true}), // If type is hasMany or belongsTo, this link to the model name it relates to relatedTo: attr('tsygan@string'), // Any type may provide a list of examples to display to the user (up to the implementor to use them or not, // typically as placeholders in inputs). examples: attr('tsygan@string', {array: true}), // Whether the field should be required - if it is, a defaultValue can be specified // For array-ed, the require applies for the entire array, not individual elements required: attr('tsygan@boolean', {defaultValue: false}), // Default value, in case the field is required // For arrays, the default is for the entire array, not for individual elements - complex objects used as // defaultValues are shallow copied, so careful with modifying them // A default value would usually override the first "example" as a placeholder in inputs defaultValue: attr('tsygan@string'), // Numerical types may have restrictions (<, <=, >, >= and step) // Step is usable only with gte, and will coerce values to match `gte + n * step` // This apply to individual elements in an array step: attr('tsygan@number'), gte: attr('tsygan@number'), gt: attr('tsygan@number'), lte: attr('tsygan@number'), lt: attr('tsygan@number'), // Any type may have a regexp validation pattern (does NOT support modifiers) // This apply to individual elements in an array // XXX future: could be an array to allow more fine grain validation // XXX implement lengths checks (can be interpolated from / to pattern?) pattern: attr('tsygan@regexp'), // Links back to the parent model this field belongs to parentModel: belongsTo('tsygan@spacedog-schema'), // This returns the type choices that are available, depending on whether the object is sealed (field has already // been saved to SpaceDog, or not) // If the former, then only subtypes changes are allowed // If the latter, then all types are available typeOptions: computed('_spacetypehard', function(){ // If it sealed, restrict to that var sth = this.get('_spacetypehard'); // Either the object is un-sealed (all types), or it is (restricted to same spacedog type) return Object.keys(types).filter(function(key){ return !sth || types[key] === sth; }); }), // XXX all these are somewhat ugly hacks // This method MUST be called after a first save, and will mark the field as "locked" on SpaceDog seal: function(){ if (!this.get('_spacetypehard')) this.set('_spacetypehard', this.get('_spacetypesoft')); }, sealed: computed('_spacetypehard', function(){ return !!this.get('_spacetypehard'); }), // The hard type will be there if the object was saved on the service already, to keep track of the actual // SpaceDog type. // This is to accomodate for the types that we don't know how to preserve (long vs. int, float vs. double) _spacetypehard: attr('string'), // The soft type if the SpaceDog type we will infer if we are saving for the first time _spacetypesoft: attr('string'), // Observes the type to adjust what we will send to SpaceDog (on first save) typeObserver: observer('type', function(){ this.set('_spacetypesoft', types[this.get('type')]); }), init: function(){ /* eslint no-dangle-underscore:0 */ this._super(...arguments); this.set('_spacetypesoft', types[this.get('type')]); }, // Helpers for component template hasRelation: computed('type', function () { const currentType = this.get('type'); return currentType === 'hasMany' || currentType === 'belongsTo'; }), hasArray: computed('type', function(){ const currentType = this.get('type'); return ['json', 'belongsTo', 'hasMany'].indexOf(currentType) === -1; }), hasLanguage: computed('type', function(){ return this.get('type') === 'string'; }), hasPattern: computed('type', function(){ return ['string', 'identifier', 'password'].indexOf(this.get('type')) !== -1; }), hasBoundaries: computed('type', function(){ return ['integer', 'number'].indexOf(this.get('type')) !== -1; }), hasEnum: computed('type', function(){ const currentType = this.get('type'); return currentType === 'enum'; }), fieldEnumSet: computed('enumSet', { get(/*key*/) { return (this.get('enumSet') || []).join(','); }, set(key, value) { if (this.get('_oldEnumSetValue') && value === this.get('_oldEnumSetValue')) return value; this.set('enumSet', (value || '').split(',')); return this.set('_oldEnumSetValue', value); } }), fieldExamples: computed('examples', { get(/*key*/) { return (this.get('examples') || []).join(','); }, set(key, value) { if (this.get('_oldExamplesValue') && value === this.get('_oldExamplesValue')) return value; this.set('examples', (value || '').split(',')); return this.set('_oldExamplesValue', value); } }) });
JavaScript
0
@@ -1965,16 +1965,177 @@ tring'), +%0A // Denote that a property is a read-only, system property (eg: think %22reset code%22)%0A // XXX no UI for that right now%0A system: attr('tsygan@boolean'), %0A%0A // N @@ -5925,32 +5925,412 @@ );%0A %7D%0A %7D),%0A%0A + fieldPattern: computed('pattern', %7B%0A get(/*key*/) %7B%0A return this.get('pattern') ? this.get('pattern').source : '';%0A %7D,%0A set(key, value) %7B%0A if (this.get('_oldEnumSetValue') && value === this.get('_oldEnumSetValue'))%0A return value;%0A this.set('pattern', value ? new RegExp(value) : '');%0A return this.set('_oldEnumSetValue', value);%0A %7D%0A %7D),%0A%0A fieldExamples:
fb5e152013abd93c4605781b90fea85c7a4411e2
use options in ConfTemplate
app/js/views/conf.js
app/js/views/conf.js
define([ 'jquery', 'underscore', 'backbone', 'helpers/conf', 'text!templates/basic_nav.html', 'text!templates/conf.html' ], function($, _, Backbone, ConfHelper, BasicNavTemplate, ConfTemplate){ var ConfView = Backbone.View.extend ({ el: '#main', initialize: function () { // unbind previous events // FIXME: need better solution for this $(this.el).unbind ('scroll'); $(this.el).unbind ('click'); // clear page content $(this.el).html (''); }, render: function () { $('#right-navbar').html (_.template (BasicNavTemplate, { title: 'Ayarlar' })); $(this.el).append (_.template (ConfTemplate)); }, events: { 'click ul.theme a': 'changeTheme' }, changeTheme: function (ev) { var theme = $(ev.currentTarget).attr ('href').replace (/^#/, ''); ConfHelper.options.theme = theme; ConfHelper.switchTheme (); ConfHelper.saveConf (); return false; }, }); return ConfView; });
JavaScript
0
@@ -711,16 +711,86 @@ Template +,%0A %7B options: ConfHelper.options %7D ));%0A%0A
0581d9e3103ab4bbbfb7415e4e22d7d0f0adc8db
Simplify performance timer
src/util/performance.js
src/util/performance.js
import { is } from 'funkis' export async function timed(fn) { if (!is(Function, fn)) { fn = Promise.resolve.bind(Promise, fn) } const start = process.hrtime() const result = await(fn()) const duration = process.hrtime(start) const ms = (duration[0] * 1e9 + duration[1]) / 1e6 return { result, duration: { ms } } }
JavaScript
0.000034
@@ -2,18 +2,19 @@ mport %7B -is +val %7D from @@ -55,88 +55,15 @@ med( -fn) %7B%0A if (!is(Function, fn)) %7B%0A fn = Promise.resolve.bind(Promise, fn)%0A %7D%0A +proc) %7B %0A c @@ -118,12 +118,33 @@ wait -(fn( + Promise.resolve(val(proc ))%0A @@ -187,22 +187,25 @@ rt)%0A +%0A -const m +duration.n s = -( dura @@ -235,15 +235,76 @@ n%5B1%5D -) / 1e6 +%0A duration.ms = duration.ns / 1e6%0A duration.s = duration.ns / 1e9 %0A%0A @@ -332,22 +332,8 @@ tion -:%0A %7B ms %7D%0A %7D%0A%7D
6c36d0680fbaf3bc8ab98f3600286428ee610a7c
move calendar if selected a date in prev/next month
src/components/calendar.js
src/components/calendar.js
import React from 'react'; import CalendarTitle from './calendarTitle'; import CalendarBody from './calendarBody'; import CalendarMonthSelect from './calendarMonthSelect' export default class Calendar extends React.Component { static defaultProps = { selectRange: false, locale: 'en-US' }; static propTypes = { onDateSelected: React.PropTypes.func, selectRange: React.PropTypes.bool, locale: React.PropTypes.string }; constructor (props) { super(props); var today = new Date(); today.setHours(0, 0, 0, 0, 0, 0); this.state = { month: today.getMonth(), year: today.getFullYear(), currentDate: today, isShowingMonthSelector: false, needTransitionEffect: false }; } moveToNextMonth () { this.setState((previousState, currentProps) => { var month = previousState.month, year = previousState.year, nextMonth = month + 1; if(nextMonth > 11) { year = year + 1; nextMonth %= 12; } return { month: nextMonth, year: year, needTransitionEffect: true }; }); } moveToPrevMonth () { this.setState((previousState, currentProps) => { var month = previousState.month, year = previousState.year, prevMonth = month - 1; if(prevMonth < 0) { year = year - 1; prevMonth += 12; } return { month: prevMonth, year: year, needTransitionEffect: true }; }); } moveToNextYear() { this.setState({year: this.state.year + 1}); } moveToPrevYear () { this.setState({year: this.state.year - 1}); } selectDate (date) { return () => { this.setState({currentDate: date}); document.getElementsByClassName(this.props.inputbox)[0].value = date; }; } selectMonth (month) { return () => { this.setState({ month: month, isShowingMonthSelector: false, needTransitionEffect: true }); }; } toggleMonthSelector () { this.setState({isShowingMonthSelector: !this.state.isShowingMonthSelector}); } onNextButtonClick () { if (this.state.isShowingMonthSelector) { return this.moveToNextYear; } return this.moveToNextMonth; } onPrevButtonClick () { if (this.state.isShowingMonthSelector) { return this.moveToPrevYear; } return this.moveToPrevMonth; } /** Lifecycle Methods **/ componentWillUpdate (nextProps, nextState) { } render() { return ( <div className='fugui-calendar'> <CalendarTitle month={this.state.month} year={this.state.year} isShowingMonthSelector={this.state.isShowingMonthSelector} onNextButtonClick={this.onNextButtonClick().bind(this)} onPrevButtonClick={this.onPrevButtonClick().bind(this)} onTitleClick={this.toggleMonthSelector.bind(this)} /> <div className='calendar_wrapper'> <CalendarBody date={new Date(this.state.year, this.state.month)} currentDate={this.state.currentDate} selectDate={this.selectDate.bind(this)} locale={this.props.locale} className={() => { var className = ''; if (this.state.isShowingMonthSelector) { className += 'blur'; } } } isShowingMonthSelector={this.state.isShowingMonthSelector} /> <CalendarMonthSelect className={this.state.isShowingMonthSelector ? 'slide_open' : 'slide_close'} onMonthSelect={this.selectMonth.bind(this)} /> </div> </div> ); } }
JavaScript
0.000006
@@ -2134,16 +2134,140 @@ = date; +%0A%0A if (date.getMonth() !== this.state.month) %7B%0A this.selectMonth(date.getMonth())();%0A %7D %0A
0b21fd4e7fba446d6dc45912dca5def4f9f6ce81
Create a dataloader for every model
packages/strapi-plugin-graphql/services/Loaders.js
packages/strapi-plugin-graphql/services/Loaders.js
'use strict'; /** * Loaders.js service * * @description: A set of functions similar to controller's actions to avoid code duplication. */ const _ = require('lodash'); const DataLoader = require('dataloader'); module.exports = { loaders: {}, initializeLoader: function() { this.resetLoaders(); // Create loaders for each relational field (exclude core models). Object.keys(strapi.models) .filter(model => model !== 'core_store') .forEach(model => { (strapi.models[model].associations || []).forEach(association => this.createLoader( association.collection || association.model, association.plugin ) ); }); // Reproduce the same pattern for each plugin. Object.keys(strapi.plugins).forEach(plugin => { Object.keys(strapi.plugins[plugin].models).forEach(model => { (strapi.plugins[plugin].models[model].associations || []).forEach( association => this.createLoader( association.collection || association.model, association.plugin ) ); }); }); }, resetLoaders: function() { this.loaders = {}; }, createLoader: function(model, plugin) { const name = plugin ? `${plugin}__${model}` : model; // Exclude polymorphic from loaders. if (name === undefined) { return; } if (this.loaders[name]) { return this.loaders[name]; } this.loaders[name] = new DataLoader( keys => { // Extract queries from keys and merge similar queries. const { queries, map } = this.extractQueries(model, _.cloneDeep(keys)); // Run queries in parallel. return Promise.all( queries.map(query => this.makeQuery(model, query)) ).then(results => { // Use to match initial queries order. return this.mapData(model, keys, map, results); }); }, { cacheKeyFn: key => { return _.isObjectLike(key) ? JSON.stringify(_.cloneDeep(key)) : key; }, } ); }, mapData: function(model, originalMap, map, results) { // Use map to re-dispatch data correctly based on initial keys. return originalMap.map((query, index) => { // Find the index of where we should extract the results. const indexResults = map.findIndex( queryMap => queryMap.indexOf(index) !== -1 ); const data = results[indexResults]; // Retrieving referring model. const ref = this.retrieveModel(model, query.options.source); if (query.single) { // Return object instead of array for one-to-many relationship. return data.find( entry => entry[ref.primaryKey].toString() === (query.params[ref.primaryKey] || '').toString() ); } // Generate constant for skip parameters. // Note: we shouldn't support both way of doing this kind of things in the future. const skip = query.options._start || 0; const limit = _.get(query, 'options._limit', 100); // Take into account the limit if its equal 0 // Extracting ids from original request to map with query results. const ids = this.extractIds(query, ref); const ast = ref.associations.find(ast => ast.alias === ids.alias); const astModel = ast ? this.retrieveModel(ast.model || ast.collection, ast.plugin) : this.retrieveModel(model); if (!_.isArray(ids)) { return data .filter(entry => entry !== undefined) .filter(entry => { const aliasEntry = entry[ids.alias]; if (_.isArray(aliasEntry)) { return _.find( aliasEntry, value => value[astModel.primaryKey].toString() === ids.value ); } const entryValue = aliasEntry[astModel.primaryKey].toString(); return entryValue === ids.value; }) .slice(skip, skip + limit); } return data .filter(entry => entry !== undefined) .filter(entry => ids .map(id => id.toString()) .includes(entry[ref.primaryKey].toString()) ) .slice(skip, skip + limit); }); }, extractIds: (query, ref) => { if (_.get(query.options, `query.${ref.primaryKey}`)) { return _.get(query.options, `query.${ref.primaryKey}`); } const alias = _.first(Object.keys(query.options.query)); const value = query.options.query[alias].toString(); return { alias, value, }; }, makeQuery: async function(model, query = {}) { if (_.isEmpty(query.ids)) { return []; } const ref = this.retrieveModel(model, query.options.source); const ast = ref.associations.find(ast => ast.alias === query.alias); const params = { ...query.options, populate: ast ? [query.alias] : [], query: {}, _start: 0, // Don't apply start or skip _limit: -1, // Don't apply a limit }; params.query[`${query.alias}_in`] = _.chain(query.ids) .filter(id => !_.isEmpty(id) || _.isInteger(id)) // Only keep valid ids .map(id => id.toString()) // convert ids to string .uniq() // Remove redundant ids .value(); // Run query and remove duplicated ID. return strapi.plugins['content-manager'].services[ 'contentmanager' ].fetchAll({ model }, params); }, retrieveModel: function(model, source) { // Retrieve refering model. return source ? strapi.plugins[source].models[model] : strapi.models[model]; }, extractQueries: function(model, keys) { const queries = []; const map = []; keys.forEach((current, index) => { // Extract query options. // Note: the `single` means that we've only one entry to fetch. const { single = false, params = {}, association } = current; const { query = {}, ...options } = current.options; // Retrieving referring model. const ref = this.retrieveModel(model, options.source); // Generate array of IDs to fetch. const ids = []; // Only one entry to fetch. if (single) { ids.push(params[ref.primaryKey]); } else if (_.isArray(query[ref.primaryKey])) { ids.push(...query[ref.primaryKey]); } else { ids.push(query[association.via]); } queries.push({ ids, options, alias: _.first(Object.keys(query)) || ref.primaryKey, }); map[queries.length - 1 > 0 ? queries.length - 1 : 0] = []; map[queries.length - 1].push(index); }); return { queries, map, }; }, };
JavaScript
0.000001
@@ -490,640 +490,255 @@ -(strapi.models%5Bmodel%5D.associations %7C%7C %5B%5D).forEach(association =%3E%0A this.createLoader(%0A association.collection %7C%7C association.model,%0A association.plugin%0A )%0A );%0A %7D);%0A%0A // Reproduce the same pattern for each plugin.%0A Object.keys(strapi.plugins).forEach(plugin =%3E %7B%0A Object.keys(strapi.plugins%5Bplugin%5D.models).forEach(model =%3E %7B%0A (strapi.plugins%5Bplugin%5D.models%5Bmodel%5D.associations %7C%7C %5B%5D).forEach(%0A association =%3E%0A this.createLoader(%0A association.collection %7C%7C association.model,%0A association.plugin%0A )%0A +this.createLoader(model);%0A %7D);%0A%0A // Reproduce the same pattern for each plugin.%0A Object.keys(strapi.plugins).forEach(plugin =%3E %7B%0A Object.keys(strapi.plugins%5Bplugin%5D.models).forEach(model =%3E %7B%0A this.createLoader(model, plugin );%0A
52f04b4f2db20252a285a6dfc590c0a8fe3f9c85
Clarify names and fix a recursive bug
src/utils/deep-clone.js
src/utils/deep-clone.js
function extend (target, source) { if (source === null || typeof source !== 'object') { return source; } if (source.constructor !== Object && source.constructor !== Array) { return source; } if ( source.constructor === Date || source.constructor === RegExp || source.constructor === Function || source.constructor === String || source.constructor === Number || source.constructor === Boolean ) { return new source.constructor(source); } target = target || new source.constructor(); for (let name in source) { target[name] = typeof target[name] === 'undefined' ? extend(source[name], null) : target[name]; } return target; } export default function (obj) { let copy; return extend(copy, obj); }
JavaScript
0.000001
@@ -630,16 +630,27 @@ extend( +undefined, source%5Bn @@ -657,14 +657,8 @@ ame%5D -, null ) : @@ -721,19 +721,22 @@ nction ( -obj +source ) %7B%0A le @@ -737,20 +737,22 @@ %7B%0A let -copy +target ;%0A retu @@ -765,17 +765,22 @@ end( -copy, obj +target, source );%0A%7D
aa0b85ae021c614a3cfaf5ec69e63215fb46c0a3
Fix setLineDash reset.
packages/vega-scenegraph/src/util/canvas/stroke.js
packages/vega-scenegraph/src/util/canvas/stroke.js
import color from './color'; export default function(context, item, opacity) { var lw = (lw = item.strokeWidth) != null ? lw : 1, lc; if (lw <= 0) return false; opacity *= (item.strokeOpacity==null ? 1 : item.strokeOpacity); if (opacity > 0) { context.globalAlpha = opacity; context.strokeStyle = color(context, item, item.stroke); context.lineWidth = lw; context.lineCap = (lc = item.strokeCap) != null ? lc : 'butt'; if (context.setLineDash) { context.setLineDash(item.strokeDash || null); context.lineDashOffset = item.strokeDashOffset || 0; } return true; } else { return false; } }
JavaScript
0
@@ -23,16 +23,33 @@ olor';%0A%0A +var Empty = %5B%5D;%0A%0A export d @@ -531,20 +531,21 @@ Dash %7C%7C -null +Empty );%0A
b1563a2a392b34cf36d2e8cd60a3ec27ecae79b3
improve iterator docs
src/core/util/iterator.js
src/core/util/iterator.js
(function(){ angular .module('material.core') .config( function($provide){ $provide.decorator('$mdUtil', ['$delegate', function ($delegate){ /** * Inject the iterator facade to easily support iteration and accessors * @see iterator below */ $delegate.iterator = Iterator; return $delegate; } ]); }); /** * iterator is a list facade to easily support iteration and accessors * * @param items Array list which this iterator will enumerate * @param reloop Boolean enables iterator to consider the list as an endless reloop */ function Iterator(items, reloop) { var trueFn = function() { return true; }; reloop = !!reloop; var _items = items || [ ]; // Published API return { items: getItems, count: count, inRange: inRange, contains: contains, indexOf: indexOf, itemAt: itemAt, findBy: findBy, add: add, remove: remove, first: first, last: last, next: angular.bind(null, findSubsequentItem, false), previous: angular.bind(null, findSubsequentItem, true), hasPrevious: hasPrevious, hasNext: hasNext }; /** * Publish copy of the enumerable set * @returns {Array|*} */ function getItems() { return [].concat(_items); } /** * Determine length of the list * @returns {Array.length|*|number} */ function count() { return _items.length; } /** * Is the index specified valid * @param index * @returns {Array.length|*|number|boolean} */ function inRange(index) { return _items.length && ( index > -1 ) && (index < _items.length ); } /** * Can the iterator proceed to the next item in the list; relative to * the specified item. * * @param item * @returns {Array.length|*|number|boolean} */ function hasNext(item) { return item ? inRange(indexOf(item) + 1) : false; } /** * Can the iterator proceed to the previous item in the list; relative to * the specified item. * * @param item * @returns {Array.length|*|number|boolean} */ function hasPrevious(item) { return item ? inRange(indexOf(item) - 1) : false; } /** * Get item at specified index/position * @param index * @returns {*} */ function itemAt(index) { return inRange(index) ? _items[index] : null; } /** * Find all elements matching the key/value pair * otherwise return null * * @param val * @param key * * @return array */ function findBy(key, val) { return _items.filter(function(item) { return item[key] === val; }); } /** * Add item to list * @param item * @param index * @returns {*} */ function add(item, index) { if ( !item ) return -1; if (!angular.isNumber(index)) { index = _items.length; } _items.splice(index, 0, item); return indexOf(item); } /** * Remove item from list... * @param item */ function remove(item) { if ( contains(item) ){ _items.splice(indexOf(item), 1); } } /** * Get the zero-based index of the target item * @param item * @returns {*} */ function indexOf(item) { return _items.indexOf(item); } /** * Boolean existence check * @param item * @returns {boolean} */ function contains(item) { return item && (indexOf(item) > -1); } /** * Return first item in the list * @returns {*} */ function first() { return _items.length ? _items[0] : null; } /** * Return last item in the list... * @returns {*} */ function last() { return _items.length ? _items[_items.length - 1] : null; } /** * Find the next item. If reloop is true and at the end of the list, it will * go back to the first item. If given ,the `validate` callback will be used * determine whether the next item is valid. If not valid, it will try to find the * next item again. * @param item * @param {optional} validate function * @param {optional} recursion limit * @returns {*} */ function findSubsequentItem(backwards, item, validate, limit) { validate = validate || trueFn; var curIndex = indexOf(item); if (!inRange(curIndex)) { return null; } var nextIndex = curIndex + (backwards ? -1 : 1); var foundItem = null; if (inRange(nextIndex)) { foundItem = _items[nextIndex]; } else if (reloop) { foundItem = backwards ? last() : first(); nextIndex = indexOf(foundItem); } if ((foundItem === null) || (nextIndex === limit)) { return null; } if (angular.isUndefined(limit)) { limit = nextIndex; } return validate(foundItem) ? foundItem : findSubsequentItem(backwards, foundItem, validate, limit); } } })();
JavaScript
0
@@ -4324,16 +4324,25 @@ alidate +Validate function @@ -4367,17 +4367,23 @@ tional%7D -r +limit R ecursion
27f6a7de35b7f222be1052efdfa44e41e7bad7d4
fix vtx normal calculation
browser/scripts/abstractThreeLoaderObjPlugin.js
browser/scripts/abstractThreeLoaderObjPlugin.js
function AbstractThreeLoaderObjPlugin(core) { Plugin.apply(this, arguments) this.desc = 'THREE.js OBJ loader' this.dirty = true this.state = { url: '' } this.input_slots = [] this.output_slots = [{ name: 'geometry', dt: core.datatypes.GEOMETRY, array: true }, { name: 'materials', dt: core.datatypes.MATERIAL, array: true }] this.geometries = [new THREE.Geometry()] this.materials = [new THREE.MeshBasicMaterial(0xff0000)] } AbstractThreeLoaderObjPlugin.prototype = Object.create(Plugin.prototype) AbstractThreeLoaderObjPlugin.prototype.update_input = function(slot, data) { return Plugin.prototype.update_input.apply(this, arguments) } AbstractThreeLoaderObjPlugin.prototype.onObjLoaded = function(geoms, mats) { this.geometries = geoms this.materials = mats for (var i = 0; i < this.geometries.length; ++i) { if (this.geometries[i].getAttribute('normal') === undefined) { this.geometries[i].computeVertexNormals(true) } } msg('Finished loading '+ this.state.url) this.updated = true } AbstractThreeLoaderObjPlugin.prototype.state_changed = function(ui) { console.log('state_changed', this.state) if (!this.state.url) return if (ui) ui.attr('title', this.state.url) else this.dirty = true }
JavaScript
0.000004
@@ -843,20 +843,112 @@ +i) %7B%0A%09%09 -if ( +var bufferGeometryHasVtxNormals =%0A%09%09%09%09this.geometries%5Bi%5D instanceof THREE.BufferGeometry &&%0A%09%09%09%09 this.geo @@ -981,17 +981,17 @@ ormal') -= +! == undef @@ -994,16 +994,453 @@ ndefined +%0A%0A%09%09var normalGeometryHasFaceNormals =%0A%09%09%09%09(this.geometries%5Bi%5D.faces && this.geometries%5Bi%5D.faces.length %3E 0 &&%0A%09%09%09%09this.geometries%5Bi%5D.faces%5B0%5D.normal.lengthSq() !== 0)%0A%0A%09%09var normalGeometryHasVtxNormals =%0A%09%09%09%09(this.geometries%5Bi%5D.faces && this.geometries%5Bi%5D.faces.length %3E 0 &&%0A%09%09%09%09this.geometries%5Bi%5D.faces%5B0%5D.vertexNormals.length %3E 0)%0A%09%09%0A%09%09if (!bufferGeometryHasVtxNormals && !normalGeometryHasFaceNormals && !normalGeometryHasVtxNormals ) %7B%0A%09%09%09t
245ff02ca3d4199d78fbc6ce0be2964dbb0c8167
Make it named
src/utils/has-parent.js
src/utils/has-parent.js
export default function (el, target) { let _el = el; while (_el !== target && _el.tagName !== 'HTML') { _el = _el.parentNode; } if (_el === target) { return true; } return false; }
JavaScript
0.999999
@@ -17,16 +17,26 @@ unction +hasParent (el, tar
4c83880d8d1e30f1e9f20a37e9337ea2be60819e
Update help link selectors, Help link URLs
github-on.js
github-on.js
///////////////////////////////////////////// // Operational variables and container setup ///////////////////////////////////////////// var page = $(".site"); container = $('<div id="howto-container"></div>'), highlight = $('<div class="gh-highlight"></div>'); answer = $('<div class="answer"></div>'); $("body").append(container); container.append(answer); container.append(highlight); ///////////////////////////////////////////// // Mapping to page content and Help links ///////////////////////////////////////////// var helpMap = [ { description: "Creating a pull request", selector: ".button", helpLink: "https://help.github.com/articles/creating-a-pull-request/" }, { description: "Permissions and repo owner", selector: ".entry-title", helpLink: "https://help.github.com/articles/permission-levels-for-a-user-account-repository/" }, { description: "Commit history page", selector: ".js-social-container", helpLink: "https://help.github.com/articles/watching-repositories/" }, { description: "Commit tease", selector: ".commit-tease", helpLink: "https://help.github.com/articles/differences-between-commit-views/" }, { description: "Clone URL box", selector: ".repository-sidebar", helpLink: "https://help.github.com/articles/differences-between-commit-views/" } ]; function github(){ var i; for(i=0;i < helpMap.length; i++){ var helpIcon = $('<a class="question" data-selector="helpMap[i].selector" href="' + helpMap[i].helpLink + '"></a>"'); container.append(helpIcon); var target = $(helpMap[i].selector), offset = target.offset(), helpLink = helpMap[i].helpLink + " .article-body p:first-child"; console.log(offset); if (offset.top > 0 && offset.left > 0){ helpIcon.css("top", offset.top + "px"); helpIcon.css("left", offset.left + "px"); } helpIcon.mouseover({selector: helpMap[i].selector, link: helpLink, offsetLeft: offset.left, offsetTop: offset.top}, function(event){ highlight.width($(event.data.selector).width()); highlight.height($(event.data.selector).height()); highlight.css("top", event.data.offsetTop + "px"); highlight.css("left", event.data.offsetLeft + "px"); highlight.toggle(); answer.css("top", event.data.offsetTop+$(event.data.selector).height() + "px"); answer.css("left", event.data.offsetLeft + "px"); answer.show(); answer.load(event.data.link); } ); helpIcon.mouseout({selector: helpMap[i].selector}, function(event){ // $(event.data.selector).css("box-shadow", "none"); highlight.toggle(); // $(event.data.selector).toggleClass("highlight"); // page.css("-webkit-filter", ""); answer.hide(); answer.html(""); } ); } } github();
JavaScript
0
@@ -573,56 +573,60 @@ n: %22 -Creating a pull request%22,%0A selector: %22.button +GitHub Logo%22,%0A selector: %22.header-logo-invertocat %22,%0A @@ -676,31 +676,24 @@ les/ -creating-a-pull-request +searching-github /%22%0A @@ -722,33 +722,18 @@ n: %22 -Permissions and repo owne +User avata r%22,%0A @@ -752,19 +752,14 @@ : %22. -entry-title +avatar %22,%0A @@ -809,44 +809,180 @@ les/ -permission-levels-for-a-user-account +how-do-i-set-up-my-profile-picture/%22%0A %7D,%0A %7B%0A description: %22Repo name & path%22,%0A selector: %22.breadcrumb%22,%0A helpLink: %22https://help.github.com/articles/working-with -rep @@ -987,17 +987,19 @@ epositor -y +ies /%22%0A %7D,%0A @@ -1024,65 +1024,61 @@ n: %22 -Commit history page%22,%0A selector: %22.js-social-container +PR, branch selector%22,%0A selector: %22.file-navigation %22,%0A @@ -1128,28 +1128,26 @@ les/ -watching-repositorie +using-pull-request s/%22%0A @@ -1183,14 +1183,24 @@ mmit - tease +s page menu link %22,%0A @@ -1224,14 +1224,9 @@ mmit --tease +s %22,%0A @@ -1276,40 +1276,40 @@ les/ +e di -fferences-between-commit-views +ting-files-in-your-repository /%22%0A @@ -1338,21 +1338,28 @@ n: %22 -Clone URL box +Unwatch/watch button %22,%0A @@ -1377,26 +1377,20 @@ : %22. -repository-sidebar +subscription %22,%0A @@ -1440,39 +1440,28 @@ les/ -differences-between-commit-v +watching-repositor ie -w s/%22%0A
a62dc02174666017a1730fe027529b6c134db2a1
Update Pointwise.js
CNN/Conv/Pointwise.js
CNN/Conv/Pointwise.js
export { ChannelPartInfo, FiltersBiasesPartInfo } from "./Pointwise/Pointwise_ChannelPartInfo.js"; export { FiltersArray_BiasesArray } from "./Pointwise/Pointwise_FiltersArray_BiasesArray.js"; export { PassThrough_FiltersArray_BiasesArray, PassThrough, AllZeros } from "./Pointwise/Pointwise_PassThrough.js"; export { Base } from "./Pointwise/Pointwise_Base.js"; export { SameWhenPassThrough } from "./Pointwise/Pointwise_SameWhenPassThrough.js"; export { SameWhenPassThrough_PrefixSqueezeExcitation } from "./Pointwise/Pointwise_SameWhenPassThrough_PrefixSqueezeExcitation.js"; export { ConstantWhenPassThrough } from "./Pointwise/Pointwise_ConstantWhenPassThrough.js";
JavaScript
0
@@ -235,22 +235,229 @@ rray -, PassThrough, + %7D from %22./Pointwise/Pointwise_PassThrough.js%22;%0Aexport %7B PassThrough_FiltersArray_BiasesArray_Bag %7D from %22./Pointwise/Pointwise_PassThrough.js%22;%0Aexport %7B PassThrough %7D from %22./Pointwise/Pointwise_PassThrough.js%22;%0Aexport %7B All
7da9e11effbdd7ce1839ab07e3f4896f3901c3fe
Reduce number of calls to database
Client/app.service.js
Client/app.service.js
/* This file is part of Rogue Vision. Copyright (C) 2016 Daniel Reischl, Rene Rathmann, Peter Tan, Tobias Dorsch, Shefali Shukla, Vignesh Govindarajulu, Aleksander Penew, Abinav Puri Rogue Vision is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Rogue Vision is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Rogue Vision. If not, see <http://www.gnu.org/licenses/>. */ /* This file contains all Angualr JS Services*/ angular.module('app') .service('percentageService', function(sessionService) { /* Provides percantage data of carriers */ var percentageData = []; function getFromDB() { /* Fetches data from backend So far this is called each time when getAll is called, but this is probably not necessary */ Papa.parse('django/dataInterface/percentages_creeping.csv?session=' +sessionService.getCurrentSession(), { download: true, dynamicTyping: true, complete: function(results) { percentageData = results.data[1]; } } ); } this.getAll = function() { getFromDB(); return percentageData; } this.getColorOfCarrier = function(carrier) { getFromDB(); var percentageOfEnergy = percentageData[carrier - 1]; var color = {'background-color': 'rgb(255,255,0)'}; if(percentageOfEnergy > 1.05) { color = {'background-color' : 'rgb(229, 28, 52)'}; } if(percentageOfEnergy <= 1.025 ) { color = {'background-color' : 'rgb(178,255,89)'}; } return color; } return { getAll: this.getAll, getColorOfCarrier: this.getColorOfCarrier }; }); /* The carrierService, proved carrier data to all controllers For now it is used to saves the carriers for comparison, chosen by the user and proved them to all controller who need the data. */ angular.module('app') .service('carrierService', function(sessionService) { var carriersForComparison = []; this.hasCarrier = function(carrierId) { return carriersForComparison.some(function(carrier){return carrier.carrierNumber == carrierId;}); } // function adds a carrier with a given ID this.addCarrier = function(newCarrier) { for(var i = 0; i < carriersForComparison.length; i++) { if (carriersForComparison[i].carrierNumber == newCarrier) { return false; } } carriersForComparison.push({carrierNumber: newCarrier}); return true; }; // returns the array with CarrierIDs to be compared this.getCarrier = function(){ return carriersForComparison; } // deletes a carrier with a given ID this.deleteCarrier = function(removeCarrier) { for(var i = 0; i < carriersForComparison.length; i++) { if (carriersForComparison[i].carrierNumber == removeCarrier) { carriersForComparison.splice(i,1); return true; } } return false; } // this function empties the array, so that no carrier item is left inside anymore. this.emptyCarrierArray = function() { carriersForComparison.splice(0,carriersForComparison.length); } // this service returns 5 functions to the caller, which he can use. return { hasCarrier: this.hasCarrier, addCarrier: this.addCarrier, getCarrier: this.getCarrier, deleteCarrier: this.deleteCarrier, emptyCarrierArray: this.emptyCarrierArray, }; }); angular.module('app') .service('sessionService', function() { var numberOfSessions = 0; var currentSession = 1; function update () { var xmlHttp = new XMLHttpRequest(); // so far session, carrier and iteration have to be set - they are disregarded however xmlHttp.open( "GET", 'django/dataInterface/values.request?session=1&carrier=1&iteration=1&value=currentSession', false ); xmlHttp.send(null); numberOfSessions = xmlHttp.responseText; // reset session number, if necessary if (currentSession < numberOfSessions) { currentSession = 1; } } this.getNumberOfSessions = function() { update(); return numberOfSessions; } this.getCurrentSession = function() { update(); return currentSession; } this.setCurrentSession = function(newSession) { if (newSession <= numberOfSessions) { currentSession = newSession; } } return { getNumberOfSessions: this.getNumberOfSessions, getCurrentSession: this.getCurrentSession, setCurrentSession: this.setCurrentSession, }; });
JavaScript
0.999577
@@ -1699,32 +1699,34 @@ carrier) %7B%0A%09 +// getFromDB();%0A%09
3f4b1ab678002fe620507393718ef114cfb0a280
Make an alias (in Course) for this.props.info
app/models/course.js
app/models/course.js
'use strict'; import * as _ from 'lodash' import * as React from 'react' import * as humanize from 'humanize-plus' import {DragDropMixin} from '../../node_modules/react-dnd/dist/ReactDND.min' import itemTypes from '../objects/itemTypes' var Course = React.createClass({ mixins: [DragDropMixin], configureDragDrop(registerType) { registerType(itemTypes.COURSE, { dragSource: { beginDrag() { return { item: {clbid: this.props.info.clbid} } }, endDrag(didDrop) { if (didDrop) { if (this.props.schedule) { console.log( 'removing course', this.props.info.clbid, 'from', this.props.schedule.id) this.props.schedule.removeCourse(this.props.info.clbid) } } } } }) }, getInitialState() { return { showTools: false } }, showTools() { console.log('show tools') this.setState({ showTools: true }) }, removeFromSemester() { this.props.schedule.removeCourse(this.props.info.clbid) }, render() { let title = this.props.info.type === 'Topic' ? this.props.info.name : this.props.info.title; let titleEl = React.DOM.h1({className: 'title'}, title) let department = React.DOM.span({className: 'department'}, this.props.info.dept) let number = React.DOM.span({className: 'number'}, this.props.info.num) let section = React.DOM.span({className: 'section'}, this.props.info.sect) let identifier = React.DOM.span({className: 'identifier'}, department, ' ', number, section) let professors = React.DOM.span({className: 'professors'}, humanize.oxford(this.props.info.profs)) let details; if (this.state.showTools) { let semesterList = React.DOM.select({className: 'semester-select'}, _.map(this.props.semesters, s => { return React.DOM.option({value: s.id, key: s.id}, s.year + '-' + s.semester) })) let deleteButton = React.DOM.button({className: 'remove-course', onClick: this.removeFromSemester}, 'Remove Course') let tools = React.DOM.span(null, semesterList, deleteButton) details = React.DOM.span({className: 'details'}, tools) } else { details = React.DOM.span({className: 'details'}, identifier, professors) } return React.DOM.article( Object.assign({ className: 'course', onClick: this.showTools, }, this.dragSourceFor(itemTypes.COURSE)), React.DOM.div({className: 'info-rows'}, titleEl, details)); } }) export default Course
JavaScript
0.000005
@@ -1010,20 +1010,21 @@ %7B%0A%09%09let -titl +cours e = this @@ -1038,66 +1038,70 @@ info -.type === 'Topic' ? this.props.info.name : this.props.info +;%0A%09%09let title = course.type === 'Topic' ? course.name : course .tit @@ -1225,31 +1225,22 @@ ment'%7D, -this.props.info +course .dept)%0A%09 @@ -1291,31 +1291,22 @@ mber'%7D, -this.props.info +course .num)%0A%09%09 @@ -1358,31 +1358,22 @@ tion'%7D, -this.props.info +course .sect)%0A%09 @@ -1543,31 +1543,22 @@ .oxford( -this.props.info +course .profs))
7cd30e77785d0e3ff5af660968d58b2926005634
update notice model
app/models/course.js
app/models/course.js
/** * Created by Songzhou Yang on 12/1/2016. */ const mongoose = require('mongoose') const NoticeSchema = new mongoose.Schema({ sequenceNum: { type: Number, index: true }, title: String, publishTime: String, state: String, content: String }) const DocumentSchema = new mongoose.Schema({ sequenceNum: { type: Number, index: true }, title: { type: String, index: true }, explanation: String, updatingTime: String, state: String, size: String, url: String }) const AssignmentSchema = new mongoose.Schema({ sequenceNum: { type: Number, index: true }, title: { type: String, index: true }, detail: String, startDate: String, dueDate: String, state: String, size: String, evaluatingTeacher: String, evaluatingDate: String, comment: String, grade: Number }) const CourseSchema = new mongoose.Schema({ courseName: { type: String, index: true }, courseID: { type: String, index: true }, unsubmittedOperations: Number, unreadNotice: Number, newFile: Number, notices: [NoticeSchema], documents: [DocumentSchema], assignments: [AssignmentSchema] }, { toObject: { transform: (doc, ret) => { delete ret._id } } }) const Course = mongoose.model('Course', CourseSchema) module.exports.Course = Course module.exports.CourseSchema = CourseSchema
JavaScript
0
@@ -198,16 +198,37 @@ String,%0A + publisher: String,%0A publis @@ -269,32 +269,113 @@ content: String%0A +%7D, %7B%0A toObject: %7B%0A transform: (doc, ret) =%3E %7B%0A delete ret._id%0A %7D%0A %7D%0A %7D)%0A%0Aconst Docume @@ -1349,24 +1349,78 @@ %7D%0A %7D%0A%7D)%0A%0A +const Notice = mongoose.model('Notice', NoticeSchema)%0A const Course @@ -1462,16 +1462,47 @@ chema)%0A%0A +module.exports.Notice = Notice%0A module.e
a8e97bbc8c46561a09dfe486fb04acdb98720421
Add 'grunt debug' task
gruntfile.js
gruntfile.js
'use strict'; module.exports = function(grunt) { // Project Configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { serverViews: { files: ['app/views/**'], options: { livereload: true, } }, serverJS: { files: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'], tasks: ['jshint'], options: { livereload: true, } }, clientViews: { files: ['public/modules/**/views/*.html'], options: { livereload: true, } }, clientJS: { files: ['public/js/**/*.js', 'public/modules/**/*.js'], tasks: ['jshint'], options: { livereload: true, } }, clientCSS: { files: ['public/**/css/*.css'], tasks: ['csslint'], options: { livereload: true, } } }, jshint: { all: { src: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js', 'public/js/**/*.js', 'public/modules/**/*.js'], options: { jshintrc: true } } }, csslint: { options: { csslintrc: '.csslintrc', }, all: { src: ['public/modules/**/css/*.css'] } }, uglify: { production: { options: { mangle: false }, files: { 'public/dist/application.min.js': '<%= applicationJavaScriptFiles %>' } } }, cssmin: { combine: { files: { 'public/dist/application.min.css': '<%= applicationCSSFiles %>' } } }, nodemon: { dev: { script: 'server.js', options: { nodeArgs: ['--debug'] } } }, concurrent: { tasks: ['nodemon', 'watch'], options: { logConcurrentOutput: true } }, env: { test: { NODE_ENV: 'test' } }, mochaTest: { src: ['app/tests/**/*.js'], options: { reporter: 'spec', require: 'server.js' } }, karma: { unit: { configFile: 'karma.conf.js' } } }); // Load NPM tasks require('load-grunt-tasks')(grunt); // Making grunt default to force in order not to break the project. grunt.option('force', true); // A Task for loading the configuration object grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() { var init = require('./config/init')(); var config = require('./config/config'); grunt.config.set('applicationJavaScriptFiles', config.assets.js); grunt.config.set('applicationCSSFiles', config.assets.css); }); // Default task(s). grunt.registerTask('default', ['jshint', 'csslint', 'concurrent']); // Lint task(s). grunt.registerTask('lint', ['jshint', 'csslint']); // Build task(s). grunt.registerTask('build', ['jshint', 'csslint', 'loadConfig' ,'uglify', 'cssmin']); // Test task. grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']); };
JavaScript
0.999998
@@ -2345,39 +2345,487 @@ -concurrent: %7B%0A tasks +'node-inspector': %7B%0A custom: %7B%0A options: %7B%0A 'web-port': 1337,%0A 'web-host': 'localhost',%0A 'debug-port': 5858,%0A 'save-live-edit': true,%0A 'no-preload': true,%0A 'stack-trace-limit': 50,%0A 'hidden': %5B%5D%0A %7D%0A %7D%0A %7D,%0A concurrent: %7B%0A default: %5B'nodemon', 'watch'%5D,%0A debug : %5B' @@ -2833,35 +2833,54 @@ odemon', 'watch' +, 'node-inspector' %5D,%0A + opti @@ -3994,16 +3994,120 @@ ncurrent +:default'%5D);%0A%0A // Debug task.%0A grunt.registerTask('debug', %5B'jshint', 'csslint', 'concurrent:debug '%5D);%0A%0A
6f3407beb609a6a876668b5ba71b4a3d0b8bfed1
Initialize buttons correctly
content/composeOverlay.js
content/composeOverlay.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/. */ (function() { var Cc = Components.classes; var Ci = Components.interfaces; var Cu = Components.utils; var MimeHeaderParser = Cc['@mozilla.org/messenger/headerparser;1'] .getService(Ci.nsIMsgHeaderParser); var { Services } = Cu.import('resource://gre/modules/Services.jsm'); var BASE = 'extensions.send-to-internals@clear-code.com.'; var SendToInternalsHelper = { checkInternals : function() { var internalDomains = Services.prefs.getComplexValue(BASE + 'domains', Ci.nsISupportsString).value; internalDomains = internalDomains.split(/[,\|\s]+/) .map(function(aDomain) { return aDomain.trim(); }) .filter(function(aDomain) { return aDomain; }); if (internalDomains.length === 0) { // alert here! return false; } var externals = this.getAllRecipients().filter(function(aAddress) { var domain = aAddress.address.split('@')[1]; return internalDomains.indexOf(domain) < 0; }, this); if (externals.length !== 0) { this.highlightExternals(externals); // alert here! return false; } return true; }, getAllRecipients: function() { var msgCompFields = gMsgCompose.compFields; Recipients2CompFields(msgCompFields); gMsgCompose.expandMailingLists(); return this.splitRecipients(msgCompFields.to, 'To') .concat(this.splitRecipients(msgCompFields.cc, 'Cc')) .concat(this.splitRecipients(msgCompFields.bcc, 'Bcc')); }, splitRecipients: function(aAddressesSource, aType){ var addresses = {}; var names = {}; var fullNames = {}; var numAddresses = MimeHeaderParser.parseHeadersWithArray( aAddressesSource, addresses, names, fullNames); var recipients = []; for (let i = 0; i < numAddresses; i++) { let address = addresses.value[i]; let domain = address.split('@')[1]; if (this.ignoredDomains.indexOf(domain) > -1) continue; recipients.push({ address: address, name: names.value[i], fullName: fullNames.value[i], type: aType }); } return recipients; } }; window.SendToInternalsHelper = SendToInternalsHelper; window.addEventListener('DOMContentLoaded', function SendToInternalsOnLoad(aEvent) { window.removeEventListener(aEvent.type, SendToInternalsOnLoad, false); var toolbar = document.getElementById('composeToolbar2'); var defaultSet = toolbar.getAttribute('defaultset'); var currentSet = toolbar.getAttribute('currentset'); if (!Services.prefs.getBoolPref(BASE + 'initialized')) { Services.prefs.setBoolPref(BASE + 'initialized', true); defaultSet = (defaultSet ? defaultSet + ',' : '' ) + 'sprint,button-sendToInternals'; toolbar.setAttribute('defaultset', defaultSet); currentSet = (currentSet ? currentSet + ',' : '' ) + 'sprint,button-sendToInternals'; toolbar.setAttribute('currentset', currentSet); } }, false); })();
JavaScript
0.000002
@@ -2950,129 +2950,8 @@ );%0A%0A - if (!Services.prefs.getBoolPref(BASE + 'initialized')) %7B%0A Services.prefs.setBoolPref(BASE + 'initialized', true);%0A de @@ -2975,16 +2975,17 @@ ltSet ? +( defaultS @@ -2984,32 +2984,33 @@ defaultSet + ',' +) : '' ) + 'sprin @@ -3001,33 +3001,33 @@ : '' ) + 'sprin -t +g ,button-sendToIn @@ -3028,34 +3028,32 @@ ndToInternals';%0A - toolbar.setAtt @@ -3086,16 +3086,135 @@ ltSet);%0A + if (!Services.prefs.getBoolPref(BASE + 'initialized')) %7B%0A Services.prefs.setBoolPref(BASE + 'initialized', true);%0A curr @@ -3236,16 +3236,17 @@ ntSet ? +( currentS @@ -3253,16 +3253,17 @@ et + ',' +) : '' ) @@ -3270,17 +3270,17 @@ + 'sprin -t +g ,button-
0de00e8023e6d523e643106f5b7e21793ce733a0
Support non-modified autocomplete results
content/composeOverlay.js
content/composeOverlay.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/. */ (function(global) { var { AutoCompleteResultCache } = Components.utils.import('resource://customizable-ldap-autocomplete-modules/AutoCompleteResultCache.jsm', {}); var AbRecipientImagePopup = { get popup() { return document.getElementById('ab-recipient-image-popup'); }, get image() { return document.getElementById('ab-recipient-image'); }, init: function() { window.removeEventListener('load', this, false); window.addEventListener('unload', this, false); window.addEventListener('keypress', this, true); window.addEventListener('popuphidden', this, true); }, destroy: function() { window.removeEventListener('unload', this, false); window.removeEventListener('keypress', this, true); window.removeEventListener('popuphidden', this, true); }, isRecipientField: function(aElement) { return ( aElement.localName == 'textbox' && aElement.getAttribute('type') == 'autocomplete' && aElement.classList.contains('textbox-addressingWidget') ); }, handleUserOperation: function(aEvent) { var field = aEvent.target; if (!this.isRecipientField(field)) return; setTimeout((function() { var maybeShown = this.handleUserOperationWithDelay(field); if (!maybeShown) this.hidePopup(); }).bind(this), 0); }, handleUserOperationWithDelay: function(aField) { if (!aField.popupOpen) return false; var result = AutoCompleteResultCache.get(aField.controller.searchString); if (!result) return false; var address = aField.controller.getValueAt(aField.popup.selectedIndex); var index = result.indexOfValue(address); if (index < 0) return false; var card = result.getCardAt(index); var book = result.getBookAt(index); this.showImageFor({ card: card, book: book, anchorElement: aField.popup }); return true; }, showImageFor: function(aParams) { var card = aParams.card; var book = aParams.book; var anchorElement = aParams.anchorElement; this.hidePopup(); if (book instanceof Compoments.interfaces.nsIAbLDAPDirectory && 'LDAPContactPhoto' in global) { let image = new Image(); image.addEventListener('load', (function() { this.image.src = image.src; this.showPopupAt(anchorElement); }).bind(this), false); LDAPContactPhoto.fetchLDAPPhoto(card, book.URI, image); return; } switch (card.getProperty('PhotoType', null)) { case 'file': case 'web': let uri = card.getProperty('PhotoURI', null); if (uri) { this.image.src = uri; this.showPopupAt(anchorElement); } return; default: break; } }, showPopupAt: function(aAnchorElement) { this.popup.openPopup(aAnchorElement, 'after_start', -1, -1, true, true); }, hidePopup: function() { this.popup.hidePopup(); }, handleEvent: function(aEvent) { switch (aEvent.type) { case 'load': this.init(); return; case 'unload': this.destroy(); return; case 'keypress': this.handleUserOperation(aEvent); return; case 'popuphidden': if (aEvent.target != this.popup) this.hidePopup(); return; } } }; window.addEventListener('load', AbRecipientImagePopup, false); global.AbRecipientImagePopup = AbRecipientImagePopup; })(this);
JavaScript
0
@@ -1633,16 +1633,19 @@ var r +awR esult = @@ -1709,46 +1709,8 @@ g);%0A - if (!result)%0A return false;%0A%0A @@ -1785,19 +1785,74 @@ x);%0A -var +if (typeof rawResult.indexOfValue == 'function') %7B%0A let index = @@ -1849,24 +1849,27 @@ et index = r +awR esult.indexO @@ -1925,27 +1925,27 @@ false;%0A%0A -var +let card = resu @@ -1965,27 +1965,27 @@ index);%0A -var +let book = resu @@ -2142,16 +2142,182 @@ n true;%0A + %7D%0A else %7B%0A let card = result.getCardAt(index);%0A this.showImageFor(%7B%0A card: card,%0A anchorElement: aField.popup%0A %7D);%0A %7D%0A %7D,%0A%0A @@ -2510,16 +2510,32 @@ f (book +&&%0A book instance
e687b441b5593305925515e6568adbe861dbed03
Change default position of NotificationView.
source/Vibrato/views/panels/NotificationView.js
source/Vibrato/views/panels/NotificationView.js
// -------------------------------------------------------------------------- \\ // File: NotificationView.js \\ // Module: PanelViews \\ // Requires: Core, Foundation, DOM, View \\ // Author: Neil Jenkins \\ // License: © 2010–2013 Opera Software ASA. All rights reserved. \\ // -------------------------------------------------------------------------- \\ "use strict"; ( function ( NS, undefined ) { var hiddenLayout = { top: 0 }; var NotificationView = NS.Class({ Extends: NS.View, Mixin: NS.AnimatableView, animateLayerDuration: 200, className: function () { return 'NotificationView' + ( this.get( 'userMayClose' ) ? ' closable' : '' ); }.property( 'userMayClose' ), destroyOnClose: true, isShowing: false, userMayClose: true, precedence: 0, timeout: 0, hiddenLayout: hiddenLayout, visibleLayout: function () { return { top: this.get( 'pxHeight' ) }; }.property(), text: '', html: '', _timer: null, show: function ( notificationsContainer ) { if ( this.get( 'isShowing' ) ) { this.hide( true ); } notificationsContainer.insertView( this ); this._show(); var timeout = this.get( 'timeout' ); if ( timeout ) { this._timer = NS.RunLoop.invokeAfterDelay( this.hide, timeout, this ); } return this.set( 'isShowing', true ); }, _show: function () { if ( this.get( 'isShowing' ) ) { this.set( 'layout', this.get( 'visibleLayout' ) ); } }.later(), hide: function ( doNotAnimate ) { if ( this.get( 'isShowing' ) ) { // If we don't have a layerAnimation object yet, we can't have // animated in, so just detach immediately. Otherwise, stop the // current layer animation, then animate out. var layerAnimation = NS.meta( this ).cache.layerAnimation, hiddenLayout = this.get( 'hiddenLayout' ); if ( !doNotAnimate && layerAnimation && this.get( 'layout' ) !== hiddenLayout ) { layerAnimation.stop(); this.set( 'layout', hiddenLayout ); } else { this.detach(); } if ( this._timer ) { NS.RunLoop.cancel( this._timer ); this._timer = null; } this.set( 'isShowing', false ); } return this; }, didAnimate: function () { this.increment( 'animating', -1 ); if ( !this.get( 'animating' ) && !this.get( 'isShowing' ) ) { this.detach(); } }, detach: function () { this.get( 'parentView' ) .removeView( this ) .notificationDidHide( this ); if ( this.get( 'destroyOnClose' ) ) { this.destroy(); } return this; }, layout: hiddenLayout, draw: function ( layer ) { this.drawNotification( layer ); if ( this.get( 'userMayClose' ) ) { var el = NS.Element.create; layer.appendChild( this._close = el( 'a.close', [ el( 'i.close-image' ), NS.loc( 'Close' ) ]) ); } }, drawNotification: function ( layer ) { var text = this.get( 'text' ), html = this.get( 'html' ); if ( text || html ) { layer.appendChild( this._textNode = NS.Element.create( 'span', { text: text || undefined, html: text ? undefined : html }) ); } }, notificationNeedsRedraw: function ( self, property, oldValue ) { return this.propertyNeedsRedraw( self, property, oldValue ); }.observes( 'text', 'html' ), redrawText: function () { this.redrawHTML(); }, redrawHTML: function () { var text = this.get( 'text' ), html = this.get( 'html' ); this._textNode.set( html ? 'html' : 'text', html || text ); }, hideOnClick: function ( event ) { if ( this.get( 'userMayClose' ) && NS.Element.contains( this._close, event.target ) ) { event.preventDefault(); this.hide(); } }.on( 'click' ) }); var NotificationContainerView = NS.Class({ Extends: NS.View, className: 'NotificationContainerView', showing: null, init: function ( mixin ) { this._waiting = []; NotificationContainerView.parent.init.call( this, mixin ); }, positioning: 'absolute', willShow: function ( notification ) { var showing = this.get( 'showing' ); if ( showing ) { if ( notification !== showing && notification.get( 'precedence' ) >= showing.get( 'precedence' ) ) { this._waiting.push( notification ); this.hide( showing ); } return false; } return true; }, show: function ( notification ) { if ( this.willShow( notification ) ) { this.set( 'showing', notification ); notification.show( this ); } }, hide: function ( notification ) { var showing = this.get( 'showing' ); if ( showing && ( !notification || notification === showing ) ) { showing.hide(); } }, notificationDidHide: function ( notification ) { this.set( 'showing', null ); var nextNotification = this._waiting.pop(); if ( nextNotification ) { this.show( nextNotification ); } } }); NS.NotificationContainerView = NotificationContainerView; NS.NotificationView = NotificationView; }( this.O ) );
JavaScript
0
@@ -1136,16 +1136,17 @@ top: +- this.get @@ -1159,16 +1159,21 @@ eight' ) + - 10 %0A @@ -3466,18 +3466,22 @@ 'i. -close-imag +icon.icon-clos e' )
763439b3abf1c5b8e6befe76ad8571a7d3c53c49
Add puppy
hungrydog.js
hungrydog.js
document.onkeydown = move; var puppy = { x: 40, y: 200, alive: true, won: false, canMove: true, }; var alien = { x: 560, y: 80, alive: true, }; var alien2 = { x: 560, y: 200, alive: true, }; var alien3 = { x: 560, y: 320, alive: true, }; document.getElementById("up").onclick = function() {move(38);}; document.getElementById("down").onclick = function() {move(40);}; document.getElementById("right").onclick = function() {move(39);}; document.getElementById("left").onclick = function() {move(37);}; var puppyImg = document.getElementById("puppy"); var alienImg = document.getElementById("alien"); var alienImg2 = document.getElementById("alien2"); var alienImg3 = document.getElementById("alien3"); var alienCount = 3; function move(direction){ if (puppy.canMove){ console.log('moving'); ai_move(alien, alienImg); ai_move(alien2, alienImg2); ai_move(alien3, alienImg3); if (direction.keyCode === 38 || direction === 38){ // move up if (puppy.y > 0){ puppy.y = (puppy.y - 40); puppyImg.style.top = (puppy.y + "px"); } }else if (direction.keyCode === 40 || direction === 40){ // move down if (puppy.y < 440){ puppy.y = (puppy.y + 40); puppyImg.style.top = (puppy.y + "px"); } }else if (direction.keyCode === 39 || direction == 39 || direction.keyCode === 76){ // move right if (puppy.x < 600){ puppy.x = (puppy.x + 40); puppyImg.style.left = (puppy.x + "px"); } }else if (direction.keyCode === 37 || direction == 37 || direction.keyCode === 74){ // move left if (puppy.x > 0){ puppy.x = (puppy.x - 40); puppyImg.style.left = (puppy.x + "px"); } } status(alien, alienImg); status(alien2, alienImg2); status(alien3, alienImg3); setTimeout(function(){ puppy.canMove = true; }, 200) puppy.canMove = false; } } function ai_move(player, playerImg){ var random = Math.floor((Math.random() * 4) + 1); // move up if (random === 1){ if (player.y > 0){ player.y = (player.y - 40); playerImg.style.top = (player.y + "px"); } }else if (random === 2){ // move down if (player.y < 440){ player.y = (player.y + 40); playerImg.style.top = (player.y + "px"); } }else if (random === 3){ // move right if (player.x < 600){ player.x = (player.x + 40); playerImg.style.left = (player.x + "px"); } }else{ //move left if (player.x > 0){ player.x = (player.x - 40); playerImg.style.left = (player.x + "px"); } } }
JavaScript
0.000262
@@ -1,32 +1,4 @@ -document.onkeydown = move;%0A%0A var @@ -2576,12 +2576,39 @@ %0A %7D%0A %7D%0A%7D%0A +%0Adocument.onkeydown = move;
64840cf042aa06cc9797040fb2bb562c1d7b00c4
Update delete all content button labels
core/client/views/debug.js
core/client/views/debug.js
/*global window, document, Ghost, $, _, Backbone, JST */ (function () { "use strict"; Ghost.Views.Debug = Ghost.View.extend({ events: { "click .settings-menu a": "handleMenuClick", "click #startupload": "handleUploadClick", "click .js-delete": "handleDeleteClick" }, initialize: function () { var view = this; this.uploadButton = this.$el.find('#startupload'); // Disable import button and initizalize BlueImp file upload this.uploadButton.prop('disabled', 'disabled'); $('#importfile').fileupload({ url: Ghost.paths.apiRoot + '/db/', limitMultiFileUploads: 1, replaceFileInput: false, headers: { 'X-CSRF-Token': $("meta[name='csrf-param']").attr('content') }, dataType: 'json', add: function (e, data) { /*jslint unparam:true*/ // Bind the upload data to the view, so it is // available to the click handler, and enable the // upload button. view.fileUploadData = data; data.context = view.uploadButton.removeProp('disabled'); }, done: function (e, data) { /*jslint unparam:true*/ $('#startupload').text('Import'); if (!data.result) { throw new Error('No response received from server.'); } if (!data.result.message) { throw new Error('Unknown error'); } Ghost.notifications.addItem({ type: 'success', message: data.result.message, status: 'passive' }); }, error: function (response) { $('#startupload').text('Import'); var responseJSON = response.responseJSON, message = responseJSON && responseJSON.error ? responseJSON.error : 'unknown'; Ghost.notifications.addItem({ type: 'error', message: ['A problem was encountered while importing new content to your blog. Error: ', message].join(''), status: 'passive' }); } }); }, handleMenuClick: function (ev) { ev.preventDefault(); var $target = $(ev.currentTarget); // Hide the current content this.$(".settings-content").hide(); // Show the clicked content this.$("#debug-" + $target.attr("class")).show(); return false; }, handleUploadClick: function (ev) { ev.preventDefault(); if (!this.uploadButton.prop('disabled')) { this.fileUploadData.context = this.uploadButton.text('Importing'); this.fileUploadData.submit(); } // Prevent double post by disabling the button. this.uploadButton.prop('disabled', 'disabled'); }, handleDeleteClick: function (ev) { ev.preventDefault(); this.addSubview(new Ghost.Views.Modal({ model: { options: { close: true, confirm: { accept: { func: function () { $.ajax({ url: Ghost.paths.apiRoot + '/db/', type: 'DELETE', headers: { 'X-CSRF-Token': $("meta[name='csrf-param']").attr('content') }, success: function onSuccess(response) { if (!response) { throw new Error('No response received from server.'); } if (!response.message) { throw new Error(response.detail || 'Unknown error'); } Ghost.notifications.addItem({ type: 'success', message: response.message, status: 'passive' }); }, error: function onError(response) { var responseText = JSON.parse(response.responseText), message = responseText && responseText.error ? responseText.error : 'unknown'; Ghost.notifications.addItem({ type: 'error', message: ['A problem was encountered while deleting content from your blog. Error: ', message].join(''), status: 'passive' }); } }); }, text: "Yes" }, reject: { func: function () { return true; }, text: "No" } }, type: "action", style: ["wide", "centered"], animation: 'fade' }, content: { template: 'blank', title: 'Would you really like to delete all content from your blog?', text: '<p>This is permanent! No backups, no restores, no magic undo button. <br /> We warned you, ok?</p>' } } })); } }); }());
JavaScript
0
@@ -5790,11 +5790,76 @@ t: %22 -Yes +Delete%22,%0A buttonClass: %22button-delete %22%0A @@ -6100,18 +6100,77 @@ text: %22 -No +Cancel%22,%0A buttonClass: %22button %22%0A
a3e9b84568b25d1c8990ffe52f07d3f87396933c
Add lodash import to RelationshipField, resolve #3241
fields/types/relationship/RelationshipField.js
fields/types/relationship/RelationshipField.js
import async from 'async'; import Field from '../Field'; import { listsByKey } from '../../../admin/client/utils/lists'; import React from 'react'; import Select from 'react-select'; import xhr from 'xhr'; import { Button, InputGroup } from 'elemental'; function compareValues (current, next) { const currentLength = current ? current.length : 0; const nextLength = next ? next.length : 0; if (currentLength !== nextLength) return false; for (let i = 0; i < currentLength; i++) { if (current[i] !== next[i]) return false; } return true; } module.exports = Field.create({ displayName: 'RelationshipField', statics: { type: 'Relationship', }, getInitialState () { return { value: null, createIsOpen: false, }; }, componentDidMount () { this._itemsCache = {}; this.loadValue(this.props.value); }, componentWillReceiveProps (nextProps) { if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return; this.loadValue(nextProps.value); }, shouldCollapse () { if (this.props.many) { // many:true relationships have an Array for a value return this.props.collapse && !this.props.value.length; } return this.props.collapse && !this.props.value; }, buildFilters () { var filters = {}; _.forEach(this.props.filters, (value, key) => { if (_.isString(value) && value[0] == ':') { // eslint-disable-line eqeqeq var fieldName = value.slice(1); var val = this.props.values[fieldName]; if (val) { filters[key] = val; return; } // check if filtering by id and item was already saved if (fieldName === ':_id' && Keystone.item) { filters[key] = Keystone.item.id; return; } } else { filters[key] = value; } }, this); var parts = []; _.forEach(filters, function (val, key) { parts.push('filters[' + key + '][value]=' + encodeURIComponent(val)); }); return parts.join('&'); }, cacheItem (item) { item.href = Keystone.adminPath + '/' + this.props.refList.path + '/' + item.id; this._itemsCache[item.id] = item; }, loadValue (values) { if (!values) { return this.setState({ loading: false, value: null, }); }; values = Array.isArray(values) ? values : values.split(','); const cachedValues = values.map(i => this._itemsCache[i]).filter(i => i); if (cachedValues.length === values.length) { this.setState({ loading: false, value: this.props.many ? cachedValues : cachedValues[0], }); return; } this.setState({ loading: true, value: null, }); async.map(values, (value, done) => { xhr({ url: Keystone.adminPath + '/api/' + this.props.refList.path + '/' + value + '?basic', responseType: 'json', }, (err, resp, data) => { if (err || !data) return done(err); this.cacheItem(data); done(err, data); }); }, (err, expanded) => { if (!this.isMounted()) return; this.setState({ loading: false, value: this.props.many ? expanded : expanded[0], }); }); }, // NOTE: this seems like the wrong way to add options to the Select loadOptionsCallback: {}, loadOptions (input, callback) { // NOTE: this seems like the wrong way to add options to the Select this.loadOptionsCallback = callback; const filters = this.buildFilters(); xhr({ url: Keystone.adminPath + '/api/' + this.props.refList.path + '?basic&search=' + input + '&' + filters, responseType: 'json', }, (err, resp, data) => { if (err) { console.error('Error loading items:', err); return callback(null, []); } data.results.forEach(this.cacheItem); callback(null, { options: data.results, complete: data.results.length === data.count, }); }); }, valueChanged (value) { this.props.onChange({ path: this.props.path, value: value, }); }, openCreate () { this.setState({ createIsOpen: true, }); }, closeCreate () { this.setState({ createIsOpen: false, }); }, onCreate (item) { this.cacheItem(item); if (Array.isArray(this.state.value)) { // For many relationships, append the new item to the end const values = this.state.value.map((item) => item.id); values.push(item.id); this.valueChanged(values.join(',')); } else { this.valueChanged(item.id); } // NOTE: this seems like the wrong way to add options to the Select this.loadOptionsCallback(null, { complete: true, options: Object.keys(this._itemsCache).map((k) => this._itemsCache[k]), }); this.toggleCreate(false); }, renderSelect (noedit) { return ( <Select.Async multi={this.props.many} disabled={noedit} loadOptions={this.loadOptions} labelKey="name" name={this.props.path} onChange={this.valueChanged} simpleValue value={this.state.value} valueKey="id" /> ); }, renderInputGroup () { // TODO: find better solution // when importing the CreateForm using: import CreateForm from '../../../admin/client/App/shared/CreateForm'; // CreateForm was imported as a blank object. This stack overflow post suggested lazilly requiring it: // http://stackoverflow.com/questions/29807664/cyclic-dependency-returns-empty-object-in-react-native // TODO: Implement this somewhere higher in the app, it breaks the encapsulation of the RelationshipField component const CreateForm = require('../../../admin/client/App/shared/CreateForm'); return ( <InputGroup> <InputGroup.Section grow> {this.renderSelect()} </InputGroup.Section> <InputGroup.Section> <Button onClick={this.openCreate} type="success">+</Button> </InputGroup.Section> <CreateForm list={listsByKey[this.props.refList.key]} isOpen={this.state.createIsOpen} onCreate={this.onCreate} onCancel={this.closeCreate} /> </InputGroup> ); }, renderValue () { return this.renderSelect(true); }, renderField () { if (this.props.createInline) { return this.renderInputGroup(); } else { return this.renderSelect(); } }, });
JavaScript
0
@@ -246,16 +246,40 @@ mental'; +%0Aimport _ from 'lodash'; %0A%0Afuncti
ac640632e5997b06151427d34adef64e53b63347
reset with value 0
filer/static/filer/js/addons/table-dropzone.js
filer/static/filer/js/addons/table-dropzone.js
// #DROPZONE# // This script implements the dropzone settings 'use strict'; /* globals Dropzone, Cl, django */ (function ($) { $(function () { var submitNum = 0; var maxSubmitNum = 0; var dropzoneInstances = []; var dropzoneBase = $('.js-filer-dropzone-base'); var dropzoneSelector = '.js-filer-dropzone'; var dropzones; var infoMessageClass = 'js-filer-dropzone-info-message'; var infoMessage = $('.' + infoMessageClass); var folderName = $('.js-filer-dropzone-folder-name'); var uploadInfoContainer = $('.js-filer-dropzone-upload-info-container'); var uploadInfo = $('.js-filer-dropzone-upload-info'); var uploadWelcome = $('.js-filer-dropzone-upload-welcome'); var uploadNumber = $('.js-filer-dropzone-upload-number'); var uploadCount = $('.js-filer-upload-count'); var uploadText = $('.js-filer-upload-text'); var uploadFileNameSelector = '.js-filer-dropzone-file-name'; var uploadProgressSelector = '.js-filer-dropzone-progress'; var uploadSuccess = $('.js-filer-dropzone-upload-success'); var uploadCanceled = $('.js-filer-dropzone-upload-canceled'); var cancelUpload = $('.js-filer-dropzone-cancel'); var dragHoverClass = 'dz-drag-hover'; var dataUploaderConnections = 'max-uploader-connections'; var dragHoverBorder = $('.drag-hover-border'); // var dataMaxFileSize = 'max-file-size'; var hiddenClass = 'hidden'; var hideMessageTimeout; var hasErrors = false; var baseUrl; var baseFolderTitle; var updateUploadNumber = function () { uploadNumber.text(maxSubmitNum - submitNum + '/' + maxSubmitNum); uploadText.removeClass('hidden'); uploadCount.removeClass('hidden'); }; var destroyDropzones = function () { $.each(dropzoneInstances, function (index) { dropzoneInstances[index].destroy(); }); }; var getElementByFile = function (file, url) { return $(document.getElementById( 'file-' + encodeURIComponent(file.name) + file.size + file.lastModified + url )); }; if (dropzoneBase && dropzoneBase.length) { baseUrl = dropzoneBase.data('url'); baseFolderTitle = dropzoneBase.data('folder-name'); $('body').data('url', baseUrl).data('folder-name', baseFolderTitle).addClass('js-filer-dropzone'); } Cl.mediator.subscribe('filer-upload-in-progress', destroyDropzones); dropzones = $(dropzoneSelector); if (dropzones.length && Dropzone) { Dropzone.autoDiscover = false; dropzones.each(function () { var dropzone = $(this); var dropzoneUrl = $(this).data('url'); var dropzoneInstance = new Dropzone(this, { url: dropzoneUrl, paramName: 'file', maxFiles: 100, // for now disabled as we don't have the correct file size limit // maxFilesize: dropzone.data(dataMaxFileSize) || 20, // MB previewTemplate: '<div></div>', clickable: false, addRemoveLinks: false, parallelUploads: dropzone.data(dataUploaderConnections) || 3, accept: function (file, done) { var uploadInfoClone; Cl.mediator.remove('filer-upload-in-progress', destroyDropzones); Cl.mediator.publish('filer-upload-in-progress'); clearTimeout(hideMessageTimeout); uploadWelcome.addClass(hiddenClass); cancelUpload.removeClass(hiddenClass); if (getElementByFile(file, dropzoneUrl).length) { done('duplicate'); } else { uploadInfoClone = uploadInfo.clone(); uploadInfoClone.find(uploadFileNameSelector).text(file.name); uploadInfoClone.find(uploadProgressSelector).width(0); uploadInfoClone .attr( 'id', 'file-' + encodeURIComponent(file.name) + file.size + file.lastModified + dropzoneUrl ) .appendTo(uploadInfoContainer); submitNum++; maxSubmitNum++; updateUploadNumber(); done(); } dropzones.removeClass('reset-hover'); infoMessage.removeClass(hiddenClass); dropzones.removeClass(dragHoverClass); }, dragover: function (dragEvent) { var folderTitle = $(dragEvent.target).closest(dropzoneSelector).data('folder-name'); var dropzoneFolder = dropzone.hasClass('js-filer-dropzone-folder'); var dropzoneBoundingRect = dropzone[0].getBoundingClientRect(); var dropzonePosition = { top: dropzoneBoundingRect.top, bottom: dropzoneBoundingRect.bottom, width: dropzoneBoundingRect.width, height: dropzoneBoundingRect.height }; if (dropzoneFolder) { dragHoverBorder.css(dropzonePosition); } $(dropzones).addClass('reset-hover'); uploadSuccess.addClass(hiddenClass); infoMessage.removeClass(hiddenClass); dropzone.addClass(dragHoverClass).removeClass('reset-hover'); folderName.text(folderTitle); }, dragleave: function () { clearTimeout(hideMessageTimeout); hideMessageTimeout = setTimeout(function () { infoMessage.addClass(hiddenClass); }, 1000); infoMessage.removeClass(hiddenClass); dropzones.removeClass(dragHoverClass); dragHoverBorder.css({ top: '', bottom: '', width: '', height: ''}); }, sending: function (file) { getElementByFile(file, dropzoneUrl).removeClass(hiddenClass); }, uploadprogress: function (file, progress) { getElementByFile(file, dropzoneUrl).find(uploadProgressSelector).width(progress + '%'); }, success: function (file) { submitNum--; updateUploadNumber(); getElementByFile(file, dropzoneUrl).remove(); }, queuecomplete: function () { if (submitNum !== 0) { return; } updateUploadNumber(); cancelUpload.addClass(hiddenClass); uploadInfo.addClass(hiddenClass); if (hasErrors) { uploadNumber.addClass(hiddenClass); setTimeout(function () { window.location.reload(); }, 1000); } else { uploadSuccess.removeClass(hiddenClass); window.location.reload(); } }, error: function (file, errorText) { updateUploadNumber(); if (errorText === 'duplicate') { return; } hasErrors = true; if (window.showError) { window.showError(file.name + ': ' + errorText); } } }); dropzoneInstances.push(dropzoneInstance); cancelUpload.on('click', function (clickEvent) { clickEvent.preventDefault(); cancelUpload.addClass(hiddenClass); uploadCanceled.removeClass(hiddenClass); dropzoneInstance.removeAllFiles(true); }); }); } }); })(django.jQuery);
JavaScript
0.00022
@@ -6868,16 +6868,17 @@ %7B top: ' +0 ', botto @@ -6881,16 +6881,17 @@ ottom: ' +0 ', width @@ -6893,16 +6893,17 @@ width: ' +0 ', heigh @@ -6906,17 +6906,19 @@ eight: ' -' +0' %7D);%0A%0A
f0d02f93005c46ce0f0acc8165bd8ad0f1618bf6
Remove log statement.
app/renderer/main.js
app/renderer/main.js
import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import App from './components/app' import configureStore from './store/configureStore' import injectTapEventPlugin from 'react-tap-event-plugin' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme' import getMuiTheme from 'material-ui/styles/getMuiTheme' import { addRequest, addResponse } from './actions' import perf from 'react-addons-perf' import { ipcRenderer } from 'electron' import { Router, IndexRoute, Route, createMemoryHistory } from 'react-router' import RequestsContainer from './components/requests' import RequestDetailsContainer from './components/response-details' import title from './components/title' injectTapEventPlugin() title() ipcRenderer.on('add-request', (e, request) => { store.dispatch(addRequest(request)) }) ipcRenderer.on('add-response', (e, response) => { store.dispatch(addResponse(response)) }) Object.defineProperty(window, 'perf', { get: () => perf }) const store = configureStore() const theme = getMuiTheme(darkBaseTheme) console.log(theme) theme.appBar.height = 32 theme.toolbar.backgroundColor = theme.palette.canvasColor theme.svgIcon.color = theme.palette.primary3Color const history = createMemoryHistory('/requests') render( <Provider store={store}> <MuiThemeProvider muiTheme={theme}> <Router history={history}> <Route path='/' component={App}> <Route path='requests'> <IndexRoute component={RequestsContainer} label='Requests' /> <Route path=':id' component={RequestDetailsContainer} label='Details' /> </Route> </Route> </Router> </MuiThemeProvider> </Provider>, document.getElementById('mount') )
JavaScript
0
@@ -1155,27 +1155,8 @@ me)%0A -console.log(theme)%0A them
53cd68bf8badf7a5a5007958e42f8ce63a999199
Fix typo in CSS import.
gsssm0.1.js
gsssm0.1.js
;(function () { "use strict"; var canvases = []; var cvs1overwrap = $("<div/>").addClass("SSM_gswrap"); var cvs1 = canvas({ resizable:false }); cvs1.container.prepend(cvs1overwrap); cvs1overwrap.append(cvs1.title_anchor).append(cvs1.wrapper).append(cvs1.caption_anchor); cvs1.overwrap = cvs1overwrap; canvases.push(cvs1); var cvs2overwrap = $("<div/>").addClass("SSM_gswrap"); var cvs2 = canvas({ resizable:false }); cvs2.container.prepend(cvs2overwrap); cvs2overwrap.append(cvs2.title_anchor).append(cvs2.wrapper).append(cvs2.caption_anchor); cvs2.overwrap = cvs2overwrap; canvases.push(cvs2); //this.canvas.wrapper.css({float:"left"}); var high = Number(window.innerHeight) - 57; // 36 for status bar, 21 for title var wide = Number(window.innerWidth) - 20 // 20 for good measure var cvsdim = Math.min(high,(wide-200)/2.0); cvs1.width = cvs1.height = cvs2.width = cvs2.height = cvsdim; // Set canvas dimensions. sphere({ canvas: cvs1, visible: false }); // Activate cvs1. sphere({ canvas: cvs2, visible: false }); // Activate cvs2. //this.canvas.wrapper.css({margin: '4px'}); //$(this.canvas.__canvas_element).css({border: '1px solid #AAA'}); //$(this.canvas.__overlay_element).css({border: '1px solid #AAA'}); print('', {end:''}); print_options({width:200, height:cvsdim}); var myStylesLocation = "https://raw.githack.com/thehappyt/SSModels/master/gsssm0.1.css"; $('<link rel="stylesheet" type="text/css" href="'+myStylesLocation+'" >') .appendTo("head"); var global = window; function Export( exports ) { if (!global.gsssm) global.gsssm = {} for(var id in exports) { if (!global[id]) global[id] = exports[id] gsssm[id] = exports[id] } } var exports = { canvases: canvases } Export(exports) }) ();
JavaScript
0
@@ -1579,14 +1579,16 @@ els/ -master +gh-pages /gss
522b81dcf393f1eaf6ab5571c422fc4a97dd0532
add route to state object
stores/ApplicationStore.js
stores/ApplicationStore.js
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var util = require('util'), EventEmitter = require('events').EventEmitter, Router = require('routr'), TimeStore = require('./TimeStore'), routes = require('../configs/routes'), debug = require('debug')('ApplicationStore'); function ApplicationStore(context, initialState) { initialState = initialState || {}; this.page = initialState.page || null; this.url = initialState.url || null; this.router = new Router(routes); this.pages = initialState.pages || [ { name: 'home', text: 'Home', url: this.router.makePath('home') }, { name: 'about', text: 'About', url: this.router.makePath('about') } ]; } ApplicationStore.storeName = 'ApplicationStore'; ApplicationStore.handlers = { 'NAVIGATE': 'handleNavigate' }; util.inherits(ApplicationStore, EventEmitter); ApplicationStore.prototype.setDispatcher = function (dispatcher) { this.dispatcher = dispatcher; }; ApplicationStore.prototype.handleNavigate = function (payload, done) { var self = this, newPage = null, route = this.router.getRoute(payload.path, {navParams: payload.params}), timeStore = this.dispatcher.getStore(TimeStore); if (route) { this.route = route; if (route.config.page) { this.pages.forEach(function (page) { if (route.name === page.name) { newPage = page; } }); } } if (newPage && newPage.name !== self.page ) { self.page = newPage.name; self.url = newPage.url; timeStore.reset(function () { debug('page switched to ' + self.page); self.emit('update'); // Store may be listening for updates to state done(); }); } else { done(); // Action has been fully handled } }; ApplicationStore.prototype.getState = function () { return { page: this.page, pages: this.pages, url: this.url }; }; module.exports = ApplicationStore;
JavaScript
0.000001
@@ -2166,16 +2166,43 @@ .pages,%0A + route: this.route,%0A
511184318bb4bddb92eced97f388a43aee6bae7c
Use for-of instead of .forEach() in newly added code.
lib/prepareImproQueryString.js
lib/prepareImproQueryString.js
const isSupportedEngine = { gm: true, sharp: true, pngcrush: true, pngquant: true, jpegtran: true, optipng: true, svgfilter: true, inkscape: true }; const resizeOptions = { ignoreAspectRatio: true, withoutEnlargement: true }; const queryStringEngineAndArgsRegex = new RegExp( `^(${Object.keys(isSupportedEngine).join('|')})=(.*)` ); module.exports = function prepareQueryString(queryString) { const keyValuePairs = queryString.split('&'); const queryStringFragments = []; let hasResize = false; let optionToResize; for (const pair of keyValuePairs) { let m; if ((m = pair.match(queryStringEngineAndArgsRegex)) !== null) { const [, engineName, engineArgs] = m; const result = [engineName]; const remaining = engineArgs.split(','); let isEngineOptions = false; let lastSeenOptionIndex = -1; let engineOptions; remaining.forEach((bit, index) => { if (engineName === 'svgfilter' && bit[0] === '-' && bit[1] === '-') { if (!isEngineOptions) { isEngineOptions = true; engineOptions = []; } engineOptions.push(bit.slice(2)); } else if (bit[0] === '-') { result.push(bit.slice(1)); lastSeenOptionIndex = index + 1; // account for the engine entry } else if (engineName === 'pngquant') { result.push(`speed=${bit}`); } else if (lastSeenOptionIndex > -1) { result[lastSeenOptionIndex] += `=${bit}`; } }); if (isEngineOptions) { result[0] += `=${engineOptions.join('+')}`; } queryStringFragments.push(...result); } else { if (pair.startsWith('setFormat=')) { let format = pair.slice(10).toLowerCase(); if (format === 'jpg') { format = 'jpeg'; } queryStringFragments.push(format); } else if (pair in resizeOptions && !hasResize) { optionToResize = pair; } else { let fragment = pair; if (pair.startsWith('resize=') && pair.indexOf(',') === -1) { // single value form of resize fragment += ','; } queryStringFragments.push(fragment); } if (pair.startsWith('resize=')) { if (optionToResize) { queryStringFragments.push(optionToResize); optionToResize = undefined; } else { hasResize = true; } } } } return queryStringFragments.join('&'); };
JavaScript
0
@@ -895,41 +895,55 @@ -remaining.forEach((bit, index) =%3E +for (const %5Bindex, bit%5D of remaining.entries()) %7B%0A @@ -1529,18 +1529,16 @@ %0A %7D -); %0A%0A
50496704bcccb61915b669f5cb2536f138881ebd
Fix error logs
lib/techs/jsdoc-json-jsdoc3.js
lib/techs/jsdoc-json-jsdoc3.js
var vow = require('vow'), path = require('path'), cp = require('child_process'), enb = require('enb'), buildFlow = enb.buildFlow || require('enb/lib/build-flow'); module.exports = buildFlow.create() .name('jsdoc-json-jsdoc3') .target('target', '?.jsdoc.json') .useFileList(['js']) .builder(function (files) { var isWinOS = path.sep === '\\', logger = this.node.getLogger(), target = this._target; if (files.length === 0) { return '{}'; } var jsdoc = cp.spawn( path.resolve(__dirname, '../../node_modules/.bin/jsdoc' + (isWinOS ? '.cmd' : '')), [ '-c', path.resolve(__dirname, '../jsdoc3/jsdoc.conf.json'), '-t', path.resolve(__dirname, '../../node_modules/jsdoc-bem/templates/docjson') ].concat(files.map(function (file) { return file.fullname; })) ), content = '', err = '', d = vow.defer(); jsdoc.stdout.on('data', function (data) { content += data; }); jsdoc.stderr.on('data', function (data) { err += data; }); jsdoc.on('close', function (code) { if (code !== 0) { logger.logWarningAction('js-doc', target, err.stack); return d.resolve('{}'); } d.resolve(content); }); return d.promise(); }) .createTech();
JavaScript
0.000004
@@ -1366,14 +1366,8 @@ err -.stack );%0A
a6aafb5675fa2c5466df62aa4b4f02603884a128
remove requirejs build from package.json
gruntfile.js
gruntfile.js
/* jshint node:true */ module.exports = function(grunt) { 'use strict'; // load all grunt tasks matching the ['grunt-*', '@*/grunt-*'] patterns require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ bower: { install: { }//just run 'grunt bower:install' and you'll see files from your Bower packages in lib directory }, requirejs: { compile: { options: { appDir: "./app", baseUrl: ".", dir: "app_build", mainConfigFile: "app/boot.js", modules: [ { name : "boot", include: [ 'services/editFormUtility', 'directives/forms/form-controls', 'directives/formats/views/form-loader', 'utilities/km-utilities', 'utilities/km-workflows', 'utilities/km-storage', 'views/index', 'views/database/index', ] }] , inlineText : true, optimize : "uglify2", optimizeCss : "standard" } } } }); grunt.registerTask('default', ['bower', 'requirejs']); };
JavaScript
0.000002
@@ -1347,21 +1347,8 @@ wer' -, 'requirejs' %5D);%0A
3f06ae93641f3fad6de55f188b31d974c6616428
bump bower.json too
gruntfile.js
gruntfile.js
module.exports = function(grunt) { // load all grunt tasks require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); var pkg = grunt.file.readJSON('package.json'); var banner = grunt.initConfig({ pkg: pkg, banner: '/**'+ '* <%= pkg.description %>\n'+ '* @author <%= pkg.author %>\n'+ '* @version v<%= pkg.version %>\n'+ '* @link <%= pkg.repository.url %>\n' + '* @license <%= pkg.license %>\n'+ '*/', bump: { options: { files: ['package.json'], commit: false, createTag: false, push: false } }, karma: { options: { configFile: 'karma.conf.js' }, unit: { singleRun: true }, server: { autoWatch: true } }, clean: pkg.main, concat: { options: { stripBanners: true, banner: '<%= banner %>' }, js: { src: ['src/angular-busy.js'], dest: 'build/angular-busy.js' } }, uglify: { js: { src: ['build/angular-busy.js'], dest: 'build/angular-busy.min.js', options: { banner: '<%= banner %>', sourceMap: true, sourceMapName: 'build/angular-busy.map' } } } }); grunt.registerTask('test', ['karma:unit']); grunt.registerTask('test-server', ['karma:server']); grunt.registerTask('build', ['clean', 'concat:js', 'uglify']); };
JavaScript
0
@@ -489,16 +489,30 @@ ge.json' +, 'bower.json' %5D,%0A %09%09%09%09
345ffd89f18b7ec9b7d7eba21b06f24318955c0f
Change gruntfile.js
gruntfile.js
gruntfile.js
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-shell-spawn'); grunt.loadNpmTasks('grunt-express-server'); grunt.loadNpmTasks('grunt-casper'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-simple-mocha'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-browserify'); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { source: { files: ['sass/**/*.scss'], tasks: ['sass'], options: { livereload: true } }, express: { files: ['**/*.js'], tasks: ['express:dev'], options: { spawn: false // for grunt-contrib-watch v0.5.0+, "nospawn: true" for lower versions. Without this option specified express won't be reloaded } } }, shell: { mongodb: { command: 'mongod', options: { async: true, stdout: false, stderr: true, //set to false to keep from failing if mongodb already running as can happen when a test fails and stops grunt without stoping the database failOnError: false, execOptions: { cwd: '.' } } } }, express: { options: { port: 8080 }, dev: { options: { script: 'server.js' } }, prod: { options: { script: 'server.js', node_env: 'production' } }, test: { options: { script: 'server.js' } } }, casper: { acceptance: { options: { test: true, }, files: { 'test/acceptance/casper-results.xml': ['test/acceptance/*_test.js'] } } }, simplemocha: { options: { colors: true, globals: ['should'], timeout: 3000, ignoreLeaks: false, ui: 'bdd', reporter: 'tap' }, all: { src: ['test/unit/*.js', 'test/api/*.js'] } }, jshint: { all: ['Gruntfile.js', 'server.js', 'api/models/**/*.js', 'test/**/*.js'], options: { jshintrc: true, globals: { console: true, module: true } } }, concat:{ options: { separator: ';' }, dist: { src: ['app/**/*.js'], dest: 'dist/<%= pkg.name %>.js' } }, clean:{ build: ['build'], prod: ['dist'] }, copy: { prod: { expand: true, cwd: 'app/assets', src: ['css/*.css', '*.html', 'images/**/*' ], dest: 'dist/', flatten: false, filter: 'isFile' }, dev: { expand: true, cwd: 'app/assets', src: ['css/*.css', '*.html', 'images/**/*' ], dest: 'build/', flatten: false, filter: 'isFile' } }, browserify: { prod: { src: ['app/assets/js/*.js'], dest: 'build/browser.js', options: { transform: ['debowerify', 'hbsfy'], debug: true } } } }); //when using watch, all the watch tasks must preceed watch in the registerTask statement grunt.registerTask('default', ['shell:mongodb', 'express:dev', 'watch']); grunt.registerTask('server', ['shell:mongodb', 'express:dev', 'watch']); grunt.registerTask('test', ['jshint', 'shell:mongodb', 'express:dev', 'casper','simplemocha', 'watch']); grunt.registerTask('Ctest', ['concat']); grunt.registerTask('Cltest', ['clean']); grunt.registerTask('build',['clean:build','copy:dev','browserify']); };
JavaScript
0.000002
@@ -3992,24 +3992,65 @@ 'default', %5B +'clean:build', 'copy:dev', 'browserify', 'shell:mongo @@ -4392,16 +4392,17 @@ :build', + 'copy:de @@ -4404,16 +4404,17 @@ py:dev', + 'browser
d84182b9fbd13d297c72312a4322c0c005e00b83
Remove linting from grunt build
gruntfile.js
gruntfile.js
'use strict'; module.exports = function(grunt) { // Unified Watch Object var watchFiles = { serverViews: ['app/views/**/*.*'], serverJS: ['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js'], clientViews: ['public/modules/**/views/**/*.html'], clientJS: ['public/js/*.js', 'public/modules/**/*.js'], clientCSS: ['public/modules/**/*.css'], mochaTests: ['app/tests/**/*.js'] }; // Project Configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { serverViews: { files: watchFiles.serverViews, options: { livereload: true } }, serverJS: { files: watchFiles.serverJS, tasks: ['jshint'], options: { livereload: true } }, clientViews: { files: watchFiles.clientViews, options: { livereload: true, } }, clientJS: { files: watchFiles.clientJS, tasks: ['jshint'], options: { livereload: true } }, clientCSS: { files: watchFiles.clientCSS, tasks: ['csslint'], options: { livereload: true } } }, jshint: { all: { src: watchFiles.clientJS.concat(watchFiles.serverJS), options: { jshintrc: true } } }, csslint: { options: { csslintrc: '.csslintrc', }, all: { src: watchFiles.clientCSS } }, uglify: { production: { options: { mangle: false }, files: { 'public/dist/application.min.js': 'public/dist/application.js' } } }, cssmin: { combine: { files: { 'public/dist/application.min.css': '<%= applicationCSSFiles %>' } } }, nodemon: { dev: { script: 'server.js', options: { nodeArgs: ['--debug'], ext: 'js,html', watch: watchFiles.serverViews.concat(watchFiles.serverJS) } } }, 'node-inspector': { custom: { options: { 'web-port': 1337, 'web-host': 'localhost', 'debug-port': 5858, 'save-live-edit': true, 'no-preload': true, 'stack-trace-limit': 50, 'hidden': [] } } }, ngAnnotate: { production: { files: { 'public/dist/application.js': '<%= applicationJavaScriptFiles %>' } } }, concurrent: { default: ['nodemon', 'watch'], debug: ['nodemon', 'watch', 'node-inspector'], options: { logConcurrentOutput: true, limit: 10 } }, env: { test: { NODE_ENV: 'test' } }, mochaTest: { src: watchFiles.mochaTests, options: { reporter: 'spec', require: 'server.js' } }, karma: { unit: { configFile: 'karma.conf.js' } } }); // Load NPM tasks require('load-grunt-tasks')(grunt); // Making grunt default to force in order not to break the project. grunt.option('force', true); // A Task for loading the configuration object grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() { var init = require('./config/init')(); var config = require('./config/config'); grunt.config.set('applicationJavaScriptFiles', config.assets.js); grunt.config.set('applicationCSSFiles', config.assets.css); }); // Default task(s). grunt.registerTask('default', ['lint', 'concurrent:default']); // Debug task. grunt.registerTask('debug', ['lint', 'concurrent:debug']); // Lint task(s). grunt.registerTask('lint', ['jshint', 'csslint']); // Build task(s). grunt.registerTask('build', ['lint', 'loadConfig', 'ngAnnotate', 'uglify', 'cssmin']); // Test task. grunt.registerTask('test', ['env:test', 'mochaTest']); };
JavaScript
0
@@ -3388,24 +3388,16 @@ uild', %5B -'lint', 'loadCon