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
63328fa4c016936a8dd538bfc92bb5950d53bed3
add timeout of 1 minute
.testem.js
.testem.js
var angularVersion; for(var i=0; i<process.argv.length;i++){ if(process.argv[i].indexOf('--angular-version=') !== -1){ angularVersion = process.argv[i].replace('--angular-version=',''); } } console.log(module.exports); var port; for(var i=0; i<process.argv.length;i++){ if(process.argv[i].indexOf('--port=') !== -1){ port = process.argv[i].replace('--port=',''); } } if(!port) { throw new Error('Port is not defined'); } var angularVersions = [ '1.0.8', '1.2.9', '1.3.11', '1.4.0' ]; var sauceLabsBrowsers = [ // {name: 'internet explorer', version: 11, platform: 'Windows 8.1'}, // {name: 'internet explorer', version: 10, platform: 'Windows 8'}, // {name: 'internet explorer', version: 9, platform: 'Windows 7'}, // {name: 'internet explorer', version: 8, platform: 'Windows XP'}, {name: 'chrome'}, {name: 'firefox'}, {name: 'opera'}, {name: 'safari', version: 8, platform: 'OS X 10.10'}, {name: 'safari', version: 7, platform: 'OS X 10.9'}, {name: 'safari', version: 6, platform: 'OS X 10.8'}, {name: 'iphone', version: '8.1', platform: 'OS X 10.10'}, {name: 'iphone', version: '7.1', platform: 'OS X 10.10'}, {name: 'iphone', version: '6.1', platform: 'OS X 10.8'}, {name: 'android', version: '5.0'}, {name: 'android', version: '4.4'}, {name: 'android', version: '4.3'}, ] var config = { before_tests: './scripts/before_tests', on_exit: 'rm -r .tmp/ || echo "tried cleaning up but could not"', src_files: [ 'src/*.coffee', 'tests/*.coffee' ], launch_in_ci: [], launch_in_dev: [] }; if(!angularVersion) { config.launchers = {}; config.serve_files = []; angularVersions.forEach(function(version){ var key = 'Angular ' + version config.launchers[key] = { command: 'testem ci --port=11'+version.replace(/\./g,'').slice(0,3)+' --file .testem.js -- --angular-version='+version, protocol: 'tap' } config.launch_in_ci.push(key); }); } else { config.launchers = {}; sauceLabsBrowsers.forEach(function(browser){ var key = ['SauceLabs', browser.name, browser.version].join(' '); var command = ['saucie', '--port="'+port+'"'] command.push('--browserNameSL="'+browser.name+'"') if(browser.version){ command.push('--versionSL="'+browser.version+'"') } if(browser.platform){ command.push('--platformSL="'+browser.platform+'"') } config.launchers[key] = { command: command.join(' '), protocol: 'tap' }; config.launch_in_ci.push(key); }); config.serve_files= [ 'bower_components/angular-'+angularVersion+'/angular.js', '.tmp/src/*.js', 'bower_components/angular-mocks-'+angularVersion+'/angular-mocks.js', '.tmp/tests/*.js' ] } console.log(config); module.exports = config;
JavaScript
0.999518
@@ -1520,16 +1520,38 @@ e'%0A %5D,%0A + timeout: 60 * 1000,%0A launch
3ad934e4f115a4c6da212d232e21dc9698fc9ba5
Clear validation messages on switch form (#33)
admin/src/scripts/components/ui/descriptoredit.js
admin/src/scripts/components/ui/descriptoredit.js
require('fileapi'); var backbone = require('backbone'); var backboneBase = require('backbone-base'); var getUri = require('get-uri'); var Goodtables = require('../goodtables'); var jsonEditor = require('json-editor'); var jtsInfer = require('jts-infer'); var highlight = require('highlight-redux'); var UploadView = require('./upload'); var registry = require('./registry'); var _ = require('underscore'); var $ = require('jquery'); // Upload data file and populate .resource array with item DataUploadView = backbone.BaseView.extend({ events: { // Set up and append .resources row 'change [data-id=input]': function(E) { FileAPI.readAsText(FileAPI.getFiles(E.currentTarget)[0], (function (EV) { if(EV.type === 'load') { getUri(['data', EV.target.type, 'utf-8'].join(':') + ',' + EV.result, (function (E, R) { if(E) throw E; jtsInfer(R, (function(E, S, SR) { if(E) throw E; this.options.form.getEditor('root.resources').addRow({ name: EV.target.name, path: EV.target.name, schema: S }); // Save data source _.last(this.options.form.getEditor('root.resources').rows).dataSource = EV.result; }).bind(this)); }).bind(this)); } else if( EV.type ==='progress' ) { this.setProgress(EV.loaded/EV.total * 100); } else { this.setError('File upload failed'); } this.$(E.currentTarget).val(''); }).bind(this)); }, 'click [data-id=upload-data-file]': function() { this.$('[data-id=input]').trigger('click'); } }, render: function() { this.$el .append('<input data-id="input" type="file" accept="text/csv" style="display: none;">') .append( $(this.options.form.theme.getButton('Upload data file', '', 'Upload data file')) .attr('data-id', 'upload-data-file') ); return this; }, setError: function() { return this; }, setProgress: function() { return this; } }); module.exports = { DescriptorEditView: backbone.BaseView.extend({ activate: function(state) { backbone.BaseView.prototype.activate.call(this, state); this.layout.upload.activate(state); return this; }, events: { 'click #validate-resources': function() { var goodTables = new Goodtables({method: 'post'}); // Clear previous this.$('#resources-validation-messages [data-id=messages]').remove(); _.each(this.layout.form.getEditor('root.resources').rows, function(R) { goodTables.run(R.dataSource, JSON.stringify( {fields: _.map(R.schema.properties, function(V, K) { return _.extend(V, {name: K}) })} )).then( function(M) { // Ok window.APP.$('#resources-validation-messages').append( _.map(M.isValid() ? ['Validation Success'] : M.getValidationErrors(), function(M) { return ['<li class="error-message" data-id="messages">', M.result_message, '</li>'].join(''); })); } ); }); } }, initialize: function(options) { highlight.configure({useBR: true}); return backbone.BaseView.prototype.initialize.call(this, options); }, render: function() { this.layout.upload = new UploadView({el: window.APP.$('#upload-data-package'), parent: this}); this.layout.registryList = new registry.ListView({el: window.APP.$('#registry-list'), parent: this}); return this; }, // Utility method to remove empty values from object recursive compactObject: function(data) { _.each(data, function(v, k) { if(_.isEmpty(v)) { delete data[k]; } else if(_.isArray(v) || _.isObject(v)) { v = this.compactObject(v); if(_.isArray(v)) v = _.compact(v); if(_.isEmpty(v)) delete data[k]; else data[k] = v; } }, this); return data; }, getFilledValues: function() { return this.compactObject(this.layout.form.getValue()); }, getValue: function () { return this.layout.form.getValue(); }, hasChanges: function() { return Boolean(this.changed); }, reset: function(schema) { var formData; // Clean up previous state if(this.layout.form) { formData = this.getFilledValues(); this.layout.form.destroy(); this.layout.uploadData.undelegateEvents().remove(); } this.layout.form = new JSONEditor(this.$('[data-id=form-container]').get(0), { schema: schema, theme: 'bootstrap3' }); this.layout.uploadData = (new DataUploadView({ el: this.layout.form.theme.getHeaderButtonHolder(), form: this.layout.form, parent: this })).render(); this.layout.form.on('ready', (function() { // There is no any good way to bind events to custom button or even add cutsom button $(this.layout.form.getEditor('root.resources').container) .children('h3').append(this.layout.uploadData.el); // Detecting changes this.changed = false; // After `ready` event fired, editor fire `change` event regarding to the initial changes this.layout.form.on('change', _.after(2, (function() { this.changed = true; window.APP.layout.download.reset(this.layout.form.getValue()).activate(); this.showResult(); }).bind(this))); // If on the previous form was entered values try to apply it to new form if(formData) { this.layout.form.setValue(_.extend({}, this.layout.form.getValue(formData), formData)); // Expand editors if it have value _.each(this.$('[data-schemapath][data-schemapath!=root]:has(.json-editor-btn-collapse)'), function(E) { if(_.isEmpty(this.layout.form.getEditor($(E).data('schemapath')).getValue())) $(E).find('.json-editor-btn-collapse').click(); }, this); } else // Collapse all this.$('.row .json-editor-btn-collapse').click(); }).bind(this)); }, showResult: function() { $('#json-code').html(highlight.fixMarkup( highlight.highlight('json', JSON.stringify(this.layout.form.getValue(), undefined, 2)).value )); return this; } }) };
JavaScript
0
@@ -2300,24 +2300,169 @@ is;%0A %7D,%0A%0A + clearResourceValidation: function() %7B%0A this.$('#resources-validation-messages %5Bdata-id=messages%5D').remove();%0A return this;%0A %7D,%0A%0A events: @@ -2459,24 +2459,24 @@ events: %7B%0A - 'click @@ -2616,39 +2616,38 @@ this. -$('#r +clearR esource -s-v +V alidation-me @@ -2647,45 +2647,8 @@ tion --messages %5Bdata-id=messages%5D').remove ();%0A @@ -4476,16 +4476,55 @@ mData;%0A%0A + this.clearResourceValidation();%0A%0A //
82c96e1f0f2e935fb7199452551655bc068e30ed
Add day 8 solution part 2
2017/08.js
2017/08.js
// Part 1 R={},document.body.innerText.split`\n`.map(l=>l&&([x,a,y,,z,o,v]=l.split` `,R[x]=(R[x]|0)+y*(a[0]=='i'?1:-1)*eval((R[z]|0)+o+v))),Math.max(...Object.values(R))
JavaScript
0.002756
@@ -163,8 +163,169 @@ ues(R))%0A +%0A// Part 2%0Am=0,R=%7B%7D,document.body.innerText.split%60%5Cn%60.map(l=%3El&&(%5Bx,a,y,,z,o,v%5D=l.split%60 %60,m=Math.max(m,R%5Bx%5D=(R%5Bx%5D%7C0)+y*(a%5B0%5D=='i'?1:-1)*eval((R%5Bz%5D%7C0)+o+v)))),m%0A
4c6e6aeba5bf49bc132b368c8d80035c992598fd
Fix incorrect query in player module
modules/player/models/queueItem.js
modules/player/models/queueItem.js
const { channels } = Core.bot /** * Represents an item in the queue */ class QueueItem { /** * Instantiates a new queue item * @param {object} data * @param {GuildQueue} queue */ constructor (data, queue) { this._d = data this.queue = queue /** * If set to true, a notification will be sent when this element starts playing. * It's set to false after such notification is sent. * @type {boolean} */ this.notify = true /** * If set to true, the stream is considered to have errors and will be skipped by the bot. * @type {boolean} */ this.error = false } /** * Unique identifier * @type {string} */ get uid () { return this._d.uid } /** * Title of the element * @type {string} */ get title () { return this._d.title } set title (v) { this._d.title = v } /** * Length of the element * @type {number} */ get duration () { let duration = this._d.duration if (!duration) return 0 // Transform the duration acording to the filters this.filters.forEach(filter => { if (filter.timeModifier) duration = Core.util.evalExpr(filter.timeModifier, duration) }) return duration } set duration (v) { this._d.duration = parseInt(v) } /** * User that requested the element * @type {Discordie.IGuildMember} */ get requestedBy () { return this.queue.guild.members.find(m => m === this._d.requestedBy) } set requestedBy (v) { this._d.requestedBy = v.id || v } /** * Voice Channel where the element will be played * @type {Discordie.IVoiceChannel} */ get voiceChannel () { return channels.find(c => c.id === this._d.voiceChannel) } set voiceChannel (v) { this._d.voiceChannel = v.id || v } /** * Text Channel where the element was requested * @type {Discordie.ITextChannel} */ get textChannel () { return channels.find(c => m.id === this._d.textChannel) } set textChannel (v) { this._d.textChannel = v.id || v } /** * Volume * @type {number} */ get volume () { return this.queue.player.volume } /** * Filters * @type {AudioFilter[]} */ get filters () { const filters = (this._d.filters || []) // Append volume filter if (this.queue.player.volume !== 1) { return filters.concat({ FFMPEGFilter: `volume=${this.queue.player.volume}`, display: '' }) } return filters } set filters (v) { let time = this.originalTime // Scale the time according to the filters. v.forEach(filter => { if (filter.timeModifier) time = Core.util.evalExpr(filter.timeModifier, time) }) this._d.time = time this._d.filters = v } /** * URL/Path of the file or stream to play * @type {string} */ get path () { return this._d.path } set path (v) { this._d.path = v } /** * URL of the element's source page * @type {string} */ get sauce () { return this._d.sauce } set sauce (v) { this._d.sauce = v } /** * URL of the element's thumbnail picture * @type {string} */ get thumbnail () { return this._d.thumbnail } set thumbnail (v) { this._d.thumbnail = v } /** * Duration of the element, without filters * @type {number} */ get originalDuration () { if (!this._d.duration) return 0 return this._d.duration } /** * Users who voted to skip this element * @type {string[]} */ get voteSkip () { return this._d.voteSkip } /** * Boolean indicating if the element is a radio stream * @type {boolean} */ get radioStream () { return this._d.radioStream } set radioStream (v) { this._d.radioStream = v } /** * Playback status. * * Can be either 'playing', 'paused', 'queue', or 'suspended' * @type {string} */ get status () { return this._d.status } set status (v) { this._d.status = v } /** * Playback position (timestamp) * @type {number} */ get time () { if (!this._d.time) return 0 return this._d.time } set time (v) { this._d.time = parseInt(v) } /** * Playback position (without filters) * @type {number} */ get originalTime () { let time = this._d.time if (!time) return 0 // Transform the time acording to the filters this.filters.forEach(filter => { if (filter.inverseTime) time = Core.util.evalExpr(filter.inverseTime, time) }) return time } /** * FFMPEG Flags (from filters and playback position) * @type {object} */ get flags () { const flags = { input: [], output: [] } const filters = [] // Apply the flags of each filter this.filters.forEach(filter => { if (filter.FFMPEGInputArgs) flags.input = flags.input.concat(filter.FFMPEGInputArgs) if (filter.FFMPEGArgs) flags.output = flags.output.concat(filter.FFMPEGArgs) if (filter.FFMPEGFilter) filters.push(filter.FFMPEGFilter) }) // Append the filters if (filters.length) flags.output.push('-af', filters.join(', ')) // Current Time if (this.originalTime > 0) flags.input.push('-ss', this.originalTime) return flags } /** * True if the item contains static filters * @type {boolean} */ get stat () { // heh return this.filters.filter(filter => filter.avoidRuntime).length } } module.exports = QueueItem
JavaScript
0.014044
@@ -1450,16 +1450,19 @@ d(m =%3E m +.id === thi @@ -1954,25 +1954,25 @@ s.find(c =%3E -m +c .id === this
3ef9ab07dce19af2b4f0b375513308fad158c222
Replace with operator assignment
src/Menu/DelayedItems.js
src/Menu/DelayedItems.js
import PropTypes from 'prop-types'; import React, { Children, cloneElement } from 'react'; import { TRANSITION_DURATION_MS, TRANSITION_SCALE_ADJUSTMENT_Y } from './constants'; const DelayedItems = WrappedComponent => class extends React.PureComponent { static propTypes = { children: PropTypes.node, applyDelays: PropTypes.bool, reverse: PropTypes.bool, }; constructor(props) { super(props); const { children } = this.props; this.state = { children }; } componentWillReceiveProps({ applyDelays: nextApplyDelays, children: nextChildren }) { const { applyDelays, children } = this.props; const isEqualChildren = () => { if (children.length !== nextChildren.length) { return false; } let i = children.length; if (i !== nextChildren.length) return false; while (i > 0) { i = i - 1; if (children[i] !== nextChildren[i]) return false; } return true; }; if (applyDelays !== nextApplyDelays) { this.setState({ children: nextApplyDelays ? this.applyTransitionDelays() : children, }); } else if (!isEqualChildren()) { this.setState({ children: nextChildren }); } } applyTransitionDelays() { const { children, reverse } = this.props; const numItems = Children.count(children); const transitionDuration = TRANSITION_DURATION_MS / 1000; const start = TRANSITION_SCALE_ADJUSTMENT_Y; const delayedChildren = Children.map(children, (child, index) => { let itemDelayFraction; if (reverse) { itemDelayFraction = (numItems - index) / numItems; } else { itemDelayFraction = index / numItems; } const delay = (start + (itemDelayFraction * (1 - start))) * transitionDuration; return cloneElement(child, { delay }); }); return delayedChildren; } render() { const { applyDelays, // eslint-disable-line no-unused-vars children, // eslint-disable-line no-unused-vars reverse, // eslint-disable-line no-unused-vars ...otherProps } = this.props; return ( <WrappedComponent {...this.state} {...otherProps} /> ); } }; export default DelayedItems;
JavaScript
0.999993
@@ -858,13 +858,10 @@ i -= i - += 1;%0A
444ad09a0ecf8d571b2c539182f0e26a20e5f224
improve doc on redux-thunk
frontend/src/actions/action.js
frontend/src/actions/action.js
export const RECEIVED_USER_PROFILE = 'RECEIVED_USER_PROFILE'; export function receivedUserProfile (json) { return { type: RECEIVED_USER_PROFILE, user: json.user } } /** * Action creator fired just before fetching data for a user profile * @type {Function} */ export const REQUESTING_USER_PROFILE = 'REQUESTING_USER_PROFILE'; export function requestingUserProfile () { return { type: REQUESTING_USER_PROFILE, } } /** * Thunk action creator, in order to be able to do async actions * Redux-thunk middleware let us use action creator that returns a function instead * of a plain object. Therefore, the returned function can delay the action dispatches * @return {[fn]} [Promise] */ export function fetchUserProfile(username) { return function (dispatch) { dispatch(requestingUserProfile()); return fetch(`http://localhost:3000/user`) .then(response => response.json()) .then(json => dispatch(receivedUserProfile(json))) .catch(e => console.log('error', e)); } }
JavaScript
0
@@ -510,16 +510,84 @@ actions +.%0A * The redux-thunk middleware let us have access the %60dispatch%60 fn %0A * Redu @@ -732,23 +732,16 @@ lay the -action dispatch @@ -741,17 +741,25 @@ ispatche -s +d action %0A * @ret
c04854697983cae13d1b6627478d56c5a35a891d
Format nested objects as JSON in table view
frontend/src/lib/formatting.js
frontend/src/lib/formatting.js
import d3 from "d3"; import inflection from "inflection"; var precisionNumberFormatter = d3.format(".2r"); var fixedNumberFormatter = d3.format(",.f"); var decimalDegreesFormatter = d3.format(".08f"); export function formatNumber(number) { if (number > -1 && number < 1) { // numbers between 1 and -1 round to 2 significant digits with extra 0s stripped off return precisionNumberFormatter(number).replace(/\.?0+$/, ""); } else { // anything else rounds to at most 2 decimal points return fixedNumberFormatter(d3.round(number, 2)); } } export function formatScalar(scalar) { if (typeof scalar === "number") { return formatNumber(scalar); } else { return String(scalar); } } export function formatCell(value, column) { if (value == undefined) { return null } else if (typeof value === "string") { return value; } else if (typeof value === "number") { if (column && (column.special_type === "latitude" || column.special_type === "longitude")) { return decimalDegreesFormatter(value) } else { return formatNumber(value); } } else { return String(value); } } export function singularize(...args) { return inflection.singularize(...args); } export function capitalize(...args) { return inflection.capitalize(...args); } // Removes trailing "id" from field names export function stripId(name) { return name && name.replace(/ id$/i, ""); }
JavaScript
0.000001
@@ -1166,16 +1166,145 @@ %7D%0A + %7D else if (typeof value === %22object%22) %7B%0A // no extra whitespace for table cells%0A return JSON.stringify(value);%0A %7D el
648aa3d207f91d8e3657261fedff923bcdba04cc
set account id on tokens correctly
api/src/plugins/openid-connect/grants/password.js
api/src/plugins/openid-connect/grants/password.js
module.exports = (options) => ({ params: ['username', 'password'], grantTypeFactory: function passwordGrantTypeFactory(providerInstance) { return async function passwordGrantType(ctx, next) { const { username, password } = ctx.oidc.params; const account = await options.authenticateUser(username, password); if (account) { const { AccessToken, IdToken } = providerInstance; const at = new AccessToken({ accountId: 'foo', clientId: ctx.oidc.client.clientId, grantId: ctx.oidc.uuid, }); const accessToken = await at.save(); const expiresIn = AccessToken.expiresIn; const token = new IdToken( Object.assign({}, await Promise.resolve(account.claims())), ctx.oidc.client.sectorIdentifier ); token.set('at_hash', accessToken); const idToken = await token.sign(ctx.oidc.client); ctx.body = { access_token: accessToken, expires_in: expiresIn, token_type: 'Bearer', id_token: idToken, }; } else { ctx.body = { error: 'invalid_grant', error_description: 'invalid credentials provided', }; } await next(); }; } });
JavaScript
0.000001
@@ -464,13 +464,25 @@ Id: -'foo' +account.accountId ,%0A @@ -868,16 +868,61 @@ sToken); +%0A token.set('sub', account.accountId); %0A%0A
2d2a8191eaec54b0ef0e259fb06eff1b0a54ea83
improve code quality
dev/main.js
dev/main.js
$(function() { let App = require("./App.vue"); new Vue({ el: "body", components: { App } }); });
JavaScript
0.000008
@@ -43,16 +43,26 @@ ue%22);%0A%0A%09 +let app = new Vue(
f1408eef99256a510bece2441a60103460dff706
Fix (very) minor comment typos
lib/common/lib/services/storageserviceclient.js
lib/common/lib/services/storageserviceclient.js
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Module dependencies. var _ = require('underscore'); var util = require('util'); var azureutil = require('../util/util'); var StorageServiceSettings = require('./storageservicesettings'); var ServiceClient = require('./serviceclient'); var Constants = require('../util/constants'); var ServiceClientConstants = require('./serviceclientconstants'); var HeaderConstants = Constants.HeaderConstants; var QueryStringConstants = Constants.QueryStringConstants; /** * Creates a new ServiceClient object. * * @constructor * @param {string} storageAccount The storage account. * @param {string} storageAccessKey The storage access key. * @param {string} host The host for the service. * @param {bool} usePathStyleUri Boolean value indicating wether to use path style uris. * @param {object} authenticationProvider The authentication provider object (e.g. sharedkey / sharedkeytable / sharedaccesssignature). */ function StorageServiceClient(storageAccount, storageAccessKey, host, usePathStyleUri, authenticationProvider) { this._setAccountCredentials(storageAccount, storageAccessKey); this.apiVersion = HeaderConstants.TARGET_STORAGE_VERSION; this.usePathStyleUri = usePathStyleUri; StorageServiceClient['super_'].call(this, host, authenticationProvider); this._initDefaultFilter(); } util.inherits(StorageServiceClient, ServiceClient); // Validation error messages StorageServiceClient.incorrectStorageAccountErr = 'You must supply an account name or use the environment variable AZURE_STORAGE_ACCOUNT if you are not running in the emulator.'; StorageServiceClient.incorrectStorageAccessKeyErr = 'You must supply an account key or use the environment variable AZURE_STORAGE_ACCESS_KEY if you are not running in the emulator.'; /** * Gets the storage settings. * * @param {string} [storageAccountOrConnectionString] The storage account or the connection string. * @param {string} [storageAccessKey] The storage access key. * @param {string} [host] The host address. * * @return {StorageServiceSettings} */ StorageServiceClient.getStorageSettings = function (storageAccountOrConnectionString, storageAccessKey, host) { var storageServiceSettings; if (_.isString(storageAccountOrConnectionString) && !storageAccessKey) { // If storageAccountOrConnectionString was passed and no accessKey was passed, assume connection string storageServiceSettings = StorageServiceSettings.createFromConnectionString(storageAccountOrConnectionString); } else if (!(storageAccountOrConnectionString && storageAccessKey) && ServiceClient.isEmulated()) { // Dev storage scenario storageServiceSettings = StorageServiceSettings.getDevelopmentStorageAccountSettings(); } else if (storageAccountOrConnectionString && storageAccessKey) { storageServiceSettings = StorageServiceSettings.createExplicitlyOrFromEnvironment(storageAccountOrConnectionString, storageAccessKey, host); } else { storageServiceSettings = StorageServiceSettings.createFromConfig(storageAccountOrConnectionString); } return storageServiceSettings; }; /** * Builds the request options to be passed to the http.request method. * * @param {WebResource} webResource The webresource where to build the options from. * @param {object} options The request options. * @param {function(error, requestOptions)} callback The callback function. * @return {undefined} */ StorageServiceClient.prototype._buildRequestOptions = function (webResource, body, options, callback) { webResource.withHeader(HeaderConstants.STORAGE_VERSION_HEADER, this.apiVersion); webResource.withHeader(HeaderConstants.DATE_HEADER, new Date().toUTCString()); webResource.withHeader(HeaderConstants.ACCEPT_HEADER, 'application/atom+xml,application/xml'); webResource.withHeader(HeaderConstants.ACCEPT_CHARSET_HEADER, 'UTF-8'); if (options) { if (options.timeoutIntervalInMs) { webResource.withQueryOption(QueryStringConstants.TIMEOUT, options.timeoutIntervalInMs); } if (options.accessConditions) { webResource.withHeaders(options.accessConditions, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_NONE_MATCH, HeaderConstants.IF_UNMODIFIED_SINCE); } if (options.sourceAccessConditions) { webResource.withHeaders(options.sourceAccessConditions, HeaderConstants.SOURCE_IF_MATCH_HEADER, HeaderConstants.SOURCE_IF_MODIFIED_SINCE_HEADER, HeaderConstants.SOURCE_IF_NONE_MATCH_HEADER, HeaderConstants.SOURCE_IF_UNMODIFIED_SINCE_HEADER); } } StorageServiceClient['super_'].prototype._buildRequestOptions.call(this, webResource, body, options, callback); }; /** * Retrieves the normalized path to be used in a request. * This takes into consideration the usePathStyleUri object field * which specifies if the request is against the emulator or against * the live service. It also adds a leading "/" to the path in case * it's not there before. * * @param {string} path The path to be normalized. * @return {string} The normalized path. */ StorageServiceClient.prototype._getPath = function (path) { if (path === null || path === undefined) { path = '/'; } else if (path.indexOf('/') !== 0) { path = '/' + path; } if (this.usePathStyleUri) { path = '/' + this.storageAccount + path; } return path; }; /** * Sets the account credentials taking into consideration the isEmulated value and the environment variables: * AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY. * * @param {string} storageAccount The storage account. * @param {string} storageAccessKey The storage access key. * @return {undefined} */ StorageServiceClient.prototype._setAccountCredentials = function (storageAccount, storageAccessKey) { if (azureutil.objectIsNull(storageAccount)) { if (process.env[ServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_ACCOUNT]) { storageAccount = process.env[ServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_ACCOUNT]; } else if (ServiceClient.isEmulated()) { storageAccount = ServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT; } } if (azureutil.objectIsNull(storageAccessKey)) { if (process.env[ServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY]) { storageAccessKey = process.env[ServiceClient.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY]; } else if (ServiceClient.isEmulated()) { storageAccessKey = ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY; } } if (!azureutil.objectIsString(storageAccount) || azureutil.stringIsEmpty(storageAccount)) { throw new Error(StorageServiceClient.incorrectStorageAccountErr); } if (!azureutil.objectIsString(storageAccessKey) || azureutil.stringIsEmpty(storageAccessKey)) { throw new Error(StorageServiceClient.incorrectStorageAccessKeyErr); } this.storageAccount = storageAccount; this.storageAccessKey = storageAccessKey; }; module.exports = StorageServiceClient;
JavaScript
0.000047
@@ -1419,16 +1419,17 @@ cating w +h ether to @@ -1448,11 +1448,11 @@ yle -uri +URI s.%0A*
6dd530e2a4b8bb2ebd8d143329b4fa0a6ba833be
Comment getEmailPusher
src/UserSettingsStore.js
src/UserSettingsStore.js
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var q = require("q"); var MatrixClientPeg = require("./MatrixClientPeg"); var Notifier = require("./Notifier"); /* * TODO: Make things use this. This is all WIP - see UserSettings.js for usage. */ module.exports = { loadProfileInfo: function() { var cli = MatrixClientPeg.get(); return cli.getProfileInfo(cli.credentials.userId); }, saveDisplayName: function(newDisplayname) { return MatrixClientPeg.get().setDisplayName(newDisplayname); }, loadThreePids: function() { if (MatrixClientPeg.get().isGuest()) { return q({ threepids: [] }); // guests can't poke 3pid endpoint } return MatrixClientPeg.get().getThreePids(); }, saveThreePids: function(threePids) { // TODO }, getEnableNotifications: function() { return Notifier.isEnabled(); }, setEnableNotifications: function(enable) { if (!Notifier.supportsDesktopNotifications()) { return; } Notifier.setEnabled(enable); }, getEnableAudioNotifications: function() { return Notifier.isAudioEnabled(); }, setEnableAudioNotifications: function(enable) { Notifier.setAudioEnabled(enable); }, changePassword: function(old_password, new_password) { var cli = MatrixClientPeg.get(); var authDict = { type: 'm.login.password', user: cli.credentials.userId, password: old_password }; return cli.setPassword(authDict, new_password); }, getEmailPusher: function(pushers, address) { if (pushers === undefined) { return undefined; } for (var i = 0; i < pushers.length; ++i) { if (pushers[i].kind == 'email' && pushers[i].pushkey == address) { return pushers[i]; } } return undefined; }, hasEmailPusher: function(pushers, address) { return this.getEmailPusher(pushers, address) !== undefined; }, addEmailPusher: function(address) { return MatrixClientPeg.get().setPusher({ kind: 'email', app_id: "m.email", pushkey: address, app_display_name: 'Email Notifications', device_display_name: address, lang: navigator.language, data: {}, append: true, // We always append for email pushers since we don't want to stop other accounts notifying to the same email address }); }, };
JavaScript
0
@@ -2153,32 +2153,284 @@ sword);%0A %7D,%0A%0A + /**%0A * Returns the email pusher (pusher of type 'email') for a given%0A * email address. Email pushers all have the same app ID, so since%0A * pushers are unique over (app ID, pushkey), there will be at most%0A * one such pusher.%0A */%0A getEmailPush
ed0380ea909378e07cb8b23709657c2327599b51
Add info to page
Display/JquerySample/jquery-demo.js
Display/JquerySample/jquery-demo.js
// Highlight correct nav item $('.active').removeClass(); $('.third-item').addClass('active'); //Get Schedules and set up table var scheduleData = JSON.stringify(false); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { var jsonResponse = JSON.parse(this.responseText); for (i = 0; i < jsonResponse.length; i++) { if (i < 6){ if(i == 0) { $('.nav-tabs').append( '<li class="active"><a data-toggle="tab" href="#' + i + '">' + jsonResponse[i].name + '</a></li>' ); if (jsonResponse[i].description== undefined){ $('.tab-content').append( '<div id="' + i + '" class="tab-pane fade in active">'+ '<blockquote class="small">This schedule does not have a description.</blockquote>' + '<h4>Events</h4>' + '</div>' ); }else{ $('.tab-content').append( '<div id="' + i + '" class="tab-pane fade in active">'+ '<blockquote>' + jsonResponse[i].description + '</blockquote>' + '<h4>Events</h4>' + '</div>' ); } } else { $('.nav-tabs').append( '<li><a data-toggle="tab" href="#' + i + '">' + jsonResponse[i].name + '</a></li>' ); if (jsonResponse[i].description== undefined){ $('.tab-content').append( '<div id="' + i + '" class="tab-pane fade">' + '<blockquote class="small">This schedule does not have a description.</blockquote>' + '<h4>Events</h4>' + '</div>' ); }else{ $('.tab-content').append( '<div id="' + i + '" class="tab-pane fade">' + '<blockquote>' + jsonResponse[i].description + '</blockquote>' + '<h4>Events</h4>' + '</div>' ); } } }else { break; } // Get events for each schedule var scheduleMedia = JSON.stringify(false); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === this.DONE) { var scheduleDetails = JSON.parse(this.responseText); var index = $("a:contains(" + scheduleDetails.name + ")").attr('href').charAt(1); if (scheduleDetails.events.length != 0){ for (x=0; x < scheduleDetails.events.length; x++){ console.log(scheduleDetails.events[x]); $('#' + index).append( // '<p>' + (x + 1) + '. ' + scheduleDetails.events[x].name + '</p>' + // '<p>' + scheduleDetails.events[x].when.startDate + '</p>' '<div class="list-group">' + '<div class="list-group-item">' + '<h5 class="list-group-item-heading">'+ (x + 1) + '. ' + scheduleDetails.events[x].name + '</h5>' + '<p class="list-group-item-text">' + scheduleDetails.events[x].when.startDate + '</p>' + '</div>' + '</div>' ); } }else if (scheduleDetails.events.length == 0){ $('#' + index).append( '<p class="small">This schedule does not have any events!</p>' ); } } }); xhr.open("GET", "https://api.whenhub.com/api/schedules/" + jsonResponse[i].id + "?filter%5Binclude%5D%5Bevents%5D=media&filter%5Binclude%5D=media"); // Replace "ACCESS_TOKEN" with your personal one xhr.setRequestHeader("authorization", "3hLISQYAANWsxUSSMbmRGT8ypbVA9L6lrrU8nnCNvfadaKYEuOnLtAENlv0h8MVz"); xhr.send(scheduleMedia); } } }); xhr.open("GET", "https://api.whenhub.com/api/users/me/schedules"); xhr.setRequestHeader("authorization", "3hLISQYAANWsxUSSMbmRGT8ypbVA9L6lrrU8nnCNvfadaKYEuOnLtAENlv0h8MVz"); xhr.send(scheduleData);
JavaScript
0
@@ -3553,16 +3553,28 @@ m-text%22%3E +Start Date: ' + sche @@ -3613,32 +3613,199 @@ Date + '%3C/p%3E' +%0A + '%3Cp class=%22list-group-item-text%22%3ENumber of media items: ' + scheduleDetails.events%5Bx%5D.media.length + '%3C/p%3E' +%0A %0A
b876a080940f0ced86fe70c6b3f8d3436d9dd3e0
Reduce duplication in test
src/modules/__tests__/api.js
src/modules/__tests__/api.js
import reducer, * as actions from '../api'; import serialize from '../../serialize'; describe('API module', () => { describe('Action Creators', () => { const resource = { type: 'widgets' }; const params = { foo: 'bar' }; const headers = { lorem: 'ipsum' }; const meta = { auth: true }; describe('get', () => { it('creates an GET request', () => { expect(actions.get(resource, { params, headers, meta })).toEqual({ type: actions.GET, payload: { params, headers, resource: serialize(resource), }, meta, }); }); }); describe('post', () => { it('creates a POST request', () => { expect(actions.post(resource, { params, headers, meta })).toEqual({ type: actions.POST, payload: { params, headers, resource: serialize(resource), }, meta, }); }); }); describe('put', () => { it('creates a PUT request', () => { expect(actions.put(resource, { params, headers, meta })).toEqual({ type: actions.PUT, payload: { params, headers, resource: serialize(resource), }, meta, }); }); }); describe('patch', () => { it('creates a PATCH request', () => { expect(actions.patch(resource, { params, headers, meta })).toEqual({ type: actions.PATCH, payload: { params, headers, resource: serialize(resource), }, meta, }); }); }); describe('del', () => { it('creates a DELETE request', () => { expect(actions.del(resource, { params, headers, meta })).toEqual({ type: actions.DELETE, payload: { params, headers, resource: serialize(resource), }, meta, }); }); }); describe('receive', () => { it('creates a RECEIVE action', () => { expect(actions.receive([resource])).toEqual({ type: actions.RECEIVE, payload: { resources: [resource], }, }); }); }); }); describe('Reducer', () => { it('returns the initial state', () => { expect(reducer(undefined, {})).toEqual({}); }); describe('handles RECEIVE', () => { it('by adding resources to their buckets', () => { const resources = [{ id: 1, type: 'widgets', attributes: { name: 'Widget #1', }, }, { id: 1, type: 'gadgets', attributes: { name: 'Gadget #1', }, }]; expect(reducer(undefined, actions.receive(resources))).toEqual({ widgets: { 1: resources[0], }, gadgets: { 1: resources[1], }, }); }); }); }); });
JavaScript
0.999151
@@ -307,1026 +307,157 @@ -describe('get', () =%3E %7B%0A it('creates an GET request', () =%3E %7B%0A expect(actions.get(resource, %7B params, headers, meta %7D)).toEqual(%7B%0A type: actions.GET,%0A payload: %7B%0A params,%0A headers,%0A resource: serialize(resource),%0A %7D,%0A meta,%0A %7D);%0A %7D);%0A %7D);%0A%0A describe('post', () =%3E %7B%0A it('creates a POST request', () =%3E %7B%0A expect(actions.post(resource, %7B params, headers, meta %7D)).toEqual(%7B%0A type: actions.POST,%0A payload: %7B%0A params,%0A headers,%0A resource: serialize(resource),%0A %7D,%0A meta,%0A +const methods = %7B 'get': 'GET', 'post': 'POST', 'put': 'PUT', 'patch': 'PATCH', 'del': 'DELETE' %7D -) ;%0A - %7D);%0A %7D);%0A%0A describe('put', () =%3E %7B%0A it('creates a PUT request', () =%3E %7B%0A expect(actions.put(resource, %7B params, headers, meta %7D)).toEqual(%7B%0A type: actions.PUT,%0A payload: %7B%0A params,%0A headers,%0A resource: serialize(resource),%0A %7D,%0A meta,%0A %7D);%0A %7D);%0A %7D);%0A%0A +%0A Object.keys(methods).forEach((method) =%3E %7B%0A @@ -465,23 +465,22 @@ escribe( -'patch' +method , () =%3E @@ -479,36 +479,38 @@ , () =%3E %7B%0A + it( -' +%60 creates a PATCH @@ -506,22 +506,36 @@ es a - PATCH +n $%7Bmethods%5Bmethod%5D%7D request ', ( @@ -522,33 +522,33 @@ method%5D%7D request -' +%60 , () =%3E %7B%0A @@ -533,32 +533,34 @@ quest%60, () =%3E %7B%0A + expect(a @@ -569,14 +569,16 @@ ions -.patch +%5Bmethod%5D (res @@ -624,32 +624,34 @@ ual(%7B%0A + type: actions.PA @@ -651,16 +651,29 @@ ions -.PATCH,%0A +%5Bmethods%5Bmethod%5D%5D,%0A @@ -697,32 +697,34 @@ + params,%0A @@ -703,32 +703,34 @@ params,%0A + head @@ -726,32 +726,34 @@ headers,%0A + reso @@ -793,371 +793,44 @@ -%7D,%0A meta,%0A %7D);%0A %7D);%0A %7D);%0A%0A describe('del', () =%3E %7B%0A it('creates a DELETE request', () =%3E %7B%0A expect(actions.del(resource, %7B params, headers, meta %7D)).toEqual(%7B%0A type: actions.DELETE,%0A payload: %7B%0A params,%0A headers,%0A resource: serialize(resource),%0A %7D,%0A meta, + %7D,%0A meta,%0A %7D); %0A
47d4d43c7c7130e2a8f3eedab6eecb9da58b80d9
add items for bindable multiple with separate function
src/mvc/bindable/Multiple.js
src/mvc/bindable/Multiple.js
Ext.define('Densa.mvc.bindable.Multiple', { extend: 'Densa.mvc.bindable.Abstract', items: null, panel: null, //optional init: function() { if (this.panel && !(this.panel instanceof Ext.panel.Panel)) Ext.Error.raise('panel config needs to be a Ext.panel.Panel'); if (!this.items) Ext.Error.raise('items config is required'); if (!(this.items instanceof Array)) Ext.Error.raise('items config needs to be an array'); if (this.items.length < 1) Ext.Error.raise('items config length needs to be >0'); for (var i=0; i<this.items.length; i++) { if (!this.items[i].isBindableController) { this.items[i] = this.items[i].getController(); } if (!this.items[i].isBindableController) { Ext.Error.raise('item is not a bindableController'); } } Ext.each(this.items, function(i) { i.on('savesuccess', function() { this.fireEvent('savesuccess'); }, this); }, this); }, load: function(row, store) { Ext.each(this.items, function(i) { i.load(row, store); }, this); }, reset: function() { Ext.each(this.items, function(i) { i.reset(); }, this); }, isDirty: function() { var ret = false; Ext.each(this.items, function(i) { if (i.isDirty()) { ret = true; return false; } }, this); return ret; }, isValid: function() { var ret = true; Ext.each(this.items, function(i) { if (!i.isValid()) { ret = false; return false; } }, this); return ret; }, save: function(syncQueue) { Ext.each(this.items, function(i) { i.save(syncQueue); }, this); }, getLoadedRecord: function() { return this.items[0].getLoadedRecord(); }, enable: function() { if (this.panel) this.panel.enable(); Ext.each(this.items, function(i) { i.enable(); }, this); }, disable: function() { if (this.panel) this.panel.disable(); Ext.each(this.items, function(i) { i.disable(); }, this); }, getPanel: function() { return this.panel; }, onAdd: function() { var ret = false; Ext.each(this.items, function(i) { if (i.onAdd()) { ret = true; return false; } }, this); return ret; }, allowDelete: function() { var ret = this.callParent(arguments); Ext.each(this.items, function(i) { ret = ret.then(function() { return i.allowDelete() }); }, this); return ret; }, allowSave: function() { var ret = this.callParent(arguments); Ext.each(this.items, function(i) { ret = ret.then(function() { return i.allowSave() }); }, this); return ret; } });
JavaScript
0
@@ -539,24 +539,81 @@ to be %3E0');%0A + var items = this.items;%0A this.items = %5B%5D;%0A for @@ -624,21 +624,16 @@ i=0; i%3C -this. items.le @@ -657,34 +657,109 @@ -if (!this.items%5Bi%5D +this.addItem(items%5Bi%5D);%0A %7D%0A %7D,%0A%0A addItem: function(item)%0A %7B%0A if (!item .isBinda @@ -791,41 +791,19 @@ - this.items%5Bi%5D = this.items%5Bi%5D +item = item .get @@ -812,28 +812,24 @@ ntroller();%0A - %7D%0A @@ -838,30 +838,17 @@ - if (! -this.items%5Bi%5D +item .isB @@ -860,36 +860,32 @@ leController) %7B%0A - Ext. @@ -933,36 +933,32 @@ ller');%0A - %7D%0A %7D%0A @@ -955,66 +955,12 @@ -%7D%0A Ext.each(this.items, function(i) %7B%0A i +item .on( @@ -995,28 +995,24 @@ - - this.fireEve @@ -1034,28 +1034,24 @@ ');%0A - %7D, this);%0A @@ -1048,31 +1048,45 @@ this);%0A +%0A - %7D, this +.items.push(item );%0A %7D
d81feda4d1e8a09156cc95530cd3d67fa5c588c1
queue name will be node_js
app/assets/javascripts/app/controllers/sidebar.js
app/assets/javascripts/app/controllers/sidebar.js
Travis.Controllers.Sidebar = SC.Object.extend({ cookie: 'sidebar_minimized', init: function() { Travis.Controllers.Workers.create(); Travis.Controllers.Jobs.create({ queue: 'builds.common' }); Travis.Controllers.Jobs.create({ queue: 'builds.rails' }); Travis.Controllers.Jobs.create({ queue: 'builds.erlang' }); Travis.Controllers.Jobs.create({ queue: 'builds.php' }); Travis.Controllers.Jobs.create({ queue: 'builds.node' }); $(".slider").click(function() { this.toggle(); }.bind(this)); if($.cookie(this.cookie) === 'true') { this.minimize(); } this.persist(); }, toggle: function() { this.isMinimized() ? this.maximize() : this.minimize(); this.persist(); }, isMinimized: function() { return $('#right').hasClass('minimized'); }, minimize: function() { $('#right').addClass('minimized'); $('#main').addClass('maximized'); }, maximize: function() { $('#right').removeClass('minimized'); $('#main').removeClass('maximized'); }, persist: function() { $.cookie(this.cookie, this.isMinimized()); } });
JavaScript
0.999998
@@ -444,16 +444,19 @@ lds.node +_js ' %7D);%0A%0A
8105f42c6b3ef5cf2d511d1a54b8f2fe7adab5fe
Improve router logic.
public/app/util/router.js
public/app/util/router.js
(function () { 'use strict'; define( [ 'lodash', 'knockout', 'page' ], function (_, ko, page) { var runHook, attach, current, applicationContainer = document.getElementById('application-container'); // Run the given named hook for the given vm. runHook = function (vm, hook, container, callback) { if (_.isFunction(vm[hook])) { return vm[hook](container, callback); } callback(); }; // Attach the view and view model specified by paths, using the given router context. attach = function (viewPath, viewModelPath, context) { var container, vm, _attach; _attach = function () { runHook(vm, 'attaching', container, function () { applicationContainer.innerHTML = ''; applicationContainer.appendChild(container); runHook(vm, 'binding', container, function () { ko.applyBindings(vm, container); runHook(vm, 'ready', container, function () { current = { vm: vm, container: container }; }); }); }); }; require([ 'text!' + viewPath + '.html', viewModelPath ], function (view, ViewModel) { container = document.createElement('div'); container.innerHTML = view; vm = new ViewModel(context); if (current) { return runHook(current.vm, 'detaching', current.container, _attach); } _attach(); }); }; // Configure and start the router. return function () { page('/', function (context) { return attach('ui/page/home', 'ui/page/Page', context); }); page('/about', function (context) { return attach('ui/page/about', 'ui/page/Page', context); }); page('/:type/search/:query?', function (context) { switch (context.params.type) { case 'library': return attach('ui/search/library', 'ui/search/Search', context); case 'photographs': return attach('ui/search/photographs', 'ui/search/Search', context); case 'museum': return attach('ui/search/museum', 'ui/search/Search', context); case 'memorials': return attach('ui/search/memorials', 'ui/search/Search', context); default: return attach('ui/error/404', 'ui/error/Error', context); } }); page('/:type/detail/:id', function (context) { switch (context.params.type) { case 'library': return attach('ui/detail/library', 'ui/detail/Detail', context); case 'photographs': return attach('ui/detail/photographs', 'ui/detail/Detail', context); case 'museum': return attach('ui/detail/museum', 'ui/detail/Detail', context); case 'memorials': return attach('ui/detail/memorials', 'ui/detail/Detail', context); default: return attach('ui/error/404', 'ui/error/Error', context); } }); page('*', function (context) { return attach('ui/error/404', 'ui/error/Error', context); }); page.start(); }; } ); }());
JavaScript
0.000001
@@ -409,24 +409,71 @@ callback) %7B%0A + callback = callback %7C%7C _.noop;%0A @@ -1241,230 +1241,48 @@ -runHook(vm, 'ready', container, function () %7B%0A current = %7B%0A vm: vm,%0A container: container%0A +current = %7B vm: vm, container: container %7D;%0A @@ -1301,33 +1301,62 @@ -%7D +runHook(vm, 'ready', container );%0A
cda1c36edef8a65f482b51b30f76a23a0e807d18
Convert manchester line names to more sensible names
src/adapters/helsinki.js
src/adapters/helsinki.js
import _ from 'lodash'; import moment from 'moment'; import ajax from '../ajax'; const id = 'helsinki'; const name = 'Helsinki'; const latitude = 60.200763; const longitude = 24.936219; const apiUrl = 'http://dev.hsl.fi/siriaccess/vm/json'; function fetch() { return ajax(apiUrl).then(_transform); } function _transform(data) { const vehicles = data.Siri.ServiceDelivery.VehicleMonitoringDelivery[0].VehicleActivity; return _.map(vehicles, _transformVehicle.bind(this, data)); } function _transformVehicle(data, vehicle) { var journey = vehicle.MonitoredVehicleJourney; // XXX: The vehicle type information is already in the lines json var routeInfo = _interpretJore(journey.LineRef.value); var lineName = routeInfo[2]; var vehicleType = routeInfo[0].toLowerCase(); return { id: journey.VehicleRef.value, type: vehicleType, line: lineName, latitude: journey.VehicleLocation.Latitude, longitude: journey.VehicleLocation.Longitude, rotation: journey.Bearing || 0, responseTime: moment(data.Siri.ServiceDelivery.ResponseTimestamp).toISOString() }; } /*eslint-disable */ // jscs:disable // From http://dev.hsl.fi/: // (Values of lineRef are "JORE codes" and can be converted to passenger-friendly line numbers using the interpret_jore example code.) // (lineRef query parameter can be added to limit the response to that single "JORE code".) // This function was automatically converted from coffeescript to js, from // https://github.com/HSLdevcom/navigator-proto/blob/master/src/routing.coffee function _interpretJore(routeId) { var mode, ref, ref1, ref2, ref3, ref4, ref5, ref6, route, routeType; if (routeId != null ? routeId.match(/^1019/) : void 0) { ref1 = ["FERRY", 4, "Ferry"], mode = ref1[0], routeType = ref1[1], route = ref1[2]; } else if (routeId != null ? routeId.match(/^1300/) : void 0) { ref2 = ["SUBWAY", 1, routeId.substring(4, 5)], mode = ref2[0], routeType = ref2[1], route = ref2[2]; } else if (routeId != null ? routeId.match(/^300/) : void 0) { ref3 = ["TRAIN", 2, routeId.substring(4, 5)], mode = ref3[0], routeType = ref3[1], route = ref3[2]; } else if (routeId != null ? routeId.match(/^10(0|10)/) : void 0) { ref4 = ["TRAM", 0, routeId.replace(/^.0*/, "")], mode = ref4[0], routeType = ref4[1], route = ref4[2]; } else if (routeId != null ? routeId.match(/^(1|2|4).../) : void 0) { ref5 = ["BUS", 3, routeId.replace(/^.0*/, "")], mode = ref5[0], routeType = ref5[1], route = ref5[2]; } else { ref6 = ["BUS", 3, routeId], mode = ref6[0], routeType = ref6[1], route = ref6[2]; } return [mode, routeType, route]; } // jscs:enable /*eslint-enable */ export { id, name, latitude, longitude, fetch };
JavaScript
1
@@ -742,24 +742,380 @@ uteInfo%5B2%5D;%0A + if (_.startsWith(lineName, 'GMN:')) %7B%0A // Helsinki data contains some Manchester vehicles also,%0A // they are prefixed with a special name.%0A // Try to make the line name sensible%0A const parts = lineName.split('GMN:');%0A if (parts.length %3E 1) %7B%0A lineName = parts%5B1%5D.replace(/:/g, '').trim();%0A %7D%0A %7D%0A%0A var vehi @@ -1229,16 +1229,25 @@ icleType + %7C%7C 'bus' ,%0A
62055fbb0041b0d98675d2d421ecb9813b519b17
Change autocomplete plugin to search box plugin, it allows us to use the enter key
app/assets/javascripts/map/views/SearchboxView.js
app/assets/javascripts/map/views/SearchboxView.js
/** * The Searchbox module. * * @return searchbox class (extends Backbone.View). */ define([ 'underscore', 'backbone', 'handlebars', 'map/views/Widget', 'map/presenters/SearchboxPresenter', 'text!map/templates/searchbox.handlebars' ], function(_, Backbone, Handlebars, Widget, Presenter, tpl) { 'use strict'; var Searchbox = Widget.extend({ className: 'widget widget-searchbox', template: Handlebars.compile(tpl), initialize: function() { _.bindAll(this, 'setAutocomplete', 'onPlaceSelected'); this.presenter = new Presenter(this); Searchbox.__super__.initialize.apply(this); this.setAutocomplete(); }, setAutocomplete: function() { this.autocomplete = new google.maps.places.SearchBox(this.$el.find('input')[0]); google.maps.event.addListener(this.autocomplete, 'places_changed', this.onPlaceSelected); }, onPlaceSelected: function() { var place = this.autocomplete.getPlaces(); if (place.length == 1) { place = place[0]; if (place && place.geometry && place.geometry.viewport) { this.presenter.fitBounds(place.geometry.viewport); } // TODO: When there isn't viewport, and there is location... if (place && place.geometry && place.geometry.location && !place.geometry.viewport) { console.log(place.geometry.location); this.presenter.setCenter(place.geometry.location.k,place.geometry.location.B); } }; ga('send', 'event', 'Map', 'Searchbox', 'Find location'); } }); return Searchbox; });
JavaScript
0
@@ -1339,56 +1339,8 @@ ) %7B%0A - console.log(place.geometry.location);%0A
50a79674d5a0d45da2aa47076b88b8ddf8488061
Support setting user's 'more.lang' property
src/api/db/validators.js
src/api/db/validators.js
/* This file is a part of libertysoil.org website Copyright (C) 2015 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import difference from 'lodash/difference'; import uniq from 'lodash/uniq'; export const User = { registration: { username: [ 'required', 'maxLength:31', { rule: (val) => { if (!val.match(/^(?!.*\.{2})[a-z0-9\-\_\'\.]+$/i)) { throw new Error("Username can contain letters a-z, numbers 0-9, dashes (-), underscores (_), apostrophes (\'), and periods (.)"); } } }], password: [ 'required', { rule: (val) => { if (!val.match(/^[\x20-\x7E]{8,}$/)) { throw new Error("Password is min. 8 characters. Password can only have ascii characters."); } } } ], firstName: [ ], lastName: [ ], // email: ['email', 'required'] email: [ 'required', { rule: (val) => { if (!val.match(/^[a-z0-9!#$%&"'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i)) { throw new Error('The email must be a valid email address'); } } } ] }, settings: { base: { }, more: { summary: ['string'], bio: ['string'], roles: ['array'], first_login: ['boolean'], avatar: ['plainObject'], head_pic: ['plainObject'], mute_all_posts: ['boolean'], firstName: ['string'], lastName: ['string'] } } }; export const School = { more: { head_pic: ['plainObject'], last_editor: ['string'] } }; export const Geotag = { more: { description: ['string'], last_editor: ['string'] } }; export const Hashtag = { more: { description: ['string'], head_pic: ['plainObject'], last_editor: ['string'] } }; export const UserMessage = { text: ['string', 'minLength:1', 'required'] }; export const ProfilePost = { text: ['string', 'maxLength:200'], html: ['string'], type: [ 'required', val => { if (!ProfilePost.TYPES.includes(val)) { throw new Error('Invalid post type'); } } ], user_id: ['required', 'uuid'], more: ['plainObject'] }; ProfilePost.TYPES = [ 'text', 'head_pic', 'avatar' ]; const SEARCH_RESULT_TYPES = [ 'hashtags', 'locations', 'posts', 'people', 'schools' ]; const SORTING_TYPES = [ '-q', '-updated_at' ]; export const SearchQuery = { limit: ['integer', 'natural'], offset: ['integer', 'natural'], show: { rule: val => { if (val) { if (typeof val === 'string') { if (val !== 'all' && !SEARCH_RESULT_TYPES.includes(val)) { throw new Error('Unsupported type of search result'); } } else if (Array.isArray(val)) { const unique = uniq(val); if (unique.length > 1 && unique.includes('all')) { throw new Error('Ambiguity between "all" and explicit type of search results'); } else if (difference(unique, SEARCH_RESULT_TYPES).length > 0) { throw new Error('At least one of presented search result types is unsupported'); } } else { throw new Error('Type of search results is expected to be a string or an array'); } } } }, sort: ['string', val => { if (val && !SORTING_TYPES.includes(val)) { throw new Error('Invalid search sorting type'); } }], q: ['string'] };
JavaScript
0
@@ -824,16 +824,116 @@ uniq';%0A%0A +const SUPPORTED_LOCALES = Object.keys(%0A require('../../consts/localization').SUPPORTED_LOCALES%0A);%0A%0A export c @@ -2266,16 +2266,229 @@ string'%5D +,%0A lang: %7B%0A rule: val =%3E %7B%0A if (val) %7B%0A if (!SUPPORTED_LOCALES.includes(val)) %7B%0A throw new Error('Locale isn%5C't supported');%0A %7D%0A %7D%0A %7D%0A %7D %0A %7D%0A
790c4c193708a0c0feed3e53ad350d739a9fbbec
Remove accidental commit of my local mapnik layer.
public/javascripts/map.js
public/javascripts/map.js
var map; var markers; var popup; OpenLayers._getScriptLocation = function () { return "/openlayers/"; } function createMap(divName) { map = new OpenLayers.Map(divName, { controls: [ new OpenLayers.Control.ArgParser(), new OpenLayers.Control.Attribution(), new OpenLayers.Control.LayerSwitcher(), new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar() ] }); var mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik", { displayOutsideMaxExtent: true, wrapDateLine: true }); map.addLayer(mapnik); var osmarender = new OpenLayers.Layer.OSM.Osmarender("Osmarender", { displayOutsideMaxExtent: true, wrapDateLine: true }); map.addLayer(osmarender); var mapnik_local = new OpenLayers.Layer.OSM("Mapnik (Local)", "http://bericote.uk.cyberscience.com/tiles/", { displayOutsideMaxExtent: true, wrapDateLine: true }); map.addLayer(mapnik_local); var maplint = new OpenLayers.Layer.OSM.Maplint("Maplint", { displayOutsideMaxExtent: true, wrapDateLine: true }); map.addLayer(maplint); var numZoomLevels = Math.max(mapnik.numZoomLevels, osmarender.numZoomLevels); markers = new OpenLayers.Layer.Markers("Markers", { displayInLayerSwitcher: false, numZoomLevels: numZoomLevels, maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508), maxResolution: 156543, units: "m", projection: "EPSG:900913" }); map.addLayer(markers); return map; } function getArrowIcon() { var size = new OpenLayers.Size(25, 22); var offset = new OpenLayers.Pixel(-30, -27); var icon = new OpenLayers.Icon("/images/arrow.png", size, offset); return icon; } function addMarkerToMap(position, icon, description) { var marker = new OpenLayers.Marker(position, icon); markers.addMarker(marker); if (description) { marker.events.register("click", marker, function() { openMapPopup(marker, description) }); } return marker; } function openMapPopup(marker, description) { closeMapPopup(); popup = new OpenLayers.Popup.AnchoredBubble("popup", marker.lonlat, sizeMapPopup(description), "<p style='padding-right: 28px'>" + description + "</p>", marker.icon, true); popup.setBackgroundColor("#E3FFC5"); map.addPopup(popup); return popup; } function closeMapPopup() { if (popup) { map.removePopup(popup); delete popup; } } function sizeMapPopup(text) { var box = document.createElement("div"); box.innerHTML = text; box.style.visibility = "hidden"; box.style.position = "absolute"; box.style.top = "0px"; box.style.left = "0px"; box.style.width = "200px"; box.style.height = "auto"; document.body.appendChild(box); var width = box.offsetWidth; var height = box.offsetHeight; document.body.removeChild(box); return new OpenLayers.Size(width + 30, height + 24); } function removeMarkerFromMap(marker){ markers.removeMarker(marker); } function getMapLayers() { var layers = ""; for (var i=0; i< this.map.layers.length; i++) { var layer = this.map.layers[i]; if (layer.isBaseLayer) { layers += (layer == this.map.baseLayer) ? "B" : "0"; } else { layers += (layer.getVisibility()) ? "T" : "F"; } } return layers; } function setMapLayers(layers) { for (var i=0; i < layers.length; i++) { var layer = map.layers[i]; var c = layers.charAt(i); if (c == "B") { map.setBaseLayer(layer); } else if ( (c == "T") || (c == "F") ) { layer.setVisibility(c == "T"); } } } function mercatorToLonLat(merc) { var lon = (merc.lon / 20037508.34) * 180; var lat = (merc.lat / 20037508.34) * 180; lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2); return new OpenLayers.LonLat(lon, lat); } function lonLatToMercator(ll) { var lon = ll.lon * 20037508.34 / 180; var lat = Math.log(Math.tan((90 + ll.lat) * Math.PI / 360)) / (Math.PI / 180); lat = lat * 20037508.34 / 180; return new OpenLayers.LonLat(lon, lat); } function scaleToZoom(scale) { return Math.log(360.0/(scale * 512.0)) / Math.log(2.0); }
JavaScript
0
@@ -988,168 +988,8 @@ );%0A%0A - var maplint = new OpenLayers.Layer.OSM.Maplint(%22Maplint%22, %7B %0A displayOutsideMaxExtent: true,%0A wrapDateLine: true%0A %7D);%0A map.addLayer(maplint);%0A%0A v
33515046e0895a0cff17b05051e94bdb589f13f4
remove logos from popups since they take too much space.
public/javascripts/map.js
public/javascripts/map.js
/** * * Map View Functionality .js * * */ // All mines object var mines = {}; /** * Load mines from Registry */ function loadMines(){ $.get("service/instances", function(response){ var response = response.instances; for (var i = 0; i < response.length; i++){ var mine = response[i]; if (mine.location.latitude != ""){ var name = mine.name; var url = mine.url; var lat = mine.location.latitude; var lon = mine.location.longitude; var logo = mine.images.logo; mines[name.toLowerCase()] = { name: name, location: { lat: lat, lon: lon, string: "" }, url: url, logo: logo } } } mineMiner().init(); }); } var mineMiner = function() { var map; function init() { map = L.map('map').setView([mines.flymine.location.lat, mines.flymine.location.lon], 3); L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>', maxZoom: 18, id: 'mapbox.streets', accessToken: 'sk.eyJ1IjoieW9jaGFubmFoIiwiYSI6ImNpazEzdHZscTAyemR4NG01cWE2enZlcDQifQ.khbJ9AQiNTIdrniQRN8gEg' }).addTo(map); L.Icon.Default.imagePath = 'images/leaflet' addMines(); } $("#map").on( "click", function() { map.invalidateSize(false); }); $("#map").mouseover(function() { map.invalidateSize(false); }); /** * Adds all mines in the JSON to the map and make nice popups for them */ function addMines(){ var mineKeys = Object.keys(mines), mine; var mineNameLayer = []; for (var i = 0; i < mineKeys.length; i++) { var minesToAdd = []; mine = mines[mineKeys[i]]; // Check for mines with same location for (var j = 0; j < mineKeys.length; j++){ var mineToCheck = mines[mineKeys[j]]; if (mineToCheck.location.lat == mine.location.lat && mineToCheck.location.lon == mine.location.lon){ minesToAdd.push(mineToCheck); } } //location and popup are re-used by the markers //and by the show all popups "mine labels" layerGroup var location = new L.LatLng(mine.location.lat, mine.location.lon), popUp = new L.Popup().setLatLng(location).setContent( makeMinePopup(minesToAdd)); //storing the popups in a layer allows us to enable or disable all at once mineNameLayer.push(popUp); //make marker L.marker(location) //push to map .addTo(map) //add the popup for it so users can click and learn things .bindPopup(popUp); } var mineLayer = L.layerGroup(mineNameLayer); L.control.layers(null,{"Mine Labels": mineLayer}).addTo(map); } /** * Format HTML for the map mine popup **/ function makeMinePopup(minesToAdd){ var mineHtml = ""; for (var j = 0; j < minesToAdd.length; j++){ mine = minesToAdd[j]; mineHtml += "<br /><a href='" + mine.url + "' target='_blank'>" + "<img src='" + mine.logo + "' /> "+ "</a>"; mineHtml += "<br /><a href='" + mine.url + "' target='_blank'>" + mine.name + "</a>"; } return mineHtml; } return { init: init } }; document.addEventListener("DOMContentLoaded", function() { loadMines(); });
JavaScript
0
@@ -2476,16 +2476,35 @@ L.Popup( +%7BcloseButton:false%7D ).setLat @@ -3161,16 +3161,33 @@ Add%5Bj%5D;%0A + if(j%3E0)%7B%0A mi @@ -3207,98 +3207,18 @@ r /%3E -%3Ca href='%22 + mine.url + %22' target='_blank'%3E%22 + %22%3Cimg src='%22 + mine.logo + %22' /%3E %22+ %22%3C/a%3E%22; +%22;%0A %7D %0A @@ -3238,14 +3238,8 @@ = %22%3C -br /%3E%3C a hr
72e32ef734dd88d675a5d5ec55d300fda9ca3ae3
touchEnable flag should be true
Resources/result.js
Resources/result.js
var html1 = '<!doctype html><html lang="ja"><head><title>Radar Chart</title><script src="./Chart.js"></script><meta charset="UTF-8"><meta name = "viewport" content = "initial-scale = 1, user-scalable = no"><style>canvas{}</style></head><body><canvas id="canvas" height="450" width="450"></canvas><script>var radarChartData = {labels : ["現実的","研究的","芸術的","社会的","企業的","慣習的"],datasets : [{fillColor : "rgba(151,187,205,0.5)",strokeColor : "rgba(151,187,205,1)",pointColor : "rgba(151,187,205,1)",pointStrokeColor : "#fff",data : ['; var html2 = ']}]}var myRadar = new Chart(document.getElementById("canvas").getContext("2d")).Radar(radarChartData,{scaleShowLabels : false, pointLabelFontSize : 10}); </script></body></html>'; var answers = new Array(); answers = Ti.App.Properties.getList('answers'); var riasecA = ['','E','C','I','I','I','E','C','E','S','R', 'E','A','I','E','R','A','I','E','S','I', 'C','R','S','E','A','I','I','R','E','A', 'E','C','I','E','S','C','E','A','R','S', 'E','C']; var riasecB = ['','S','A','R','S','A','R','S','I','R','A', 'C','S','C','S','C','E','R','C','A','E', 'S','A','R','A','S','C','A','C','R','C', 'S','R','R','I','I','A','R','S','A','C', 'I','I']; var result = {R:0,I:0,A:0,S:0,E:0,C:0}; for(var i=0; i != answers.length; i++){ var reasec = new Array(); if(answers[i] == 1){ reasec = riasecA; }else{ reasec = riasecB; } for(var key in result){ // Ti.API.info('key: ', key); // Ti.API.info('answers[i]: ', answers[i]); if(reasec[i] == key){ // Ti.API.info('result[key]: ', result[key]); result[key] += 1; } } } var riasecText = 'R:' + result['R'] + ' I:' + result['I'] + ' A:' + result['A'] + ' S:' + result['S'] + ' E:' + result['E'] + ' C:' + result['C']; Ti.UI.currentWindow.backgroundColor = "#fff"; var tableView = Ti.UI.createTableView({ separatorColor : '#fff' }); Ti.UI.currentWindow.add(tableView); // riasecText var row = Ti.UI.createTableViewRow({}); row.add( Ti.UI.createLabel({ text: riasecText }) ); tableView.appendRow(row); // graph var webview = Ti.UI.createWebView(); var graphSize = Ti.Platform.displayCaps.platformWidth; if(graphSize > 600){ graphSize = 600; } var resultUrl = "http://www.july.co.jp/~mz/tmp/result.html?w="+graphSize //var resultUrl = "result.html?w="+graphSize +"&R="+result['R'] +"&I="+result['I'] +"&A="+result['A'] +"&S="+result['S'] +"&E="+result['E'] +"&C="+result['C']; Ti.API.info('URL: ', resultUrl); webview.url = resultUrl; var row = Ti.UI.createTableViewRow({height: graphSize}); row.add(webview); tableView.appendRow(row); // reset var row = Ti.UI.createTableViewRow({ backgroundColor : '#fff', touchEnabled : false, selectionStyle :'none' }); var doitButton = Ti.UI.createButton({ separatorColor : '#000', title: 'リセット', font:{fontSize:9}, width: 'auto' }); doitButton.addEventListener("click", function(){ Ti.API.info('properties initializing ...'); Ti.App.Properties.setInt('questionNumber', 0); var answers = new Array(); answers[0] = 0; Ti.App.Properties.setList('answers', answers); Ti.API.info('properties initializing complete.'); Ti.UI.currentTab.open(Ti.UI.createWindow({url: "question.js"})); }); row.add(doitButton); tableView.appendRow(row);
JavaScript
0.99995
@@ -2794,17 +2794,45 @@ ize:9%7D,%0A -%09 + touchEnabled : true,%0A width: ' @@ -2890,16 +2890,18 @@ tion()%7B%0A +// %09Ti.API. @@ -2933,24 +2933,24 @@ zing ...');%0A - %09Ti.App.Prop @@ -3078,16 +3078,18 @@ swers);%0A +// %09Ti.API. @@ -3180,24 +3180,24 @@ (%7Burl: %22 -question +mainMenu .js%22%7D));
faa7ad152e1c8fe415f15f0ef3c97715385a04d5
tag control functions in ui/index.js
src/node_modules/ui/index.js
src/node_modules/ui/index.js
var React = require('react') var r = require('r-dom') var debug = require('debug')('ui:index') var getDefaultRoleTypes = require('graph-view/get-default-role-types') var getRoleTypes = require('graph-view/get-role-types') var getUniLinkLabels = require('graph-view/get-uni-link-labels') var each = require('lodash.foreach') var clone = require('lodash.clone') var contains = require('lodash.contains') var types = require('types') var Layout = require('layout') var extend = require('xtend') var FourOhFourPage = require('./404') module.exports = React.createClass({ getInitialState: function () { debug('getInitialState:model.roles', this.props.model.roles) var initialState = { roleTypes: getRoleTypes( getDefaultRoleTypes(), this.props.model.roles ), linkLabels: getUniLinkLabels(this.props.model.relationshipGraph) } return initialState }, render: function () { var route = this.props.route debug('linkLabels', this.state.linkLabels) var props = extend( this.props, { roleTypes: this.state.roleTypes, linkLabels: this.state.linkLabels, updateActiveTags: this.updateActiveTags.bind(this) } ) var Page if (route) { Page = types.indexedByCollection[route.collection].Page } else { Page = FourOhFourPage } debug('render', props) return ( r(Layout, props, r(Page, props) ) ) }, componentDidMount: function () { this.props.model.on('change', function (model, val) { var nextRoleTypes = getRoleTypes( this.state.roleTypes, model.relationships ) var nextLinkLabels = getUniLinkLabels(model.relationshipGraph) this.setState({ roleTypes: nextRoleTypes, linkLabels: nextLinkLabels }) this.forceUpdate() }, this) }, updateActiveTags: function (type, activeTags) { var tagObject = clone(this.state[type]) debug('tagObject', tagObject, type, activeTags) var newState = {} each(tagObject, function (tagType, tagTypeId) { if (contains(activeTags, tagTypeId)) { tagType.active = true } else { tagType.active = false } }) newState[type] = tagObject debug('newState', newState) this.setState(newState) } })
JavaScript
0.000001
@@ -1159,17 +1159,16 @@ ctiveTag -s : this.u @@ -1181,17 +1181,60 @@ ctiveTag -s +.bind(this),%0A clearTag: this.clearTag .bind(th @@ -1914,16 +1914,19 @@ %0A %7D,%0A%0A + // updateA @@ -1963,24 +1963,27 @@ iveTags) %7B%0A + // var tagOb @@ -2015,18 +2015,21 @@ ype%5D)%0A +// + debug('t @@ -2072,17 +2072,16 @@ ags) - %0A +%0A // - var @@ -2094,21 +2094,28 @@ te = %7B%7D%0A + // %0A +// + each(tag @@ -2151,24 +2151,27 @@ gTypeId) %7B%0A + // if (con @@ -2199,24 +2199,27 @@ TypeId)) %7B%0A + // tagTy @@ -2236,24 +2236,27 @@ = true%0A + // %7D%0A els @@ -2247,16 +2247,19 @@ %7D%0A + // els @@ -2264,22 +2264,25 @@ lse %7B%0A +// + tagType. @@ -2301,23 +2301,447 @@ se%0A + // %7D%0A + //%0A // %7D)%0A //%0A // newState%5Btype%5D = tagObject%0A // debug('newState', newState)%0A // this.setState(newState)%0A // %7D,%0A%0A updateActiveTag: function (type, newActiveTag) %7B%0A var newState = %7B%7D%0A var tagObject = clone(this.state%5Btype%5D)%0A each(tagObject, function (tagType, tagTypeId) %7B%0A if (newActiveTag === tagTypeId %7C%7C newActiveTag === tagType.model.pluralName ) %7B%0A tagType.active = true%0A %7D %0A %7D)%0A %0A @@ -2732,25 +2732,24 @@ %7D%0A %7D)%0A -%0A newState @@ -2830,12 +2830,405 @@ ate)%0A %7D +,%0A%0A clearTag: function (type, tag) %7B%0A return function () %7B%0A var newState = %7B%7D%0A var tagObject = clone(this.state%5Btype%5D)%0A each(tagObject, function (tagType, tagTypeId) %7B%0A if (tag === tagTypeId %7C%7C tag === tagType.model.pluralName ) %7B%0A tagType.active = false%0A %7D%0A %7D)%0A newState%5Btype%5D = tagObject%0A this.setState(newState)%0A %7D.bind(this)%0A %7D%0A %0A%7D)%0A
e24a06cb0b88e0746fb3577aee4750ebdd3e1a3a
fix in auto refreshing (wrong npm repo)
workflow.js
workflow.js
var q = require('bluebird'); var registry = require("npm-registry"); var _ = require('underscore'); var database = require("./lib/database.js"); // crawlers var keywords = require("npm-keywords"); var ghClient = require("./lib/github.js"); var npmClient = require("./lib/npm.js"); var npmHistory = require("./lib/npmHistory.js"); // helpers var postProcessor = require("./lib/util/postProcessor.js"); var workflow = function(opts) { this.keys = opts.keys || []; this.refreshTime = opts.refreshTime || 3600; this.updateInterval = opts.updateInterval || 60; this.db = new database(); this.dbLoad = this.db.load(); this.pkgs = []; this.npm = new registry({ registry: opts.registryURL }); }; workflow.prototype.start = function() { return this.run().then(function() { this.reloadCron = setInterval(this.run.bind(this), this.refreshTime * 1000); this.updateCron = setInterval(this.updateCronJob.bind(this), this.updateInterval * 1000); }.bind(this)); }; // 1) download package list workflow.prototype.run = function run() { var self = this; return keywords(this.keys, this.npm).map(this.downloadPkg.bind(this)).then(function(pkgs) { // on succes: save to DB console.log("workflow: trying to save into DB."); self.pkgs = pkgs.map(function(el) { return { name: el.name, version: el.version }; }); self.dbLoad .then(self.db.loadCache.bind(self.db)) .then(function() { return self.db.save(pkgs); }); }).then(function() { console.log("workflow: load complete."); }); }; // 2) crawl the package from NPM workflow.prototype.downloadPkg = function(name) { // also support pkg object with name attribute if (name.name !== undefined) { name = name.name; } return new npmClient(name, this.npm).then(this.postDownload.bind(this)); }; // 3) other info workflow.prototype.postDownload = function(pkg) { var postOpts = { keys: this.keys }; var ps = []; ps.push(new ghClient(pkg)); ps.push(new npmHistory(pkg)); return q.all(ps).then(function() { return postProcessor(pkg, postOpts); }).catch(function(err) { if (err != undefined && err.name !== "queryEvents") { // event errors can happen - ignore them console.log("downloaderr", err); } else { console.log(arguments); } return pkg; }); }; // update a single pkg workflow.prototype.updatePkg = function(pkg) { return this.downloadPkg(pkg).then(function(newPkg) { var index = _.indexOf(_.pluck(this.pkgs, "name"), newPkg.name); this.pkgs[index] = newPkg; this.db.updatePkg(newPkg); console.log("package update saved: ", newPkg.name); }.bind(this)).catch(function(err) { console.log("err during package update: ", pkg.name); console.log(err); }); }; // crons the npm registry manually and checks for package updates workflow.prototype.updateCronJob = function updateCronJob() { var self = this; this.pkgs.forEach(function(oldPkg) { return new npmClient(oldPkg.name + "@latest", this.npm).then(function(newPkg) { // we have only the latest version -> download entire package if (oldPkg.version !== newPkg.version && newPkg.name !== undefined) { console.log("new package uploaded: ", newPkg.name); self.updatePkg(newPkg.name); } }.bind(this)); }); }; workflow.prototype.stop = function() { clearInterval(this.updateCron); clearInterval(this.reloadCron); }; module.exports = workflow;
JavaScript
0
@@ -3037,20 +3037,20 @@ atest%22, -this +self .npm).th @@ -3166,17 +3166,16 @@ rsion != -= newPkg. @@ -3191,33 +3191,32 @@ & newPkg.name != -= undefined) %7B%0A @@ -3262,32 +3262,64 @@ : %22, newPkg.name +, newPkg.version, oldPkg.version );%0A self.
7a5da4f4115cadc62caa71e82e7237d7692dbec5
Update broker.js
src/parties/Broker/broker.js
src/parties/Broker/broker.js
import Company from '../Company/company' /** * Class representing a Broker * @memberof module:parties * @extends module:parties.Company */ class Broker extends Company { /** * Construct a new Broker instance * @param {object} params - Broker creation options: * @param {number} params.assetManagerId - Asset Manager ID of the Broker __(required)__ * @param {string} params.partyId - Party ID of the Broker __(required)__ * @param {string} [params.partyStatus=Active] - Status of the Broker * @param {string} [params.baseCurrency] - Base Currency of the Broker (e.g. SGD, USD) * @param {string} [params.description] - Description of the Broker * @param {string} [params.licenseNumber] - Company license number (if applicable) * @param {string} [params.licenseType] - Company license type * @param {string} [params.assetsUnderManagement] - Value of assets under management * @param {string} [params.registrationNumber] - Business registration number (if applicable) * @param {string} [params.yearOfIncorporation] - Year of incorporation * @param {string} [params.contactNumber] - Contact number * @param {object} [params.addresses] - Object of Addresses associated with the Broker * @param {object} [params.emails] - Object of Emails associated with the Broker * @param {object} [params.references] - Object of References associated with the Broker * @param {object} [params.comments] - Object of Comments associated with the Broker * @param {object} [params.links] - Object of Links associated with the Broker * @param {string} [params.legalName]- Legal name of the Asset Manager associated with this party * @param {string} [params.displayName] - Display name of the Asset Manager associated with this party * @param {string} [params.url] - Url of this Party * @param {string} [params.createdBy] - ID of the user that created the Broker * @param {string} [params.updatedBy] - ID of the user that updated the Broker * @param {date} [params.createdTime] - Time that the Broker was created * @param {date} [params.updatedTime] - Time that the Broker was updated * @param {number} [params.version] - Version number of the Broker */ constructor({ assetManagerId, partyId, partyStatus='Active', baseCurrency, description='', yearOfIncorporation, contactNumber, addresses={}, emails={}, references={}, comments={}, links={}, legalName, displayName, url, createdBy, updatedBy, createdTime, updatedTime, version }) { super({ assetManagerId, partyId, partyStatus, baseCurrency, description, yearOfIncorporation, contactNumber, addresses, emails, references, comments, links, legalName, displayName, url, createdBy, updatedBy, createdTime, updatedTime, version }) } } export default Broker
JavaScript
0.000001
@@ -1075,69 +1075,8 @@ ion%0A - * @param %7Bstring%7D %5Bparams.contactNumber%5D - Contact number%0A * @@ -2287,35 +2287,16 @@ ration,%0A - contactNumber,%0A addr @@ -2632,29 +2632,8 @@ on,%0A - contactNumber,%0A
36478e47a08436da5392d1842d2654a9559c9906
Initialize database on startup
server/config/environment/production.js
server/config/environment/production.js
'use strict'; // Production specific configuration // ================================== var production = { server: { staticDir : '/../../dist' }, // MongoDB connection options mongodb: { uri: 'mongodb://localhost/devnews-dev' }, seedDB: false }; // if OPENSHIFT env variables are present, use the available connection info: if (process.env.MONGOLAB_URI) { production.mongodb.uri = process.env.MONGOLAB_URI; } else if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD) { production.mongodb.uri = 'mongodb://' + process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' + process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' + process.env.OPENSHIFT_MONGODB_DB_HOST + ':' + process.env.OPENSHIFT_MONGODB_DB_PORT + '/' + process.env.OPENSHIFT_APP_NAME; } module.exports = production;
JavaScript
0.000001
@@ -278,12 +278,11 @@ DB: -fals +tru e%0A%7D;
aedcf33df52bcfd734271432a7251898a45b6052
Handle mongo error in ensureTextIndex
lib/list/ensureTextIndex.js
lib/list/ensureTextIndex.js
var debug = require('debug')('keystone:core:list:ensureTextIndex'); // A basic string hashing function function hashString (string) { var char; var hash = 0; if (string.length === 0) return hash; for (var i = 0; i < string.length; i++) { char = string.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; // Convert to 32bit integer } return hash; } /** * Does what it can to ensure the collection has an appropriate text index. * * Works around unreliable behaviour with the Mongo drivers ensureIndex() * Specifically, when the following are true.. * - Relying on collection.ensureIndexes() to create text indexes * - A text index already exists on the collection * - The existing index has a different definition but the same name * The index is not created/updated and no error is returned, either by the * ensureIndexes() call or the connection error listener. * Or at least that's what was happening for me (mongoose v3.8.40, mongodb v1.4.38).. */ function ensureTextIndex (callback) { var list = this; var collection = list.model.collection; var textIndex = list.buildSearchTextIndex(); var fieldsHash = Math.abs(hashString(Object.keys(textIndex).sort().join(';'))); var indexNamePrefix = 'keystone_searchFields_textIndex_'; var newIndexName = indexNamePrefix + fieldsHash; // We use this later to create a new index if needed var createNewIndex = function () { collection.createIndex(textIndex, { name: newIndexName }, function (result) { debug('collection.createIndex() result for \'' + list.key + '\:', result); return callback(); }); }; collection.getIndexes(function (err, indexes) { if (err) throw err; // Not sure what else to do here.. var indexNames = Object.keys(indexes); // debug('indexes', indexes); // debug('indexNames', indexNames); // Search though the for (var i = 0; i < indexNames.length; i++) { var existingIndexName = indexNames[i]; var isText = false; // Check we're dealing with a text index for (var h = 0; h < indexes[existingIndexName].length; h++) { var column = indexes[existingIndexName][h]; if (column[1] === 'text') isText = isText || true; } // Skip non-text indexes if (!isText) continue; // Already exists with correct def if (existingIndexName === newIndexName) { debug('Existing text index \'' + existingIndexName + '\' already matches the searchFields for \'' + list.key + '\''); return; } // Exists but hash (def) doesn't match // Check for 'searchFields_text_index' for backwards compatibility if (existingIndexName.slice(0, indexNamePrefix.length) === indexNamePrefix || existingIndexName === 'searchFields_text_index') { debug('Existing text index \'' + existingIndexName + '\' doesn\'t match the searchFields for \'' + list.key + '\' and will be recreated as \'' + newIndexName + '\''); collection.dropIndex(existingIndexName, function (result) { debug('collection.dropIndex() result for \'' + list.key + '\:', result); createNewIndex(); }); return; } // It's a text index but not one of ours; nothing we can do debug('Existing text index \'' + existingIndexName + '\' in \'' + list.key + '\' not recognised; no action taken'); return; } // No text indexes found at all; create ours now debug('No existing text index found in \'' + list.key + '\'; Creating ours now'); createNewIndex(); }); } module.exports = ensureTextIndex;
JavaScript
0
@@ -1675,161 +1675,400 @@ rr) -throw err; // Not sure what else to do +%7B%0A%09%09%09if (err.code === 26) %7B%0A%09%09%09%09// if the database doesn't exist, we'll get error code 26 %22no database%22 here -.. %0A%09%09 -var indexNames = Object.keys( +%09%09// that's fine, we just default the indexes object so the new text index -es); %0A +%09%09 %09%09// -debug('indexes', indexes);%0A%09%09// debug('indexNames', +gets created when the database is connected.%0A%09%09%09%09indexes = %7B%7D;%0A%09%09%09%7D else %7B%0A%09%09%09%09// otherwise, we've had an unexpected error, so we throw it%0A%09%09%09%09throw err;%0A%09%09%09%7D%0A%09%09%7D%0A%09%09var indexNames = Object.keys( index -Nam es);
463a2ea05b34d46c600aec162b6b0b6f14fd6315
Fix #clearPaths mixin
lib/mincer/helpers/paths.js
lib/mincer/helpers/paths.js
/** internal * mixin Paths * * An internal mixin whose public methods are exposed on the [[Environment]] * and [[Index]] classes. * * Provides helpers to work with `Hike.Trail` instance. **/ // REQUIRED PROPERTIES ///////////////////////////////////////////////////////// // // - `__trail__` (Hike.Trail) // //////////////////////////////////////////////////////////////////////////////// 'use strict'; // internal var getter = require('../common').getter; //////////////////////////////////////////////////////////////////////////////// /** * Paths#root -> String * * Returns [[Environment]] root. * * All relative paths are expanded with root as its base. * To be useful set this to your applications root directory. **/ getter(module.exports, 'root', function () { return this.__trail__.root; }); /** * Paths#paths -> Array * * Returns an `Array` of path `String`s. * * These paths will be used for asset logical path lookups. * * Note that a copy of the `Array` is returned so mutating will * have no affect on the environment. See [[Paths#appendPath]], * [[Paths#prependPath]], and [[Paths#clearPaths]]. **/ getter(module.exports, 'paths', function () { return this.__trail__.paths.toArray(); }); /** * Paths#prependPath(path) -> Void * * Prepend a `path` to the `paths` list. * Paths at the end have the least priority. **/ module.exports.prependPath = function (path) { this.__trail__.paths.prepend(path); }; /** * Paths#appendPath(path) -> Void * * Append a `path` to the `paths` list. * Paths at the beginning have a higher priority. **/ module.exports.appendPath = function (path) { this.__trail__.paths.append(path); }; /** * Paths#clearPaths() -> Void * * Clear all paths and start fresh. * * There is no mechanism for reordering paths, so its best to * completely wipe the paths list and reappend them in the order * you want. **/ module.exports.clearPaths = function () { var trail = this.__trail__; this.paths.forEach(function (path) { trail.remove(path); }); }; /** * Paths#extensions -> Array * * Returns an `Array` of extensions. * * These extensions maybe omitted from logical path searches. * * [".js", ".css", ".coffee", ".sass", ...] **/ getter(module.exports, 'extensions', function () { return this.__trail__.extensions.toArray(); });
JavaScript
0
@@ -2052,16 +2052,22 @@ trail. +paths. remove(p
549689b99c4961328c2da06d65f087b53d927c40
use last call stack when payload is undefined
lib/model/callStackModel.js
lib/model/callStackModel.js
'use strict' 'use babel' const {Emitter} = require('atom') class CallStackModel { constructor (service) { this.service = service this.emitter = new Emitter() this.selectedIndex = 0 this.service.onPaused(this._pausedHandler.bind(this)) } getCallStack () { return this.callstack } getSelectedIndex () { return this.selectedIndex } onChange (handler) { return this.emitter.on('changed', handler) } _pausedHandler (payload) { if (payload.command === 'UPDATE_CALLSTACK') { this.callstack = payload.callFrames this.callstack.forEach((ele, index) => { if (ele.callFrameId === payload.currentCallFrameId) { this.selectedIndex = index } }, this) this.emitter.emit('changed', this) } } destroy () { this.emitter.dispose() } } module.exports = CallStackModel
JavaScript
0.000004
@@ -560,16 +560,34 @@ llFrames + %7C%7C this.callstack %0A t
a8fcdea1428f2a8f364fd84fc210d32d77aeb283
Fix mongo plugin
lib/plugins/mongo-plugin.js
lib/plugins/mongo-plugin.js
const mongodb = require('mongodb'); const Plugin = require('../plugin'); module.exports = Plugin.define('mongo', [], { defaultConfig: { 'uri': null, 'prefix': '', }, }, { async start (config) { if (!config.uri) { throw new Error('MongoDB URI (config path: "uri") not set'); } const mongo = await mongodb.MongoClient.connect(config.uri); this.mongo = mongo; this.bot.mongo = { collection (name, ...rest) { return mongo.collection(`${config.prefix}${name}`, ...rest); }, }; }, async stop (config) { await this.mongo.close(); }, }); module.exports = mongodb.ObjectId;
JavaScript
0
@@ -618,16 +618,25 @@ .exports +.ObjectId = mongo
964001619a1dfa6df7461b1f0a63287d0b2616db
fix oauth plugin for IE8
lib/plugins/sammy.oauth2.js
lib/plugins/sammy.oauth2.js
(function($) { Sammy = Sammy || {}; // Sammy.OAuth2 is a plugin for using OAuth 2.0 to authenticate users and // access your application's API. Requires Sammy.Session. // // Triggers the following events: // // * `oauth.connected` - Access token set and ready to use. Triggered when new // access token acquired, of when application starts and already has access // token. // * `oauth.disconnected` - Access token reset. Triggered by // loseAccessToken(). // * `oauth.denied` - Authorization attempt rejected. // // ### Example // // this.use('Storage'); // this.use('OAuth2'); // this.oauthorize = "/oauth/authorize"; // // // The quick & easy way // this.requireOAuth(); // // Specific path // this.requireOAuth("/private"); // // Filter you can apply to specific URLs // this.before(function(context) { return context.requireOAuth(); }) // // Apply to specific request // this.get("/private", function(context) { // this.requireOAuth(function() { // // Do something // }); // }); // // // Sign in/sign out. // this.bind("oauth.connected", function() { $("#signin").hide() }); // this.bind("oauth.disconnected", function() { $("#signin").show() }); // // // Handle access denied and other errors // this.bind("oauth.denied", function(evt, error) { // this.partial("admin/views/no_access.tmpl", { error: error.message }); // }); // // // Sign out. // this.get("#/signout", function(context) { // context.loseAccessToken(); // context.redirect("#/"); // }); // Sammy.OAuth2 = function(app) { app.use('JSON'); this.authorize = "/oauth/authorize"; // Use this on request that require OAuth token. You can use this in a // filter: it will redirect and return false if the access token is missing. // You can use it in a route, it will redirect to get the access token, or // call the callback function if it has an access token. this.helper("requireOAuth", function(cb) { if (this.app.getAccessToken()) { if (cb) { cb.apply(this); } } else { this.redirect(this.app.authorize + "?state=" + escape(this.path)); return false; } }); // Use this to sign out. this.helper("loseAccessToken", function() { this.app.loseAccessToken(); }); // Use this in your application to require an OAuth access token on all, or // the specified paths. It sets up a before filter on the specified paths. this.requireOAuth = function(options) { this.before(options || {}, function(context) { return context.requireOAuth(); }); } // Returns the access token. Uses Sammy.Session to store the token. this.getAccessToken = function() { return this.session("oauth.token"); } // Stores the access token in the session. this.setAccessToken = function(token) { this.session("oauth.token", token); this.trigger("oauth.connected"); } // Lose access token: use this to sign out. this.loseAccessToken = function() { this.session("oauth.token", null); this.trigger("oauth.disconnected"); } // Add OAuth 2.0 access token to all XHR requests. $(document).ajaxSend(function(evt, xhr) { var token = app.getAccessToken(); if (token) { xhr.setRequestHeader("Authorization", "OAuth " + token); } }); // Converts query string parameters in fragment identifier to object. function parseParams(path) { var hash = path.match(/#(.*)$/)[1]; var pairs = hash.split("&"), params = {}; for (var i in pairs) { var splat = pairs[i].split("="); params[splat[0]] = splat[1].replace(/\+/g, " "); } return params; } var start_url; // Capture the application's start URL, we'll need that later on for // redirection. this.bind("run", function(evt, params) { start_url = params.start_url || "#"; if (this.app.getAccessToken()) { this.trigger("oauth.connected"); } }); // Intercept OAuth authorization response with access token, stores it and // redirects to original URL, or application root. this.before(/#(access_token=|[^\\].*\&access_token=)/, function(context) { var params = parseParams(context.path); this.app.setAccessToken(params.access_token); // When the filter redirected the original request, it passed the original // request's URL in the state parameter, which we get back after // authorization. context.redirect(params.state.length === 0 ? this.app.start_url : unescape(params.state)); return false; }).get(/#(access_token=|[^\\].*\&access_token=)/, function(context) { }); // Intercept OAuth authorization response with error (typically access // denied). this.before(/#(error=|[^\\].*\&error=)/, function(context) { var params = parseParams(context.path); var message = params.error_description || "Access denined"; context.trigger("oauth.denied", { code: params.error, message: message }); return false; }).get(/#(error=|[^\\].*\&error=)/, function(context) { }); } })(jQuery);
JavaScript
0
@@ -3770,27 +3770,69 @@ -for (var i in pairs +var i, len = pairs.length;%0A%0A for (i = 0; i %3C len; i += 1 ) %7B%0A
ac7b73afefa038b11feaf3704573dcbe263f36c5
use colors/safe (#3548)
lib/reporters/base_color.js
lib/reporters/base_color.js
require('colors') function BaseColorReporter () { this.USE_COLORS = true this.LOG_SINGLE_BROWSER = '%s: ' + '%s'.cyan + '\n' this.LOG_MULTI_BROWSER = '%s %s: ' + '%s'.cyan + '\n' this.SPEC_FAILURE = '%s %s FAILED'.red + '\n' this.SPEC_SLOW = '%s SLOW %s: %s'.yellow + '\n' this.ERROR = '%s ERROR'.red + '\n' this.FINISHED_ERROR = ' ERROR'.red this.FINISHED_SUCCESS = ' SUCCESS'.green this.FINISHED_DISCONNECTED = ' DISCONNECTED'.red this.X_FAILED = ' (%d FAILED)'.red this.TOTAL_SUCCESS = 'TOTAL: %d SUCCESS'.green + '\n' this.TOTAL_FAILED = 'TOTAL: %d FAILED, %d SUCCESS'.red + '\n' } // PUBLISH module.exports = BaseColorReporter
JavaScript
0
@@ -1,8 +1,45 @@ +const %7B red, yellow, green, cyan %7D = require( @@ -45,16 +45,21 @@ ('colors +/safe ')%0A%0Afunc @@ -145,33 +145,34 @@ = '%25s: ' + -'%25s'.cyan +cyan('%25s') + '%5Cn'%0A th @@ -210,17 +210,18 @@ ' + -'%25s'.cyan +cyan('%25s') + ' @@ -247,16 +247,20 @@ ILURE = +red( '%25s %25s F @@ -265,20 +265,17 @@ FAILED' -.red +) + '%5Cn'%0A @@ -293,16 +293,23 @@ _SLOW = +yellow( '%25s SLOW @@ -320,15 +320,9 @@ %25s' -.yellow +) + ' @@ -336,24 +336,28 @@ his.ERROR = +red( '%25s ERROR'.r @@ -354,20 +354,17 @@ s ERROR' -.red +) + '%5Cn'%0A @@ -392,16 +392,20 @@ R = +red( ' ERROR' .red @@ -400,20 +400,17 @@ ' ERROR' -.red +) %0A this. @@ -428,16 +428,22 @@ CCESS = +green( ' SUCCES @@ -444,22 +444,17 @@ SUCCESS' -.green +) %0A this. @@ -477,16 +477,20 @@ ECTED = +red( ' DISCON @@ -496,20 +496,17 @@ NNECTED' -.red +) %0A%0A this @@ -517,16 +517,20 @@ AILED = +red( ' (%25d FA @@ -535,20 +535,17 @@ FAILED)' -.red +) %0A%0A this @@ -561,16 +561,22 @@ CCESS = +green( 'TOTAL: @@ -590,14 +590,9 @@ ESS' -.green +) + ' @@ -617,16 +617,20 @@ AILED = +red( 'TOTAL: @@ -655,12 +655,9 @@ ESS' -.red +) + '
dfa567d762645410155932942b591c994164619c
Update BoundsArraySet_Pointwise.js
CNN/Conv/BoundsArraySet/BoundsArraySet_Pointwise.js
CNN/Conv/BoundsArraySet/BoundsArraySet_Pointwise.js
export { Pointwise }; import * as FloatValue from "../../Unpacker/FloatValue.js"; import * as ValueDesc from "../../Unpacker/ValueDesc.js"; import * as Weights from "../../Unpacker/Weights.js"; import { ConvBiasActivation } from "./BoundsArraySet_ConvBiasActivation.js"; import { ChannelPartInfo, FiltersBiasesPartInfo } from "../Pointwise/Pointwise_ChannelPartInfo.js"; /** * The element value bounds for pointwise convolution-bias-activation. * * - Only input0 is used. The input1 is always undefined. * - Only outputChannelCount0 is used. The outputChannelCount1 is always zero. * * @see ConvBiasActivation */ class Pointwise extends ConvBiasActivation { /** * - The .input0 will be set as input0. * - The .afterUndoPreviousActivationEscaping will be set according to input0 and input0.scaleArraySet.undo.scales. */ constructor( input0, outputChannelCount0 ) { super( input0, outputChannelCount0 ); } /** * Set this.bPassThrough[] according to inChannelPartInfoArray. * * @param {Pointwise.FiltersBiasesPartInfo[]} aFiltersBiasesPartInfoArray * The input channel range array which describe lower/higher half channels index range. */ set_bPassThrough_all_byChannelPartInfoArray( aFiltersBiasesPartInfoArray ) { let outChannelBegin = 0, outChannelEnd = 0; // [ outChannelBegin, outChannelEnd ) are output channels of the current FiltersBiasesPart. FiltersBiasesPartIndexLoop: for ( let aFiltersBiasesPartIndex = 0; aFiltersBiasesPartIndex < aFiltersBiasesPartInfoArray.length; ++aFiltersBiasesPartIndex ) { let aFiltersBiasesPartInfo = aFiltersBiasesPartInfoArray[ aFiltersBiasesPartIndex ]; let inChannelPartInfoArray = aFiltersBiasesPartInfo.aChannelPartInfoArray; outChannelBegin = outChannelEnd; // Begin from the ending of the previous FiltersBiasesPart. { let outChannel = outChannelBegin; InChannelPartIndexLoop: for ( let inChannelPartIndex = 0; inChannelPartIndex < inChannelPartInfoArray.length; ++inChannelPartIndex ) { let inChannelPartInfo = inChannelPartInfoArray[ inChannelPartIndex ]; for ( let outChannelSub = 0; outChannelSub < inChannelPartInfo.outputChannelCount; ++outChannelSub, ++outChannel ) { if ( outChannel >= this.outputChannelCount0 ) break InChannelPartIndexLoop; // Never exceeds the total output channel count. this.bPassThrough[ outChannel ] = inChannelPartInfo.bPassThrough; } // outChannelSub, outChannel } // inChannelPartIndex outChannelEnd = outChannel; // Record the ending output channel index of the current FiltersBiasesPart. } } // aFiltersBiasesPartIndex } }
JavaScript
0
@@ -14,16 +14,42 @@ twise %7D; +%0Aexport %7B PointwisePool %7D; %0A%0Aimport @@ -1208,16 +1208,92 @@ range.%0A + *%0A * @return %7BBoundsArraySet.Pointwise%7D%0A * Return the this object.%0A */%0A @@ -2829,10 +2829,611 @@ %0A%0A -%7D%0A%0A%7D%0A + return this;%0A %7D%0A%0A%7D%0A%0A%0A/**%0A * Providing BoundsArraySet.Pointwise%0A *%0A */%0Aclass PointwisePool extends Pool.Root %7B%0A%0A constructor() %7B%0A super( Pointwise, PointwisePool.setAsConstructor );%0A %7D%0A%0A /**%0A * @param %7BDepthwise%7D this%0A * The Depthwise object to be initialized.%0A *%0A * @return %7BDepthwise%7D%0A * Return the this object.%0A */%0A static setAsConstructor( input0, outputChannelCount0 ) %7B%0A this.set_input0_outputChannelCount0( input0, outputChannelCount0 );%0A return this;%0A %7D%0A%0A%7D%0A%0A/**%0A * Used as default BoundsArraySet.Pointwise provider.%0A */%0APointwisePool.Singleton = new PointwisePool(); %0A
4cbedf555f12175d6407b0947ab99f66aaf9945b
Send same thing in both parameters
myModules/zsoServerComunication.js
myModules/zsoServerComunication.js
//save requests to files var mongo = require('./mongoFunctions.js'), assert = require('assert'), request= require('request'), jsonFromHtml = require('./getJsonFromHtml.js'), userMod = require('./getSubstitution.js'), querystring = require('querystring'), messenger = require('./messengerBot.js'), setTime = require('./setTime.js'), callFunc = require('./postCallFunctions.js'); /* module to comunicate with ZSO11 server */ var time = new setTime(); var getSomeSubstitution = function(date,callback){ time.tommorowIs(); var tomorrow = time.displayTime(); var day = ''; if (date == tomorrow){ day = 'tomorrow'; } else { time.todayIs(); var today = time.displayTime(); if (date == today){ day = 'today'; } } getData(date,function(data){ convertToSubstitutions(data,function(convertedData){ if(day != ''){ callFunc.getChanges({param:day}, function(obj){ messenger.notification(convertedData, obj, function(res){ console.log(res); }); }); } classListFromDate(convertedData,function(res){ var dataToSave={}; dataToSave['substitution']=convertedData; dataToSave['userList']=res; console.log('before saving'+ dataToSave['userList']); saveSubstitutions(date,dataToSave,function(){ mongo.findById(date,'substitutions',function(err,x){ console.log('save substitution '+ x.userList,x.date); setImmediate(function() { callback(convertedData); }); }) }) }) }) }) } function classListFromDate(convertedData,callback){ var classList=[]; if (convertedData =='no substitutions'){ setImmediate(function(){ callback({}); }); } else{ var changes = convertedData; for(var i=0;i<changes.length;i++){ var oneChange = changes[i]; var newClass = oneChange['classes']; for(var j =0;j<newClass.length;j++){ if(classList.indexOf(newClass[j])==-1){ classList[classList.length]=newClass[j]; } } } setImmediate(function(){ callback(classList); }); } } var getData = function(date,callback){ downloadData(date,function(err,body){ if(err){ getCookie(function(){ downloadData(date,function(err1,newBody){ setImmediate(function() { callback(newBody); }); }) }); } else{ setImmediate(function() { callback(body); }); } }); } function getParams(callback){ var url='http://zso11.edupage.org/substitution/?'; request(url,function(err,res,body){ if(!err && res.statusCode ==200){ getGPIDandGSH(body,function(params){ var cookie=res.headers['set-cookie']; var data = { 'gpid':params[0], 'gsh':params[1], 'cookie':cookie } saveToCollection(['testCollection',data],function(){ console.log('data added: '+data); }) }); //save somewhere } setImmediate(function() { callback(); }); }); } function downloadData(date,callback){ var url1='http://zso11.edupage.org/gcall'; mongo.findById('params','testCollection',function(err1,params){ console.log('params',params); var cookie=params['cookie']; var form = { gpid:params['gpid'], gsh:params['gsh'], action:"switch", date:date, _LJSL:"2,1" }; var formData = querystring.stringify(form); var contentLength = formData.length; request({ headers: { 'Content-Length': contentLength, 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie' : cookie }, uri: url1, body: formData, method: 'POST' }, function (err, res, body) { assert.equal(null,err); setImmediate(function() { callback(body.length<100,body); }); }); }); } var getCookie=function(callback){ var url='http://zso11.edupage.org/substitution/?'; request(url,function(err,res,body){ if(!err && res.statusCode ==200){ getGPIDandGSH(body,function(params){ var cookie=res.headers['set-cookie']; var data = { 'gpid':params[0], 'gsh':params[1], 'cookie':cookie } console.log(JSON.stringify(data)); mongo.modifyById('params','testCollection',data,function(){ console.log('cookies saved: '+data); setImmediate(function() { callback(data); }); }) }); //save somewhere } }); } function checkIfAnySubstitutions(callback){ var res; getData(date,function(body){ if(body.indexOf('column') != -1){ res=true; console.log('i see something'); }else{ res=false; console.log('nothing') } setImmediate(function() { callback(res); }); }) } function saveSubstitutions(date,data,callback){ var dataToSave={}; dataToSave['substitution']=data.substitution; dataToSave['userList']=data.userList; dataToSave['date']=date; mongo.modifyById(date,'substitutions',dataToSave,function(){ setImmediate(function() { callback(); //callback not necessary }); //ok; }) } function convertToSubstitutions(data,callback){ var substitution2 =new jsonFromHtml(); var user2= new userMod(); var allChanges; substitution2.fileString=data; var err=substitution2.testIfCorrectFile(); if(err){ substitution2.getJsonObj(); user2.keyArray=JSON.parse(substitution2.keyObj); user2.dataArray=JSON.parse(substitution2.dataObj); allChanges=user2.changes(); } else{ allChanges='no substitutions'; } setImmediate(function() { callback(allChanges); //respond with converted changes }); } function getGPIDandGSH (data,callback){ //take params to send request var a=data.indexOf('gsh'); var gpidIndex; var gshIndex; for (var i=0; i<11;i++){ if (data.charAt(a-i)=='='){ gpidIndex=a-i; break; } } for (var i=0; i<20;i++){ if (data.charAt(a+i)=='"'){ gshIndex=a+i; break; } } var gpid=data.slice(gpidIndex+1,a-1); var gsh=data.slice(a+4,gshIndex); setImmediate(function() { callback([gpid,gsh]); }); } exports.subs = getSomeSubstitution; exports.getData = getData; exports.downloadData = downloadData; exports.getCookie = getCookie; exports.convert = convertToSubstitutions; exports.save = saveSubstitutions; exports.getGPIDandGSH = getGPIDandGSH;
JavaScript
0
@@ -930,16 +930,32 @@ ata, obj +%5B'substitution'%5D , functi
66599b3eaf28d6e0ea01b39d2fa3b78849a3da14
Update jquery.cronui.js
i18n/jquery.cronui.js
i18n/jquery.cronui.js
;(function($){ $.fn.cronui.data['ru-RU'] = { periods: ['Минута', 'Час', 'День', 'Неделю', 'Месяц', 'Год'], days: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"], months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"], period: 'Каждый/-ую', minute: 'Минута', hour: 'Час', month: 'Месяц', dom: 'День месяца', dow: 'День недели' }; }(jQuery));
JavaScript
0.000001
@@ -131,23 +131,8 @@ s: %5B -%22%D0%92%D0%BE%D1%81%D0%BA%D1%80%D0%B5%D1%81%D0%B5%D0%BD%D1%8C%D0%B5%22, %22%D0%9F%D0%BE%D0%BD
d3b24fd83f6c201b37ef3d2f5bda57676a94e4a9
use require and module.exports instead of import/export for the Pusher client
javascript_client/subscriptions/PusherLink.js
javascript_client/subscriptions/PusherLink.js
// An Apollo Link for using graphql-pro's Pusher subscriptions // // @example Adding subscriptions to a HttpLink // // Load Pusher and create a client // import Pusher from "pusher-js" // var pusherClient = new Pusher("your-app-key", { cluster: "us2" }) // // // Build a combined link, initialize the client: // const pusherLink = new PusherLink({pusher: pusherClient}) // const link = ApolloLink.from([authLink, pusherLink, httpLink]) // const client = new ApolloClient(link: link, ...) // // @example Building a subscription, then subscribing to it // subscription = client.subscribe({ // variables: { room: roomName}, // query: gql` // subscription MessageAdded($room: String!) { // messageWasAdded(room: $room) { // room { // messages { // id // body // author { // screenname // } // } // } // } // } // ` // }) // // subscription.subscribe({ next: ({data, errors}) => { // // Do something with `data` and/or `errors` // }}) // import {ApolloLink, Observable} from "apollo-link" class PusherLink extends ApolloLink { constructor(options) { super() // Retain a handle to the Pusher client this.pusher = options.pusher } request(operation, forward) { return new Observable((observer) => { // Check the result of the operation forward(operation).subscribe({ next: (data) => { // If the operation has the subscription header, it's a subscription const subscriptionChannel = this._getSubscriptionChannel(operation) if (subscriptionChannel) { // This will keep pushing to `.next` this._createSubscription(subscriptionChannel, observer) } else { // This isn't a subscription, // So pass the data along and close the observer. observer.next(data) observer.complete() } }}) }) } _getSubscriptionChannel(operation) { const response = operation.getContext().response // Check to see if the response has the header const subscriptionChannel = response.headers.get("X-Subscription-ID") return subscriptionChannel } _createSubscription(subscriptionChannel, observer) { const pusherChannel = this.pusher.subscribe(subscriptionChannel) // Subscribe for more update pusherChannel.bind("update", function(payload) { if (!payload.more) { // This is the end, the server says to unsubscribe pusher.unsubscribe(subscriptionChannel) observer.complete() } const result = payload.result if (result) { // Send the new response to listeners observer.next(result) } }) } } export default PusherLink
JavaScript
0
@@ -1098,16 +1098,48 @@ %0A//%0A -import %7B +var ApolloLink = require(%22apollo-link%22). Apol @@ -1144,17 +1144,20 @@ olloLink -, +%0Avar Observa @@ -1163,15 +1163,19 @@ able -%7D from + = require( %22apo @@ -1183,16 +1183,28 @@ lo-link%22 +).Observable %0A%0Aclass @@ -2835,22 +2835,24 @@ %0A%7D%0A%0A -export default +module.exports = Pus
a581a6ec94ea56879fe2767d50f2ffbb6943c468
Update CheckBox.js
src/checkbox/CheckBox.js
src/checkbox/CheckBox.js
import React from 'react' import { StyleSheet, TouchableOpacity, View, Platform } from 'react-native' import Text from '../text/Text' import fonts from '../config/fonts' import colors from '../config/colors' import FAIcon from 'react-native-vector-icons/FontAwesome' import getIconType from '../helpers/getIconType' let styles = {} const CheckBox = ({component, checked, iconRight, title, center, right, containerStyle, textStyle, onPress, onLongPress, onIconPress, onLongIconPress, checkedIcon, uncheckedIcon, iconType, checkedColor, uncheckedColor, checkedTitle, fontFamily}) => { let Icon = FAIcon if (iconType) { Icon = getIconType(iconType) } const Component = component || TouchableOpacity let iconName = uncheckedIcon if (checked) { iconName = checkedIcon } return ( <Component onLongPress={onLongPress} onPress={onPress} style={[ styles.container, containerStyle && containerStyle ]}> <View style={[ styles.wrapper, ]}> { !iconRight && ( <Icon color={checked ? checkedColor : uncheckedColor} name={iconName} size={24} onLongPress={onLongIconPress} onPress={onIconPress} /> ) } <Text style={[ styles.text, textStyle && textStyle, fontFamily && {fontFamily} ]}> {checked ? checkedTitle || title : title} </Text> { iconRight && ( <Icon color={checked ? checkedColor : uncheckedColor} name={iconName} size={24} /> ) } </View> </Component> ) } CheckBox.defaultProps = { checked: false, iconRight: false, right: false, center: false, checkedColor: 'green', uncheckedColor: '#bfbfbf', checkedIcon: 'check-square-o', uncheckedIcon: 'square-o' } // CheckBox.propTypes = { // component, checked, iconRight, title, center, containerStyle, textStyle, onPress, checkedIcon, uncheckedIcon, iconType, checkedColor, uncheckedColor, checkedTitle // } styles = StyleSheet.create({ wrapper: { flexDirection: 'row', alignItems: 'center' }, container: { margin: 5, marginLeft: 10, marginRight: 10, backgroundColor: '#fafafa', borderColor: '#ededed', borderWidth: 1, padding: 10, borderRadius: 3 }, text: { marginLeft: 10, marginRight: 10, color: colors.grey1, ...Platform.select({ ios: { fontWeight: 'bold' }, android: { fontFamily: fonts.android.bold } }) } }) export default CheckBox
JavaScript
0.000001
@@ -997,24 +997,116 @@ es.wrapper,%0A + right && %7BjustifyContent: 'flex-end'%7D,%0A center && %7BjustifyContent: 'center'%7D%0A %5D%7D%3E%0A
b918e05a6bd3b108584964340a2250fda4346bbd
initialize @children array before using it
src/child-observation.js
src/child-observation.js
import {DOM} from 'aurelia-pal'; import {metadata} from 'aurelia-metadata'; import {HtmlBehaviorResource} from './html-behavior'; function createChildObserverDecorator(selectorOrConfig, all) { return function(target, key, descriptor) { let actualTarget = typeof key === 'string' ? target.constructor : target; //is it on a property or a class? let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, actualTarget); if (typeof selectorOrConfig === 'string') { selectorOrConfig = { selector: selectorOrConfig, name: key }; } if (descriptor) { descriptor.writable = true; } selectorOrConfig.all = all; r.addChildBinding(new ChildObserver(selectorOrConfig)); }; } /** * Creates a behavior property that references an array of immediate content child elements that matches the provided selector. */ export function children(selectorOrConfig: string | Object): any { return createChildObserverDecorator(selectorOrConfig, true); } /** * Creates a behavior property that references an immediate content child element that matches the provided selector. */ export function child(selectorOrConfig: string | Object): any { return createChildObserverDecorator(selectorOrConfig, false); } class ChildObserver { constructor(config) { this.name = config.name; this.changeHandler = config.changeHandler || this.name + 'Changed'; this.selector = config.selector; this.all = config.all; } create(viewHost, viewModel, controller) { return new ChildObserverBinder(this.selector, viewHost, this.name, viewModel, controller, this.changeHandler, this.all); } } const noMutations = []; function trackMutation(groupedMutations, binder, record) { let mutations = groupedMutations.get(binder); if (!mutations) { mutations = []; groupedMutations.set(binder, mutations); } mutations.push(record); } function onChildChange(mutations, observer) { let binders = observer.binders; let bindersLength = binders.length; let groupedMutations = new Map(); for (let i = 0, ii = mutations.length; i < ii; ++i) { let record = mutations[i]; let added = record.addedNodes; let removed = record.removedNodes; for (let j = 0, jj = removed.length; j < jj; ++j) { let node = removed[j]; if (node.nodeType === 1) { for (let k = 0; k < bindersLength; ++k) { let binder = binders[k]; if (binder.onRemove(node)) { trackMutation(groupedMutations, binder, record); } } } } for (let j = 0, jj = added.length; j < jj; ++j) { let node = added[j]; if (node.nodeType === 1) { for (let k = 0; k < bindersLength; ++k) { let binder = binders[k]; if (binder.onAdd(node)) { trackMutation(groupedMutations, binder, record); } } } } } groupedMutations.forEach((value, key) => { if (key.changeHandler !== null) { key.viewModel[key.changeHandler](value); } }); } class ChildObserverBinder { constructor(selector, viewHost, property, viewModel, controller, changeHandler, all) { this.selector = selector; this.viewHost = viewHost; this.property = property; this.viewModel = viewModel; this.controller = controller; this.changeHandler = changeHandler in viewModel ? changeHandler : null; this.usesShadowDOM = controller.behavior.usesShadowDOM; this.all = all; if (!this.usesShadowDOM && controller.view && controller.view.contentView) { this.contentView = controller.view.contentView; } else { this.contentView = null; } } matches(element) { if (element.matches(this.selector)) { if (this.contentView === null) { return true; } let contentView = this.contentView; let assignedSlot = element.auAssignedSlot; if (assignedSlot && assignedSlot.projectFromAnchors) { let anchors = assignedSlot.projectFromAnchors; for (let i = 0, ii = anchors.length; i < ii; ++i) { if (anchors[i].auOwnerView === contentView) { return true; } } return false; } return element.auOwnerView === contentView; } return false; } bind(source) { let viewHost = this.viewHost; let viewModel = this.viewModel; let observer = viewHost.__childObserver__; if (!observer) { observer = viewHost.__childObserver__ = DOM.createMutationObserver(onChildChange); let options = { childList: true, subtree: !this.usesShadowDOM }; observer.observe(viewHost, options); observer.binders = []; } observer.binders.push(this); if (this.usesShadowDOM) { //if using shadow dom, the content is already present, so sync the items let current = viewHost.firstElementChild; if (this.all) { let items = viewModel[this.property]; if (!items) { items = viewModel[this.property] = []; } else { items.length = 0; } while (current) { if (this.matches(current)) { items.push(current.au && current.au.controller ? current.au.controller.viewModel : current); } current = current.nextElementSibling; } if (this.changeHandler !== null) { this.viewModel[this.changeHandler](noMutations); } } else { while (current) { if (this.matches(current)) { let value = current.au && current.au.controller ? current.au.controller.viewModel : current; this.viewModel[this.property] = value; if (this.changeHandler !== null) { this.viewModel[this.changeHandler](value); } break; } current = current.nextElementSibling; } } } } onRemove(element) { if (this.matches(element)) { let value = element.au && element.au.controller ? element.au.controller.viewModel : element; if (this.all) { let items = this.viewModel[this.property]; let index = items.indexOf(value); if (index !== -1) { items.splice(index, 1); } return true; } return false; } return false; } onAdd(element) { if (this.matches(element)) { let value = element.au && element.au.controller ? element.au.controller.viewModel : element; if (this.all) { let items = this.viewModel[this.property]; let index = 0; let prev = element.previousElementSibling; while (prev) { if (this.matches(prev)) { index++; } prev = prev.previousElementSibling; } items.splice(index, 0, value); return true; } this.viewModel[this.property] = value; if (this.changeHandler !== null) { this.viewModel[this.changeHandler](value); } } return false; } unbind() { if (this.viewHost.__childObserver__) { this.viewHost.__childObserver__.disconnect(); this.viewHost.__childObserver__ = null; } } }
JavaScript
0.000001
@@ -6094,32 +6094,33 @@ let items = +( this.viewModel%5Bt @@ -6124,32 +6124,73 @@ l%5Bthis.property%5D + %7C%7C (this.viewModel%5Bthis.property%5D = %5B%5D)) ;%0A let in @@ -6565,16 +6565,17 @@ items = +( this.vie @@ -6587,32 +6587,73 @@ l%5Bthis.property%5D + %7C%7C (this.viewModel%5Bthis.property%5D = %5B%5D)) ;%0A let in
e7e95f5d4b9b8b21fa2c97bec22b9e6df9386450
Add mkdirp to create a @<scope> folder before doing symlink so that yarn link works (#910)
src/cli/commands/link.js
src/cli/commands/link.js
/* @flow */ import type {Reporter} from '../../reporters/index.js'; import type Config from '../../config.js'; import {MessageError} from '../../errors.js'; import * as fs from '../../util/fs.js'; const invariant = require('invariant'); const path = require('path'); export async function getRegistryFolder(config: Config, name: string): Promise<string> { if (config.modulesFolder) { return config.modulesFolder; } const src = path.join(config.linkFolder, name); const {_registry} = await config.readManifest(src); invariant(_registry, 'expected registry'); const registryFolder = config.registries[_registry].folder; return path.join(config.cwd, registryFolder); } export async function run( config: Config, reporter: Reporter, flags: Object, args: Array<string>, ): Promise<void> { if (args.length) { for (const name of args) { const src = path.join(config.linkFolder, name); if (await fs.exists(src)) { const folder = await getRegistryFolder(config, name); const dest = path.join(folder, name); await fs.unlink(dest); await fs.mkdirp(path.dirname(dest)); await fs.symlink(src, dest); reporter.success(reporter.lang('linkRegistered', name)); } else { throw new MessageError(reporter.lang('linkMissing', name)); } } } else { // add cwd module to the global registry const manifest = await config.readRootManifest(); const name = manifest.name; if (!name) { throw new MessageError(reporter.lang('unknownPackageName')); } const linkLoc = path.join(config.linkFolder, name); if (await fs.exists(linkLoc)) { throw new MessageError(reporter.lang('linkCollision', name)); } else { await fs.symlink(config.cwd, linkLoc); reporter.success(reporter.lang('linkRegistered', name)); reporter.info(reporter.lang('linkInstallMessage', name)); } } }
JavaScript
0
@@ -1736,24 +1736,70 @@ %7D else %7B%0A + await fs.mkdirp(path.dirname(linkLoc));%0A await
c684662c5543e12fa7edeb52fac8c2cd83a01d4b
Add workaround for 2.12.x support
addon/helpers/utils.js
addon/helpers/utils.js
function save() { this._super.apply(this, arguments); this._save(); } function saveIfChanged(key) { this._super.apply(this, arguments); if (key !== '_isInitialContent') { this._save(); } } export { save, saveIfChanged };
JavaScript
0
@@ -137,16 +137,293 @@ ents);%0A%0A + // TODO: v2.0 - Remove workaround and drop support for 2.12.x%0A // Ember 2.12.x sets __OWNER__ and __NAME_KEY__ on factoryFor().create()%0A // which results in a premature save hat overwrites the already stored data.%0A if (/%5E__OWNER%7CNAME_KEY__/.test(key)) %7B%0A return;%0A %7D%0A%0A if (ke
631b6991eb2253b4b39cb3e899030e9efd1e90ed
rename private methods.
addon/services/intl.js
addon/services/intl.js
/** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ import { getOwner } from '@ember/application'; import { computed, get, set } from '@ember/object'; import Evented from '@ember/object/evented'; import { assert } from '@ember/debug'; import { makeArray } from '@ember/array'; import { assign } from '@ember/polyfills'; import Service from '@ember/service'; import { next, cancel } from '@ember/runloop'; import { FormatDate, FormatMessage, FormatNumber, FormatRelative, FormatTime } from '../-private/formatters'; import isArrayEqual from '../-private/utils/is-array-equal'; import normalizeLocale from '../-private/utils/normalize-locale'; import getDOM from '../-private/utils/get-dom'; import hydrate from '../-private/utils/hydrate'; import TranslationContainer from '../-private/store/container'; export default Service.extend(Evented, { /** @public **/ formats: null, /** @public **/ locale: computed({ set(_, localeName) { const proposed = makeArray(localeName).map(normalizeLocale); if (!isArrayEqual(proposed, this._locale)) { this._locale = proposed; cancel(this._timer); this._timer = next(() => this.trigger('localeChanged')); this.updateDocumentLanguage(this._locale); } return this._locale; }, get() { return this._locale; }, }), /** * Returns the first locale of the currently active locales * * @property primaryLocale * @public */ primaryLocale: computed.readOnly('locale.0'), /** @public **/ formatRelative: formatter('relative'), /** @public **/ formatMessage: formatter('message'), /** @public **/ formatNumber: formatter('number'), /** @public **/ formatTime: formatter('time'), /** @public **/ formatDate: formatter('date'), /** * Returns an array of registered locale names * * @property locales * @public */ locales: computed.readOnly('_translationContainer.locales'), /** @private **/ _locale: null, /** @private **/ _translationContainer: null, /** @private **/ _timer: null, /** @public **/ init() { this._super(...arguments); const initialLocale = get(this, 'locale') || ['en-us']; this.setLocale(initialLocale); this._owner = getOwner(this); this._translationContainer = TranslationContainer.create(); this._formatters = { message: new FormatMessage(), relative: new FormatRelative(), number: new FormatNumber(), time: new FormatTime(), date: new FormatDate(), }; if (!this.formats) { this.formats = this._owner.resolveRegistration('formats:main') || {}; } hydrate(this, this._owner); }, willDestroy() { this._super(...arguments); cancel(this._timer); }, /** @public **/ lookup(key, localeName, options = {}) { const localeNames = this.localeWithDefault(localeName); let translation; for (let i = 0; i < localeNames.length; i++) { translation = this._translationContainer.lookup(localeNames[i], key); if (translation !== undefined) { break; } } if (!options.resilient && translation === undefined) { const missingMessage = this._owner.resolveRegistration('util:intl/missing-message'); return missingMessage.call(this, key, localeNames, options); } return translation; }, /** @public **/ t(key, options = {}) { let defaults = [key]; let ast; if (options.default) { defaults = defaults.concat(options.default); } while (!ast && defaults.length) { ast = this.lookup(defaults.shift(), options.locale, assign({}, options, { resilient: defaults.length > 0 })); } return this.formatMessage(ast, options); }, /** @public **/ exists(key, localeName) { const localeNames = this.localeWithDefault(localeName); assert(`[ember-intl] locale is unset, cannot lookup '${key}'`, Array.isArray(localeNames) && localeNames.length); return localeNames.some((localeName) => this._translationContainer.has(localeName, key)); }, /** @public */ setLocale(locale) { set(this, 'locale', locale); }, /** @public **/ addTranslations(localeName, payload) { this._translationContainer.push(normalizeLocale(localeName), payload); }, /** @public **/ translationsFor(localeName) { return this._translationContainer.lookupTranslationObject(normalizeLocale(localeName), false); }, /** @private **/ getFormat(formatType, format) { const formats = get(this, 'formats'); if (formats && formatType && typeof format === 'string') { return get(formats, `${formatType}.${format}`); } }, /** @private **/ localeWithDefault(localeName) { if (!localeName) { return this._locale || []; } if (typeof localeName === 'string') { return makeArray(localeName).map(normalizeLocale); } if (Array.isArray(localeName)) { return localeName.map(normalizeLocale); } }, /** @private **/ updateDocumentLanguage(locales) { const dom = getDOM(this); if (dom) { const [primaryLocale] = locales; const html = dom.documentElement; html.setAttribute('lang', primaryLocale); } }, }); function formatter(name) { return function (value, options, formats) { let formatOptions = options; if (options && typeof options.format === 'string') { formatOptions = assign({}, this.getFormat(name, formatOptions.format), formatOptions); } return this._formatters[name].format(value, formatOptions, { formats: formats || this.formats, locale: this.localeWithDefault(formatOptions && formatOptions.locale), }); }; }
JavaScript
0
@@ -949,32 +949,198 @@ formats: null,%0A%0A + /**%0A * Returns an array of registered locale names%0A *%0A * @property locales%0A * @public%0A */%0A locales: computed.readOnly('_translationContainer.locales'),%0A%0A /** @public ** @@ -1446,16 +1446,17 @@ this. +_ updateDo @@ -2038,211 +2038,8 @@ /** -%0A * Returns an array of registered locale names%0A *%0A * @property locales%0A * @public%0A */%0A locales: computed.readOnly('_translationContainer.locales'),%0A%0A /** @private **/%0A _locale: null,%0A%0A /** @pr @@ -2071,16 +2071,53 @@ ontainer +: null,%0A%0A /** @private **/%0A _locale : null,%0A @@ -2917,32 +2917,33 @@ aleNames = this. +_ localeWithDefaul @@ -3882,24 +3882,25 @@ ames = this. +_ localeWithDe @@ -4532,16 +4532,17 @@ e **/%0A +_ getForma @@ -4754,24 +4754,25 @@ ivate **/%0A +_ localeWithDe @@ -5076,16 +5076,17 @@ e **/%0A +_ updateDo @@ -5502,16 +5502,17 @@ %7D, this. +_ getForma @@ -5689,16 +5689,17 @@ e: this. +_ localeWi
76c61b45cd48599812fa4972ab324d79b2fd9506
Add youtube playlist thumbnail buttons.
js/content_scripts/youtube-content-scripts.js
js/content_scripts/youtube-content-scripts.js
initYouTubeList(); chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.action == "getPlaylistUrls") { initYouTubeList(); sendResponse({urlList: JSON.stringify(urlList)}); } else if (request.action == "onPlayback") { $("video")[0].pause(); } } ); /** * if this is youtube page which is part of a playlist , show all videos and the option to queue them all * */ function initYouTubeList(){ var tabUrl = window.location.href; var youTubeListId = getURLParameter(tabUrl, 'list'); if (youTubeListId && youTubeListId != playlistId){ playlistId = youTubeListId; extractVideosFromYouTubePlaylist(youTubeListId); } } function extractVideosFromYouTubePlaylist(playListID, token) { var videoURL = 'https://www.youtube.com/watch?v='; var playListURL = '//www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults=50&playlistId=' + playListID + '&key=AIzaSyA3INgfTLddMbrJm8f68xpvfPZDAzDqk10'; if (token) { playListURL = playListURL + '&pageToken=' + token; } $.getJSON(playListURL, function (data) { var nextPageToken; if (data.nextPageToken) { nextPageToken = data.nextPageToken; } $.each(data.items, function (i, item) { var videoID = item.contentDetails.videoId; var url = videoURL + videoID; urlList.push(url); }); if (nextPageToken) { extractVideosFromYouTubePlaylist(playListID, startIndex + itemsPerPage); } }); } var playlistId; var urlList = []; function getURLParameter(tabUrl, sParam) { var sPageURL = tabUrl.substring(tabUrl.indexOf('?') + 1 ); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam) { return sParameterName[1]; } } return null; } // On page thumbnail actions. var observer = new MutationObserver(mutations => { for (const mutation of mutations) { for (const node of mutation.addedNodes) { if (node.nodeName.match(/^YTD.*VIDEO-RENDERER$/)) initButtons(node); } } }); observer.observe(document, { childList: true, subtree: true, }); initButtons(document); function initButtons(parent) { for (const thumbnail of parent.querySelectorAll('ytd-thumbnail')) { if (thumbnail.querySelector('.ptk-thumbnail-buttons')) continue; thumbnail.appendChild(createThumbnailButtons()); } } function createThumbnailButtons() { const iconsBaseUrl = 'https://storage.googleapis.com/material-icons/external-assets/v4/icons/svg'; const container = document.createElement('div'); container.className = 'ptk-thumbnail-buttons'; container.style.cssText = 'width: 96px; height: 32px; padding: 2px; margin: auto; z-index: 100; position: absolute; top: 0; left: 0; right: 0; bottom: 20px;'; container.appendChild(createThumbnailButton('Play now', `${iconsBaseUrl}/ic_play_arrow_white_24px.svg`, 'playThis')); container.appendChild(createThumbnailButton('Play this Next', `${iconsBaseUrl}/ic_playlist_play_white_24px.svg`, 'playThisNext')); container.appendChild(createThumbnailButton('Queue', `${iconsBaseUrl}/ic_playlist_add_white_24px.svg`, 'queueThis')); return container; } function createThumbnailButton(title, image, action) { const button = document.createElement('a'); button.className = 'ptk-thumbnail-button'; button.style.cssText = 'width: 28px; height: 28px; margin: 2px; cursor: pointer; opacity: 0.8; display: inline-flex; align-items: center; justify-content: center; border-radius: 2px; background-color: #111;'; button.title = title; button.innerHTML = `<iron-icon src="${image}">`; button.onclick = (event) => { event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); button.style.cursor = 'wait'; chrome.extension.sendMessage({action: action, url: (button.parentNode.parentNode.querySelector('a#thumbnail') || {}).href}, () => button.style.cursor = 'pointer'); return false; }; return button; }
JavaScript
0
@@ -2266,24 +2266,233 @@ RER$/)) init +VideoButtons(node);%0A if (node.nodeName.match(/%5EYTD.*PLAYLIST-RENDERER$/)) initPlaylistButtons(node);%0A if (node.nodeName.match(/%5EYTD-PLAYLIST-SIDEBAR-PRIMARY-INFO-RENDERER$/)) initPlaylist Buttons(node @@ -2589,24 +2589,60 @@ e,%0A%7D);%0A%0Ainit +VideoButtons(document);%0AinitPlaylist Buttons(docu @@ -2662,16 +2662,21 @@ ion init +Video Buttons( @@ -2889,32 +2889,292 @@ ns());%0A %7D%0A%7D%0A%0A +function initPlaylistButtons(parent) %7B%0A for (const thumbnail of parent.querySelectorAll('ytd-playlist-thumbnail')) %7B%0A if (thumbnail.querySelector('.ptk-thumbnail-buttons')) continue;%0A%0A thumbnail.appendChild(createThumbnailButtons());%0A %7D%0A%7D%0A%0A function createT
3e3730f030a071831c54cdad6f876ead52ba94c9
move association mapping to the initialize method
lib/waterline/core/index.js
lib/waterline/core/index.js
/** * Dependencies */ var _ = require('underscore'), extend = require('../utils/extend'), schemaUtils = require('../utils/schema'), Model = require('../model'), Cast = require('./typecast'), Schema = require('./schema'), Validator = require('./validations'), AdapterLoader = require('./adapters'), Transformer = require('./transformations'); /** * Core * * Setup the basic Core of a collection to extend. */ var Core = module.exports = function(options) { // Set Defaults this.adapter = this.adapter || {}; this.attributes = this.attributes || {}; // Construct our internal objects this._cast = new Cast(); this._schema = new Schema(this); this._validator = new Validator(); // Normalize attributes, extract instance methods, and callbacks // Note: this is ordered for a reason! this._callbacks = schemaUtils.normalizeCallbacks(this); this._instanceMethods = schemaUtils.instanceMethods(this.attributes); this._associations = schemaUtils.associations(this.attributes); this.attributes = schemaUtils.normalizeAttributes(this.attributes); this.autoPK = Object.getPrototypeOf(this).hasOwnProperty('autoPK') ? this.autoPK : true; this.autoCreatedAt = Object.getPrototypeOf(this).hasOwnProperty('autoCreatedAt') ? this.autoCreatedAt : true; this.autoUpdatedAt = Object.getPrototypeOf(this).hasOwnProperty('autoUpdatedAt') ? this.autoUpdatedAt : true; this.hasSchema = Object.getPrototypeOf(this).hasOwnProperty('schema') ? this.schema : true; this.migrate = Object.getPrototypeOf(this).hasOwnProperty('migrate') ? this.migrate : 'alter'; // Initalize the internal values from the model this._initialize(options); return this; }; _.extend(Core.prototype, { /** * Initialize * * Setups internal mappings from an extended model. */ _initialize: function(options) { var self = this; options = options || {}; options.adapters = options.adapters || {}; // Extend a base Model this._model = Model.inject(this, this._instanceMethods); // Initialize internal objects from attributes this._schema.initialize(this.attributes, this._associations, this.hasSchema); this._cast.initialize(this._schema.schema); this._validator.initialize(this.attributes, this.types); // Build Data Transformer this._transformer = new Transformer(this.attributes, this._associations); // Transform Schema this._schema.schema = this._transformer.serialize(this._schema.schema); // Set TableName with Identity as a fallback for compatibility this._tableName = this.tableName || this.identity || options.tableName || options.identity; // Grab information about the adapters var adapterInfo = AdapterLoader(this.adapter, options.adapters); // Normalize Adapter Definition with actual methods this.adapter = adapterInfo.adapter; // Record all the different adapters specified this._adapterDefs = adapterInfo.adapterDefs; } }); // Make Extendable Core.extend = extend;
JavaScript
0.000001
@@ -977,74 +977,8 @@ s);%0A - this._associations = schemaUtils.associations(this.attributes);%0A th @@ -2013,16 +2013,112 @@ hods);%0A%0A + // Map association keys%0A this._associations = schemaUtils.associations(this.attributes);%0A %0A //
22d739993473b0d514e1c81fa0af886e7750fb81
fix bug
lib/wechat-enterprise-im.js
lib/wechat-enterprise-im.js
'use strict'; var xml2js = require('xml2js'); var ejs = require('ejs'); var Session = require('./session'); var List = require('./list'); var WXBizMsgCrypt = require('wechat-crypto'); var load = function (stream, callback) { var buffers = []; stream.on('data', function (trunk) { buffers.push(trunk); }); stream.on('end', function () { callback(null, Buffer.concat(buffers)); }); stream.once('error', callback); }; /*! * 将xml2js解析出来的对象转换成直接可访问的对象 */ var formatMessage = function (result) { var message = {}; if (typeof result === 'object') { for (var key in result) { if (result[key].length === 1) { var val = result[key][0]; if (typeof val === 'object') { message[key] = formatMessage(val); } else { message[key] = (val || '').trim(); } } else { message = result[key].map(formatMessage); } } } return message; }; var respond = function (handler) { return function (req, res, next) { res.reply = function (content) { res.writeHead(200); res.end(content); }; handler.handle(req.weixin, req, res, next) }; }; /** * 微信自动回复平台的内部的Handler对象 * @param {Object} config 企业号的开发者配置对象 * @param {Function} handle handle对象 * * config: * ``` * { * token: '', // 公众平台上,开发者设置的Token * encodingAESKey: '', // 公众平台上,开发者设置的EncodingAESKey * corpId: '', // 企业号的CorpId * } * ``` */ var Handler = function (config, handle) { this.config = config; this.handle = handle; }; /** * 根据Handler对象生成响应方法,并最终生成中间件函数 */ Handler.prototype.middlewarify = function () { var that = this; var config = this.config; that.cryptor = new WXBizMsgCrypt(config.token, config.encodingAESKey, config.corpId); var _respond = respond(this); return function (req, res, next) { var method = req.method; var signature = req.query.msg_signature; var timestamp = req.query.timestamp; var nonce = req.query.nonce; var cryptor = req.cryptor || that.cryptor; if (method === 'GET') { var echostr = req.query.echostr; if (signature !== cryptor.getSignature(timestamp, nonce, echostr)) { res.writeHead(401); res.end('Invalid signature'); return; } var result = cryptor.decrypt(echostr); // TODO 检查corpId的正确性 res.writeHead(200); res.end(result.message); } else if (method === 'POST') { load(req, function (err, buf) { if (err) { return next(err); } var xml = buf.toString('utf-8'); if (!xml) { var emptyErr = new Error('body is empty'); emptyErr.name = 'Wechat'; return next(emptyErr); } xml2js.parseString(xml, {trim: true}, function (err, result) { if (err) { err.name = 'BadMessage' + err.name; return next(err); } var xml = formatMessage(result.xml); var encryptMessage = xml.Encrypt; if (signature !== cryptor.getSignature(timestamp, nonce, encryptMessage)) { res.writeHead(401); res.end('Invalid signature'); return; } var decrypted = cryptor.decrypt(encryptMessage); var messageWrapXml = decrypted.message; if (messageWrapXml === '') { res.writeHead(401); res.end('Invalid corpid'); return; } req.weixin_xml = messageWrapXml; xml2js.parseString(messageWrapXml, {trim: true}, function (err, result) { if (err) { err.name = 'BadMessage' + err.name; return next(err); } req.weixin = formatMessage(result.xml); _respond(req, res, next); }); }); }); } else { res.writeHead(501); res.end('Not Implemented'); } }; }; /** * 根据口令 * * Examples: * 使用wechat作为自动回复中间件的三种方式 * ``` * wechat(config, function (req, res, next) {}); * * wechat(config, wechat.text(function (message, req, res, next) { * // TODO * }).location(function (message, req, res, next) { * // TODO * })); * * wechat(config) * .text(function (message, req, res, next) { * // TODO * }).location(function (message, req, res, next) { * // TODO * }).middleware(); * ``` * 静态方法 * * - `text`,处理文字推送的回调函数,接受参数为(text, req, res, next)。 * - `image`,处理图片推送的回调函数,接受参数为(image, req, res, next)。 * - `voice`,处理声音推送的回调函数,接受参数为(voice, req, res, next)。 * - `video`,处理视频推送的回调函数,接受参数为(video, req, res, next)。 * - `location`,处理位置推送的回调函数,接受参数为(location, req, res, next)。 * - `link`,处理链接推送的回调函数,接受参数为(link, req, res, next)。 * - `event`,处理事件推送的回调函数,接受参数为(event, req, res, next)。 * @param {Object} config 企业号的开发者配置对象 * @param {Function} handle 生成的回调函数,参见示例 */ var middleware = function (config, handle) { return new Handler(config, handle).middlewarify(); }; middleware.reply = reply; module.exports = middleware;
JavaScript
0.000001
@@ -4912,35 +4912,8 @@ %7D;%0A%0A -middleware.reply = reply;%0A%0A modu
5059d05e75d4992aea8dc826529ca14eb550c48e
Update user-service.js
www/user/user-service.js
www/user/user-service.js
'use strict'; angular.module('MyApp.services').service('User', function($q, $firebase, FIREBASE_ROOT, Auth) { var usersRef = new Firebase(FIREBASE_ROOT + '/users'); var currentUser = null; this.loadCurrentUser = function() { var defer = $q.defer(); var currentUserRef = usersRef.child(Auth.currentUser.uid); currentUser = $firebase(currentUserRef); currentUser.$on('loaded', defer.resolve); return defer.promise; }; this.create = function(id, email) { var users = $firebase(usersRef); return users.$child(id).$set({ email: email }); }; this.recordPasswordChange = function() { var now = Math.floor(Date.now() / 1000); return currentUser.$update({ passwordLastChangedAt: now }); }; this.hasChangedPassword = function() { return angular.isDefined(currentUser.passwordLastChangedAt); }; });
JavaScript
0.000002
@@ -900,14 +900,441 @@ %0A %7D;%0A + %0A this.manageSubscriptions = function(subs) %7B%09%09%0A var users = $firebase(usersRef);%09%09%0A %09%09%0A for (var key in users) %7B%09%09%0A var obj = users%5Bkey%5D;%09%09%0A if (key.toLowerCase() === Auth.currentUser.uid) %7B%09%09%0A subscribed = subs;%09%09%0A console.log(subscribed);%09%09%0A %7D%09%09%0A %7D%09%09%0A return users.$child(Auth.currentUser.uid).$set(%7B subscribed: subs %7D);%09%09%0A %7D;%0A %7D);%0A
5a723d0cd2676cfecd83f1a0edd7717fadb75b82
remove useless override
src/ValidationError.js
src/ValidationError.js
class ValidationError extends Error { constructor(validation) { super(ValidationError.message); this.validation = validation; // We don't want to capture the Stack, no useful information there this.stack = ""; } // Pretty print the error inspect(depth, opts) { let validationString = JSON.stringify(this.validation, null, ' ') // removes quotes from prop names .replace(/\"([^(\")"]+)\":/g,"$1:"); // ident properly for final string const [first, ...rest] = validationString.split('\n'); const formattedRest = rest.map(s => ` ${s}`); validationString = [first, ...formattedRest].join('\n'); return `{ ${this.toString()}\n validation: ${validationString}\n}`; } toString() { return `${this.constructor.name}: ${ValidationError.message}`; }; // We don't want to capture the Stack, no useful information there captureStackTrace () {} } ValidationError.message = "Modern Validator encountered validation error(s)."; module.exports = ValidationError;
JavaScript
0.000002
@@ -884,108 +884,8 @@ %7D; -%0A%0A // We don't want to capture the Stack, no useful information there%0A captureStackTrace () %7B%7D %0A%7D%0A%0A
fcbcdee6aa18c9f507c7a8d981fb8d77f319997f
Allow more information for casting
src/_column-matches.js
src/_column-matches.js
import { isArray } from 'lodash'; import strategies from './strategies'; const defaultTransform = (v = '') => v && v.toLowerCase && v.toLowerCase(); const defaultCastingStrategy = v => (isArray(v) ? v : String(v)); const _columnMatches = ({ query, castingStrategy = defaultCastingStrategy, column = {}, row, strategy = strategies.infix, transform = defaultTransform }) => { const property = column.property; if (!property) { return false; } const value = row[`_${property}`] || row[property]; if (value == null) { return false; } // Pick resolved value by convention const resolvedValue = castingStrategy(value); return strategy(transform(query)).evaluate(transform(resolvedValue)); }; export default _columnMatches;
JavaScript
0
@@ -641,16 +641,24 @@ gy(value +, column );%0A%0A re
add1cc0cfff66946f3052cf637c130400e4424f0
Change Claims header title
src/components/Claims.js
src/components/Claims.js
import React, { Component } from 'react'; import claims from '../../data/claims.json'; import documents from '../../data/documents.json'; console.log(claims, documents); import Sidebar from './Sidebar'; import Header from'./Header'; import NavBar from './NavBar'; import logo from '../logo.svg'; import '../App.css'; import '../themify-icons/themify-icons.css'; export default class Claims extends Component { render() { return ( <div className="col-md-12"> <h5 className="over-title">Defining a <span className="text-bold">Fieldset</span></h5> <p className="margin-bottom-30"> is used as a wrapper right inside the form element. Right after you define a fieldset, you can include a legend title by using. Here's some HTML to help make copy paste. </p> <div className="row"> <div className="col-md-6"> <fieldset> <legend> Your Account </legend> <div className="form-group"> <label> E-mail <span className="symbol required"></span> </label> <div className="form-group"> <input type="email" placeholder="Text Field" name="email" id="email" className="form-control"/> </div> </div> </fieldset> <fieldset> <legend> Choose a password </legend> <div className="form-group"> <label> Password </label> <input type="text" className="form-control" placeholder="Repeat Password"/> </div> <div className="form-group"> <label> Repeat Password <span className="symbol required"></span> </label> <input type="email" placeholder="Text Field" name="email" id="email" className="form-control"/> </div> </fieldset> </div> <div className="col-md-6"> <fieldset> <legend> Personal Information </legend> <div className="row"> <div className="col-md-6"> <div className="form-group"> <label> First Name </label> <input type="text" name="firstName" className="form-control" placeholder="Enter your First Name"/> </div> </div> <div className="col-md-6"> <div className="form-group"> <label className="control-label"> Last Name </label> <input type="text" name="lastName" className="form-control" placeholder="Enter your Last Name"/> </div> </div> </div> <div className="row"> <div className="col-md-6"> <div className="form-group"> <label className="block"> Gender </label> <div className="clip-radio radio-primary"> <input type="radio" id="female" name="gender" value="female"/> <label for="female"> Female </label> <input type="radio" id="male" name="gender" value="male" checked="checked"/> <label for="male"> Male </label> </div> </div> </div> <div className="col-md-6"> <div className="form-group"> <label> Choose your country or region </label> <select name="country" className="form-control"> <option value="">&nbsp;</option> <option value="AL">Alabama</option> <option value="AK">Alaska</option> <option value="AZ">Arizona</option> <option value="AR">Arkansas</option> <option value="CA">California</option> <option value="CO">Colorado</option> <option value="CT">Connecticut</option> <option value="DE">Delaware</option> <option value="FL">Florida</option> <option value="GA">Georgia</option> <option value="HI">Hawaii</option> <option value="ID">Idaho</option> <option value="IL">Illinois</option> <option value="IN">Indiana</option> <option value="IA">Iowa</option> <option value="KS">Kansas</option> <option value="KY">Kentucky</option> <option value="LA">Louisiana</option> <option value="ME">Maine</option> <option value="MD">Maryland</option> <option value="MA">Massachusetts</option> <option value="MI">Michigan</option> <option value="MN">Minnesota</option> <option value="MS">Mississippi</option> <option value="MO">Missouri</option> <option value="MT">Montana</option> <option value="NE">Nebraska</option> <option value="NV">Nevada</option> <option value="NH">New Hampshire</option> <option value="NJ">New Jersey</option> <option value="NM">New Mexico</option> <option value="NY">New York</option> <option value="NC">North Carolina</option> <option value="ND">North Dakota</option> <option value="OH">Ohio</option> <option value="OK">Oklahoma</option> <option value="OR">Oregon</option> <option value="PA">Pennsylvania</option> <option value="RI">Rhode Island</option> <option value="SC">South Carolina</option> <option value="SD">South Dakota</option> <option value="TN">Tennessee</option> <option value="TX">Texas</option> <option value="UT">Utah</option> <option value="VT">Vermont</option> <option value="VA">Virginia</option> <option value="WA">Washington</option> <option value="WV">West Virginia</option> <option value="WI">Wisconsin</option> <option value="WY">Wyoming</option> </select> </div> </div> </div> </fieldset> <fieldset> <legend> Terms &amp; Condition </legend> <div className="row"> <div className="col-md-12"> <div className="form-group"> <label className="checkbox-inline clip-check"> <input type="checkbox" name="newsletter"/> <i></i> I read and accept the terms and conditions </label> </div> </div> </div> </fieldset> </div> </div> </div> ) } }
JavaScript
0
@@ -512,62 +512,27 @@ le%22%3E -Defining a %3Cspan className=%22text-bold%22%3EFieldset%3C/span%3E +Claims/Attestations %3C/h5
8dfa19e22397180ff80857b6660145eafa6e17bd
rename "master" -> "main" (git branch)
src/components/Footer.js
src/components/Footer.js
import React from 'react'; import FontList from '../components/FontList'; class Footer extends React.Component { render() { const props = this.props; const data = props.data; return ( <div className="clearfix bg-white bg-fallback-white py2 md-py4" style={{minHeight: `60vh`}}> <div className="mx-auto max-width-5 px2 sm-px3"> <div className="md-flex flex-wrap"> <div className="col-12 lg-col-4 md-pr4 mb4 lg-mt4"> <p lang="ja" className="notranslate">ぜひ定期的にチェックしてください。</p> <p lang="ja" className="notranslate"> このページでは、Google Fontsに追加された新しいフォントのサンプルをご利用いただけます。また、Google での試験運用や技術についてお知らせすることもあります。 </p> <p lang="en">Check back often!</p> <p lang="en"> We’ll update this page with samples as new Japanese fonts are added to Google Fonts, and provide information about our own experiments and technology when possible. </p> <ul className="list-style-none p0 m0" lang="en"> <li> <a href={`${data.repository}/blob/master/CONTRIBUTING.md`} aria-label="Read more about contributing to this open source site."> Contribute </a> </li> <li className="fill-navy"> <a href={`https://twitter.com/${data.social.twitter}`}> @{data.social.twitter} on Twitter </a> </li> <li className="fill-navy"> <a href={`https://github.com/${data.social.github}`}> @{data.social.github} on GitHub </a> </li> </ul> </div> <div className="col-12 md-col-8"> <div className="clearfix mb4"> <h3 className="h3 mt0">Featured Typefaces</h3> <FontList color="black" maxFontSize={48} textAlignment="left" firstColumnLgCol={3} {...props} /> </div> <div className="clearfix"> <h3 className="h3">Made by Friends of Google Fonts</h3> <div className="sm-flex mxn1" lang="en"> <div className="col-12 sm-col-6 px1"> <a className="" href={data.authors.marikotakagi.url}> {data.authors.marikotakagi.name} </a> <p className="mt0">{data.authors.marikotakagi.credit}</p> </div> <div className="col-12 sm-col-6 px1"> <a className="" href={data.authors.kennethormandy.url}> {data.authors.kennethormandy.name} </a> <p className="mt0">{data.authors.kennethormandy.credit}</p> </div> </div> </div> </div> </div> </div> </div> ); } } export default Footer;
JavaScript
0
@@ -1225,12 +1225,10 @@ b/ma -ster +in /CON
c739a116db50207adfcfa7ddeecc0a26bb64b63e
replace vw at header component to %
src/components/Header.js
src/components/Header.js
import React from 'react'; import { css } from 'glamor'; import Logo from './Logo'; import Infos from './Infos'; import Title from './Title'; import BackgroundPattern from '../media/images/backgroundPattern.png'; const styles = { container: css({ backgroundImage: `url(${BackgroundPattern})`, color: 'white', width: '100vw', height: '100vh', minWidth: '100vw', display: 'flex', alignItems: 'center', flexDirection: 'column', justifyContent: 'space-between', }), }; const Header = () => ( <div {...styles.container}> <Title /> <Logo /> <Infos /> </div> ); export default Header;
JavaScript
0
@@ -326,26 +326,25 @@ width: '100 -vw +%25 ',%0A heigh @@ -377,10 +377,9 @@ '100 -vw +%25 ',%0A
bbf04a74ad407c48a463e689092dc7ec3fab8e7b
Reorder header per client. Closes #199
src/components/Header.js
src/components/Header.js
import React, { PropTypes } from 'react'; import { throttle } from 'lodash'; import { Link } from 'react-router'; import socialMediaLinks from '../../static/socialMediaLinks.json'; /** * Header block at top of site, with logo and nav links */ export default class Header extends React.Component { static propTypes = { actions: PropTypes.object, menuOpen: PropTypes.bool, mode: PropTypes.string } constructor (props) { super(props); this.onScroll = throttle(this.onScroll, 100); this.lastScrollTop = 0; } componentWillMount () { this.setState({ headerHeight: null }); } componentDidMount () { let headerHeight = this.refs.header.offsetHeight; this.lastScrollTop = window.scrollY; const delta = 5; if (!this.state.headerHeight || headerHeight !== this.state.headerHeight ) { this.setState({ headerHeight, delta }); } window.addEventListener('scroll', this.onScroll.bind(this)); } componentWillUnmount () { window.removeEventListener('scroll', this.onScroll.bind(this)); } onScroll (e) { const { delta, headerHeight } = this.state; let scrollPos = window.scrollY; if (Math.abs(this.lastScrollTop - scrollPos) <= delta) return; if (scrollPos > this.lastScrollTop && scrollPos > headerHeight) { this.refs.header.classList.add('nav-up'); } else if (scrollPos < headerHeight) { this.refs.header.classList.remove('nav-up'); } this.lastScrollTop = scrollPos; } render () { // Don't let the body scroll if menu open document.body.classList.toggle('mobile-menu-open', this.props.menuOpen); return ( <header ref='header' className={ 'site-header' + (this.props.menuOpen ? ' menu-open' : '') }> <h1><Link to={ `/home/${ this.props.mode }` } onClick={ this.props.actions.menuHidden }>BLUE<span className="site-header-green">GREENWAY</span></Link></h1> <div className='menu'> <ul> <li><Link to={ `/stories/${ this.props.mode }` } onClick={ this.props.actions.menuHidden } activeClassName='active'><span>Stories</span></Link></li> <li><Link to={ `/events/${ this.props.mode }` } onClick={ this.props.actions.menuHidden } activeClassName='active'><span>Events</span></Link></li> <li><Link to={ `/projects/${ this.props.mode }` } onClick={ this.props.actions.menuHidden } activeClassName='active'><span>Projects</span></Link></li> <li><Link to={ `/about/page` } onClick={ this.props.actions.menuHidden } activeClassName='active'><span>About</span></Link></li> </ul> <div className='menu-social-media'> <div className='menu-social-media-buttons'> <a href={ socialMediaLinks.facebook } className='menu-social-media-button menu-social-media-facebook'></a> <a href={ socialMediaLinks.twitter } className='menu-social-media-button menu-social-media-twitter'></a> <a href={ socialMediaLinks.instagram } className='menu-social-media-button menu-social-media-instagram'></a> </div> </div> </div> <a className='site-header-toggle-menu' onClick={ this.props.actions.menuToggled }> <div className='site-header-show-menu'> <div className='site-header-show-menu-bar'></div> <div className='site-header-show-menu-bar'></div> <div className='site-header-show-menu-bar'></div> </div> <div className='site-header-hide-menu'>&#10005;</div> </a> </header> ); } }
JavaScript
0
@@ -1895,36 +1895,18 @@ %7B %60/ -stories/$%7B this.props.mode %7D +about/page %60 %7D @@ -1982,15 +1982,13 @@ pan%3E -Stories +About %3C/sp @@ -2030,12 +2030,14 @@ %7B %60/ -even +projec ts/$ @@ -2132,20 +2132,22 @@ '%3E%3Cspan%3E -Even +Projec ts%3C/span @@ -2175,38 +2175,36 @@ li%3E%3CLink to=%7B %60/ -projec +even ts/$%7B this.props @@ -2279,38 +2279,36 @@ ='active'%3E%3Cspan%3E -Projec +Even ts%3C/span%3E%3C/Link%3E @@ -2332,34 +2332,52 @@ Link to=%7B %60/ -about/page +stories/$%7B this.props.mode %7D %60 %7D onClick= @@ -2433,37 +2433,39 @@ ='active'%3E%3Cspan%3E -About +Stories %3C/span%3E%3C/Link%3E%3C/
a3f67930793c1e494617c43803648392c1454fcc
change default module name
src/components/config.js
src/components/config.js
var colors = [ '#008EBA', '#99CC00', '#AA66CC', '#FD7400', '#723147', '#FF5F5F', '#AC59D6', '#6B5D99', '#FFBB33', '#FF4444', '#1F8A70', '#9BCF2E', '#004358', '#979C9C', '#962D3E', '#35478C', '#5F9C6D', '#FD7400', '#16193B', '#7FB2F0' ]; var config = { colors, scopeLogs: false, moduleName: 'ngx.default', routeProviderName: '$routeProvider', baseUrl: '', html5: true }; class ConfigManager { constructor() { } useHtml5() { if (arguments.length == 1) { config.html5 = !!arguments[0]; } else { return config.html5; } } setBaseUrl(baseUrl) { config.baseUrl = baseUrl; } getBaseUrl() { return config.baseUrl; } getColors() { return config.colors; } enableScopeLogs(){ config.scopeLogs = true; } disableScopeLogs(){ config.scopeLogs = false; } isScopeLogsEnabled() { return !!config.scopeLogs; } setRouteProviderName(provider) { config.routeProviderName = provider; } getRouteProviderName() { return config.routeProviderName; } setModuleName(name) { config.moduleName = name; } getModuleName() { return config.moduleName; } } export default new ConfigManager();
JavaScript
0.000001
@@ -335,18 +335,23 @@ e: ' -ngx.defaul +frankland.valen t',%0A
a24a492bc61bd7381bf78b55bbd74a6c50b364c5
add blog and youtube links
src/components/header.js
src/components/header.js
import React from 'react' import { NavLink } from 'react-router-dom' import logo from '../logo.jpg' export default () => ( <nav className='pa3 pa4-ns mb4'> <NavLink className='link f6 f5-ns ttu near-black dib mr3' to='/'><img alt='avatar' className='br-100 h2 h3-ns w2 w3-ns dib v-mid' src={logo} /></NavLink> <NavLink activeClassName='b' className='link f6 f5-ns ttu near-black hover-near-white hover-bg-near-black dib mr3 pa1 br1 ba b--near-black' to='/schedule'>schedule</NavLink> <a className='link f6 f5-ns ttu near-black hover-near-white hover-bg-near-black dib mr3 pa1 br1 ba b--near-black' href='https://twitch.tv/bsdlp' title='twitch'>twitch</a> <a className='link f6 f5-ns ttu near-black hover-near-white hover-bg-near-black dib mr3 pa1 br1 ba b--near-black' href='https://twitter.com/bsdlp' title='twitter'>twitter</a> </nav> )
JavaScript
0
@@ -844,16 +844,399 @@ ter%3C/a%3E%0A + %3Ca className='link f6 f5-ns ttu near-black hover-near-white hover-bg-near-black dib mr3 pa1 br1 ba b--near-black' href='https://medium.com/@bsdlp' title='blog'%3Eblog%3C/a%3E%0A %3Ca className='link f6 f5-ns ttu near-black hover-near-white hover-bg-near-black dib mr3 pa1 br1 ba b--near-black' href='https://www.youtube.com/channel/UCQkMNF9ZWl7ehUNEYZuLvOQ' title='youtube'%3Eyoutube%3C/a%3E%0A %3C/nav%3E
a1e90f64703472196ac2e3e93d9e4a3ba929d8cb
add REQUEST_BUS_STOPS_AROUND_ME action and action factory
src/actions/actions.js
src/actions/actions.js
import fetch from 'isomorphic-fetch' // // action types // export const REQUEST_BUS_STOPS_AROUND_ME = 'REQUEST_BUS_STOPS_AROUND_ME' export const RECEIVE_BUS_STOPS_AROUND_ME = 'RECEIVE_BUS_STOPS_AROUND_ME' // // action creators // export function requestBusStopsAroundMe(meters, coors) { return { type: REQUEST_BUS_STOPS_AROUND_ME, meters, coors } } export function receiveBusStopsAroundMe(BusStopsAroundMe) { return { type: RECEIVE_BUS_STOPS_AROUND_ME, BusStopsAroundMe } } 5*
JavaScript
0
@@ -1,42 +1,4 @@ -import fetch from 'isomorphic-fetch'%0A%0A //%0A/ @@ -94,80 +94,62 @@ ME'%0A -export const RECEIVE_BUS_STOPS_AROUND_ME = 'RECEIVE_BUS_STOPS_AROUND_ME' +%0A//%0A// other constants%0A//%0A%0Aexport loadingState = false %0A%0A// @@ -288,170 +288,164 @@ -meters,%0A coors%0A %7D%0A%7D%0A%0Aexport function receiveBusS +text: 'get all the routes and bus s tops -A + a round -Me(BusStopsAroundMe) %7B%0A return %7B%0A type: RECEIVE_BUS_STOPS_AROUND_ME,%0A BusStopsAroundM + user geolocalizacion',%0A meters: meters,%0A latitude: coors.laitude,%0A longitude: coors.longitud e%0A %7D%0A%7D%0A 5*%0A @@ -444,8 +444,4 @@ %7D%0A%7D%0A - 5*%0A
9480c748e474be3fc1d700c3ccf513681297bf6b
fix memberlist bug
src/components/navbar.js
src/components/navbar.js
import React, { Component } from 'react'; import { SplitButton, MenuItem, Popover, OverlayTrigger, Navbar, NavItem, Nav, Button, ButtonGroup, Glyphicon, InputGroup, FormGroup, FormControl } from 'react-bootstrap'; import axios from 'axios'; class navbar extends Component { constructor(props) { super(props); this.state = {}; this.popover = ( <Popover id="popover-trigger-click-root-close" title="No Team Selected" /> ); this.selectTeam = this.selectTeam.bind(this); } componentDidMount() { this.selectTeam(this.props.selectedTeam.id); } selectTeam = (teamId) => { if (typeof this.props.teams === 'undefined' || this.props.teams.length === 0) { axios.get('/api/profile') .then((res) => { let team; team = res.data.teams[0]; const teamMemberCnt = res.data.teams[0].members.length; this.popover = ( <Popover id="popover-trigger-click-root-close" title={`${teamMemberCnt} members`}> {team.members.map(this.renderemail)} </Popover> ); }) .catch((err) => { console.log(err); }); } else { const teamName = this.props.teams.find(team => team.id === teamId).name; const teamMemberCnt = this.props.teams.find(team => team.id === teamId).members.length; this.popover = ( <Popover id="popover-trigger-click-root-close" title={`${teamMemberCnt} members`}> {this.renderMemberList(teamId)} </Popover> ); this.props.setSelectedTeam({ id: teamId, name: teamName, }); } } renderTeamList() { if (typeof this.props.user.team === 'undefined' || this.props.user.team.length === 0) { return <option>No team, haha.</option>; } else { return this.props.user.team.map(item => <MenuItem value={item} key={item} eventKey={item}>{this.props.teams.find(team => team.id === item).name}</MenuItem>); } } renderMemberList(teamId) { const selectedTeamObj = this.props.teams.find(team => team.id === teamId); return selectedTeamObj.members.map(item => <li key={item.id}>{item.username} <a href={`mailto:${item.email}`}><u>{item.email}</u></a></li>); } renderemail = (item) => { return <li key={item.id}>{item.username} <a href={`mailto:${item.email}`}><u>{item.email}</u></a></li>; } handleNavLink() { window.location = '/logout'; } render() { return ( <Navbar className="nav-not-react"> <Navbar.Header> <Navbar.Brand> <h2 className="logo"> <span className="letter letter-width">c</span> <span className="awesome letter-width">a</span> <span className="wtf letter-width">l</span> <span className="cool letter-width">t</span> <span className="awesome letter-width">c</span> <span className="letter letter-width">h</span> <span className="wtf letter-width">a</span> </h2> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> <NavItem> <OverlayTrigger id="nav-overlay" trigger="click" rootClose placement="bottom" overlay={this.popover}> <SplitButton title={this.props.selectedTeam.name || 'Select Team'} id="dropdown-team-sel" onSelect={event => this.selectTeam(event)}> {this.renderTeamList()} </SplitButton> </OverlayTrigger> </NavItem> </Nav> <Nav pullRight> <NavItem> <Navbar.Form> <FormGroup> <InputGroup> <InputGroup.Addon><Glyphicon glyph="search" /></InputGroup.Addon> <FormControl type="text" placeholder="Search" /> </InputGroup> </FormGroup> </Navbar.Form> </NavItem> <NavItem> <ButtonGroup> <Button>{this.props.user.username}</Button> <Button onClick={this.handleNavLink} bsStyle="danger">Logout</Button> </ButtonGroup> </NavItem> </Nav> </Navbar.Collapse> </Navbar> ); } } export default navbar;
JavaScript
0.000001
@@ -711,15 +711,19 @@ api/ -profile +team/select ')%0A @@ -760,38 +760,134 @@ -le +cons t team -;%0A +id = res.data.id;%0A axios.get('/api/profile')%0A .then((resp) =%3E %7B%0A const team +s = res +p .dat @@ -897,13 +897,122 @@ eams -%5B0%5D;%0A +;%0A for (let i = 0; i %3C teams.length; i += 1) %7B%0A if (teamid === teams%5Bi%5D.id) %7B%0A @@ -1043,24 +1043,15 @@ t = -res.data. teams%5B -0 +i %5D.me @@ -1070,24 +1070,32 @@ ;%0A + this.popover @@ -1091,32 +1091,40 @@ his.popover = (%0A + %3CPop @@ -1216,21 +1216,33 @@ + %7Bteam +s%5Bi%5D .members @@ -1269,32 +1269,40 @@ l)%7D%0A + %3C/Popover%3E%0A @@ -1302,24 +1302,161 @@ %3E%0A + );%0A %7D%0A %7D%0A %7D)%0A .catch((erro) =%3E %7B%0A console.log(erro);%0A %7D );%0A %7D
113c579707135f9a95c3ad84acf0919bbcf40d88
Add object counter.
qml/scripts/levelLogic.js
qml/scripts/levelLogic.js
var NUM_ROCKETS = 5; var rocketUrl = Qt.resolvedUrl("../entities/Rocket.qml"); var objects = {}; var gravityWells = []; var impulse = Qt.point(0,0); var objectSettings = {"x": 0, "y": 0, "rotation": 60, "target": null } function init() { } function createRockets(target) { for(var i = 0; i < NUM_ROCKETS; i++) { var randomPosX = generateRandomValueBetween(20, level.width-20); var randomPosY = generateRandomValueBetween(20, level.height-20); objectSettings.x = randomPosX; objectSettings.y = randomPosY; objectSettings.target = target; var entityId = entityManager.createEntityFromUrlWithProperties(rocketUrl, objectSettings); addObject(entityId); } } function setGravityWells(wells) { gravityWells = wells; } function generateRandomValueBetween(minimum, maximum) { return Math.random()*(maximum-minimum) + minimum; } function addObject(entityId) { objects[entityId] = entityManager.getEntityById(entityId); } function removeObject(entityId) { delete objects[entityId]; } function applyGravity() { for(var i = 0; i < gravityWells.length; ++i) { var gravityPosition = gravityWells[i].getPosition(); for(var j in objects) { var object = objects[j]; if(object.getPosition) { var objectPosition = object.getPosition(); var dx = gravityPosition.x - objectPosition.x; var dy = gravityPosition.y - objectPosition.y; var distance = dx*dx + dy*dy; var angle = Math.atan2(dy, dx); impulse.x = 10*Math.cos(angle); impulse.y = 10*Math.sin(angle); object.applyGravityImpulse(impulse); } } } }
JavaScript
0
@@ -90,16 +90,38 @@ s = %7B%7D;%0A +var objectsCount = 0;%0A var grav @@ -974,16 +974,34 @@ ityId);%0A + objectsCount++;%0A %7D%0A%0Afunct @@ -1057,16 +1057,33 @@ ityId%5D;%0A + objectsCount--%0A %7D%0A%0Afunct
2847c820f2f1dcb4de3a4a79ef247f82d6a00582
fix #244
methods/indicators/RSI.js
methods/indicators/RSI.js
// required indicators var EMA = require('./EMA.js'); var Indicator = function(weight) { this.lastPrice = 0; this.weight = weight; this.weightEma = 2 * weight - 1; this.avgU = new EMA(this.weightEma); this.avgD = new EMA(this.weightEma); this.u = 0; this.d = 0; this.rs = 0; this.rsi = 0; this.age = 0; } Indicator.prototype.update = function(candle) { var open = candle.open; var close = candle.close; if(close > open) { this.u = close - open; this.d = 0; } else { this.u = 0; this.d = open - close; } this.avgU.update(this.u); this.avgD.update(this.d); this.rs = this.avgU.result / this.avgD.result; this.rsi = 100 - (100 / (1 + this.rs)); this.age++; } module.exports = Indicator;
JavaScript
0.000001
@@ -98,12 +98,12 @@ last -Pric +Clos e = @@ -379,35 +379,16 @@ var -open = candle.open;%0A var c +currentC lose @@ -415,19 +415,36 @@ if(c -lose %3E open +urrentClose %3E this.lastClose ) %7B%0A @@ -707,16 +707,48 @@ .age++;%0A + this.lastClse = currentClose;%0A %7D%0A%0Amodul
5b62e0495f587402177e08eb03a3940136e9ba86
Set the 404.swig rendering to use the blank.swig layout
middleware/controllers.js
middleware/controllers.js
'use strict'; var debug = require('debug')('fundation'); var debugRoutes = require('debug')('fundation:controllers'); var glob = require("glob"); var path = require('path'); /** * Routes * * @param {Application} app * @api private */ module.exports = function(app) { debug("Setting up Controllers"); // // Remove the x-powered-by // app.use(function (req, res, next) { res.header("X-powered-by", "Fundation, the fun way to go!"); next(); }); // // Enable case sensitivity // "/Foo" and "/foo" will be treated as seperate routes // app.set('case sensitive routing', true); // // Enable strict routing, // "/foo" and "/foo/" will be treated as seperate routes // app.set('strict routing', true); // Read the routes folder glob("controllers/*.js", function (error, files) { // Add all of the routes files.forEach(function (routePath) { // http://stackoverflow.com/questions/5055853/how-do-you-modularize-node-js-w-express debugRoutes("Route: " + routePath); require(path.resolve(routePath))(app); }); // 404 for pages not in the routes app.use(function (req, res, next) { res.status(404); res.render('404.swig'); }); // http://expressjs.com/starter/faq.html#how-do-you-setup-an-error-handler app.use(function (error, req, res, next) { // output errors debug(error); switch(error.status) { case 400: res.status(400); res.render('404.swig'); break; case 404: res.status(404); res.render('404.swig'); break; default: res.status(500); res.render('500.swig', { error: ( app.get('env') === 'production' ) ? '' : error.stack, layout: "blank.swig" }); } }); }); };
JavaScript
0
@@ -1518,32 +1518,80 @@ ender('404.swig' +, %7B%0A layout: %22blank.swig%22%0A %7D );%0A bre @@ -1666,24 +1666,72 @@ r('404.swig' +, %7B%0A layout: %22blank.swig%22%0A %7D );%0A
3c9c7d909a2046fb7f4bba55a165ea46e5e22def
Optimize Trending Movies and Upcoming Movies Queries.
src/app/index.route.js
src/app/index.route.js
(function() { 'use strict'; angular .module('movieApp') .config(routerConfig); /** @ngInject */ function routerConfig($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/', templateUrl: 'app/main/main.html', controller: 'MainController', controllerAs: 'vm', resolve: { trendingMovies: function ($http) { return $http.get('https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=6101bba1eadfefbac6a1e1549e861665') .then(function (res) { return res.data.results; }); }, upcomingMovies: function ($http) { return $http.get('https://api.themoviedb.org/3/discover/movie?primary_release_date.gte=2017-05-24&api_key=6101bba1eadfefbac6a1e1549e861665') .then(function (res) { return res.data.results; }); } } }); $urlRouterProvider.otherwise('/'); } })();
JavaScript
0
@@ -392,32 +392,33 @@ ction ($http) %7B%0A +%0A retu @@ -417,232 +417,799 @@ -return $http.get('https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=6101bba1eadfefbac6a1e1549e861665')%0A .then(function (res) %7B%0A return res.data.results;%0A %7D); +var storedValue = localStorage.getItem('trendingMovies');%0A var lastUpdate = localStorage.getItem('trendingMoviesUpdateTime');%0A%0A var duration = lastUpdate ? (lastUpdate - (new Date).getTime()) : 0;%0A%0A if(duration %3E 3600000)%0A storedValue = null;%0A%0A var httpRequest = $http.get('https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=6101bba1eadfefbac6a1e1549e861665')%0A .then(function (res) %7B%0A localStorage.setItem('trendingMovies', JSON.stringify(res.data.results));%0A localStorage.setItem('trendingMoviesUpdateTime', (new Date).getTime());%0A return res.data.results;%0A %7D);%0A%0A return storedValue ? JSON.parse(storedValue) : httpRequest;%0A %0A @@ -1259,24 +1259,25 @@ n ($http) %7B%0A +%0A @@ -1276,22 +1276,477 @@ -return +var storedValue = localStorage.getItem('upcomingMovies');%0A var lastUpdate = localStorage.getItem('upcomingMoviesUpdateTime');%0A%0A var duration = lastUpdate ? (lastUpdate - (new Date).getTime()) : 0;%0A%0A if(duration %3E 3600000)%0A storedValue = null;%0A%0A var today = new Date();%0A var queryDate = (today.getFullYear() + 1) + '-' + today.getMonth() + '-' + today.getDate();%0A%0A var httpRequest = $http.g @@ -1822,18 +1822,24 @@ gte= -2017-05-24 +' + queryDate +' &api @@ -1935,49 +1935,300 @@ -return res.data.results;%0A %7D) +localStorage.setItem('upcomingMovies', JSON.stringify(res.data.results));%0A localStorage.setItem('upcomingMoviesUpdateTime', (new Date).getTime());%0A return res.data.results;%0A %7D);%0A%0A return storedValue ? JSON.parse(storedValue) : httpRequest ;%0A
b791c78ebfde6e3721b6818edda9875198538cb2
Remove created flag
migration/fixtures/v12.js
migration/fixtures/v12.js
/* eslint-disable no-magic-numbers */ // NOTE This file is an important documentation of the data structure at v12. // NOTE The properties changed from the prev version are marked with NOTE var c = require('./common'); var db = require('tresdb-db'); module.exports = { collections: { config: [{ key: 'schemaVersion', value: 12, // NOTE }], // NOTE New collection attachments: [ { key: 'ewdsf3kk', user: 'admin', time: '2009-09-04T23:44:21.000Z', filepath: '2009/RxRvKSlbl/radar.jpg', // the uploads/ contains this... mimetype: 'image/jpeg', thumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg', // ...and this. thumbmimetype: 'image/jpeg', deleted: false, data: {}, // optional additional data e.g. overlay positions }, { key: 'adebd2rq', user: 'admin', time: '2009-09-04T23:44:21.000Z', filepath: '2021/EdvjkeEdf/tunnel-ground.jpg', // see uploads/ mimetype: 'image/jpeg', /// small pic = same image thumbfilepath: '2021/EdvjkeEdf/tunnel-ground.jpg', thumbmimetype: 'image/jpeg', deleted: false, data: {}, }, ], entries: [{ _id: db.id('581f166110a1482dd0b7ea01'), attachments: [], // NOTE comments: [], // NOTE created: true, // NOTE deleted: false, flags: [], // NOTE locationId: c.irbeneId, markdown: 'A ghost town', // NOTE published: false, // NOTE time: '2009-09-04T23:44:21.000Z', type: 'location_entry', user: 'admin', // NOTE possible entry.overlay moved to attachment.data.overlay }, { _id: db.id('581f166110a1482dd0b7ea02'), attachments: ['ewdsf3kk'], // NOTE comments: [ { time: '2009-10-04T19:55:01.000Z', user: 'admin', message: 'Hello world', attachments: [], // NOTE }, { time: '2021-02-10T20:30:01.000Z', user: 'admin', message: 'Tunnel ground', attachments: ['adebd2rq'], // NOTE }, ], created: true, // NOTE deleted: false, flags: ['visit'], // NOTE locationId: c.irbeneId, markdown: '', // NOTE null to '' published: false, // NOTE time: '2009-10-02T11:11:01.000Z', type: 'location_entry', user: 'admin', }], // No event _ids needed, they are created in run time. events: [{ data: { lng: 21.857705, lat: 57.55341, }, locationId: c.irbeneId, locationName: 'Irbene', time: '2009-07-30T10:44:57.000Z', type: 'location_created', user: 'admin', }, { data: { entryId: db.id('581f166110a1482dd0b7ea01'), markdown: 'A ghost town', created: true, // NOTE changed value // NOTE no need to list empty flags, comments or attachments // NOTE implicit published:false and deleted:false }, locationId: c.irbeneId, locationName: 'Irbene', time: '2009-09-04T23:44:21.000Z', type: 'location_entry_created', user: 'admin', }, { data: { newTags: ['abandoned'], oldTags: [], }, locationId: c.irbeneId, locationName: 'Irbene', time: '2009-09-04T23:45:20.000Z', type: 'location_tags_changed', // legacy event type user: 'admin', }, { data: { entryId: db.id('581f166110a1482dd0b7ea02'), created: true, // NOTE markdown: '', // NOTE null to '' attachments: ['ewdsf3kk'], // NOTE ref to attachment key // NOTE isVisit:false converted to implicit flags:[] }, locationId: c.irbeneId, locationName: 'Irbene', time: '2009-10-02T11:11:01.000Z', type: 'location_entry_created', user: 'admin', }, { data: { entryId: db.id('581f166110a1482dd0b7ea02'), message: 'Dang radar, dude', // NOTE no change but implicit attachments:[] }, locationId: c.irbeneId, locationName: 'Irbene', time: '2009-10-04T19:55:01.000Z', type: 'location_entry_comment_created', user: 'admin', }], users: [{ admin: true, email: '[email protected]', hash: c.PASSWORD, name: 'admin', points: 0, // points7days: created by worker // points30days: created by worker status: 'active', createdAt: '2009-07-29T12:34:56.000Z', // NOTE loginAt: '2009-10-05T12:34:56.000Z', // NOTE }], locations: [{ _id: c.irbeneId, creator: 'admin', deleted: false, geom: { type: 'Point', coordinates: [21.857705, 57.55341], }, layer: 12, childLayer: 0, isLayered: true, name: 'Irbene', points: 0, places: [], status: 'abandoned', type: 'default', visits: [], text1: '', text2: '', }], }, };
JavaScript
0.000001
@@ -1334,37 +1334,8 @@ OTE%0A - created: true, // NOTE%0A @@ -2097,37 +2097,8 @@ %5D,%0A - created: true, // NOTE%0A
875c5e1f10d31e09372050ed58f41f9d7748aab6
set background color of views
main/viewManager.js
main/viewManager.js
var viewMap = {} // id: view function createView (id, webPreferencesString, boundsString, events) { let view = new electron.BrowserView(JSON.parse(webPreferencesString)) events.forEach(function (ev) { view.webContents.on(ev.event, function (e) { if (ev.options && ev.options.preventDefault) { e.preventDefault() } mainWindow.webContents.send('view-event', { id: id, name: ev.event, args: Array.prototype.slice.call(arguments).slice(1) }) }) }) view.webContents.on('ipc-message', function (e, data) { mainWindow.webContents.send('view-ipc', { id: id, name: data[0], data: data[1] }) }) view.setBounds(JSON.parse(boundsString)) viewMap[id] = view return view } function destroyView (id) { // destroy an associated partition var partition = viewMap[id].webContents.getWebPreferences().partition if (partition) { session.fromPartition(partition).destroy() } if (viewMap[id] === mainWindow.getBrowserView()) { mainWindow.setBrowserView(null) } viewMap[id].destroy() delete viewMap[id] } function setView (id) { mainWindow.setBrowserView(viewMap[id]) } function setBounds (id, bounds) { viewMap[id].setBounds(bounds) } function focusView (id) { viewMap[id].webContents.focus() } function hideCurrentView () { var view = mainWindow.getBrowserView() if (view) { view.setBounds({x: 0, y: 0, width: 0, height: 0}) } mainWindow.webContents.focus() } function getView (id) { return viewMap[id] } ipc.on('createView', function (e, args) { createView(args.id, args.webPreferencesString, args.boundsString, args.events) }) ipc.on('destroyView', function (e, id) { destroyView(id) }) ipc.on('setView', function (e, args) { setView(args.id) setBounds(args.id, args.bounds) if (args.focus) { focusView(args.id) } }) ipc.on('setBounds', function (e, args) { setBounds(args.id, args.bounds) }) ipc.on('focusView', function (e, id) { focusView(id) }) ipc.on('hideCurrentView', function (e) { hideCurrentView() }) ipc.on('callViewMethod', function (e, data) { var webContents = viewMap[data.id].webContents var result = webContents[data.method].apply(webContents, data.args) if (data.callId) { mainWindow.webContents.send('async-call-result', {callId: data.callId, data: result}) } }) ipc.on('getCapture', function (e, data) { viewMap[data.id].webContents.capturePage(function (img) { var size = img.getSize() if (size.width === 0 && size.height === 0) { return } img = img.resize({width: data.width, height: data.height}) mainWindow.webContents.send('captureData', {id: data.id, url: img.toDataURL()}) }) }) global.getView = getView
JavaScript
0
@@ -726,16 +726,51 @@ ring))%0A%0A + view.setBackgroundColor('#fff')%0A%0A viewMa
23038c3ebb6d632dac0e611b52b49feda0d49baa
Refactor to create closure
bin/gest.js
bin/gest.js
#! /usr/bin/env node const args = require('args') const path = require('path') const { printSchema } = require('graphql') const chalk = require('chalk') const gest = require('../src/index') const REPL = require('../src/REPL') const { readFile, checkPath, flagsToOptions, colorResponse, errorMessage, findFiles } = require('../src/util') args .option(['S', 'schema'], 'Path to your GraphQL schema') .option(['I', 'inspect'], 'Print your GraphQL schema options') .option(['H', 'header'], 'HTTP request header') .option(['B', 'baseUrl'], 'Base URL for sending HTTP requests') .option('all', 'Run all *.query files') const flags = args.parse(process.argv) try { if (!flags.help && !flags.version) { let config try { config = require(path.join(process.cwd(), 'package.json')).gest } catch (e) {} const options = Object.assign({ schema: 'schema.js' }, config, flagsToOptions(flags)) const schema = require(path.join(process.cwd(), options.schema)) if (flags.inspect) { console.log(printSchema(schema)) process.exit() } if (flags.all) { findFiles() .then(values => values.map(v => { console.log(`${chalk.black.bgYellow(' RUNS ')} ${chalk.dim(v.replace(process.cwd(), '.'))}`) return v }) .map(v => readFile(v) .then(gest(schema, options)) .then(value => { if (value.errors && value.data) return `${chalk.black.bgYellow(' WARNING ')} ${chalk.dim(v.replace(process.cwd(), '.'))}` if (value.errors) return `${chalk.black.bgRed(' FAIL ')} ${chalk.dim(v.replace(process.cwd(), '.'))}` return `${chalk.black.bgGreen(' PASS ')} ${chalk.dim(v.replace(process.cwd(), '.'))}` }) .then(console.log) .catch(console.log) )) .catch(console.log) } else { // DEFAULT COMMAND if (args.sub && args.sub.length) { checkPath(path.join(process.cwd(), args.sub[0])) .then(readFile) .catch(() => args.sub[0]) .then(gest(schema, options)) .then(colorResponse) .then(console.log) .catch(console.log) } else { // REPL REPL(schema, options) } } } } catch (e) { console.log(errorMessage(e)) }
JavaScript
0
@@ -1182,53 +1182,16 @@ cons -ole.log(%60$%7Bchalk.black.bgYellow(' RUNS ')%7D $%7B +t rep = chal @@ -1230,11 +1230,8 @@ .')) -%7D%60) %0A @@ -1243,49 +1243,63 @@ -return v%0A %7D)%0A .map(v =%3E +console.log(%60$%7Bchalk.black.bgYellow(' RUNS ')%7D $%7Brep%7D%60) %0A @@ -1492,48 +1492,11 @@ %7D $%7B -chalk.dim(v.replace(process.cwd(), '.')) +rep %7D%60%0A @@ -1573,48 +1573,11 @@ %7D $%7B -chalk.dim(v.replace(process.cwd(), '.')) +rep %7D%60%0A @@ -1638,48 +1638,11 @@ %7D $%7B -chalk.dim(v.replace(process.cwd(), '.')) +rep %7D%60%0A @@ -1734,16 +1734,17 @@ +%7D ))%0A
e0462872d6103adc00adab64c31a728d4c90b92b
update bin
bin/jung.js
bin/jung.js
#!/usr/bin/env node var Jung = require('../').Jung , nopt = require('nopt') , fs = require('fs') , path = require('path') , color = require('bash-color') , jung = require('../package.json') var noptions = { root: Array , files: Array , dirs: Array , notfiles: Array , notdirs: Array , wait: Number , run: Boolean , timeout: Number , kill: Boolean , quiet: Boolean , help: Boolean , version: Boolean } var shorts = { r: ['--root'] , R: ['--run'] , d: ['--dirs'] , f: ['--files'] , w: ['--wait'] , t: ['--timeout'] , D: ['--notdirs'] , F: ['--notfiles'] , q: ['--quiet'] , k: ['--kill'] , h: ['--help'] , v: ['--version'] } var options = nopt(noptions, shorts, process.argv) , commandPos = process.argv.indexOf('--') + 1 if(options.version) return version() if(options.help || !commandPos) return help() var command = process.argv.slice(commandPos) options.names = (nopt( noptions , shorts , process.argv.slice(0, process.argv.indexOf('--')) ).argv.remain || []).map(resolve) var jungInstance = Jung(options, command) jungInstance.start() if(!options.quiet) { jungInstance.on('error', displayError) jungInstance.on('killing', displayKill) jungInstance.on('queueing', displayQueue) jungInstance.on('running', displayRun) jungInstance.on('ran', displayRan) } function displayRun(command) { process.stdout.write(color.green('** Running `' + command + '`') + '\n') } function displayKill() { process.stdout.write(color.red('** Killing old process') + '\n') } function displayQueue() { process.stdout.write(color.blue('-- Queueing new process') + '\n') } function displayRan(command, code) { if(!code) return process.stderr.write(color.red('@@ Command exited with code ' + code) + '\n') } function displayError(error) { process.stderr.write(color.red(error.message) + '\n') } function version() { return process.stdout.write( color.yellow('jung version ' + jung.version) + '\n' ) } function help() { version() return fs.createReadStream(path.join(__dirname, '..', 'help.txt')) .pipe(process.stderr) } function resolve(name) { return path.resolve(name) }
JavaScript
0
@@ -18,20 +18,18 @@ de%0A%0Avar -Jung +fs = requi @@ -36,27 +36,21 @@ re(' -../').Jung +fs') %0A , -nopt +path = r @@ -61,21 +61,25 @@ re(' -nopt')%0A , fs +path')%0A%0Avar color = r @@ -82,37 +82,45 @@ = require(' -fs +bash-color ')%0A , -path +nopt = require(' @@ -123,54 +123,59 @@ re(' -path')%0A , color = require('bash-color +nopt')%0A%0Avar jung = require('../package.json ')%0A , -j +J ung @@ -188,28 +188,16 @@ ire('../ -package.json ')%0A%0Avar
cc539d96bc2d14796279fc2c4c867bb6a3b2df06
Fix buffers completion when there are some tabs with undefined title.
src/background/tabs.js
src/background/tabs.js
const closeTab = (id) => { return browser.tabs.remove(id); }; const reopenTab = () => { return browser.sessions.getRecentlyClosed({ maxResults: 1 }).then((sessions) => { if (sessions.length === 0) { return; } let session = sessions[0]; if (session.tab) { return browser.sessions.restore(session.tab.sessionId); } return browser.sessions.restore(session.window.sessionId); }); }; const selectAt = (index) => { return browser.tabs.query({ currentWindow: true }).then((tabs) => { if (tabs.length < 2) { return; } if (index < 0 || tabs.length <= index) { throw new RangeError(`tab ${index + 1} does not exist`); } let id = tabs[index].id; return browser.tabs.update(id, { active: true }); }); }; const selectByKeyword = (current, keyword) => { return browser.tabs.query({ currentWindow: true }).then((tabs) => { let matched = tabs.filter((t) => { return t.url.includes(keyword) || t.title.includes(keyword); }); if (matched.length === 0) { throw new RangeError('No matching buffer for ' + keyword); } for (let tab of matched) { if (tab.index > current.index) { return browser.tabs.update(tab.id, { active: true }); } } return browser.tabs.update(matched[0].id, { active: true }); }); }; const getCompletions = (keyword) => { return browser.tabs.query({ currentWindow: true }).then((tabs) => { let matched = tabs.filter((t) => { return t.url.includes(keyword) || t.title.includes(keyword); }); return matched; }); }; const selectPrevTab = (current, count) => { return browser.tabs.query({ currentWindow: true }).then((tabs) => { if (tabs.length < 2) { return; } let select = (current - count + tabs.length) % tabs.length; let id = tabs[select].id; return browser.tabs.update(id, { active: true }); }); }; const selectNextTab = (current, count) => { return browser.tabs.query({ currentWindow: true }).then((tabs) => { if (tabs.length < 2) { return; } let select = (current + count) % tabs.length; let id = tabs[select].id; return browser.tabs.update(id, { active: true }); }); }; const selectFirstTab = () => { return browser.tabs.query({ currentWindow: true }).then((tabs) => { let id = tabs[0].id; return browser.tabs.update(id, { active: true }); }); }; const selectLastTab = () => { return browser.tabs.query({ currentWindow: true }).then((tabs) => { let id = tabs[tabs.length - 1].id; return browser.tabs.update(id, { active: true }); }); }; const reload = (current, cache) => { return browser.tabs.reload( current.id, { bypassCache: cache } ); }; const updateTabPinned = (current, pinned) => { return browser.tabs.query({ currentWindow: true, active: true }) .then(() => { return browser.tabs.update(current.id, { pinned: pinned }); }); }; const toggleTabPinned = (current) => { updateTabPinned(current, !current.pinned); }; const duplicate = (id) => { return browser.tabs.duplicate(id); }; export { closeTab, reopenTab, selectAt, selectByKeyword, getCompletions, selectPrevTab, selectNextTab, selectFirstTab, selectLastTab, reload, updateTabPinned, toggleTabPinned, duplicate };
JavaScript
0
@@ -1511,32 +1511,43 @@ udes(keyword) %7C%7C + t.title && t.title.include
2f9bb88adb9323c5adda0481a87cf3e97a881b6f
Fix package.json location
bin/moro.js
bin/moro.js
#!/usr/bin/env node 'use strict' // packages const prog = require('caporal') const chalk = require('chalk') const updateNotifier = require('update-notifier') // ours const pkg = require('./package.json') updateNotifier({ pkg }).notify() const spinner = require('../lib/utils/spinner.js') console.log(` ${chalk.red('💙')} Moro \\o/ `) spinner.start() const VERSION = pkg.version const COMMAND_DESCRIPTIONS = require('../lib/constants.json').TEXT.commands // importing all the commands const configManager = require('../lib/utils/configManager.js') configManager.initConfigFile() const commands = require('../lib/commands.js') const helpers = require('../lib/utils/helpers.js') // All the possible commands and arguments: // moro // moro hi // moro hi 08:23 // moro bye // moro bye 17:30 // moro break 32 // moro break -32 // moro clear --yes // moro report // moro report --all // moro status // moro config --day 8.5 // moro config --break 45 // moro config --format 'ddd, MMM, DD' // moro config --database-path '/home/GraceHopeer/moro.db' prog // default command .version(VERSION) .description(COMMAND_DESCRIPTIONS.default) .action(commands.nextUndoneAction) // // //////////////////// // hi // .command('hi', COMMAND_DESCRIPTIONS.hi) .alias('h') .argument('[start]', COMMAND_DESCRIPTIONS.hiStart, /^\d\d:\d\d$/) .action(commands.setStart) // // //////////////////// // bye // .command('bye', COMMAND_DESCRIPTIONS.bye) .alias('b') .argument('[end]', COMMAND_DESCRIPTIONS.byeEnd, /^\d\d:\d\d$/) .action(commands.setEnd) // // //////////////////// // break // .command('break', COMMAND_DESCRIPTIONS.break) .argument('<duration>', COMMAND_DESCRIPTIONS.breakDuration, /^[\d]+$/) .action(commands.setBreak) // // //////////////////// // // report // .command('report', COMMAND_DESCRIPTIONS.report) .alias('r') .option('--all', COMMAND_DESCRIPTIONS.reportAll) .action(commands.report) // // //////////////////// // // status // .command('status', COMMAND_DESCRIPTIONS.status) .alias('st') .action(commands.report) // // //////////////////// // clear // .command('clear', '') .option('--yes', 'you need to confirm before I remove everything') .action((args, options, logger) => { commands.clearData(args, options, logger, spinner) }) // // //////////////////// // config // .command('config', COMMAND_DESCRIPTIONS.config) .alias('c') .option('--day <duration>', COMMAND_DESCRIPTIONS.configDay, prog.FLOAT) .option('--break <duration>', COMMAND_DESCRIPTIONS.breakDuration, prog.INT) .option( '--format <pattern>', COMMAND_DESCRIPTIONS.configPattern, helpers.formatValidator ) .option( '--database-path [path]', COMMAND_DESCRIPTIONS.dbPath, helpers.pathValidator ) .action(commands.setConfig) // // //////////////////// // note // .command('note', COMMAND_DESCRIPTIONS.note) .alias('n') .argument('[note...]', COMMAND_DESCRIPTIONS.noteNote) .action(commands.addNote) // // //////////////////// // about // .command('about', COMMAND_DESCRIPTIONS.about) .alias('a') .action(commands.about) // let it begin! prog.parse(process.argv)
JavaScript
0.000236
@@ -183,16 +183,17 @@ quire('. +. /package
12a00da402b2da010275b4ba96f26ac9fd98b953
remove bookmark correctly
src/bookmarks/index.js
src/bookmarks/index.js
const Ractive = require('ractive'); const fade = require('ractive-transitions-fade'); const { EVENT, bookmarks, github, helper } = require('../services'); const $ = require('../util'); const BuildStatus = require('./build-status'); const DEFAULT_REPO_NAME = 'Pages'; // for ungrouped pages const DEFAULT_PROJECTS_REPO_NAME = 'Projects'; // for ungrouped projects const issueTypeCls = { pr: 'ion-ios-git-pull-request', issue: 'ion-ios-bug-outline', project: 'ion-ios-cube-outline', page: 'ion-ios-document-outline', default: 'ion-ios-document-outline', }; const template = ` {{#groupedBookmarks:repo}} <div class="repo-box"> <h2> {{#if hasUrl }} <span class="hdr">{{repoShortName}}</span> {{else}} <a href="{{repoUrl}}" class="hdr" on-click="openRepo">{{repoShortName}}</a> {{/if}} </h2> <ul class="repo-box-issues"> {{#items}} <li class="issue-box {{issueCls(this)}} {{state}} type-{{type}} {{unread ? 'unread' : ''}}" fade-in-out> <i class="issue-icon {{issueIcon(this)}}"></i> <a href="{{url}}" class="btn bookmark" title="{{id || name}}" on-click="openIssue">{{name}}</a> {{#if type === 'pr'}}<BuildStatus issue="{{this}}" />{{/if}} </li> {{/items}} </ul> </div> {{/groupedBookmarks}} `; const data = { bookmarks: [], issueIcon: iss => issueTypeCls[iss.type], issueCls: iss => { const repo = (iss.repo || '').replace(/[\/\.]/g, '-').toLowerCase(); return iss.id ? `issue-${repo}-${iss.id}` : ''; }, }; let throttled = null; const throttle = () => { if (throttled) clearTimeout(throttled); throttled = setTimeout(() => { throttled = null; }, 1000); }; function openIssue (e) { e.original.preventDefault(); if (throttled) return throttle(); // if clicked during quiet time - throttle again throttle(); const iss = e.get(); if (iss) { iss.unread = false; bookmarks.setUnreadByUrl(iss.url, false); $.trigger(EVENT.url.change.to, iss.url); } } function openRepo (e) { $.trigger(EVENT.url.change.to, e.get().repoUrl); return false; } function addBookmark (issue) { issue = copleteIssueModel(issue); bookmarks.add(issue); data.bookmarks.push(issue); render(data.bookmarks); github.checkIssuesForUpdates([issue]).then(() => render(data.bookmarks)); } function removeBookmark (issue) { bookmarks.remove(issue); const idx = data.bookmarks.indexOf(issue); Module.splice('bookmarks', idx - 1, 1); } function onUrlChanged (wv, issue) { if (!issue || !issue.url) return; const iss = data.bookmarks.filter(i => i.url === issue.url)[0]; if (iss) iss.unread = false; bookmarks.setUnreadByUrl(issue.url, false); } function refresh (full) { if (Module && full === true) { data.bookmarks = []; Module.reset(data); } bookmarks.get() .then(render) .then(github.checkIssuesForUpdates) .then(render); } function copleteIssueModel (iss) { if (!iss.repo) { if (helper.getPageActualTypeFromUrl(iss.url) === 'project') { iss.repo = DEFAULT_PROJECTS_REPO_NAME; iss.type = 'project'; } else { iss.repo = DEFAULT_REPO_NAME; iss.type = 'page'; } } iss.build = iss.build || {}; return iss; } function render (issues) { issues = issues.map(copleteIssueModel); issues = helper.mergeArrays(issues, data.bookmarks); Module.set('bookmarks', issues); return issues; } function oninit () { $.on(EVENT.bookmark.add, addBookmark); $.on(EVENT.bookmark.remove, removeBookmark); $.on(EVENT.bookmarks.refresh, () => refresh(true)); $.on(EVENT.url.change.done, onUrlChanged); this.on({ openRepo, openIssue }); refresh(); } const Module = new Ractive({ el: '#subnav .subnav-bookmarks .subnav-section-list', data, template, oninit, components: { BuildStatus }, computed: { groupedBookmarks: function () { return helper.groupIssues(this.get('bookmarks')); } }, transitions: { fade } }); module.exports = Module;
JavaScript
0
@@ -2332,65 +2332,42 @@ );%0A%09 -const idx = data.bookmarks.indexOf(issue);%0A%09 +Module.set('bookmarks', Module. -splice +get ('bo @@ -2378,20 +2378,40 @@ rks' -, idx - 1, 1 +).filter(i =%3E i.id !== issue.id) );%0A%7D
95e2a4aab8a354a5d90643d32c0a7c3febfd82e0
Fix failure to generate endpoint responses caused by a missing return in getter
api/controllers/rat.js
api/controllers/rat.js
'use strict' const { Rat } = require('../db') const RatQuery = require('../Query/RatQuery') const { CustomPresenter } = require('../classes/Presenters') const APIEndpoint = require('../APIEndpoint') const { Ships } = require('./ship') const { NotFoundAPIError } = require('../APIError') class Rats extends APIEndpoint { async search (ctx) { let ratsQuery = new RatQuery(ctx.query, ctx) let result = await Rat.findAndCountAll(ratsQuery.toSequelize) return Rats.presenter.render(result.rows, ctx.meta(result, ratsQuery)) } async findById (ctx) { let ratQuery = new RatQuery({id: ctx.params.id}, ctx) let result = await Rat.findAndCountAll(ratQuery.toSequelize) return Rats.presenter.render(result.rows, ctx.meta(result, ratQuery)) } async create (ctx) { this.requireWritePermission(ctx, ctx.data) if (!ctx.data.userId) { ctx.data.userId = ctx.state.user.data.id } let result = await Rat.create(ctx.data) ctx.response.status = 201 let renderedResult = Rats.presenter.render(result, ctx.meta(result)) process.emit('ratCreated', ctx, renderedResult) return renderedResult } async update (ctx) { this.requireWritePermission(ctx, ctx.data) let rat = await Rat.findOne({ where: { id: ctx.params.id } }) if (!rat) { throw new NotFoundAPIError({ parameter: 'id' }) } this.requireWritePermission(ctx, rat) await Rat.update(ctx.data, { where: { id: ctx.params.id } }) let ratQuery = new RatQuery({id: ctx.params.id}, ctx) let result = await Rat.findAndCountAll(ratQuery.toSequelize) let renderedResult = Rats.presenter.render(result.rows, ctx.meta(result, ratQuery)) process.emit('ratUpdated', ctx, renderedResult) return renderedResult } async delete (ctx) { let rat = await Rat.findOne({ where: { id: ctx.params.id } }) if (!rat) { throw new NotFoundAPIError({ parameter: 'id' }) } rat.destroy() process.emit('ratDeleted', ctx, CustomPresenter.render({ id: ctx.params.id })) ctx.status = 204 return true } getReadPermissionForEntity (ctx, entity) { if (entity.userId === ctx.state.user.data.id) { return ['rat.write', 'rat.write.me'] } return ['rat.write'] } getWritePermissionForEntity (ctx, entity) { if (entity.userId === ctx.state.user.data.id) { return ['rat.write', 'rat.write.me'] } return ['rat.write'] } static get presenter () { class RatsPresenter extends APIEndpoint.presenter { relationships () { return { ships: Ships.presenter } } } RatsPresenter.prototype.type = 'rats' } } module.exports = Rats
JavaScript
0.00001
@@ -202,18 +202,14 @@ onst - %7B Ships - %7D = r @@ -2717,16 +2717,41 @@ 'rats'%0A + return RatsPresenter%0A %7D%0A%7D%0A%0Am
e2f6125de937936a79a865cdb66a1fba7f0e829e
load user list + handle users order #62.
src/client/js/users.js
src/client/js/users.js
function loadUsers(callback) { $('#content').load(`/_users.html`, callback); }
JavaScript
0
@@ -14,69 +14,2735 @@ User -s(callback) %7B%0A $('#content').load(%60/_users.html%60, callback); +List(apiRoute, page, url) %7B%0A showLoader();%0A $('#users_order_dropdown').dropdown(%7B%0A onChange: function (value, text) %7B handleUsersOrder(value, page); %7D%0A %7D);%0A $.get(apiRoute)%0A .done(function (result) %7B%0A printUserItems(result.data);%0A let paginator = $('#user_paginator');%0A printPaginator(paginator, page, result.last_page, url);%0A hideLoader();%0A %7D)%0A .fail(function (error) %7B%0A $('#user_list').html('No se pueden obtener los repositorios en este momento.');%0A hideLoader();%0A %7D);%0A%7D%0A%0Afunction handleUsersOrder(value, page) %7B%0A switch (value) %7B%0A case 'date_asc':%0A app.setLocation(%60#/users/order/date/asc/page/$%7Bpage%7D%60);%0A break;%0A case 'date_desc':%0A app.setLocation(%60#/users/order/date/desc/page/$%7Bpage%7D%60);%0A break;%0A case 'name_asc':%0A app.setLocation(%60#/users/order/name/asc/page/$%7Bpage%7D%60);%0A break;%0A case 'name_desc':%0A app.setLocation(%60#/users/order/name/desc/page/$%7Bpage%7D%60);%0A break;%0A case 'pulls_asc':%0A app.setLocation(%60#/users/order/pullrequests/asc/page/$%7Bpage%7D%60);%0A break;%0A case 'pulls_desc':%0A app.setLocation(%60#/users/order/pullrequests/desc/page/$%7Bpage%7D%60);%0A break;%0A case 'reviews_asc':%0A app.setLocation(%60#/users/order/reviews/asc/page/$%7Bpage%7D%60);%0A break;%0A case 'reviews_desc':%0A app.setLocation(%60#/users/order/reviews/desc/page/$%7Bpage%7D%60);%0A break;%0A case 'accepted_reviews_asc':%0A app.setLocation(%60#/users/order/reviews/accepted/asc/page/$%7Bpage%7D%60);%0A break;%0A case 'accepted_reviews_desc':%0A app.setLocation(%60#/users/order/reviews/accepted/desc/page/$%7Bpage%7D%60);%0A break;%0A case 'commented_reviews_asc':%0A app.setLocation(%60#/users/order/reviews/commented/asc/page/$%7Bpage%7D%60);%0A break;%0A case 'commented_reviews_desc':%0A app.setLocation(%60#/users/order/reviews/commented/desc/page/$%7Bpage%7D%60);%0A break;%0A case 'changes_requested_reviews_asc':%0A app.setLocation(%60#/users/order/reviews/changes_requested/asc/page/$%7Bpage%7D%60);%0A break;%0A case 'changes_requested_reviews_desc':%0A app.setLocation(%60#/users/order/reviews/changes_requested/desc/page/$%7Bpage%7D%60);%0A break;%0A case 'dismissed_reviews_asc':%0A app.setLocation(%60#/users/order/reviews/dismissed/asc/page/$%7Bpage%7D%60);%0A break;%0A case 'dismissed_reviews_desc':%0A app.setLocation(%60#/users/order/reviews/dismissed/desc/page/$%7Bpage%7D%60);%0A break;%0A %7D %0A%7D
4d731dc41293cef0f422cf60dc2cdabb8ddff6a8
test refactored changes
respondToSMS-NodeJS/index.js
respondToSMS-NodeJS/index.js
//'use strict'; var qs = require('querystring'); var twilio = require('twilio'); var cookie = require('cookie'); var crypto = require('crypto'); var encryptKey = "s0m3Rand0mStr!ng"; // this should be put into a config var, env var var encryptStandard = "aes256"; module.exports = function (context, req) { context.log('JavaScript HTTP trigger function processed a request.'); var formValues = qs.parse(req.body); var cookieSession = getCookieSession(req.headers.cookie); //context.log(formValues); var twiml = new twilio.TwimlResponse(); twiml.message('You said: ' + formValues.Body); var encryptSessionString = encrypt(JSON.stringify(session)) var setCookie = cookie.serialize("session", encryptSessionString, { secure: true }); res = { status: 200, body: twiml.toString(), headers: { 'Content-Type': 'application/xml', 'Set-Cookie': setCookie }, isRaw: true }; context.done(null, res); }; function encrypt(text) { var cipher = crypto.createCipher(encryptStandard, encryptKey) var crypted = cipher.update(text, 'utf8', 'hex') crypted += cipher.final('hex'); return crypted; } function decrypt(text) { var decipher = crypto.createDecipher(encryptStandard, encryptKey) var dec = decipher.update(text, 'hex', 'utf8') dec += decipher.final('utf8'); return dec; } function getCookieSession(cookie) { var cookies = cookie.parse(req.headers.cookie || "", { secure: true }); var cookieSession; if (cookies.session) { context.log("session cookie found"); var decryptCookie = decrypt(cookies.session); context.log("session cookie : " + decryptCookie); cookieSession = JSON.parse(decryptCookie); } else { // set first time cookie for Twilio context.log("no cookie name found"); cookieSession = { askQueued: false, name: "xbob" }; } return cookieSession; }
JavaScript
0.000001
@@ -1,11 +1,9 @@ %EF%BB%BF -// 'use str @@ -414,35 +414,29 @@ .body);%0A -var cookieS +req.s ession = get @@ -452,31 +452,16 @@ sion(req -.headers.cookie );%0A / @@ -636,16 +636,20 @@ ringify( +req. session) @@ -756,16 +756,20 @@ );%0A%0A +var res = %7B%0A @@ -957,24 +957,25 @@ true%0A %7D;%0A +%0A context. @@ -995,415 +995,13 @@ s);%0A -%7D;%0A%0Afunction encrypt(text) %7B%0A var cipher = crypto.createCipher(encryptStandard, encryptKey)%0A var crypted = cipher.update(text, 'utf8', 'hex')%0A crypted += cipher.final('hex');%0A return crypted;%0A%7D%0A%0Afunction decrypt(text) %7B%0A var decipher = crypto.createDecipher(encryptStandard, encryptKey)%0A var dec = decipher.update(text, 'hex', 'utf8')%0A dec += decipher.final('utf8');%0A return dec;%0A%7D%0A%0A +%0A func @@ -1026,18 +1026,19 @@ ion( -cookie) %7B%0A +req) %7B%0A @@ -1092,32 +1092,36 @@ %7C %22%22, %7B%0A + + secure: true%0A @@ -1117,24 +1117,28 @@ e: true%0A + %7D);%0A var @@ -1129,16 +1129,20 @@ %7D);%0A + var @@ -1161,16 +1161,20 @@ n;%0A%0A + + if (cook @@ -1184,24 +1184,28 @@ .session) %7B%0A + cont @@ -1241,24 +1241,28 @@ %22);%0A + + var decryptC @@ -1295,16 +1295,20 @@ ssion);%0A + @@ -1358,32 +1358,36 @@ okie);%0A%0A + cookieSession = @@ -1417,18 +1417,26 @@ e);%0A + + %7D%0A + else @@ -1475,32 +1475,36 @@ Twilio %0A + + context.log(%22no @@ -1516,32 +1516,36 @@ e name found%22);%0A + cookieSe @@ -1596,11 +1596,19 @@ -%7D%0A%0A + %7D%0A%0A @@ -1629,9 +1629,421 @@ ession;%0A -%7D + %7D%0A%7D;%0A%0Afunction encrypt(text) %7B%0A var cipher = crypto.createCipher(encryptStandard, encryptKey)%0A var crypted = cipher.update(text, 'utf8', 'hex')%0A crypted += cipher.final('hex');%0A return crypted;%0A%7D%0A%0Afunction decrypt(text) %7B%0A var decipher = crypto.createDecipher(encryptStandard, encryptKey)%0A var dec = decipher.update(text, 'hex', 'utf8')%0A dec += decipher.final('utf8');%0A return dec;%0A%7D%0A%0A
3be3264a48dc3b31b90c6f644308866eb592b7de
add save to localstorage
app/components/Home.js
app/components/Home.js
import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Home.module.css'; const { TextField,Snackbar } = require('material-ui'); const GitHubApi = require("github-api"); var slug = require('limax'); var moment = require('moment'); var marked = require('marked'); var toMarkdown = require('to-markdown'); export default class Home extends Component { constructor() { super(); this.state = { autoHideDuration: 0, sending: 0, title: "", author: "白米君", url: "", date: moment(Date.now()).format('YYYY-MM-DD'), message: "" }; this.handleSubmit = this.handleSubmit.bind(this); this.handleTitleChange = this.handleTitleChange.bind(this); this.handleAuthorChange = this.handleAuthorChange.bind(this); this.handleDateChange = this.handleDateChange.bind(this); this.handleURLChange = this.handleURLChange.bind(this); } handleSubmit() { var that = this; this.setState({ sending: 1 }); if (localStorage.getItem('token') === null || localStorage.getItem('repo') === null) { that.setState({message: "跳转到设置中..."}); that.refs.snackbar.show(); return; } var token = localStorage.getItem('token'); var username = localStorage.getItem('repo').split("/")[0]; var reponame = localStorage.getItem('repo').split("/")[1]; var github = new GitHubApi({ token: token, auth: "oauth" }); var repo = github.getRepo(username, reponame); var options = { author: {name: username, email: '[email protected]'}, committer: {name: username, email: '[email protected]'}, encode: true }; var md = toMarkdown(document.getElementById('editor').innerHTML); var data = { title: that.state.title, author: that.state.author, url: '/' + that.state.url, date: '/' + that.state.date, content: md }; //repo.write('master', 'path/to/file', 'YOUR_NEW_CONTENTS', 'YOUR_COMMIT_MESSAGE', options, function(err) { // console.log(data); //}); //repo.read('master', 'README.md', function (err, data) { // that.setState({message: "上传成功" + data}); // that.refs.snackbar.show(); // that.setState({ // sending: 0 // }); //}); }; handleTitleChange(e) { this.setState({ title: e.target.value, url: slug(e.target.value, {tone: false}) }); }; handleAuthorChange(e) { this.setState({ author: e.target.value }); }; handleDateChange(e) { this.setState({ date: e.target.value }); }; handleURLChange(e) { this.setState({ url: e.target.value }); }; static getStyles() { return { link: { marginLeft: "2em" }, author: { marginLeft: "2em", width: "4em" }, date: { marginLeft: "2em", width: "10em" } }; }; render() { var inlineStyles = Home.getStyles(); var Message = this.state.message; return ( <div> <div className={styles.article}> <div className={styles.titleLine}> <div className={styles.headLine}> <i className="fa fa-fw fa-edit mode"></i> <TextField defaultValue={this.state.title} onChange={this.handleTitleChange} floatingLabelText="标题" hintText="标题"/> <TextField style={inlineStyles.author} defaultValue={this.state.author} onChange={this.handleAuthorChange} floatingLabelText="作者" hintText="白米粥"/> <TextField style={inlineStyles.link} defaultValue={this.state.url} value={this.state.url} onChange={this.handleURLChange} floatingLabelText="链接名" hintText="baimizhou-2014"/> <TextField style={inlineStyles.date} defaultValue={this.state.date} onChange={this.handleDateChange} type="date" floatingLabelText="日期" /> </div> <div className={styles.publish}> <button type="submit" className="fa fa-fw fa-paper-plane-o mode" onClick={this.handleSubmit} disabled={this.sending}/> </div> </div> <div id="editor" className={styles.editor}> 说说你的故事... </div> </div> <Snackbar ref="snackbar" message={Message} autoHideDuration={this.state.autoHideDuration}/> </div> ); } }
JavaScript
0
@@ -927,16 +927,394 @@ );%0A %7D%0A%0A + componentDidMount() %7B%0A if(localStorage.getItem('data') !== null )%7B%0A var data = JSON.parse(localStorage.getItem('data'));%0A this.setState(%7B%0A title: data.title,%0A author: data.author,%0A url: data.url,%0A date: data.date,%0A content: data.content%0A %7D);%0A document.getElementById('editor').innerHTML = data.contentHTML;%0A %7D%0A %7D%0A%0A handle @@ -2074,24 +2074,20 @@ var -md = toMarkdown( +innerHTML = docu @@ -2125,16 +2125,51 @@ nnerHTML +;%0A var md = toMarkdown(innerHTML );%0A%0A @@ -2255,22 +2255,16 @@ url: - '/' + that.st @@ -2287,14 +2287,8 @@ ate: - '/' + tha @@ -2318,18 +2318,105 @@ tent -: md%0A %7D +HTML: innerHTML,%0A content: md%0A %7D;%0A%0A localStorage.setItem('data', JSON.stringify(data)) ;%0A%0A @@ -4675,17 +4675,16 @@ ext=%22%E6%97%A5%E6%9C%9F%22 - /%3E%0A%0A
c309046aa15355082b010bebee6b9116f5cabc8f
Enable clicking on 3D plots (requires rgl modification)
inst/www/glbinding.js
inst/www/glbinding.js
var glOutputBinding = new Shiny.OutputBinding(); $.extend(glOutputBinding, { find: function(scope) { return $(scope).find('.shiny-gl-output'); }, renderValue: function(el, data) { if (!data || !data.html){ return; } $(el).html(data.html); setTimeout(function() { // check to see whether we're using the old or new RGL function type. oldFun = window[data.prefix + "webGLStart"]; newObj = window[data.prefix + "WebGL"]; if(typeof oldFun === 'function'){ oldFun(); } else if(typeof newObj === 'object'){ newObj.start(); newObj.onZoom(function(zoom){ Shiny.onInputChange('.clientdata_gl_output_' + el.id + '_zoom', zoom); }); newObj.onFOV(function(fov){ Shiny.onInputChange('.clientdata_gl_output_' + el.id + '_fov', fov); }); newObj.onPan(function(pan){ Shiny.onInputChange('.clientdata_gl_output_' + el.id + '_pan', pan.getAsArray()); }); } else{ throw new Error("Could not find method of starting WebGL scene."); } }, 0); } }); Shiny.outputBindings.register(glOutputBinding, 'shinyRGL.glbinding'); /** * Update the GL Size as the widget becomes visible. */ $(document).ready(function(){ $('body').on('shown.sendOutputHiddenState hidden.sendOutputHiddenState', '*', function(){sendGLSize();}); }); $(window).resize(debounce(500, sendGLSize)); // The server needs to know the size of each image and plot output element, // in case it is auto-sizing // Author: Joe Cheng // https://github.com/rstudio/shiny/blob/master/inst/www/shared/shiny.js // Modified by: Jeff Allen function sendGLSize() { $('.shiny-gl-output').each(function() { if (this.offsetWidth !== 0 || this.offsetHeight !== 0) { Shiny.onInputChange('.clientdata_gl_output_' + this.id + '_width', this.offsetWidth); Shiny.onInputChange('.clientdata_gl_output_' + this.id + '_height', this.offsetHeight); } }); } $(function() { // Init Shiny a little later than document ready, so user code can // run first (i.e. to register bindings) setTimeout(sendGLSize, 1); }); // Returns a debounced version of the given function. // Debouncing means that when the function is invoked, // there is a delay of `threshold` milliseconds before // it is actually executed, and if the function is // invoked again before that threshold has elapsed then // the clock starts over. // // For example, if a function is debounced with a // threshold of 1000ms, then calling it 17 times at // 900ms intervals will result in a single execution // of the underlying function, 1000ms after the 17th // call. // Author: Joe Cheng // https://github.com/rstudio/shiny/blob/master/inst/www/shared/shiny.js function debounce(threshold, func) { var timerId = null; var self, args; return function() { self = this; args = arguments; if (timerId !== null) { clearTimeout(timerId); timerId = null; } timerId = setTimeout(function() { timerId = null; func.apply(self, args); }, threshold); }; }
JavaScript
0
@@ -1011,24 +1011,205 @@ %7D);%0A +newObj.onClick(function(x, y)%7B%0A Shiny.onInputChange(el.id + '.click', %5Bx,y%5D);%0A Shiny.onInputChange('.clientdata_gl_output_' + el.id + '_click', %5Bx,y%5D);%0A %7D); %0A %7D els
e76db0ea9c90f31b801156e85d7181b0237c809e
Add some more logging to figure out what's going on
app/lib/users/index.js
app/lib/users/index.js
var db = require('../database'); var messenger = require('../messenger'); var _ = require('lodash'); function User(doc) { // Call the new constructor in case your forgot it. if (!(this instanceof User)) { return new User(doc); } // Assume that if you just get a string, that it's a phone number. // TODO: Validate this with some regex or something. if (typeof doc === 'string') doc = { _id: doc }; // Extend the User model with whatever is being stored in CouchDB. _.extend(this, doc); // Override the document type with 'user' no matter what. this.type = 'user'; } User.create = function (doc) { if (typeof doc === 'string') doc = { _id: doc }; return new User(doc); }; User.find = function (phoneNumber, callback) { db.get(phoneNumber, function (err, doc) { if (err) { callback(err); return; } if (doc.type && doc.type === 'user') { callback(null, User.create(doc)); } else { var error = { error: 'invalid_type', reason: 'type is not "user"' }; callback(error, null); } }); }; User.findOrCreate = function (phoneNumber, callback) { User.find(phoneNumber, function (err, doc) { if (!err && doc) { callback(null, doc); return; } if (err.error === 'not_found' && err.reason === 'missing') { var user = User.create(phoneNumber); user.save(function () { callback(null, user); }); } else { callback(err); } }); }; User.prototype.save = function (callback) { db.save(this, callback); }; User.prototype.destroy = function (callback) { db.remove(this._id, callback); }; User.prototype.message = function (message, callback) { console.log('Sending:', message); messenger.send(this._id, message); if (typeof callback === 'function') callback(); }; User.prototype.setStatus = function (status, callback) { this.status = status; this.save(callback); }; module.exports = User;
JavaScript
0
@@ -1826,16 +1826,88 @@ back) %7B%0A + console.log('Setting status of ' + this._id + ' to ' + status + '.');%0A this.s
6c18b74b7e647fccf0c48747026d7e1a78ad176d
Update moves.js
mods/trademarked/moves.js
mods/trademarked/moves.js
'use strict'; exports.BattleMovedex = { "copycat": { num: 383, accuracy: true, basePower: 0, category: "Status", desc: "The user uses the last move used by any Pokemon, including itself. Fails if no move has been used, or if the last move used was Assist, Belch, Bestow, Chatter, Circle Throw, Copycat, Counter, Covet, Destiny Bond, Detect, Dragon Tail, Endure, Feint, Focus Punch, Follow Me, Helping Hand, Hold Hands, King's Shield, Mat Block, Me First, Metronome, Mimic, Mirror Coat, Mirror Move, Nature Power, Protect, Rage Powder, Roar, Sketch, Sleep Talk, Snatch, Spiky Shield, Struggle, Switcheroo, Thief, Transform, Trick, or Whirlwind.", shortDesc: "Uses the last move used in the battle.", id: "copycat", name: "Copycat", pp: 20, priority: 0, flags: {}, onHit: function(pokemon) { let noCopycat = { assist: 1, bestow: 1, chatter: 1, circlethrow: 1, copycat: 1, counter: 1, covet: 1, destinybond: 1, detect: 1, dragontail: 1, endure: 1, feint: 1, focuspunch: 1, followme: 1, helpinghand: 1, mefirst: 1, metronome: 1, mimic: 1, mirrorcoat: 1, mirrormove: 1, naturepower: 1, protect: 1, ragepowder: 1, roar: 1, sketch: 1, sleeptalk: 1, snatch: 1, struggle: 1, switcheroo: 1, thief: 1, transform: 1, trick: 1, whirlwind: 1 }; if (pokemon.ability == "copycat") { noCopycat.batonpass = 1; noCopycat.partingshot = 1; } if (!this.lastMove || noCopycat[this.lastMove]) { return false; } this.useMove(this.lastMove, pokemon); }, secondary: false, target: "self", type: "Normal", contestType: "Cute", }, "batonpass": { num: 226, accuracy: true, basePower: 0, category: "Status", desc: "The user is replaced with another Pokemon in its party. The selected Pokemon has the user's stat stage changes, confusion, and certain move effects transferred to it.", shortDesc: "User switches, passing stat changes and more.", id: "batonpass", isViable: true, name: "Baton Pass", pp: 40, priority: 0, flags: {}, selfSwitch: 'copyvolatile', onAfterMove: function(pokemon) { this[pokemon.side.id].lastPshot=this.turn; }, onTryHit: function(target) { let oppside; if(target.side.id=='p1')oppside='p2'; if(target.side.id=='p2')oppside='p1'; if(this[oppside].lastPshot==this.turn) return false; }, secondary: false, target: "self", type: "Normal", contestType: "Cute", }, "partingshot": { num: 575, accuracy: 100, basePower: 0, category: "Status", desc: "Lowers the target's Attack and Special Attack by 1 stage. If this move is successful, the user switches out even if it is trapped and is replaced immediately by a selected party member. The user does not switch out if there are no unfainted party members.", shortDesc: "Lowers target's Atk, Sp. Atk by 1. User switches.", id: "partingshot", isViable: true, name: "Parting Shot", pp: 20, priority: 0, flags: { protect: 1, reflectable: 1, mirror: 1, sound: 1, authentic: 1 }, selfSwitch: true, boosts: { atk: -1, spa: -1, }, onAfterMove: function(pokemon) { this[pokemon.side.id].lastPshot=this.turn; }, onTryHit: function(target) { let oppside; if(target.side.id=='p1')oppside='p2'; if(target.side.id=='p2')oppside='p1'; if(this[oppside].lastPshot==this.turn) return false; }, secondary: false, target: "normal", type: "Dark", contestType: "Cool", }, };
JavaScript
0.000001
@@ -3108,2923 +3108,7 @@ %7D,%0A - %22batonpass%22: %7B%0A num: 226,%0A accuracy: true,%0A basePower: 0,%0A category: %22Status%22,%0A desc: %22The user is replaced with another Pokemon in its party. The selected Pokemon has the user's stat stage changes, confusion, and certain move effects transferred to it.%22,%0A shortDesc: %22User switches, passing stat changes and more.%22,%0A id: %22batonpass%22,%0A isViable: true,%0A name: %22Baton Pass%22,%0A pp: 40,%0A priority: 0,%0A flags: %7B%7D,%0A selfSwitch: 'copyvolatile',%0A onAfterMove: function(pokemon)%0A %7B%0A this%5Bpokemon.side.id%5D.lastPshot=this.turn;%0A %7D,%0A onTryHit: function(target)%0A %7B%0A let oppside;%0A if(target.side.id=='p1')oppside='p2';%0A if(target.side.id=='p2')oppside='p1';%0A if(this%5Boppside%5D.lastPshot==this.turn)%0A return false;%0A %7D,%0A secondary: false,%0A target: %22self%22,%0A type: %22Normal%22,%0A contestType: %22Cute%22,%0A %7D,%0A %22partingshot%22: %7B%0A num: 575,%0A accuracy: 100,%0A basePower: 0,%0A category: %22Status%22,%0A desc: %22Lowers the target's Attack and Special Attack by 1 stage. If this move is successful, the user switches out even if it is trapped and is replaced immediately by a selected party member. The user does not switch out if there are no unfainted party members.%22,%0A shortDesc: %22Lowers target's Atk, Sp. Atk by 1. User switches.%22,%0A id: %22partingshot%22,%0A isViable: true,%0A name: %22Parting Shot%22,%0A pp: 20,%0A priority: 0,%0A flags: %7B%0A protect: 1,%0A reflectable: 1,%0A mirror: 1,%0A sound: 1,%0A authentic: 1%0A %7D,%0A selfSwitch: true,%0A boosts: %7B%0A atk: -1,%0A spa: -1,%0A %7D,%0A onAfterMove: function(pokemon)%0A %7B%0A this%5Bpokemon.side.id%5D.lastPshot=this.turn;%0A %7D,%0A onTryHit: function(target)%0A %7B%0A let oppside;%0A if(target.side.id=='p1')oppside='p2';%0A if(target.side.id=='p2')oppside='p1';%0A if(this%5Boppside%5D.lastPshot==this.turn)%0A return false;%0A %7D,%0A secondary: false,%0A target: %22normal%22,%0A type: %22Dark%22,%0A contestType: %22Cool%22,%0A %7D,%0A %7D;%0A
33bae59d7752ec77aab9338f2ea98fe93be7f0d7
add width and height to video
src/components/home.js
src/components/home.js
import React from "react"; import Footer from "./footer"; import Banner from "./banner"; export default class Home extends React.Component { constructor(props) { super(props) this.state = { body: null } } componentDidMount = () => { let unauthBody = ( <div> <h2 id="slogan">We Produce Your Future</h2> <h3 id="placeholder">Placeholder Video</h3> <video controls><source src="/static/videos/placeholder.mp4"/></video> <div id="rev-container"> <h3 id="reviews">Reviews</h3> <div id="reviews-container"> <p>There are no reviews</p> </div> </div> </div> ); this.setState({ body: sessionStorage.getItem("loggedIn") ? ( <div className="admin-body"> <div className="edit-music"> <h2>Edit Music</h2> <h4>Title</h4> <input className="music-up" type="text" id="title" placeholder="Enter song title" required/> <h4>Artist Name</h4> <input className="music-up" type="text" id="artist-name" placeholder="Enter artist name" required/> <h4>Genre</h4> <input className="music-up" type="text" id="genre" placeholder="Genre" required/> <h4>Price</h4> <input className="music-up" type="text" id="price" placeholder="Price" required/> <h4>Video ID</h4> <input className="music-up" type="text" id="video-id" placeholder="Video ID, e.g., d1eaQrxA6ZE" required/><br/> <button className="update" onClick={this.handleMusicUpdate}>Update Music</button> </div> <div className="edit-events"> <h2>Edit Events</h2> <h4>Location</h4> <input className="event-up" type="text" id="location" placeholder="Enter location" required/> <h4>Description</h4> <textarea className="event-up" id="description" required></textarea><br/> <button className="update" onClick={this.handleEventsUpdate}>Update Events</button> </div> </div> ) : unauthBody }); } handleMusicUpdate = () => { let title = document.getElementById("title").value; let artist = document.getElementById("artist-name").value; let genre = document.getElementById("genre").value; let price = document.getElementById("price").value; let videoId = document.getElementById("video-id").value; if (!title || !artist || !genre || !price || !videoId) { return; } let musicData = { title: title, artist: artist, genre: genre, price: price, id: videoId }; fetch("/update-music", { method: "post", headers: { "Content-Type": "application/json" }, body: JSON.stringify(musicData) }).then((res) => { return res.json(); }).then((json) => { if (json.data === "success") { alert("Successfully Updated Music"); Array.prototype.forEach.call(document.getElementsByClassName("music-up"), (element) => { element.value = ""; }); } }) }; handleEventsUpdate = () => { let location = document.getElementById("location").value; let description = document.getElementById("description").value; if (!location || !description) { return; } let eventsData = { location: location, description: description } fetch("/events-update", { method: "post", headers: { "Content-Type": "application/json" }, body: JSON.stringify(eventsData) }).then((res) => { return res.json(); }).then((json) => { if (json.data === "success") { alert("Successfully Updated Events"); Array.prototype.forEach.call(document.getElementsByClassName("event-up"), (element) => { element.value = ""; }) } }) } render() { return ( <div id="home-container"> <div id="not-footer"> <Banner/> <div className="body"> {this.state.body} </div> </div> <Footer/> </div> ) } }
JavaScript
0
@@ -441,16 +441,47 @@ %3Cvideo + id=%22home-video%22 preload=%22none%22 control
4fa3dad1159e5f4ab61072002264d82b684a00a4
Throw an error, not just a plain string
src/EventContext.js
src/EventContext.js
"use strict"; import Guard from './Guard'; class EventContext { constructor(modelId, eventType, event) { Guard.isString(modelId, "The modelId should be a string"); Guard.isString(eventType, "The eventType should be a string"); Guard.isDefined(event, "The event should be defined"); this._modelId = modelId; this._eventType = eventType; this._event = event; this._isCanceled = false; this._isCommitted = false; } get isCanceled() { return this._isCanceled; } get isCommitted() { return this._isCommitted; } get modelId() { return this._modelId; } get event() { return this._event; } get eventType() { return this._eventType; } cancel() { if(!this._isCanceled) { this._isCanceled = true; } else { throw 'event is already canceled'; } } commit() { if(!this._isCommitted) { this._isCommitted = true; } else { throw 'event is already committed'; } } } export default EventContext;
JavaScript
0.000014
@@ -884,32 +884,42 @@ throw +new Error( 'event is alread @@ -926,19 +926,21 @@ y cancel +l ed' +) ;%0A
baaa1e94526d7da77332648d384e6c085ce2b285
Fix linux issue with process.env usage. See https://github.com/electron/electron/issues/3306
app/services/config.js
app/services/config.js
'use strict'; const fs = require('fs'); const path = require('path'); const angular = require('angular'); const process = require('process'); angular.module('app').factory('config', config); config.$inject = []; const configPath = path.join(process.env.USER_DATA_PATH, 'user.json'); function config() { let config; if (fs.existsSync(configPath)) { try { config = JSON.parse(fs.readFileSync(configPath)); } catch (e) { console.error(`Error when loading config: ${e.stack}`); } } if (!config) { config = {}; } // implements some methods from the Storage Web API return { getItem(key) { return config[key]; }, setItem(key, value) { config[key] = value; return new Promise(function(resolve) { // Running writing to file async. We don't really care if it fails. fs.writeFile( configPath, JSON.stringify(config, null, 2), // We write the file in a restricted way so we can potentially add // credentials to it later. {mode: '600'}, resolve ); }); } }; }
JavaScript
0.000021
@@ -105,23 +105,24 @@ ;%0Aconst -process +%7Bremote%7D = requi @@ -125,23 +125,24 @@ equire(' -process +electron ');%0A%0Aang @@ -239,16 +239,23 @@ th.join( +remote. process. @@ -287,16 +287,57 @@ .json'); +%0Aconsole.log('Config path:', configPath); %0A%0Afuncti
46c9fac82938ef57b5639561ddecc874054a3c3f
Fix settings
app/shared-settings.js
app/shared-settings.js
export const ownAddress = 'http://localhost:3000';
JavaScript
0.000001
@@ -31,21 +31,13 @@ p:// -localhost:3000 +izm.io ';%0A
1e063619a4c53de906bdc35d820ab9d3809df430
Change stats order
app/stats/statModel.js
app/stats/statModel.js
"use strict"; //Load dependencies var applicationStorage = process.require("core/applicationStorage"); /** * Insert a stat object * @param tier * @param raid * @param stat * @param callback */ module.exports.insertOne = function (tier, raid, stats, callback) { var collection = applicationStorage.mongo.collection("progress_stats"); var obj = {tier: tier, raid: raid, stats: stats} collection.insertOne(obj, function (error) { callback(error); }); }; /** * Return the last stat (max 200) * @param raid * @param callback */ module.exports.getStats = function (tier, raid, limit, callback) { var collection = applicationStorage.mongo.collection("progress_stats"); collection.find({tier: tier, raid: raid}, {stats:1,_id:1}) .sort({_id: 1}) .limit(limit) .toArray(function (error, stats) { console.log(stats); callback(error, stats); }); };
JavaScript
0
@@ -779,16 +779,17 @@ t(%7B_id: +- 1%7D)%0A
a8420e148b9f55f3a0d043f7c05e4ce24a861076
Check if doc already optimized
optimize_pdfs.js
optimize_pdfs.js
#!/usr/bin/env node const { MONGODB: DB, ES } = process.env const child_process = require('child_process') const fs = require('fs') const mongoose = require('mongoose') mongoose.Promise = global.Promise const elasticsearch = require('elasticsearch') let es = new elasticsearch.Client({ host: ES }) let db = mongoose.createConnection(DB) db.on('error', err => { console.error(err) process.exit(1) }) db.on('open', () => { require('./lib/dbModel.js')(db, es).then(({PastPaperDoc, PastPaperPaperBlob}) => { PastPaperDoc.find({}).cursor().eachAsync(async function (doc) { try { console.log('Processing ' + doc._id) let pdfBlob = await doc.getFileBlob() let newBlob = null newBlob = await doOptimize(pdfBlob) doc.fileBlob = null await PastPaperPaperBlob.remove({docId: doc._id}) let chunkSize = 10 * 1024 * 1024 for (let off = 0; off < newBlob.length; off += chunkSize) { let slice = newBlob.slice(off, off + chunkSize) let dbBlobFrag = new PastPaperPaperBlob({ docId: doc._id, offset: off, data: slice }) await dbBlobFrag.save() } await doc.save() } catch (e) { process.stderr.write(`Error when processing ${doc._id}: ${e.toString()}\n`) return } }).then(() => { process.exit() }) }, err => { console.error(err) process.exit(1) }) }) function doOptimize (pdfBlob) { return new Promise((resolve, reject) => { // For some reason if we want gs to write to any file in /dev/fd, it segfaults. // let cp = child_process.spawn('gs', // ['-sDEVICE=pdfwrite', '-dFastWebView', '-dNOPAUSE', '-dBATCH', '-sOutputFile=| cat - >&3', '-'], // { // cwd: '/tmp/', // stdio: [ // 'pipe', // input from stdin // 'inherit', // stdout // 'inherit', // stderr // 'pipe' // fd=3 as pipe // ] // }) // let [sI, _, _2, sO] = cp.stdio // let receivedBytes = 0 // let outBuffer = Buffer.allocUnsafe(1000) // sO.on('data', data => { // if (receivedBytes + data.length <= outBuffer.length) { // let len = data.copy(outBuffer, receivedBytes) // receivedBytes += len // } else { // let allocNewSize = Math.max(outBuffer.length * 2, receivedBytes + data.length) // let newBuffer = Buffer.allocUnsafe(allocNewSize) // outBuffer.copy(newBuffer, 0, 0, receivedBytes) // delete outBuffer // outBuffer = newBuffer // let len = data.copy(outBuffer, receivedBytes) // receivedBytes += len // } // }) // let exitCode = null // let readDone = false // let done = false // sO.on('end', () => { // if (exitCode !== null) { // finish() // } else { // readDone = true // } // }) let cp = child_process.spawn('gs', ['-sDEVICE=pdfwrite', '-dFastWebView', '-dNOPAUSE', '-dBATCH', '-sOutputFile=/tmp/optimize_pdfjs_tmpout.pdf', '-'], { cwd: '/tmp/', stdio: [ 'pipe', 'inherit', 'inherit' ] }) let sI = cp.stdin let done = false cp.on('exit', (code, sig) => { if (done) return if (code === null && sig !== null) { done = true reject(new Error(`Process killed because ${sig}`)) } if (code !== null && code !== 0) { done = true reject(new Error(`Process exited with code ${code}`)) } finish() }) cp.on('error', err => { if (done) return done = true reject(err) }) sI.on('error', err => { if (done) return done = true reject(err) }) sI.end(pdfBlob) function finish () { if (done) return done = true fs.readFile('/tmp/optimize_pdfjs_tmpout.pdf', {encoding: null, flag: 'r'}, (err, data) => { if (err) { reject(err) } else { resolve(data) } }) } }) }
JavaScript
0
@@ -631,16 +631,75 @@ oc._id)%0A + if (doc.gs_optimized) %7B%0A return%0A %7D%0A @@ -1238,32 +1238,70 @@ ave()%0A %7D%0A + doc.set('gs_optimized', true)%0A await do
b6835cfeacb5d8e5784d1dd7bf22dda6b2a90ab7
remove sort and filter
torrent/index.js
torrent/index.js
const Webtorrent = require('webtorrent'); const pump = require('pump'); const mime = require('mime'); const rangeParser = require('range-parser'); const admin = require("firebase-admin"); const firestore = admin.firestore(); const _ = require('lodash'); const webtorrent = new Webtorrent(); const listTorrent = {} // From https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent function encodeRFC5987 (str) { return encodeURIComponent(str) // Note that although RFC3986 reserves "!", RFC5987 does not, // so we do not need to escape it .replace(/['()]/g, escape) // i.e., %27 %28 %29 .replace(/\*/g, '%2A') // The following are not required for percent-encoding per RFC5987, // so we can allow for a little better readability over the wire: |`^ .replace(/%(?:7C|60|5E)/g, unescape) } class Torrent { constructor() { firestore.collection('session') .orderBy('date') .limit(1) .onSnapshot(snapshot => { snapshot.docChanges.forEach(change => { if (change.type === 'added') { this.addNewTorrent(change.doc.id, change.doc.data().torrentUrl); } }); }); } addNewTorrent(sessionId, torrentFile) { webtorrent.add(torrentFile, (torrent) => { console.log(`Torrent for ${sessionId} is available`); listTorrent[sessionId] = _.orderBy(torrent.files, ['length'], ['desc'])[0]; }); } serveFile(req, res) { if (!listTorrent[req.params.id]) { return res.sendStatus(404); } const file = listTorrent[req.params.id]; res.statusCode = 200 res.setHeader('Content-Type', mime.lookup(file.name)) // Support range-requests res.setHeader('Accept-Ranges', 'bytes') // Set name of file (for "Save Page As..." dialog) res.setHeader( 'Content-Disposition', 'inline; filename*=UTF-8\'\'' + encodeRFC5987(file.name) ) // Support DLNA streaming res.setHeader('transferMode.dlna.org', 'Streaming') res.setHeader( 'contentFeatures.dlna.org', 'DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000' ) // `rangeParser` returns an array of ranges, or an error code (number) if // there was an error parsing the range. var range = rangeParser(file.length, req.headers.range || '') if (Array.isArray(range)) { res.statusCode = 206 // indicates that range-request was understood // no support for multi-range request, just use the first range range = range[0] res.setHeader( 'Content-Range', 'bytes ' + range.start + '-' + range.end + '/' + file.length ) res.setHeader('Content-Length', range.end - range.start + 1) } else { range = null res.setHeader('Content-Length', file.length) } if (req.method === 'HEAD') { return res.end() } pump(file.createReadStream(range), res) } } module.exports = Torrent;
JavaScript
0
@@ -949,59 +949,8 @@ n')%0A - .orderBy('date')%0A .limit(1)%0A
65f244f5c55b20d2d1bd7b3f18e7fa9b2478c79c
fix the sorting algorithm for live-updating elements
browser.js
browser.js
var through = require('through'); var hyperglue = require('hyperglue'); var domify = require('domify'); module.exports = function (html, opts, cb) { if (typeof opts === 'function') { cb = opts; opts = {}; } if (!opts) opts = {}; var elements = {}; var className = classNameOf(html); var tr = through(function (line) { var row; if (isInt8Array(line)) { var s = ''; for (var i = 0; i < line.length; i++) s += line[i]; line = s; } if (typeof line === 'string') { try { row = JSON.parse(line) } catch (err) { this.emit('error', err) } } else row = line; var res = cb.call(this, row); if (!res) return; var keys = objectKeys(res); var streams = []; for (var i = 0; i < keys.length; i++) (function (key) { var x = res[key]; if (isStream(x)) { delete res[key]; streams.push([ key, x ]); } else if (x && typeof x === 'object' && isStream(x._html)) { var st = x._html; delete x._html; streams.push([ key, st ]); } else if (x && typeof x === 'object' && isStream(x._text)) { var st = x._text; delete x._text; streams.push([ key, st ]); } })(keys[i]); var type, elem; if (opts.key && row.key && elements[row.key]) { elem = hyperglue(elements[row.key], res); type = 'update'; } else { elem = hyperglue(html, res); type = 'element'; } if (opts.key && row.key) { elements[row.key] = elem; } for (var i = 0; i < streams.length; i++) (function (ks) { var key = ks[0], stream = ks[1]; tr.emit('stream', stream, elem); var cur = elem.querySelector(key); if (!cur) return; stream.on('element', function (elem) { cur.appendChild(elem); stream.removeListener('data', ondata); }); stream.on('data', ondata); function ondata (e) { cur.innerHTML += e } })(streams[i]); this.emit(type, elem); this.queue(elem.outerHTML); }); tr.prependTo = function (t) { var target = getTarget(t); tr.on('element', function (elem) { target.insertBefore(elem, target.childNodes[0]); }); return tr; }; tr.appendTo = function (t) { var target = getTarget(t); tr.on('element', function (elem) { target.appendChild(elem); }); return tr; }; tr.sortTo = function (t, cmp) { if (typeof cmp !== 'function') { throw new Error('comparison function not provided'); } var target = getElem(t); var nodes = [].slice.call(target.getElementsByClassName(className)); var sorted = nodes.slice().sort(cmp); for (var i = 0; i < nodes.length; i++) { if (target.childNodes[i] === sorted[i]) continue; target.removeChild(sorted[i]); target.insertBefore(sorted[i], target.childNodes[i]); } tr.on('element', onupdate); tr.on('update', onupdate); getTarget(t, target); return tr; function onupdate (elem) { var nodes = target.getElementsByClassName(className); for (var i = 0; i < nodes.length; i++) { if (nodes[i] === elem) continue; var n = cmp(elem, nodes[i]); if (n < 0) { if (hasChild(target, elem)) { target.removeChild(elem); } target.insertBefore(elem, nodes[i]); return; } } target.appendChild(elem); } }; var emittedElements = false; tr.className = className; return tr; function getTarget (t, target) { if (!target) target = getElem(t); tr.emit('parent', target); if (!className) return target; if (emittedElements) return target; emittedElements = true; var elems = target.querySelectorAll('.' + className); for (var i = 0; i < elems.length; i++) { var elem = elems[i]; var key = opts.key && elem.getAttribute(opts.key); if (key) elements[key] = elem; tr.emit('element', elem); } return target; } }; function classNameOf (html) { var elems = domify(html); if (elems.length) return elems[0].getAttribute('class'); } function hasChild (node, child) { var nodes = node.childNodes; for (var i = 0; i < nodes.length; i++) { if (nodes[i] === child) return true; } return false; } function getElem (target) { if (typeof target === 'string') { return document.querySelector(target); } return target; } function isInt8Array (line) { return line && typeof line === 'object' && line.constructor === 'function' && line.constructor.name === 'Int8Array' ; } function isStream (x) { return x && typeof x.pipe === 'function'; } var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) keys.push(key); return keys; };
JavaScript
0.000252
@@ -3087,21 +3087,22 @@ var -nodes +sorted = %5B%5D.sl @@ -3165,34 +3165,14 @@ -var sorted - = nodes.slice() .sor @@ -3199,37 +3199,38 @@ (var i = 0; i %3C -nodes +sorted .length; i++) %7B%0A @@ -3479,24 +3479,169 @@ pdate', -onupdate +function (elem) %7B%0A if (hasChild(target, elem)) %7B%0A target.removeChild(elem);%0A %7D%0A onupdate(elem);%0A %7D );%0A
6b4aa9676278f06b75baee839623fbde5252e56c
change scope of numSteps
orbits/orbits.js
orbits/orbits.js
var orbits = document.getElementById('orbits'); var prototypeCircle = document.getElementById('circle1'); prototypeCircle.style.display = "none"; (function () { var numSteps = 80; var fps = 1000/25; function getCircleLocation (circle) { return { x: parseInt(circle.getAttribute('cx')), y: parseInt(circle.getAttribute('cy')) }; } function newCircle (circleToClone, cx, cy) { var circle = circleToClone.cloneNode(false); circle.setAttribute('id', ''); circle.setAttribute('cx', cx); circle.setAttribute('cy', cy); circle.style.display = "block"; orbits.appendChild(circle); return circle; } var Motions = (function() { function* diagonal(cPosition, xDirection, yDirection, stepSize) { cPosition = yield cPosition; var xStep = xDirection * stepSize; var yStep = yDirection * stepSize; while (1) { var next = { x: cPosition.value.x + xStep, y: cPosition.value.y + yStep }; cPosition = yield next; } } var moveDiagonal = function (circle, xDirection, yDirection, fps) { var val; var cx = parseInt(circle.getAttribute('cx')); var cy = parseInt(circle.getAttribute('cy')); var kissIt = diagonal({x: cx, y: cy}, xDirection, yDirection, 3); var last = kissIt.next(); var count = 0; var roll = function () { last = kissIt.next(last); val = last.value; cx = val.x; cy = val.y; this.setAttribute('cx', cx.toString()); this.setAttribute('cy', cy.toString()); count += 1; if (count > numSteps) { clearInterval(rollInterval); } }; var rollInterval = setInterval(roll.bind(circle), fps); }; var orbitCircle = function (circle, radius, fps) { var rads = 0; var cx; var cy; var sun = { x: parseInt(circle.getAttribute('cx')), y: parseInt(circle.getAttribute('cy')) }; setInterval(function () { rads += .1; cx = radius * Math.sin(rads); cy = radius * Math.cos(rads); cx += sun.x; cy += sun.y; circle.setAttribute('cx', cx); circle.setAttribute('cy', cy); }, fps); }; var oscillate = function (circle, start, end, fps) { var rads = 0; var step = 10; var cx; var cy; setInterval(function () { rads += .4; cx = parseInt(circle.getAttribute('cx')); cy = parseInt(circle.getAttribute('cy')); cx += step; cy = cy + 30 * Math.sin(rads); if (cx + step >= end || cx + step <= start) { step *= -1; } circle.setAttribute('cx', cx); circle.setAttribute('cy', cy); }, fps); }; var spinOrbit = function (circle, radius, oscillation, fps) { var orbitRads = 0; var oscillatingRads = 0; var c = getCircleLocation(circle); var cx; var cy; setInterval(function () { orbitRads += .1; oscillatingRads += .5; cx = radius * Math.sin(orbitRads); cy = radius * Math.cos(orbitRads); cx += c.x + oscillation * Math.sin(oscillatingRads); cy += c.y + oscillation * Math.cos(oscillatingRads); circle.setAttribute('cx', cx); circle.setAttribute('cy', cy); }, fps); }; var oscillatingOrbit = function (circle, radius, oscillation, fps) { var orbitRads = 0; var oscillatingRads = 0; var c = getCircleLocation(circle); var radiusModified; var cx; var cy; setInterval(function () { orbitRads += .1; oscillatingRads += .8; radiusModified = oscillation * Math.sin(oscillatingRads); cx = radius * Math.sin(orbitRads); cy = radius * Math.cos(orbitRads); cx += c.x + radiusModified; cy += c.y + radiusModified; circle.setAttribute('cx', cx); circle.setAttribute('cy', cy); }, fps); }; return { moveDiagonal: moveDiagonal, oscillatingOrbit: oscillatingOrbit, oscillate: oscillate, spinOrbit: spinOrbit, orbitCircle: orbitCircle }; }()); /** bind the Add Circle Form */ (function () { var form = document.getElementById("addCircle"); var select = form.querySelector("select[name='direction']"); // add the motion options for (kk in Motions) { if (!Motions.hasOwnProperty(kk)) { continue; } var option = document.createElement('option'); option.setAttribute('name', kk); option.text = kk; select.appendChild(option); } var button = form.querySelector('button'); var cxElm = form.querySelector("input[name='cx']"); var cyElm = form.querySelector("input[name='cy']"); var cx, cy; var motion; button.addEventListener('click', function () { cx = cxElm.value; cy = cyElm.value; motion = select.value; var circle = newCircle(prototypeCircle, cx, cy); Motions[motion](circle, 1, 1, fps); }); }()); // //var circle2 = newCircle(circle1, 500, 500); //var circle3 = newCircle(circle1, 500, 0); //var circle4 = newCircle(circle1, 0, 500); //var circle5 = newCircle(circle1, 150, 150); //var circle6 = newCircle(circle1, 350, 150); //var circle7 = newCircle(circle1, 50, 50); //var circle8 = newCircle(circle1, 0, 100); //var circle9 = newCircle(circle1, 250, 250); //var circle10 = newCircle(circle1, 250, 250); // //moveCircle(circle1, 1, 1, fps); //moveCircle(circle2, -1, -1, fps); //moveCircle(circle3, -1, 1, fps); //moveCircle(circle4, 1, -1, fps); // //orbitCircle(circle5, 80, fps); //orbitCircle(circle6, 80, fps); //orbitCircle(circle7, 20, fps); //oscillate(circle8, 0, 500); // //spinOrbit(circle9, 150, 50, fps); // //oscillatingOrbit(circle10, 200, 50, fps); }());
JavaScript
0
@@ -160,28 +160,8 @@ ) %7B%0A - var numSteps = 80; %0A v @@ -178,17 +178,16 @@ 000/25;%0A -%0A functi @@ -653,24 +653,47 @@ unction() %7B%0A + var numSteps = 80;%0A function
7ac3784f32cedf7b98e9609d6404bc2c5f86228f
Increase the ratio used to select an overview level from a bounding box
lib/cartodb/models/dataview/overviews/base.js
lib/cartodb/models/dataview/overviews/base.js
var _ = require('underscore'); var BaseWidget = require('../base'); function BaseOverviewsDataview(query, queryOptions, BaseDataview, queryRewriter, queryRewriteData, options) { this.BaseDataview = BaseDataview; this.query = query; this.queryOptions = queryOptions; this.queryRewriter = queryRewriter; this.queryRewriteData = queryRewriteData; this.options = options; this.baseDataview = new this.BaseDataview(this.query, this.queryOptions); } module.exports = BaseOverviewsDataview; BaseOverviewsDataview.prototype = new BaseWidget(); BaseOverviewsDataview.prototype.constructor = BaseOverviewsDataview; // TODO: parameterized these settings var SETTINGS = { // use overviews as a default fallback strategy defaultOverviews: false, // minimum ratio of bounding box size to grid size zoomLevelFactor: 100.0 }; // Compute zoom level so that the the resolution grid size of the // selected overview is smaller (zoomLevelFactor times smaller at least) // than the bounding box size. BaseOverviewsDataview.prototype.zoomLevelForBbox = function(bbox) { var pxPerTile = 256.0; var earthWidth = 360.0; // TODO: now we assume overviews are computed for 1-pixel tolerance; // should use extended overviews metadata to compute this properly. if ( bbox ) { var bboxValues = _.map(bbox.split(','), function(v) { return +v; }); var w = Math.abs(bboxValues[2]-bboxValues[0]); var h = Math.abs(bboxValues[3]-bboxValues[1]); var maxDim = Math.min(w, h); // Find minimum suitable z // note that the QueryRewirter will use the minimum level overview // of level >= z if it exists, and otherwise the base table var z = Math.ceil(-Math.log(maxDim*pxPerTile/earthWidth/SETTINGS.zoomLevelFactor)/Math.log(2.0)); return Math.max(z, 0); } return 0; }; BaseOverviewsDataview.prototype.rewrittenQuery = function(query) { var zoom_level = this.zoomLevelForBbox(this.options.bbox); return this.queryRewriter.query(query, this.queryRewriteData, { zoom_level: zoom_level }); }; // Default behaviour BaseOverviewsDataview.prototype.defaultSql = function(psql, filters, override, callback) { var query = this.query; var dataview = this.baseDataview; if ( SETTINGS.defaultOverviews ) { query = this.rewrittenQuery(query); dataview = new this.BaseDataview(query, this.queryOptions); } return dataview.sql(psql, filters, override, callback); }; // default implementation that can be override in derived classes: BaseOverviewsDataview.prototype.sql = function(psql, filters, override, callback) { return this.defaultSql(psql, filters, override, callback); }; BaseOverviewsDataview.prototype.search = function(psql, userQuery, callback) { return this.baseDataview.search(psql, userQuery, callback); }; BaseOverviewsDataview.prototype.format = function(result) { return this.baseDataview.format(result); }; BaseOverviewsDataview.prototype.getType = function() { return this.baseDataview.getType(); }; BaseOverviewsDataview.prototype.toString = function() { return this.baseDataview.toString(); };
JavaScript
0
@@ -808,16 +808,84 @@ id size%0A + // (this would ideally be based on the viewport size in pixels)%0A zoom @@ -899,17 +899,18 @@ ctor: 10 -0 +24 .0%0A%7D;%0A%0A/
dbc354ffb00b6c098c08f67ab6e4115b1236b503
Update flairs for RimWorld
modules/flair/RimWorld.js
modules/flair/RimWorld.js
const base = require( './base.js' ); module.exports = Object.assign( {}, base, { list: [ 'extralife', 'fun', 'gold', 'granite', 'jade', 'limestone', 'marble', 'mod', 'mod2', 'plasteel', 'pmfaf', 'sandstone', 'ship', 'silver', 'slate', 'steel', 'uranium', 'war', 'wood', ], type: 'author_flair_css_class', } );
JavaScript
0
@@ -87,16 +87,37 @@ list: %5B%0A + 'community',%0A
2f626d6a5861fdc12d63d1d994ca449ff8ce1a61
fix header
src/foam/nanos/ruler/CompositeRuleAction.js
src/foam/nanos/ruler/CompositeRuleAction.js
/** * @license * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'foam.nanos.ruler', name: 'CompositeRuleAction', documentation: 'Runs multiple rule actions from one action. Completes actions sequentially in array, and actions stack.', implements: ['foam.nanos.ruler.RuleAction'], javaImports: [ 'foam.nanos.ruler.RuleAction', ], properties: [ { class: 'FObjectArray', of: 'foam.nanos.ruler.RuleAction', name: 'ruleActions' } ], methods: [ { name: 'applyAction', javaCode: ` for ( RuleAction action : getRuleActions() ) { action.applyAction(x, obj, oldObj, ruler, agency); } ` } ] });
JavaScript
0.000001
@@ -31,18 +31,24 @@ 019 -Google Inc +The FOAM Authors . Al @@ -72,563 +72,51 @@ .%0A * -%0A * Licensed under the Apache License, Version 2.0 (the %22License%22);%0A * you may not use this file except in compliance with the License.%0A * You may obtain a copy of the License at%0A *%0A * http://www.apache.org/licenses/LICENSE-2.0%0A *%0A * Unless required by applicable law or agreed to in writing, software%0A * distributed under the License is distributed on an %22AS IS%22 BASIS,%0A * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A * See the License for the specific language governing permissions and%0A * limitations under the License. + http://www.apache.org/licenses/LICENSE-2.0 %0A */
c553f2c7c57c74bf53d5431e71ce5d6b259f8e19
Correct send function in Ports.writableStream
src/Native/Ports.js
src/Native/Ports.js
Elm.Native.Ports = {}; Elm.Native.Ports.make = function(localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.Ports = localRuntime.Native.Ports || {}; if (localRuntime.Native.Ports.values) { return localRuntime.Native.Ports.values; } var NS; var Promise // WRITABLE STREAMS function writableStream(name) { if (!NS) { NS = Elm.Native.Signal.make(localRuntime); } if (!Promise) { Promise = Elm.Native.Promise.make(localRuntime); } var stream = NS.input(name); function send(value) { return Promise.asyncFunction(function(callback) { localRuntime.setTimeout(function() { localRuntime.notify(stream.id, value); }, 0); succeed(Utils.Tuple0); }); } return { stream: stream, mailbox: { ctor: 'Mailbox', _0: send } }; } // INPUTS function inputValue(name, type, converter) { return initialValue(name, type, converter); } function inputStream(name, type, converter) { var input = setupSendSignal(name, type, converter); localRuntime.foreignInput[name] = { send: input.send }; return input.signal; } function inputVarying(name, type, converter) { var value = initialValue(name, type, converter); var input = setupSendSignal(name, type, converter, value); localRuntime.foreignInput[name] = { send: input.send }; return input.signal; } function setupSendSignal(name, type, converter, initialValue) { if (!NS) { NS = Elm.Native.Signal.make(localRuntime); } var signal = NS.input(name, initialValue); function send(jsValue) { try { var elmValue = converter(jsValue); } catch(e) { throw new Error(inputError(name, type, "You just sent the value:\n\n" + " " + JSON.stringify(input.value) + "\n\n" + "but it cannot be converted to the necessary type.\n" + e.message )); } setTimeout(function() { localRuntime.notify(signal.id, elmValue); }, 0); } return { send: send, signal: signal }; } function initialValue(name, type, converter) { var nameExists = name in localRuntime.givenInputs; if (!nameExists) { throw new Error(inputError(name, type, "You must provide an initial value! Something like this in JS:\n\n" + " Elm.fullscreen(Elm.MyModule, { " + name + ": ... });" )); } var input = localRuntime.givenInputs[name]; input.used = true; try { return converter(input.value); } catch(e) { throw new Error(inputError(name, type, "You gave an initial value of:\n\n" + " " + JSON.stringify(input.value) + "\n\n" + "but it cannot be converted to the necessary type.\n" + e.message )); } } function inputError(name, type, message) { return "Input Error:\n" + "Regarding the input named '" + name + "' with type:\n\n" + " " + type.split('\n').join('\n ') + "\n\n" + message; } // OUTPUTS function outputValue(name, converter, value) { localRuntime.foreignOutput[name] = converter(value); return value; } function outputStream(name, converter, value) { localRuntime.foreignOutput[name] = setupSubscription(converter, value); return value; } function outputVarying(name, converter, value) { localRuntime.foreignOutput[name] = setupSubscription(converter, value); return value; } function setupSubscription(converter, signal) { var subscribers = []; function subscribe(handler) { subscribers.push(handler); } function unsubscribe(handler) { subscribers.pop(subscribers.indexOf(handler)); } function notify(elmValue) { var jsValue = converter(elmValue); var len = subscribers.length; for (var i = 0; i < len; ++i) { subscribers[i](jsValue); } } if (!NS) { NS = Elm.Native.Signal.make(localRuntime); } NS.output('output', notify, signal); return { subscribe: subscribe, unsubscribe: unsubscribe }; } return localRuntime.Native.Ports.values = { inputValue: inputValue, inputStream: inputStream, inputVarying: inputVarying, outputValue: outputValue, outputStream: outputStream, outputVarying: outputVarying, writableStream: writableStream }; };
JavaScript
0.000001
@@ -289,16 +289,66 @@ Promise%0A +%09var Utils = Elm.Native.Utils.make(localRuntime);%0A %0A%0A%09// WR @@ -749,16 +749,33 @@ 0);%0A%09%09%09%09 +callback(Promise. succeed( @@ -787,16 +787,17 @@ .Tuple0) +) ;%0A%09%09%09%7D);
fe8644987044b4ace5de39fde88084a9506ab2c3
refactor of DelegatedSourceDependency to es6 (#3784)
lib/dependencies/DelegatedSourceDependency.js
lib/dependencies/DelegatedSourceDependency.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var ModuleDependency = require("./ModuleDependency"); function DelegatedSourceDependency(request) { ModuleDependency.call(this, request); } module.exports = DelegatedSourceDependency; DelegatedSourceDependency.prototype = Object.create(ModuleDependency.prototype); DelegatedSourceDependency.prototype.constructor = DelegatedSourceDependency; DelegatedSourceDependency.prototype.type = "delegated source";
JavaScript
0
@@ -97,11 +97,27 @@ %0A*/%0A -var +%22use strict%22;%0Aconst Mod @@ -168,16 +168,13 @@ );%0A%0A -function +class Del @@ -199,21 +199,17 @@ ency -(request) %7B%0A%09 + extends Modu @@ -224,167 +224,90 @@ ency -.call(this, request);%0A%7D%0Amodule.exports = DelegatedSourceDependency;%0A%0ADelegatedSourceDependency.prototype = Object.create(ModuleDependency.prototype);%0AD + %7B%0A%09constructor(request) %7B%0A%09%09super(request);%0A%09%7D%0A%0A%09get type() %7B%0A%09%09return %22d elegated Sour @@ -306,135 +306,64 @@ ated -S + s ource -Dependency.prototype.constructor = DelegatedSourceDependency;%0ADelegatedSourceDependency.prototype.type = %22delegated source%22 +%22;%0A%09%7D%0A%7D%0A%0Amodule.exports = DelegatedSourceDependency ;%0A
aa4179bf3c71e9c884584be2d3bbb9ba14dbfb73
Refactoring the code
src/PrimeFactors.js
src/PrimeFactors.js
"use strict"; function PrimeFactors() { } PrimeFactors.prototype.result = []; PrimeFactors.prototype.getPrimeFactors = function(number) { this.result = this.isPrime(number) ? [number] : []; if(this.result.length == 0) { var primeNumbers = []; for(var k=2; k<number; k++) { if(this.isPrime(k)) { primeNumbers.push(k); } } for(var i=0; i<primeNumbers.length; i++){ var primeDivisor = primeNumbers[i], remainder = this.pushPrime(number, primeDivisor); while(remainder) { remainder = this.pushPrime(remainder, primeDivisor); } } } return this.result; } PrimeFactors.prototype.isPrime = function(number) { var isPrime = true; for(var i=2; i<number; i++) { if(number%i==0) isPrime = false; } return isPrime; } PrimeFactors.prototype.pushPrime = function (number, divisor) { if(number % divisor == 0) { this.result.push(divisor); return number/divisor; } else { return false; } }
JavaScript
0.673673
@@ -33,16 +33,42 @@ tors() %7B +%09%0A%09this.primeNumbers = %5B%5D; %0A%7D%0A%0APrim @@ -223,125 +223,62 @@ %09if( +! this. -result.length == 0) %7B%0A%09%09var primeNumbers = %5B%5D;%0A%09%09%0A%09%09for(var k=2; k%3Cnumber; k++) %7B%0A%09%09%09if(this.isPrime(k)) %7B%0A%09%09%09%09p +firstNumberIsPrime()) %7B%09%09%09%09%09%09%09%09%0A%09%09this.generateP rime @@ -288,26 +288,22 @@ bers -.push(k +For(number ); -%0A %09%09 -%09%7D%0A%09%09%7D %0A%09%09%0A @@ -319,16 +319,21 @@ i=0; i%3C +this. primeNum @@ -358,184 +358,67 @@ %0A%09%09%09 -var primeDivisor = primeNumbers%5Bi%5D,%0A%09%09%09remainder = this.pushPrime(number, primeDivisor);%0A%09%09%09%0A%09%09%09while(r +this.pushPrimeR ema +n inder -) %7B%0A%09%09%09%09remainder = this.pushPrime(remainder, primeDivisor +s(number, this.primeNumbers%5Bi%5D ); -%0A %09%09%09 -%7D %0A%09%09%7D @@ -447,17 +447,16 @@ ult;%0A%7D%0A%0A -%0A PrimeFac @@ -609,24 +609,281 @@ isPrime;%0A%7D%0A%0A +PrimeFactors.prototype.firstNumberIsPrime = function()%7B%0A%09return (this.result.length != 0);%0A%7D%0A%0APrimeFactors.prototype.generatePrimeNumbersFor = function(number)%7B%0A%09for(var k=2; k%3Cnumber; k++) %7B%0A%09%09if(this.isPrime(k)) %7B%0A%09%09%09this.primeNumbers.push(k);%0A%09%09%7D%0A%09%7D%0A%7D%0A%0A%0A PrimeFactors @@ -934,16 +934,39 @@ isor) %7B%0A +%09var result = false;%0A%09%0A %09if(numb @@ -1019,20 +1019,22 @@ r);%0A%09%09re -turn +sult = number/ @@ -1048,33 +1048,240 @@ ;%0A%09%7D - else %7B%0A%09%09return false +%0A%09return result;%0A%7D%0A%0APrimeFactors.prototype.pushPrimeRemaninders = function(number, primeDivisor)%7B%0A%09var remainder = this.pushPrime(number, primeDivisor);%09%09%09%0A%09while(remainder) %7B%0A%09%09remainder = this.pushPrime(remainder, primeDivisor) ;%0A%09%7D +%09 %0A%7D -%0A
61099843b70b807d6d00c32315360e837f011476
remove display name
.eslintrc.js
.eslintrc.js
module.exports = { env: { browser: true, node: true }, extends: [ 'standard', 'plugin:prettier/recommended', 'plugin:react/recommended' ], plugins: ['@typescript-eslint'], parser: '@typescript-eslint/parser', parserOptions: { sourceType: 'module', project: './tsconfig.json', ecmaFeatures: { jsx: true } }, rules: { '@typescript-eslint/adjacent-overload-signatures': 'error', 'prettier/prettier': [ 'error', { singleQuote: true, semi: false } ], yoda: 'off', 'react/prop-types': 'off', 'import/first': 'off', 'no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': 'error', 'no-dupe-class-members': 'off' }, globals: { browser: true } }
JavaScript
0.000284
@@ -558,24 +558,57 @@ oda: 'off',%0A + 'react/display-name': 'off',%0A 'react/p
f1662f6564c3441e4c315b0cb34f2fb54f9b5e4e
add rule to prefer const declarations
.eslintrc.js
.eslintrc.js
module.exports = { "env": { "browser": true, "es6": true }, "globals": { "$": true, "droll": true, }, "rules": { "no-console": 2, "no-extra-semi": 2, "no-inner-declarations": 2, "no-mixed-spaces-and-tabs": 2, "no-redeclare": 2, "no-unreachable": 2, "indent": [ "error", "tab" ] } };
JavaScript
0
@@ -12,20 +12,17 @@ rts = %7B%0A - +%09 %22env%22: %7B @@ -22,24 +22,18 @@ env%22: %7B%0A - +%09%09 %22browser @@ -41,24 +41,18 @@ : true,%0A - +%09%09 %22es6%22: t @@ -55,27 +55,21 @@ %22: true%0A - %7D,%0A +%09%7D,%0A%09 %22globals @@ -73,24 +73,18 @@ als%22: %7B%0A - +%09%09 %22$%22: tru @@ -86,24 +86,18 @@ : true,%0A - +%09%09 %22droll%22: @@ -107,19 +107,13 @@ ue,%0A - %7D,%0A +%09%7D,%0A%09 %22rul @@ -119,24 +119,18 @@ les%22: %7B%0A - +%09%09 %22no-cons @@ -134,32 +134,26 @@ onsole%22: 2,%0A - +%09%09 %22no-extra-se @@ -156,32 +156,26 @@ a-semi%22: 2,%0A - +%09%09 %22no-inner-de @@ -186,32 +186,26 @@ ations%22: 2,%0A - +%09%09 %22no-mixed-sp @@ -219,32 +219,26 @@ d-tabs%22: 2,%0A - +%09%09 %22no-redeclar @@ -244,24 +244,18 @@ re%22: 2,%0A - +%09%09 %22no-unre @@ -271,83 +271,158 @@ 2,%0A -%0A %22indent%22: %5B%0A %22error%22,%0A %22tab%22%0A %5D%0A +%09%09%22prefer-const%22: %5B%0A%09%09%09%22warn%22,%0A%09%09%09%7B%0A%09%09%09%09%22destructuring%22: %22any%22,%0A%09%09%09%09%22ignoreReadBeforeAssign%22: false%0A%09%09%09%7D%0A%09%09%5D,%0A%0A%09%09%22indent%22: %5B%0A%09%09%09%22error%22,%0A%09%09%09%22tab%22%0A%09%09%5D%0A%09 %7D%0A%7D -;%0A
b8357ff8e4e041246761c8eaef06ca135731b365
Update eslint settings
.eslintrc.js
.eslintrc.js
module.exports = { "parser": "babel-eslint", "env": { "browser": true, "jest": true, "node": true, "es6": true }, "extends": ["eslint:recommended", "plugin:react/recommended"], "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "react", "flowtype" ], "settings": { "react": { "version": "16.5", "flowVersion": "0.81" } }, "rules": { "flowtype/define-flow-type": 1, "flowtype/require-valid-file-annotation": ["error", "always"], "react/no-unescaped-entities": ["off"], "indent": ["error", 2], "linebreak-style": ["error", "unix"], "quotes": ["error", "single", "avoid-escape"], "semi": ["error", "always"], "no-var": ["error"], "brace-style": ["error"], "array-bracket-spacing": ["error", "never"], "block-spacing": ["error", "always"], "no-spaced-func": ["error"], "no-whitespace-before-property": ["error"], "space-before-blocks": ["error", "always"], "keyword-spacing": ["error"] } };
JavaScript
0
@@ -438,9 +438,9 @@ %2216. -5 +6 %22,%0A @@ -463,17 +463,17 @@ n%22: %220.8 -1 +4 %22%0A %7D%0A
bc4b64b6ec2d60860f48134f99aaafd19df0af3c
Update eslint-rules
.eslintrc.js
.eslintrc.js
module.exports = { parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features sourceType: 'module', // Allows for the use of imports }, extends: [ 'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin 'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier 'plugin:prettier/recommended', // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. ], rules: { '@typescript-eslint/ban-ts-comment': 'warn', 'no-console': 'warn', }, };
JavaScript
0
@@ -736,24 +736,76 @@ %0A rules: %7B%0A + '@typescript-eslint/no-empty-interface': 'off',%0A '@typesc
f23ee47e6767cb51f822123307b946ff77814d41
Disable the template-string linter — it’s just too loud right now. Hopefully we’ll get back to it.
.eslintrc.js
.eslintrc.js
const schemaJson = require('./app/graph/schema.json'); const ERROR = 'error'; const WARN = 'warn'; const OFF = 'off'; module.exports = { parser: 'babel-eslint', extends: [ 'eslint:recommended', 'plugin:import/react', 'plugin:import/recommended', 'plugin:react/recommended', 'plugin:flowtype/recommended' ], globals: { require: true, Features: true, process: true, Stripe: true }, env: { es6: true, browser: true }, plugins: [ 'import', 'react', 'flowtype', 'relay', 'graphql' ], rules: { 'array-bracket-spacing': [ ERROR, 'never' ], 'arrow-parens': WARN, 'arrow-spacing': WARN, 'brace-style': [ ERROR, '1tbs', { allowSingleLine: true } ], 'comma-dangle': [ ERROR, 'never' ], 'comma-spacing': ERROR, 'comma-style': [ ERROR, 'last' ], 'curly': [ ERROR, 'all' ], 'eqeqeq': [ ERROR, 'smart' ], 'id-length': ERROR, 'indent': [ ERROR, 2, { SwitchCase: 1, MemberExpression: 1, FunctionDeclaration: { parameters: 'first' }, FunctionExpression: { parameters: 'first' } } ], 'jsx-quotes': ERROR, 'key-spacing': ERROR, 'keyword-spacing': ERROR, 'linebreak-style': ERROR, 'no-const-assign': ERROR, 'no-duplicate-imports': ERROR, 'no-else-return': WARN, 'no-eval': ERROR, 'no-implied-eval': ERROR, 'no-multi-spaces': ERROR, 'no-new-require': ERROR, 'no-trailing-spaces': ERROR, 'no-unsafe-negation': ERROR, 'no-unused-vars': [ ERROR, { varsIgnorePattern: '^_' } ], 'no-useless-rename': WARN, 'no-var': WARN, 'object-curly-spacing': [ ERROR, 'always' ], 'one-var': [ ERROR, { initialized: 'never' } ], 'one-var-declaration-per-line': ERROR, 'prefer-const': WARN, 'radix': WARN, 'semi': ERROR, 'semi-spacing': ERROR, 'space-before-function-paren': [ ERROR, 'never' ], 'space-in-parens': [ ERROR, 'never' ], 'space-infix-ops': ERROR, 'space-unary-ops': ERROR, 'strict': ERROR, 'unicode-bom': ERROR, 'flowtype/delimiter-dangle': ERROR, 'flowtype/no-dupe-keys': ERROR, 'flowtype/no-primitive-constructor-types': ERROR, 'flowtype/object-type-delimiter': ERROR, 'flowtype/require-valid-file-annotation': ERROR, 'flowtype/semi': ERROR, 'import/extensions': ERROR, 'import/unambiguous': OFF, 'import/no-unresolved': OFF, // Handled by Flow. 'react/display-name': [ ERROR, { ignoreTranspilerName: false } ], 'react/forbid-prop-types': OFF, 'react/jsx-boolean-value': [ ERROR, 'always' ], 'react/jsx-closing-bracket-location': ERROR, 'react/jsx-curly-spacing': ERROR, 'react/jsx-equals-spacing': [ ERROR, 'never' ], 'react/jsx-first-prop-new-line': [ ERROR, 'multiline' ], 'react/jsx-handler-names': ERROR, 'react/jsx-indent': [ ERROR, 2 ], 'react/jsx-indent-props': [ ERROR, 2 ], 'react/jsx-key': ERROR, 'react/jsx-max-props-per-line': [ ERROR, { when: 'multiline' } ], 'react/jsx-no-bind': [ WARN, { ignoreRefs: true } ], 'react/jsx-no-comment-textnodes': ERROR, 'react/jsx-no-duplicate-props': ERROR, 'react/jsx-no-literals': OFF, 'react/jsx-no-target-blank': ERROR, 'react/jsx-no-undef': ERROR, 'react/jsx-pascal-case': ERROR, 'react/jsx-sort-prop-types': OFF, 'react/jsx-sort-props': OFF, 'react/jsx-uses-react': ERROR, 'react/jsx-uses-vars': ERROR, 'react/jsx-wrap-multilines': ERROR, 'react/no-array-index-key': WARN, 'react/no-danger': OFF, 'react/no-danger-with-children': ERROR, 'react/no-deprecated': WARN, 'react/no-did-mount-set-state': ERROR, 'react/no-did-update-set-state': ERROR, 'react/no-direct-mutation-state': ERROR, 'react/no-is-mounted': ERROR, 'react/no-multi-comp': [ ERROR, { ignoreStateless: true } ], 'react/no-set-state': OFF, 'react/no-string-refs': ERROR, 'react/no-unescaped-entities': ERROR, 'react/no-unknown-property': ERROR, 'react/no-unused-prop-types': ERROR, 'react/prefer-es6-class': ERROR, 'react/prefer-stateless-function': OFF, 'react/prop-types': ERROR, 'react/react-in-jsx-scope': ERROR, 'react/require-optimization': ERROR, 'react/require-render-return': ERROR, 'react/self-closing-comp': WARN, 'react/sort-comp': OFF, 'react/style-prop-object': WARN, 'react/jsx-tag-spacing': ERROR, 'react/void-dom-elements-no-children': ERROR, 'relay/graphql-syntax': ERROR, 'relay/compat-uses-vars': WARN, 'relay/graphql-naming': ERROR, 'relay/generated-flow-types': WARN, 'relay/no-future-added-value': WARN, 'relay/unused-fields': WARN, 'graphql/named-operations': [ WARN, { env: 'relay', schemaJson } ], 'graphql/no-deprecated-fields': [ ERROR, { env: 'relay', schemaJson } ], 'graphql/template-strings': [ ERROR, { env: 'relay', tagName: 'graphql', schemaJson } ] } };
JavaScript
0
@@ -4790,32 +4790,88 @@ emaJson %7D %5D,%0A + // Disabled for now %E2%80%94 it%E2%80%99s just a bit too noisy.%0A // 'graphql/templa @@ -4881,29 +4881,28 @@ strings': %5B -ERROR +WARN , %7B env: 're @@ -4911,24 +4911,23 @@ y', -tagName: 'graphq +validators: 'al l',
eaccd9a3bf626818dc61320fb863a5bb6e635aae
Fix line length of deprecation message
app/components/job-infrastructure-notification.js
app/components/job-infrastructure-notification.js
import Component from '@ember/component'; import { computed } from 'ember-decorators/object'; import { alias, equal } from 'ember-decorators/object/computed'; import { service } from 'ember-decorators/service'; import moment from 'moment'; const NOVEMBER_2017_RETIREMENT = '2017-11-28T12:00:00-08:00'; const LATEST_TRUSTY_RELEASE = '2017-12-12T17:25:00-00:00'; export default Component.extend({ @service auth: null, @service features: null, @alias('job.queue') queue: null, @alias('job.config') jobConfig: null, @computed('job.isFinished') conjugatedRun(isFinished) { return isFinished ? 'ran' : 'is running'; }, @equal('queue', 'builds.linux') isLegacyInfrastructure: null, @equal('queue', 'builds.ec2') isTrustySudoFalse: null, @computed('job.startedAt', 'queue', 'job.config.dist') isTrustySudoRequired(startedAt, queue, dist) { if (queue === 'builds.gce' && dist === 'trusty') { const jobRanAfterReleaseDate = Date.parse(startedAt) > Date.parse(LATEST_TRUSTY_RELEASE); if (jobRanAfterReleaseDate) { return true; } } return false; }, @equal('queue', 'builds.macstadium6') isMacStadium6: null, @computed('queue', 'job.config.dist', 'job.config.language') isPreciseEOL(queue, dist, language) { if (queue === 'builds.gce' && dist === 'precise') { if (language !== 'android') { return true; } } }, @alias('jobConfig.osx_image') macOSImage: null, deprecatedXcodeImages: ['xcode8.1', 'xcode8.2', 'xcode6.4'], imageToRetirementDate: { 'xcode8.1': NOVEMBER_2017_RETIREMENT, 'xcode8.2': NOVEMBER_2017_RETIREMENT }, imageToNewImage: { 'xcode8.1': 'xcode8.3', 'xcode8.2': 'xcode8.3' }, newImageStrings: { 'xcode8.3': 'Xcode 8.3', 'xcode7.3': 'Xcode 7.3.1', 'xcode6.4': 'Xcode 6.4' }, @computed('isMacStadium6', 'macOSImage') isDeprecatedOrRetiredMacImage(isMacStadium6, macOSImage) { return isMacStadium6 && this.get('deprecatedXcodeImages').includes(macOSImage); }, // eslint-disable-next-line @computed('job.startedAt', 'macOSImage', 'job.isFinished', 'conjugatedRun', 'isDeprecatedOrRetiredMacImage') deprecatedOrRetiredMacImageMessage(startedAt, image, isFinished, conjugatedRun) { if (image === 'xcode6.4') { return `Running builds with Xcode 6.4 in Travis CI is deprecated and will be removed in January 2019. If Xcode 6.4 is critical to your builds, please contact our support team at <a href="mailto:[email protected]">[email protected]</a> to discuss options.`; } const retirementDate = Date.parse(this.get('imageToRetirementDate')[image]); const newImage = this.get('imageToNewImage')[image]; const newImageString = this.get('newImageStrings')[newImage]; const newImageAnchor = newImageString.replace(' ', '-'); const newImageURLString = `<a href='https://docs.travis-ci.com/user/reference/osx/#${newImageAnchor}'>${newImageString}</a>`; const imageRetirementAnnouncementURL = 'https://blog.travis-ci.com/2017-11-21-xcode8-3-default-image-announce'; const jobRanBeforeRetirementDate = Date.parse(startedAt) < retirementDate; const retirementDateIsInTheFuture = retirementDate > new Date(); const formattedRetirementDate = moment(retirementDate).format('MMMM D, YYYY'); const retirementLink = `<a href='${imageRetirementAnnouncementURL}'> ${retirementDateIsInTheFuture ? 'will be retired' : 'was retired'} on ${formattedRetirementDate}</a>`; let retirementSentence, routingSentence; if (retirementDateIsInTheFuture) { retirementSentence = `This job ${conjugatedRun} on an OS X image that ${retirementLink}.`; } else { retirementSentence = ` This job ${isFinished ? 'was configured to run on' : 'is configured to run on'} an OS X image that ${retirementLink}.`; } if (retirementDateIsInTheFuture) { routingSentence = `After that, it will route to our ${newImageURLString} image.`; } else if (jobRanBeforeRetirementDate) { routingSentence = `New jobs will route to our ${newImageURLString} image.`; } else { routingSentence = `It was routed to our ${newImageURLString} image.`; } return `${retirementSentence} ${routingSentence}`; } });
JavaScript
0.9995
@@ -2364,17 +2364,17 @@ will be - +%0A removed @@ -2462,17 +2462,17 @@ ort team - +%0A at %3Ca hr
31bfdcddaa1bc68b911d0ff8cdc044090566aa2c
Fix BibTeX output path
src/Rules/BibTeX.js
src/Rules/BibTeX.js
/* @flow */ import path from 'path' import BuildState from '../BuildState' import File from '../File' import Rule from '../Rule' import type { Message } from '../types' export default class BibTeX extends Rule { static fileTypes: Set<string> = new Set(['ParsedLaTeXAuxilary']) static description: string = 'Runs BibTeX to process bibliography files (bib) when need is detected.' input: ?File static async appliesToFile (buildState: BuildState, jobName: ?string, file: File): Promise<boolean> { if (!await super.appliesToFile(buildState, jobName, file)) return false return !!file.value && !!file.value.bibdata } async initialize () { await this.getResolvedInput('.log-ParsedLaTeXLog') this.input = await this.getResolvedInput('.aux') } async addInputFileActions (file: File): Promise<void> { if (!this.constructor.commands.has(this.command) || !this.constructor.phases.has(this.phase)) { return } switch (file.type) { case 'ParsedLaTeXLog': if (file.value && file.value.messages.some((message: Message) => /run BibTeX/.test(message.text))) { this.addAction(file) } break case 'ParsedLaTeXAuxilary': break default: await super.addInputFileActions(file) break } } async preEvaluate () { if (!this.input) this.actions.delete('run') } constructProcessOptions () { const options: Object = { cwd: this.rootPath } if (this.options.outputDirectory) { options.env = Object.assign({}, process.env, { BIBINPUTS: ['.', this.options.outputDirectory].join(path.delimiter) }) } return options } constructCommand () { return ['bibtex', this.input ? this.input.normalizedFilePath : ''] } async processOutput (stdout: string, stderr: string): Promise<boolean> { const databasePattern = /^Database file #\d+: (.*)$/mg let match await this.getResolvedOutputs(['.bbl', '.blg']) while ((match = databasePattern.exec(stdout)) !== null) { await this.getInput(path.resolve(this.rootPath, match[1])) if (this.options.outputDirectory) { await this.getInput(path.resolve(this.rootPath, this.options.outputDirectory, match[1])) } } return true } }
JavaScript
0.000045
@@ -717,55 +717,157 @@ -this.input = await this.getResolvedInput( +const %7B dir, name %7D = path.parse(this.firstParameter.normalizedFilePath)%0A this.input = await this.getInput(path.format(%7B dir, name, ext: '.aux' + %7D) )%0A @@ -2022,54 +2022,167 @@ -await this.getResolvedOutputs(%5B'.bbl', '.blg'%5D +const %7B dir, name %7D = path.parse(this.firstParameter.normalizedFilePath)%0A await this.getOutputs(%5B'.bbl', '.blg'%5D.map(ext =%3E path.format(%7B dir, name, ext %7D)) )%0A%0A
ae14b93b1a63c1023502230b89756aef1c683bc3
Update paths
cautils.js
cautils.js
var exec = require('child_process').exec; var fs = require('fs'); var path = require('path'); var async = require('async'); var scrypt = require("scrypt"); var mystatus = { init: false, status: 'idle' }; //Let's see the state of the CA var serversslfiles = [ 'ca.crt', 'dh2048.pem', 'server.cnf', 'server.crt', 'server.key', 'ta.key' ]; var casslfiles = ['ca-sign.cnf','DOMAIN.txt','ca.cnf','ca.key','ca.crt']; var tmppwpath = "/tmp/pw.txt"; var caconfigdir = "/persistant/openssl"; //Chaining the ASync Calls (Async Heaven) //Check to see if the files are already created on the fs to set the state. var cafilesmissing = false; var serverfilesmissing = false; async.each(serversslfiles,function(filename,callback){ fs.exists(caconfigdir+'/server/'+filename,function(exists){ if(!exists){ serverfilesmissing=true; callback(); } else{ callback(); } }); },function(){ async.each(casslfiles,function(filename,callback){ fs.exists(caconfigdir+'/ca/'+filename,function(exists){ if(!exists){ cafilesmissing=true; callback(); } else{ callback(); } }); },function(){ if(cafilesmissing==false && serverfilesmissing==false){ //ALL CA and Server files are present. Server has been initialized. mystatus.init=true; } }); }); //This stores the password to disk function storepw(pw, callback){ var key = new Buffer(pw); var salt = new Buffer("we need to change this"); //Synchronous var scryptpw = scrypt.hashSync(key,{"N":16384,"r":8,"p":1},64,salt); fs.writeFile(tmppwpath, scryptpw, function(err){ if(err){ callback(err); //return; } else { console.log('Password written to disk unencrypted to: ' + tmppwpath); callback(); } }); } //this removes the password from the disk function removepw(){ fs.writeFile(tmppwpath, "123456789012345601982301983019830129381029381029381203980123980123981203981203980789012345678901234567890", function(err){ if(err){ console.log('ERROR HASHING OUT FILE'); return; } fs.unlinkSync(tmppwpath); console.log('removing pw file') }); } // Initilized the CA, Creates CA Files and Server Certs for OVPN function init(capassword, callback) { if (mystatus.status == 'busy') { callback(new Error('status: busy')); } else { mystatus.status = 'busy'; } storepw(capassword, function(err) { console.log('storepw called'); if (err) { //console.log(err); callback(err); }else { console.log('sdcsdcsdcsdc'); var cmd = '/opt/config.sh -i -d kisspi.com --caconfigdir=' + caconfigdir + ' --outputconfigdir=/persistant/openvpn-server/etc/openssl'; exec(cmd, function (error, stdout, stderr) { mystatus.status = 'idle'; mystatus.init = true; console.log(stdout); removepw(); callback(); }); } }); } // Generate and Sign Certificates for new client. function createClient(name, capassword, callback){ if (mystatus.init == false) { console.log('init false'); callback(new Error('init: false')); return; } if (mystatus.status == 'busy') { console.log('busy'); callback(new Error('status: busy')); return; } else { mystatus.status = 'busy'; } storepw(capassword, function(err){ console.log('storepw called'); if (err) { console.log('error storing pw'); removepw(); callback(err); }else{ console.log('Creating Client'); var cmd = 'createClientCert -n ' + name + ' -c ' + caconfigdir; exec(cmd, function(err, stdout, code) { //console.log(stdout); if (err instanceof Error) { //throw err; mystatus.status = 'idle'; removepw(); callback(new Error('Bad Password')); } else { //console.log('Exit Code: ' + process.exit(code)); console.log('createClientOVPN: openssl command completed.'); mystatus.status = 'idle'; genovpnConfig(name, function(){ removepw(); callback(); }); } }); } }); } //Generate the VPN Configuration for the Client function genovpnConfig(name, callback){ var cmd = 'buildOVPNClientConfig -n ' + name + ' --configdir=' + caconfigdir; exec(cmd, function(err, stdout, code) { if (err instanceof Error) { //throw err; mystatus.status = 'idle'; callback(new Error('Error Genreating Config...')); } else { callback(); } }); } //Return the status function status(){ return mystatus; } // Look on the file system and see what clients have already been created function showClients(callback) { function getDirectories(srcpath) { return fs.readdirSync(srcpath).filter(function(file) { return fs.statSync(path.join(srcpath, file)).isDirectory(); }); } var dirs=getDirectories(caconfigdir); // This code sucks, no time to figure out how to DRY it. Suggestions/fix's welcome! var i = dirs.indexOf("server"); if(i != -1) { dirs.splice(i, 1); } i = dirs.indexOf("ca"); if(i != -1) { dirs.splice(i, 1); } i = dirs.indexOf("client"); if(i != -1) { dirs.splice(i, 1); } callback(dirs); } module.exports.init = init; module.exports.status = status; module.exports.createClient = createClient; module.exports.storepw = storepw; module.exports.removepw = removepw; module.exports.showClients = showClients;
JavaScript
0.000001
@@ -486,16 +486,69 @@ penssl%22; +%0Avar openvpnssldir = %22/mnt/securefwd-openvpn.openssl%22 %0A%0A//Chai @@ -2939,47 +2939,25 @@ dir= -/persistant/openvpn-server/etc/openssl' +' + openvpnssldir ;%0A%0A
06a10924a18ea2c91d358dbfd6926b2093183700
Send notifications from the verification
src/Verification.js
src/Verification.js
const Notification = require('./Notification'); async function Verification( request, reply ) { console.log(request); // const notificationResult = await Notification({ // status: 'Error', // description: `There was an error proccesing`, // room: request.query.hipchat, // url: request.query.site, // }); return reply({}); } module.exports = Verification;
JavaScript
0
@@ -40,16 +40,111 @@ ation'); +%0Aconst fetch = require('node-fetch'); // polyfill%0A%0Aconst SCORE = %7B%0A GOOD: 75,%0A AVARAGE: 45,%0A%7D %0A%0Aasync @@ -152,19 +152,23 @@ unction -Ver +sendNot ificatio @@ -174,228 +174,1138 @@ on( -reques +total = 0, url, hipcha t, rep -ly +ort ) %7B%0A -console.log(request);%0A // const notificationResult = await Notification(%7B%0A // status: 'Error',%0A // description: %60There was an error proccesing%60,%0A // room: request.query.hipchat,%0A // +// Set error as default.%0A let notificationOpts = %7B%0A room: hipchat,%0A url: url,%0A description: %60The score for your %3Ca href=%22$%7Burl%7D%22%3Esite%3C/a%3E was %3Ca href=%22$%7Breport%7D%22%3E%3Cb%3E$%7Btotal.toFixed(2)%7D / 100%3C/b%3E%3C/a%3E. %3Ca href=%22$%7Breport%7D%22%3EFull report%3C/a%3E.%60,%0A %7D%0A%0A if ( total %3E= SCORE.GOOD ) %7B%0A notificationOpts.status = 'Good';%0A %7D else if ( total %3E= SCORE.AVARAGE ) %7B%0A notificationOpts.status = 'Avarage';%0A %7D else %7B%0A notificationOpts.status = 'Fail';%0A %7D%0A return await Notification(notificationOpts);%0A%7D%0A%0Aasync function Verification( request, reply ) %7B%0A const %7B id %7D = request.query;%0A const BASE = %60https://www.webpagetest.org/jsonResult.php?test=$%7Bid%7D%60;%0A const testRequest = await fetch(BASE);%0A const json = await testRequest.json();%0A const data = 'data' in json ? json.data : %7B%7D;%0A let %7B lighthouse, html_result_url %7D = data;%0A lighthouse = lighthouse %7C%7C %7B%7D;%0A const %7B url %7D = lighthouse;%0A const score = lighthouse.aggregations.reduce( (accumulator, item) =%3E %7B%0A return accumulator + item.total;%0A %7D, 0);%0A const total = score * 100;%0A const result = sendNotification(total, url -: +, req @@ -1313,26 +1313,39 @@ est. -query.site,%0A // %7D +params.hipchat, html_result_url );%0A @@ -1358,18 +1358,22 @@ n reply( -%7B%7D +result );%0A%7D%0A%0Amo
d9881a3c7b991639bd0f90c90c1445ba338a5d85
update Thead
src/_Thead/Thead.js
src/_Thead/Thead.js
/** * @file Thead component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import Th from '../_Th'; import HorizontalAlign from '../_statics/HorizontalAlign'; import SelectMode from '../_statics/SelectMode'; import SelectAllMode from '../_statics/SelectAllMode'; import SortingType from '../_statics/SortingType'; import Util from '../_vendors/Util'; import TableFragment from '../_statics/TableFragment'; import TableCalculation from '../_vendors/TableCalculation'; class Thead extends Component { static Align = HorizontalAlign; static SelectMode = SelectMode; static SelectAllMode = SelectAllMode; static SortingType = SortingType; constructor(props, ...restArgs) { super(props, ...restArgs); } render() { const { className, style, columns, baseColIndex, sorting, defaultSortingType, sortingAscIconCls, sortingDescIconCls, onSortChange, ...restProps } = this.props, columnsWithSpan = TableCalculation.getColumnsWithSpan(TableFragment.HEAD, columns); return ( <thead className={className} style={style}> <tr> { columnsWithSpan ? columnsWithSpan.map(({column, span}, colIndex) => column ? <Th {...restProps} key={colIndex} className={column.headClassName} style={column.headStyle} renderer={column.headRenderer} align={column.headAlign} colIndex={baseColIndex + colIndex} span={span} sorting={sorting} defaultSortingType={column.defaultSortingType || defaultSortingType} sortingAscIconCls={sortingAscIconCls} sortingDescIconCls={sortingDescIconCls} sortable={column.sortable} sortingProp={column.sortingProp} onSortChange={onSortChange}/> : null ) : null } </tr> </thead> ); } } Thead.propTypes = { className: PropTypes.string, style: PropTypes.object, /** * Children passed into table header. */ columns: PropTypes.arrayOf(PropTypes.shape({ /** * width of column */ width: PropTypes.number, /** * minimum width of column */ minWidth: PropTypes.number, /** * The class name of header. */ headClassName: PropTypes.string, /** * Override the styles of header. */ headStyle: PropTypes.object, /** * The render content in header. * (1) string,example: 'id' * (2) callback,example:function (colIndex) {return colIndex;} */ headRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), /** * align of table header cell */ headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * column span of table header */ headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * The class name of td. */ bodyClassName: PropTypes.string, /** * Override the styles of td. */ bodyStyle: PropTypes.object, /** * The render content in table. * (1) data key,example: 'id' * (2) data key tamplate,example:'${id} - ${name}' * (3) callback,example:function (rowData, rowIndex, colIndex) {return rowData.id;} */ bodyRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), /** * align of table body cell */ bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * column span of table body */ bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * The class name of footer. */ footClassName: PropTypes.string, /** * Override the styles of footer. */ footStyle: PropTypes.object, /** * The render content in footer. * (1) string,example: 'id' * (2) callback,example:function (colIndex) {return colIndex;} */ footRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), /** * align of table footer cell */ footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)), /** * column span of table foot */ footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), /** * If true,this column can be sorted. */ sortable: PropTypes.bool, /** * Sorting property. */ sortingProp: PropTypes.string, defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)) })).isRequired, data: PropTypes.array, baseColIndex: PropTypes.number, /** * sorting */ sorting: PropTypes.shape({ prop: PropTypes.string, type: PropTypes.oneOf(Util.enumerateValue(SortingType)) }), defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)), sortingAscIconCls: PropTypes.string, sortingDescIconCls: PropTypes.string, onSortChange: PropTypes.func }; Thead.defaultProps = { baseColIndex: 0, defaultSortingType: SortingType.ASC, sortingAscIconCls: 'fas fa-sort-up', sortingDescIconCls: 'fas fa-sort-down' }; export default Thead;
JavaScript
0
@@ -2833,32 +2833,50 @@ rayOf(PropTypes. +arrayOf(PropTypes. shape(%7B%0A%0A @@ -5605,16 +5605,17 @@ %0A %7D)) +) .isRequi
890e2298ae1af3efafcdfd5e49e70ca4de9b642a
change error throwing to console warning when having same api name in models
src/ajax-manager.js
src/ajax-manager.js
// use global count instead of jquery global event because it does't support cross domain request window.__apiCount__ = 0 window.__apiCounter = { add () { window.__apiCount__++ }, remove () { window.__apiCount__-- }, get: function () { return window.__apiCount__ } } // function getMessage (xhr) { // let message = '' // try { // let response = JSON.parse(xhr.responseText) // message = response.message || response.msg // } catch (e) { // message = xhr.responseText // } // if (xhr.status === 0 && xhr.statusText === 'timeout') message = '请求超时' // if (xhr.status === 200 && !message) message = xhr.statusText // return message // } // function handleError (errTextMap = {}, xhr, toast) { // let message = getMessage(xhr) // if (message) console.warn('Ajax: ' + message) // if (xhr.status !== 200 && toast) toast({message: errTextMap[xhr.status] || message || '请求失败', duration: 3500}) // } // function handleSuccess (xhr, toast) { // let message = getMessage(xhr) // if (xhr.status === 200) { // if (toast) toast({ message: '请求成功' }) // } else { // if (toast) { // toast({ // message: '请求异常', // iconClass: 'ion-android-cancel' // }) // } // if (message) console.warn('Ajax: ' + message) // } // } if (!window.__apiConfig__) window.__apiConfig__ = {} if (!window.__apiRoot__) window.__apiRoot__ = null function getUrl (modelName, modelConfig = {}, registerConfig = {}, config = {}) { let windowApiConfig = window.__apiConfig__[modelName] if (!windowApiConfig) windowApiConfig = {} let url = windowApiConfig.url || config.url || modelConfig.url || registerConfig.url || '' let apiRoot = window.__apiRoot__ || config.__apiRoot || modelConfig.__apiRoot || registerConfig.__apiRoot || '' let ignoreGlobalApiRoot = windowApiConfig.ignoreGlobalApiRoot || config.__ignoreGlobalApiRoot || modelConfig.__ignoreGlobalApiRoot || registerConfig.__ignoreGlobalApiRoot return ignoreGlobalApiRoot ? url : (apiRoot + url) } let apiRegister = function (modelsArray = [], registerConfig = {}, jquery) { let $ = jquery // merge all models let models = {} modelsArray.forEach((m, i) => { for (let key in m) { let model = m[key] // test if there are api useing same name if (key in models) throw new Error(`model: api should not have same name "${key}".`) models[key] = model } }) // globle config // $.ajaxSetup(Object.assign({}, models.__globlal || {}, { // // reset data and event // data: null, // beforeSend: null, // success: null, // error: null, // complete: null // })) let globalEvents = { // events set in __global and register should be add in this array beforeSend: [], success: [], error: [], complete: [] } function fireGlobalEvents (funcArray, argsArray) { for (let i = 0; i < funcArray.length; i++) { if (typeof funcArray[i] === 'function') funcArray[i](...argsArray) } } function fireLocalEvent (localEvent, argsArray) { if (typeof localEvent === 'function') localEvent(...argsArray) } let startAndStopEvents = { ajaxStart: [], ajaxStop: [] } function fireStartAndStopEvents (eventType, argsArray) { for (let i = 0; i < startAndStopEvents[eventType].length; i++) { if (typeof startAndStopEvents[eventType][i] === 'function') startAndStopEvents[eventType][i](...argsArray) } } let apis = {} for (let key in models) { if (!/^__/g.test(key)) { apis[key] = function (config = {}, triggerAjaxStartAndStopEvent = true, triggerGlobalEvents = true) { // merge event Object.keys(globalEvents).map(eventName => { if (registerConfig[eventName]) globalEvents[eventName].push(registerConfig[eventName]) if (models.__globlal[eventName]) globalEvents[eventName].push(models.__globlal[eventName]) }) Object.keys(startAndStopEvents).map(eventName => { if (registerConfig[eventName]) startAndStopEvents[eventName].push(registerConfig[eventName]) if (models.__globlal[eventName]) startAndStopEvents[eventName].push(models.__globlal[eventName]) }) let localEvents = { beforeSend: null, success: null, error: null, complete: null } Object.keys(localEvents).map(eventName => { localEvents[eventName] = config[eventName] || models[key][eventName] }) // merge data let allData = Object.assign( {}, registerConfig.data || {}, models.__globlal.data || {}, models[key].data || {}, config.data || {}) // merge config let allConfig = Object.assign( {}, registerConfig || {}, models[key] || {}, config, { url: getUrl(key, models[key], registerConfig, config), data: allData, beforeSend (xhr) { if (triggerAjaxStartAndStopEvent) { window.__apiCounter.add() fireStartAndStopEvents('ajaxStart', [xhr]) } if (triggerGlobalEvents) fireGlobalEvents(globalEvents.beforeSend, [xhr]) fireLocalEvent(localEvents.beforeSend, [xhr]) }, success (data, statusText, xhr) { if (triggerGlobalEvents) fireGlobalEvents(globalEvents.success, [data, statusText, xhr]) fireLocalEvent(localEvents.success, [data, statusText, xhr]) }, error (xhr, statusText, error) { if (triggerGlobalEvents) fireGlobalEvents(globalEvents.error, [xhr, statusText, error]) fireLocalEvent(localEvents.error, [xhr, statusText, error]) }, complete (xhr, statusText) { if (triggerAjaxStartAndStopEvent) { window.__apiCounter.remove() fireStartAndStopEvents('ajaxStop', [xhr, statusText]) } if (triggerGlobalEvents) fireGlobalEvents(globalEvents.complete, [xhr, statusText]) fireLocalEvent(localEvents.complete, [xhr, statusText]) } } ) // format data when post application json if (allConfig.contentType && allConfig.contentType.toLowerCase().trim() === 'application/json') { allConfig.data = JSON.stringify(allData) } // if got window api config use the type in it if (window.__apiConfig__ && window.__apiConfig__[key] && window.__apiConfig__[key].type) { allConfig.type = window.__apiConfig__[key].type } return $.ajax(allConfig) } } } return apis } export default apiRegister
JavaScript
0
@@ -2330,24 +2330,27 @@ e name%0A + // if (key in @@ -2423,16 +2423,120 @@ ey%7D%22.%60)%0A + if (key in models) console.warn(%60ajaxManager: api in models should not have same name %22$%7Bkey%7D%22.%60)%0A mo
fa5f5ce25ca9af9b8c022d8b86809cafbbcac64a
Add AngularyticsProvider.setPageChangeEvent()
src/angularytics.js
src/angularytics.js
(function(){ angular.module('angularytics', []).provider('Angularytics', function() { var eventHandlersNames = ['Google']; this.setEventHandlers = function(handlers) { if (angular.isString(handlers)) { handlers = [handlers]; } eventHandlersNames = []; angular.forEach(handlers, function(handler) { eventHandlersNames.push(capitalizeHandler(handler)) }); } var capitalizeHandler = function(handler) { return handler.charAt(0).toUpperCase() + handler.substring(1); } this.$get = function($injector, $rootScope, $location) { // Helper methods var eventHandlers = []; angular.forEach(eventHandlersNames, function(handler) { eventHandlers.push($injector.get('Angularytics' + handler + 'Handler')); }); var forEachHandlerDo = function(action) { angular.forEach(eventHandlers, function(handler) { action(handler); }); } // Event listeing $rootScope.$on('$locationChangeSuccess', function() { forEachHandlerDo(function(handler) { var url = $location.path(); if (url) { handler.trackPageView(url); } }) }); var service = {}; // Just dummy function so that it's instantiated on app creation service.init = function() { } service.trackEvent = function(category, action, opt_label, opt_value, opt_noninteraction) { forEachHandlerDo(function(handler) { if (category && action) { handler.trackEvent(category, action, opt_label, opt_value, opt_noninteraction); } }); } return service; }; }); })();
JavaScript
0
@@ -599,32 +599,220 @@ ng(1);%0A %7D +%0A %0A var pageChangeEvent = '$locationChangeSuccess';%0A this.setPageChangeEvent = function(newPageChangeEvent) %7B%0A pageChangeEvent = newPageChangeEvent;%0A %7D %0A%0A this.$ @@ -1358,32 +1358,23 @@ $on( -'$locationChangeSuccess' +pageChangeEvent , fu