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
ff0e3ffa5ec552bb704107286d55d26e7b7d060e
Increase font size.
server/image-handler.js
server/image-handler.js
var _ = require('lodash'); var gm = require('gm'); gm = gm.subClass({ imageMagick: true }); var log = require('./logger').log; exports.getFirstFrameOfGif = function(imageBuffer, callback) { gm(imageBuffer, 'image.gif[0]') .toBuffer('PNG', function(err, buffer) { if (err) { log.error("Could not extract first frame from gif"); callback(null); return; } callback(buffer); }); }; exports.annotate = function(imageBuffer, extension, messages, callback) { var sizeContent = function(width,height,content) { if (!content) { content = ''; } var tokens = content.split(/\n+/); console.dir(tokens); var longestToken = 1; for (var a=0;a<tokens.length;a++) { longestToken = Math.max(longestToken,tokens[a].length); } var low = 1; var high = Math.max(18,height/5); var fontSize = high; var numLettersCanFit = Math.floor((width/fontSize)*1.5); console.log(numLettersCanFit + " " + longestToken + " " + low + " " + high); if (true) { // Use bisection to get the right font size for (var a=0;a<50;a++) { var mid = (low+high)/2; console.log(mid); fontSize = mid; // You can fit 14 M's when (width/fontSize) == 10 numLettersCanFit = Math.floor((width/fontSize)*1.5); if (numLettersCanFit < longestToken) { high = mid; } else { low = mid; } } fontSize = low; numLettersCanFit = Math.floor((width/fontSize)*1.5); } console.log(numLettersCanFit + " " + longestToken + " " + low + " " + high); console.log(fontSize); fontSize /= Math.max(1.0, tokens.length / 2.0 ); return {text:content, fontSize:fontSize}; }; var drawContent = function(handler, content, width, height, gravity) { var finalText = content.text; var fontSize = content.fontSize; var tokens = finalText.split(/\n+/); for (var a=0;a<tokens.length;a++) { var drawHeight = 0; if (gravity.substring(0,5) == 'South') { drawHeight = (tokens.length-1-a)*(fontSize*7/8); } else if(gravity.substring(0,5) == 'North') { drawHeight = a*fontSize*7/8; } else { drawHeight = (a - (tokens.length-1)/2.0)*fontSize*7/8; } var left = 0; if (_.endsWith(gravity, "East") || _.endsWith(gravity, "West")) { left = 10; } var border = fontSize/20; handler = handler .font("./Impact.ttf", fontSize) .fill('white') .stroke("black", border) .drawText(left, drawHeight, tokens[a], gravity); } return handler; }; var handler = gm(imageBuffer, extension); handler .size(function(err, value) { if (err) { console.log("Error: " + err); return; } console.dir(value); handler = handler.coalesce(); for (var a=0;a<messages.length;a++ ){ var content = sizeContent( value.width,value.height, messages[a].content); var location = null; var halign = messages[a].halign; var valign = messages[a].valign; if (halign == 'left') { if (valign == 'top') { location = 'NorthWest'; } else if (valign == 'bottom') { location = 'SouthWest'; } else { location = 'West'; } } else if (halign == 'right') { if (valign == 'top') { location = 'NorthEast'; } else if (valign == 'bottom') { location = 'SouthEast'; } else { location = 'East'; } } else { if (valign == 'top') { location = 'North'; } else if (valign == 'bottom') { location = 'South'; } else { location = 'Center'; } } handler = drawContent(handler, content, value.width, value.height, location); } handler .toBuffer(extension, function(err, buffer) { if (err) { callback(null); return; } callback(buffer); }); }); }; exports.minSize = function(data, extension, width, height, callback) { var handler = gm(data, extension); handler .size(function(err, value) { if (value.width <= width && value.height <= height) { // Image is already small enough callback(data); return; } handler .resize(width, height) .toBuffer(extension, function(err, buffer) { if (err) { callback(null); return; } callback(buffer); }); }); }; exports.maxSize = function(data, extension, width, height, callback) { var handler = gm(data, extension); handler .size(function(err, value) { if (value.width >= width && value.height >= height) { // Image is already large enough callback(data); return; } handler .resize(width, height) .toBuffer(extension, function(err, buffer) { if (err) { callback(null); return; } callback(buffer); }); }); };
JavaScript
0
@@ -928,32 +928,33 @@ dth/fontSize)*1. +7 5);%0A console. @@ -1313,24 +1313,25 @@ fontSize)*1. +7 5);%0A%0A @@ -1525,16 +1525,17 @@ Size)*1. +7 5);%0A
4d8019cc48591c42b059a586de45afec8ff293cc
fix user-badge links
lib/header/user-badge/component.js
lib/header/user-badge/component.js
import React, { Component } from 'react' import { Link } from 'react-router' import bus from 'bus' import t from 't-component' import config from 'lib/config' import userConnector from 'lib/site/connectors/user' export class UserBadge extends Component { static links = [ config.frequentlyAskedQuestions ? { label: t('help.faq.title'), path: '/help/faq' } : false ].filter((p) => p) constructor (props) { super(props) this.state = { menuUserBadge: false, canChangeTopics: false } } componentDidMount () { bus.on('forum:change', this.setChangeTopicsPermission) } componentWillUnmount () { bus.off('forum:change', this.setChangeTopicsPermission) } setChangeTopicsPermission = (forum) => { this.setState({ canChangeTopics: (forum && forum.privileges.canChangeTopics) }) } toggleMenu = (e) => { this.setState({ menuUserBadge: !this.state.menuUserBadge }) } render () { const userAttrs = this.props.user.state.value let menuItemAdmin = null if (userAttrs.privileges && userAttrs.privileges.canManage) { if (config.multiForum) { menuItemAdmin = ( <li> <Link to='/settings/forums'> {t('header.forums')} </Link> </li> ) } else { menuItemAdmin = ( <li> <Link to='/admin'> {t('header.admin')} </Link> </li> ) } } const classes = ['user-badge', 'header-item'] if (this.state.menuUserBadge) classes.push('active') return ( <div className={classes.join(' ')} onClick={this.toggleMenu}> <button href='#' className='header-link'> <img src={userAttrs.avatar} alt='' /> <span className='name hidden-xs-down'>{userAttrs.firstName}</span> <span className='caret hidden-xs-down' /> </button> <ul className='dropdown-list'> {menuItemAdmin} <li className='notifications-li'> <Link to='/notifications'>{t('notifications.title')}</Link> </li> <li> <Link to='/settings'> {t('header.settings')} </Link> </li> {UserBadge.links.map((link) => ( <li><Link to={link.path}>{link.label}</Link></li> ))} <li> <a onClick={this.props.user.logout}> {t('header.logout')} </a> </li> </ul> </div> ) } } export default userConnector(UserBadge)
JavaScript
0.000001
@@ -2290,16 +2290,19 @@ ap((link +, i ) =%3E (%0A @@ -2315,17 +2315,50 @@ %3Cli -%3E + key=%7B%60link-$%7Bi%7D%60%7D%3E%0A %3CLink to @@ -2389,16 +2389,29 @@ %7D%3C/Link%3E +%0A %3C/li%3E%0A
e396807e558bf337b540b2130a1d55ee0289e9da
Fix broken behavior when 'claimArticle' is used without notification
app/assets/javascripts/actions/assignment_actions.js
app/assets/javascripts/actions/assignment_actions.js
import API from '../utils/api.js'; import * as types from '../constants'; import logErrorMessage from '../utils/log_error_message'; import request from '../utils/request'; import { addNotification } from './notification_actions.js'; const fetchAssignmentsPromise = (courseSlug) => { return request(`/courses/${courseSlug}/assignments.json`) .then((res) => { if (res.ok && res.status === 200) { return res.json(); } return Promise.reject(res); }) .catch((error) => { logErrorMessage(error); return error; }); }; export const fetchAssignments = courseSlug => (dispatch) => { return ( fetchAssignmentsPromise(courseSlug) .then((resp) => { dispatch({ type: types.RECEIVE_ASSIGNMENTS, data: resp }); }) .catch(response => dispatch({ type: types.API_FAIL, data: response })) ); }; export const addAssignment = assignment => (dispatch) => { return API.createAssignment(assignment) .then(resp => dispatch({ type: types.ADD_ASSIGNMENT, data: resp })) .catch(response => dispatch({ type: types.API_FAIL, data: response })); }; export const randomPeerAssignments = randomAssignments => (dispatch) => { dispatch({ type: types.LOADING_ASSIGNMENTS }); return API.createRandomPeerAssignments(randomAssignments) .then(resp => dispatch({ type: types.RECEIVE_ASSIGNMENTS, data: resp })) .catch(response => dispatch({ type: types.API_FAIL, data: response })); }; export const deleteAssignment = assignment => (dispatch) => { return API.deleteAssignment(assignment) .then(resp => dispatch({ type: types.DELETE_ASSIGNMENT, data: resp })) .catch(response => dispatch({ type: types.API_FAIL, data: response })); }; const claimAssignmentPromise = (assignment) => { return request(`/assignments/${assignment.id}/claim`, { method: 'PUT', body: JSON.stringify(assignment) }) .then(res => res.json()); }; export const claimAssignment = (assignment, successNotification) => (dispatch) => { return claimAssignmentPromise(assignment) .then((resp) => { if (resp.assignment) { dispatch(addNotification(successNotification)); dispatch({ type: types.UPDATE_ASSIGNMENT, data: resp }); } else { dispatch({ type: types.API_FAIL, data: resp }); } }) .catch(response => dispatch({ type: types.API_FAIL, data: response })); }; export const updateAssignmentStatus = (assignment, status) => () => { const body = { id: assignment.id, status, user_id: assignment.user_id }; return request(`/assignments/${assignment.id}/status.json`, { body: JSON.stringify(body), method: 'PATCH' }).then((res) => { if (res.ok && res.status === 200) { return res.json(); } return Promise.reject(res); }) .catch((error) => { logErrorMessage(error); return error; }); };
JavaScript
0.000148
@@ -2121,32 +2121,59 @@ nment) %7B%0A + if (successNotification) %7B dispatch(addNot @@ -2204,16 +2204,18 @@ ation)); + %7D %0A
de534245c53424cebb18f437e2cf59ab8a0cc600
Fix failing test
spec/spec.fourth-wall.js
spec/spec.fourth-wall.js
function setupMoment(date, anObject) { spyOn(anObject, "moment"); anObject.moment.plan = function () { var realMoment = anObject.moment.originalValue; // set "now" to a fixed date to enable static expectations if (!arguments.length) { return realMoment(date); } return realMoment.apply(null, arguments); } } describe("Fourth Wall", function () { describe("Repos", function () { describe("schedule", function () { var repos; beforeEach(function() { spyOn(FourthWall, "getQueryVariable"); spyOn(window, "setInterval"); spyOn(FourthWall.Repos.prototype, "fetch"); spyOn(FourthWall.Repos.prototype, "updateList"); repos = new FourthWall.Repos(); }); it("updates the repo list every 15 minutes by default", function () { repos.schedule(); expect(repos.updateList.callCount).toEqual(1); expect(setInterval.argsForCall[0][1]).toEqual(900000); var callback = setInterval.argsForCall[0][0]; callback(); expect(repos.updateList.callCount).toEqual(2); }); it("updates the repo list at a configurable interval", function () { FourthWall.getQueryVariable.andReturn(120); repos.schedule(); expect(setInterval.argsForCall[0][1]).toEqual(120000); var callback = setInterval.argsForCall[0][0]; callback(); expect(repos.updateList).toHaveBeenCalled(); }); it("updates the status every 60 seconds by default", function () { repos.schedule(); expect(setInterval.argsForCall[1][1]).toEqual(60000); var callback = setInterval.argsForCall[1][0]; callback(); expect(repos.fetch).toHaveBeenCalled(); }); it("updates the status at a configurable interval", function () { FourthWall.getQueryVariable.andReturn(10); repos.schedule(); expect(setInterval.argsForCall[1][1]).toEqual(10000); var callback = setInterval.argsForCall[1][0]; callback(); expect(repos.fetch).toHaveBeenCalled(); }); }); }); describe("Repo", function () { describe("initialize", function () { it("instantiates an internal Master model", function () { var repo = new FourthWall.Repo(); expect(repo.master instanceof FourthWall.MasterStatus).toBe(true); }); it("instantiates an internal list of pull requests", function () { var repo = new FourthWall.Repo(); expect(repo.pulls instanceof FourthWall.Pulls).toBe(true); }); it("triggers a change when the master status changes", function () { var repo = new FourthWall.Repo(); var changed = false; repo.on('change', function () { changed = true; }); repo.master.set('failed', 'true'); expect(changed).toBe(true); }); }); describe("fetch", function () { it("fetches new master and pulls data", function () { spyOn(FourthWall.MasterStatus.prototype, "fetch"); spyOn(FourthWall.Pulls.prototype, "fetch"); var repo = new FourthWall.Repo(); repo.fetch(); expect(repo.master.fetch).toHaveBeenCalled(); }); }); }); describe("Pull", function () { describe("initialize", function () { var pull; beforeEach(function() { spyOn(FourthWall.Comment.prototype, "fetch"); spyOn(FourthWall.Status.prototype, "fetch"); pull = new FourthWall.Pull({ head: {sha: 'foo'} }, { collection: {} }); }); it("instantiates an internal Comment model", function () { expect(pull.comment instanceof FourthWall.Comment).toBe(true); }); it("triggers a change when the comment changes", function () { var changed = false; pull.on('change', function () { changed = true; }); pull.comment.set('foo', 'bar'); expect(changed).toBe(true); }); it("fetches new comment data when the comment URL changes", function () { pull.set('comments_url', 'foo'); expect(pull.comment.url).toEqual('foo'); expect(pull.comment.fetch).toHaveBeenCalled(); }); it("fetches new comment data when pull data has been fetched", function () { pull.fetch() expect(pull.comment.fetch).toHaveBeenCalled(); }); it("instantiates an internal Status model", function () { expect(pull.status instanceof FourthWall.Status).toBe(true); }); it("fetches new status data when the head changes", function () { pull.set('head', 'foo'); expect(pull.status.fetch).toHaveBeenCalled(); }); it("triggers a change when the status changes", function () { var changed = false; pull.on('change', function () { changed = true; }); pull.status.set('foo', 'bar'); expect(changed).toBe(true); }); }); describe("parse", function () { it("calculates seconds since pull request creation date", function () { spyOn(FourthWall.Pull.prototype, "elapsedSeconds").andReturn(60); spyOn(FourthWall.Comment.prototype, "fetch"); spyOn(FourthWall.Status.prototype, "fetch"); var pull = new FourthWall.Pull({ head: {sha: 'foo'} }, { collection: {} }); var result = pull.parse({ created_at: "2013-09-02T10:00:00+01:00" }); expect(pull.elapsedSeconds).toHaveBeenCalledWith("2013-09-02T10:00:00+01:00"); expect(result.elapsed_time).toEqual(60); }); }); describe("elapsedSeconds", function () { it("calculates seconds in working time since creation date", function () { setupMoment("2013-09-09T10:01:00+01:00", window) spyOn(FourthWall.Comment.prototype, "fetch"); spyOn(FourthWall.Status.prototype, "fetch"); var pull = new FourthWall.Pull({ head: {sha: 'foo'} }, { collection: {} }); var result = pull.parse({ created_at: "2013-09-02T10:00:00+01:00" }); var fullDay = 8 * 60 * 60; var expected = 7.5 * 60 * 60 // day 1: from 10:00 to 17:30 + fullDay * 4 // days 2 - 4: tuesday to friday, weekend ignored + 31 * 60 // today: from 9:30 to 10:01 expect(result.elapsed_time).toEqual(expected); }); }); }); describe("Pulls", function () { describe("url", function () { it("constructs a URL from user name and repo name", function () { var pulls = new FourthWall.Pulls([], { userName: 'foo', repo: 'bar' }); expect(pulls.url()).toEqual('https://api.github.com/repos/foo/bar/pulls'); }); }); }); describe("ListItems", function () { describe("fetch", function () { it("collects open pull requests from repos", function () { var repo = new FourthWall.Repo({ userName: 'foo', repo: 'bar' }); repo.pulls.reset(); var items = new FourthWall.ListItems([], { repos: new FourthWall.Repos([ ]) }); }); }); }); });
JavaScript
0.000209
@@ -6367,16 +6367,17 @@ o 10:01%0A +%0A @@ -6406,21 +6406,95 @@ time).to -Equal +BeGreaterThan(expected - 120);%0A expect(result.elapsed_time).toBeLessThan (expecte @@ -6494,16 +6494,22 @@ expected + + 120 );%0A
ced547d4bac3d52282483f843a510c7c5bfa6a76
make final test
des_sample.js
des_sample.js
var assert = require('assert'); var crypto = require('crypto');
JavaScript
0.00016
@@ -53,12 +53,1310 @@ ('crypto');%0A +%0Afunction test_des(param) %7B%0A var key = new Buffer(param.key);%0A var iv = new Buffer(param.iv ? param.iv : 0)%0A var plaintext = param.plaintext%0A var alg = param.alg%0A var autoPad = param.autoPad%0A%0A //encrypt%0A var cipher = crypto.createCipheriv(alg, key, iv);%0A cipher.setAutoPadding(autoPad) //default true%0A var ciph = cipher.update(plaintext, 'utf8', 'hex');%0A ciph += cipher.final('hex');%0A // console.log(alg, ciph)%0A%0A //decrypt%0A var decipher = crypto.createDecipheriv(alg, key, iv);%0A cipher.setAutoPadding(autoPad)%0A var txt = decipher.update(ciph, 'hex', 'utf8');%0A txt += decipher.final('utf8');%0A assert.equal(txt, plaintext, 'fail');%0A console.log('%E7%AE%97%E6%B3%95:', alg, '%E5%8E%9F%E6%96%87:', plaintext, '%E5%8A%A0%E5%AF%86:', ciph, '%E8%A7%A3%E5%AF%86:', txt);%0A%7D%0A%0A// do test%0A%0Atest_des(%7B%0A alg: 'des-ecb',%0A autoPad: true,%0A key: '01234567',%0A plaintext: '99999999',%0A iv: null%0A%7D)%0A%0Atest_des(%7B%0A alg: 'des-cbc',%0A autoPad: true,%0A key: '12345678',%0A plaintext: '99999999',%0A iv: '12345678'%0A%7D)%0A%0Atest_des(%7B%0A alg: 'des-ede3', //3des-ecb%0A autoPad: true,%0A key: '0123456789abcd0123456789',%0A plaintext: '99999999',%0A iv: null%0A%7D)%0A%0Atest_des(%7B%0A alg: 'des-ede3-cbc', //3des-cbc%0A autoPad: true,%0A key: '12345678901234567890abcd',%0A plaintext: '99999999',%0A iv: '12345678'%0A%7D)
b14b5d08a804641aedb2225f99f8040fe8b01f0c
Fix request
lib/index.js
lib/index.js
var config = require('config'); var SparkPost = require('sparkpost'); var client = new SparkPost(config.Email.SparkPostKey); /*** * Send an email via SparkPost * @param message The message object you want to send. Has .html and .text properties * @param options Send options. * @param callback * @constructor */ exports.SendEmail = function(message, options, callback, isTest) { if (isTest === undefined) { isTest = callback; callback = options; options = undefined; } var request = { transmissionBody: { content: { from: { email: config.Email.Address, name: config.Email.Name }, subject: message.subject, html: message.html, text: message.text }, recipients: [{ address: { name: message.to.name, email: message.to.email } }] } }; if (options) { if (options.from) { if (options.from.email) { request.transmissionBody.content.from.email = options.from.email; } if (options.from.name) { request.transmissionBody.content.from.name = options.from.name; } } // If we have a reply to, add it to the email headers if (options.replyTo) { request.transmissionBody.content.reply_to = options.replyTo; } if (options.track_opens) { request.transmissionBody.open_tracking = options.track_opens; } if (options.track_clicks) { request.transmissionBody.click_tracking = options.track_clicks; } } if (isTest) { return callback(request.transmissionBody); } client.transmissions.send(request.transmissionBody, function(e) { callback(request, e); }); };
JavaScript
0.000001
@@ -1892,33 +1892,16 @@ (request -.transmissionBody , functi
0587664760886f8ab3237c64bfb4fdb5768034ee
Make end-transaction warnings more obvious when debugging
lib/instrumentation/transaction.js
lib/instrumentation/transaction.js
'use strict' var uuid = require('node-uuid') var debug = require('debug')('opbeat') var Trace = require('./trace') module.exports = Transaction function Transaction (agent, name, type, result) { Object.defineProperty(this, 'name', { configurable: true, enumerable: true, get: function () { return this._customName || this._defaultName }, set: function (name) { debug('setting transaction name %o', { uuid: this._uuid, name: name }) this._customName = name } }) this._defaultName = name this.type = type this.result = result this.traces = [] this.ended = false this._uuid = uuid.v4() this._agent = agent debug('start transaction %o', { uuid: this._uuid, name: name, type: type, result: result }) // A transaction should always have a root trace spanning the entire // transaction. this._rootTrace = new Trace(this) this._rootTrace.start('transaction', 'transaction') this._start = this._rootTrace._start this.duration = this._rootTrace.duration.bind(this._rootTrace) } Transaction.prototype.setDefaultName = function (name) { debug('setting default transaction name: %s', name) this._defaultName = name } Transaction.prototype.end = function () { if (this.ended) return debug('cannot end already ended transaction %o', { uuid: this._uuid }) this._rootTrace.end() this.ended = true var trace = this._agent._instrumentation.currentTrace // These two edge-cases should normally not happen, but if the hooks into // Node.js doesn't work as intended it might. In that case we want to // gracefully handle it. That involves ignoring all traces under the given // transaction as they will most likely be incomplete. We still want to send // the transaction without any traces to Opbeat as it's still valuable data. if (!trace) { debug('no current trace found %o', { current: trace, traces: this.traces.length, uuid: this._uuid }) this.traces = [] } else if (trace.transaction !== this) { debug('transaction is out of sync %o', { traces: this.traces.length, uuid: this._uuid, other: trace.transaction._uuid }) this.traces = [] } this._agent._instrumentation.addEndedTransaction(this) debug('ended transaction %o', { uuid: this._uuid, type: this.type, result: this.result }) } Transaction.prototype._recordEndedTrace = function (trace) { if (this.ended) { debug('Can\'t record ended trace after parent transaction have ended - ignoring %o', { uuid: this._uuid }) return } if (!this._agent._instrumentation.currentTrace) { if (this._agent._instrumentation._buildTraceFailed) { // in case the buildTraceFailed boolean is true, we have no way of // knowing if traces are missing between the given trace and the // traces already pushed to the stack. In that case it's better to bail debug('No current trace available - restore not possible!', { uuid: this._uuid }) return } debug('No current trace available - attempting restore', { uuid: this._uuid }) this._agent._instrumentation.currentTrace = trace } this.traces.push(trace) }
JavaScript
0.000012
@@ -1834,16 +1834,25 @@ debug(' +WARNING: no curre @@ -2012,16 +2012,25 @@ debug(' +WARNING: transact
75384d50a7872c38cf7b2c8b3d271b9df80c9211
Improve search and mentions suggestions
app/assets/javascripts/app/views/search_base_view.js
app/assets/javascripts/app/views/search_base_view.js
app.views.SearchBase = app.views.Base.extend({ initialize: function(options) { this.ignoreDiasporaIds = []; this.typeaheadInput = options.typeaheadInput; this.setupBloodhound(options); if(options.customSearch) { this.setupCustomSearch(); } this.setupTypeahead(); // TODO: Remove this as soon as corejavascript/typeahead.js has its first release this.setupMouseSelectionEvents(); if(options.autoselect) { this.setupAutoselect(); } }, bloodhoundTokenizer: function(str) { if(typeof str !== "string") { return []; } return str.split(/[\s\.:,;\?\!#@\-_\[\]\{\}\(\)]+/).filter(function(s) { return s !== ""; }); }, setupBloodhound: function(options) { var bloodhoundOptions = { datumTokenizer: function(datum) { var nameTokens = this.bloodhoundTokenizer(datum.name); var handleTokens = datum.handle ? this.bloodhoundTokenizer(datum.handle) : []; return nameTokens.concat(handleTokens); }.bind(this), queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: { url: "/contacts.json", transform: this.transformBloodhoundResponse, cache: false }, sufficient: 5 }; // Allow bloodhound to look for remote results if there is a route given in the options if(options.remoteRoute) { bloodhoundOptions.remote = { url: options.remoteRoute + ".json?q=%QUERY", wildcard: "%QUERY", transform: this.transformBloodhoundResponse }; } this.bloodhound = new Bloodhound(bloodhoundOptions); }, setupCustomSearch: function() { var self = this; this.bloodhound.customSearch = function(query, sync, async) { var _sync = function(datums) { var results = datums.filter(function(datum) { return datum.handle !== undefined && self.ignoreDiasporaIds.indexOf(datum.handle) === -1; }); sync(results); }; self.bloodhound.search(query, _sync, async); }; }, setupTypeahead: function() { this.typeaheadInput.typeahead({ hint: false, highlight: true, minLength: 2 }, { name: "search", display: "name", limit: 5, source: this.bloodhound.customSearch !== undefined ? this.bloodhound.customSearch : this.bloodhound, templates: { /* jshint camelcase: false */ suggestion: HandlebarsTemplates.search_suggestion_tpl /* jshint camelcase: true */ } }); }, transformBloodhoundResponse: function(response) { return response.map(function(data) { // person if(data.handle) { data.person = true; return data; } // hashtag return { hashtag: true, name: data.name, url: Routes.tag(data.name.substring(1)) }; }); }, _deselectAllSuggestions: function() { this.$(".tt-suggestion").removeClass("tt-cursor"); }, _selectSuggestion: function(suggestion) { this._deselectAllSuggestions(); suggestion.addClass("tt-cursor"); }, // TODO: Remove this as soon as corejavascript/typeahead.js has its first release setupMouseSelectionEvents: function() { var self = this, selectSuggestion = function(e) { self._selectSuggestion($(e.target).closest(".tt-suggestion")); }, deselectAllSuggestions = function() { self._deselectAllSuggestions(); }; this.typeaheadInput.on("typeahead:render", function() { self.$(".tt-menu .tt-suggestion").off("mouseover").on("mouseover", selectSuggestion); self.$(".tt-menu .tt-suggestion *").off("mouseover").on("mouseover", selectSuggestion); self.$(".tt-menu .tt-suggestion").off("mouseleave").on("mouseleave", deselectAllSuggestions); }); }, // Selects the first result when the result dropdown opens setupAutoselect: function() { var self = this; this.typeaheadInput.on("typeahead:render", function() { self._selectSuggestion(self.$(".tt-menu .tt-suggestion").first()); }); }, ignorePersonForSuggestions: function(person) { if(person.handle) { this.ignoreDiasporaIds.push(person.handle); } }, });
JavaScript
0
@@ -774,50 +774,78 @@ -var nameTokens = this.bloodhoundTokenizer( +// hashtags%0A if(typeof datum.handle === %22undefined%22) %7B return %5B datu @@ -850,18 +850,20 @@ tum.name -); +%5D; %7D %0A @@ -867,67 +867,68 @@ -var handleTokens = datum.handle ? this.bloodhoundTokenizer( +// people%0A if(datum.name === datum.handle) %7B return %5B datu @@ -939,15 +939,12 @@ ndle -) : %5B %5D; + %7D %0A @@ -959,38 +959,64 @@ urn -nameTokens.concat(handleTokens +this.bloodhoundTokenizer(datum.name).concat(datum.handle );%0A
547d756fe6fad2f9cef7d41c757f8ddc0c017e19
Clean up from loging/new tab
app/scripts/controllers/dashboard/dashboard.js
app/scripts/controllers/dashboard/dashboard.js
(function() { 'use strict'; angular.module('sslv2App') .controller('DashboardCtrl', DashboardCtrl); DashboardCtrl.$inject = ['$state', '$cookies']; function DashboardCtrl($state, $cookies) { // console.log($cookies); // console.log($cookies.getObject(sessionStorage.getItem('id'))); // console.log($cookies.get('id')); var vm = this; var profile = localStorage.getItem('id');; vm.full_name = localStorage.getItem('full_name'); vm.email = profile.email; vm.logout = logout; function logout(){ //$cookies.remove(profile.id); sessionStorage.clear(); var rememberEmail = localStorage.getItem('email'); localStorage.clear(); localStorage.setItem('email',rememberEmail); $state.go('login'); } } })();
JavaScript
0
@@ -203,148 +203,8 @@ ) %7B%0A - // console.log($cookies);%0A // console.log($cookies.getObject(sessionStorage.getItem('id')));%0A // console.log($cookies.get('id'));%0A @@ -408,10 +408,8 @@ -// $coo
97d59a87efe6548d840a482a2a494760d4e740b5
add remove method to typeahead
grails-app/assets/javascripts/imms.form.pack.js
grails-app/assets/javascripts/imms.form.pack.js
// bootstrap 3.1.1 // + datetimepicker 3.0.0 https://github.com/Eonasdan/bootstrap-datetimepicker http://eonasdan.github.io/bootstrap-datetimepicker // + typeahead https://github.com/bassjobsen/Bootstrap-3-Typeahead // // //= require imms.datatable.pack //= require imms.datepicker.pack //= require_self (function($, Backbone, _, moment, Bloodhound, App){ App.view.TypeAhead = App.View.extend({ events : { "change" : "onSelect" }, onSelect : function() { var item = this.$el.data("selected-value"); App.logDebug("on select " + item); if(this.$values != undefined) { App.logDebug("this.$values is ok "); this.$values.children("input").each(function(){ var $this = $(this); App.logDebug("data-field " + $this.data("field")); if($this.data("field")) { var val = item ? item[$this.data("field")] : null; if(val) $this.val(val); else { if(item) App.logErr("Warning. data not exist for field: " + $this.data("field")); } } }); } }, // <input class=".type-ahead" id="assetInstance-type" data-field="type" data-domain="assetType" data-display-key='value' data-items='all' data-minLength='2'/> // <div id="type-values"> // <input type="hidden" name="typeId" data-field="id"> // <input type="hidden" name="typeCd" data=field="code"> // </div> initialize: function(opt) { this.field = this.$el.data("field"); // fieldName this.key = this.$el.data("domain"); //domain class this.$values = this.$el.parent().find("#"+this.field + "-values"); this.displayKey = this.$el.data("display-key") || "value"; this.name = opt.name || this.key; //http://stackoverflow.com/questions/14901535/bootstrap-typeahead-ajax-result-format-example/14959406#14959406 //http://tatiyants.com/how-to-use-json-objects-with-twitter-bootstrap-typeahead/ this.$el.typeahead({ isObjectItem : true, displayKey : this.displayKey, autoSelect : false, remoteUrl : this.$el.data("source-url") || App.url + "/typeAhead/" + this.key, remoteDefaultOpts : { max : 50} }); } }); App.view.EditableForm = App.View.extend({ datePickers : [], typeAheadFields : [], events : { "click .buttons .btn" : "doAction" }, remove: function() { _.each(this.datePickers, function() { this.remove()}); return Backbone.View.prototype.remove.apply(this, arguments); }, initialize: function(opt) { _.each(this.$(".date"), function(elem){ var dpEl = this.$el.selector + " #" + elem.id; // so datepicker element must have ID this.datePickers.push(new App.view.DatePicker({ el : dpEl, pubSub : this.pubSub})); }, this); _.each(this.$(".type-ahead"), function(elem){ var dpEl = this.$el.selector + " #" + elem.id; // so typeahead element must have ID this.typeAheadFields.push(new App.view.TypeAhead({ el : dpEl, pubSub : this.pubSub})); }, this); }, doAction : function(evt) { var $btn = $(evt.currentTarget); App.logDebug("doAction "); return false; } }); App.view.TableFormTabs = App.View.extend({ el : '#content-section', table : null, form : null, events : { "click .nav-tabs li:eq(0) a" : "buildTable", "click .nav-tabs li:eq(1) a" : "buildForm" }, remove: function() { if(this.table != null) this.table.remove(); if(this.form != null) this.form.remove(); return Backbone.View.prototype.remove.apply(this, arguments); }, initialize: function() { this.setupTab(); }, setupTab : function() { var $tableLi = this.$(".nav-tabs li:eq(0)"), $formLi = this.$(".nav-tabs li:eq(1)"); var $tableA = $tableLi.find("a"), $formA = $formLi.find("a"); this.tableEl = this.$($tableA.attr("href")); this.formEl = this.$($formA.attr("href")); if(this.tableEl == undefined || this.formEl == undefined) App.logErr("Please check the tab UI"); if($tableLi.hasClass("active")) { $tableA.tab("show"); this.buildTable(); } else { $formA.tab("show"); this.buildForm(); } }, buildTable : function() { if(this.table == undefined) this.table = new App.view.TableRegion( {el: this.tableEl, key: this.key} ); }, buildForm : function() { if(this.form == undefined) this.form = new App.view.EditableForm( {el: this.formEl, key: this.key} ); } }); })(jQuery, Backbone, _, moment, Bloodhound, App);
JavaScript
0
@@ -2451,32 +2451,259 @@ %7D);%0A + %7D,%0A remove: function() %7B%0A if(this.$el.data('typeahead')) %7B%0A this.$el.data('typeahead').destroy();%0A %7D%0A return Backbone.View.prototype.remove.apply(this, arguments);%0A %7D%0A %7D) @@ -2977,24 +2977,95 @@ remove()%7D);%0A + _.each(this.typeAheadFields, function() %7B this.remove()%7D);%0A
7236996be64bc98f8cdc58c3b854519fa1c2e3f5
Fix test config.
spec/util/config-mock.js
spec/util/config-mock.js
var validator = require("../../lib/config/validator"); module.exports = { databaseUri: "nedb://spec-db", homeServerUrl: "https://some.home.server.goeshere", homeServerDomain: "some.home.server", homeServerToken: "foobar", botLocalpart: "monkeybot", appServiceToken: "it's a secret", appServiceUrl: "https://mywuvelyappservicerunninganircbridgeyay.gome", port: 2 }; module.exports.roomMapping = { server: "irc.example", botNick: "ro_bot_nick", channel: "#coffee", roomId: "!foo:bar" }; var serverConfig = { "irc.example": { botConfig: { nick: module.exports.roomMapping.botNick }, dynamicChannels: { enabled: true }, mappings: { "#coffee": [module.exports.roomMapping.roomId] } } }; var config = validator.loadConfig({ appService: { hs: module.exports.homeServerUrl, hsDomain: module.exports.homeServerDomain, token: module.exports.appServiceToken, as: module.exports.appServiceUrl, port: module.exports.port, localpart: module.exports.botLocalpart }, ircService: { databaseUri: module.exports.databaseUri, servers: serverConfig } }); module.exports.ircConfig = config; module.exports.serviceConfig = config.appService;
JavaScript
0
@@ -882,17 +882,44 @@ h -s +omeserver: %7B%0A url : module @@ -954,11 +954,13 @@ -hsD + d omai @@ -993,18 +993,54 @@ erDomain -, %0A + %7D,%0A appservice: %7B%0A @@ -1086,18 +1086,23 @@ -as + url : module @@ -1123,18 +1123,48 @@ rviceUrl -, %0A + %7D,%0A http: %7B%0A @@ -1188,16 +1188,26 @@ rts.port +%0A %7D ,%0A
e5bb36b8ee9718b5b6b765ca3fdbfda7431eb61b
test is now es6
app/templates/test/test.js
app/templates/test/test.js
'use strict' var test = require('tape') , <%= repoName %> = require('../') test('<%= repoName %>#get', function getTest(t){ t.plan(2) t.doesNotThrow( <%= repoName %>.get , 'does not throw' ) t.ok( 'I was too lazy to write any tests. Shame on me.' , 'must have at least one test' ) })
JavaScript
0
@@ -1,81 +1,69 @@ -'use strict'%0A%0Avar test = require('tape')%0A , %3C%25= repoName %25%3E = require('../') +import test from 'tape'%0Aimport %3C%25= repoName %25%3E from '../index.js' %0A%0Ate @@ -92,27 +92,15 @@ t', -function getTest(t) +(t) =%3E %7B%0A
444c56ed67d4bf98c5d81a48334468999d7fe69c
Fix Webpack Middleware in Browsersync
app/templates/src/gulpfile/tasks/browsersync.js
app/templates/src/gulpfile/tasks/browsersync.js
/** * Browser Sync * @description Refresh the Browser after File Change. */ import kc from '../../config.json' import gulp from 'gulp' import browserSync from 'browser-sync' import webpack from 'webpack' import webpackDevMiddleware from 'webpack-dev-middleware' import webpackHotMiddleware from 'webpack-hot-middleware' import webpackSettings from '../../webpack.dev.config.babel' const bundler = webpack(webpackSettings) const browserSyncTask = () => { // Build a condition when Proxy is active let bsProxy let bsServer // Condition for Proxy if(kc.browsersync.proxy) { bsProxy = { target: kc.browsersync.proxy, ws: true, middleware: [ webpackDevMiddleware(bundler, { publicPath: webpackSettings.output.publicPath, stats: { colors: true } }), webpackHotMiddleware(bundler) ] } bsServer = false } else { bsProxy = false bsServer = { baseDir : kc.dist.browserSyncDir } } // Browser Sync browserSync.init({ debugInfo: true, watchTask: true, proxy: bsProxy, ghostMode: { clicks: true, scroll: true, links: true, forms: true }, logLevel: 'info', notify: { styles: [ 'padding: 8px 16px;', 'position: fixed;', 'font-size: 12px;', 'font-weight: bold', 'z-index: 9999;', 'top: inherit', 'border-radius: 0', 'right: 0;', 'bottom: 0;', 'color: #f4f8f9;', 'background-color: #026277;', 'text-transform: uppercase' ] }, server: bsServer, open: kc.browsersync.openbrowser, files: [ kc.dist.js + '**/*.js', kc.dist.css + '**/*.css',<% if (projectUsage == 'Integrate in CraftCMS' ) { %> kc.dist.markup + 'templates/**/*.{php,html,twig}',<% } else if (projectUsage == 'Integrate in Wordpress') { %> kc.dist.markup + '**/*.{php,html,png,txt,md}',<% } else { %> kc.dist.base + '**/*.{php,html}',<% } %> kc.dist.cssimg + '**/*.{jpg,gif,png,svg}' ] }); }; gulp.task('browser-sync', browserSyncTask) module.exports = browserSyncTask
JavaScript
0.000001
@@ -651,218 +651,8 @@ true -,%0A middleware: %5B%0A webpackDevMiddleware(bundler, %7B%0A publicPath: webpackSettings.output.publicPath,%0A stats: %7B colors: true %7D%0A %7D),%0A webpackHotMiddleware(bundler)%0A %5D %0A @@ -869,16 +869,226 @@ bsProxy, +%0A middleware: %5B%0A webpackDevMiddleware(bundler, %7B%0A publicPath: webpackSettings.output.publicPath,%0A stats: %7B colors: true %7D%0A %7D),%0A webpackHotMiddleware(bundler)%0A %5D, %0A%0A
ae65c7453c43c3fc4b5156ada42b4d6ae7781649
fix bug
src/admin/directives/nd-navigation.directive.js
src/admin/directives/nd-navigation.directive.js
/** * ndNavigation Directives */ angular.module('directives').directive('ndNavigation', ['$templateCache', '$rootScope', '$state', '$timeout', '$http', '$filter', 'account', function ($templateCache, $rootScope, $state, $timeout, $http, $filter, account) { return { restrict: 'E', template: $templateCache.get('navigation.view.html'), link: function (scope, element) { /** * 初始化变量 */ scope.notFoundPages = false; scope.notFoundContents = false; scope.auth = {}; scope.categories = []; scope.user = {}; /** * 激活滑动门 */ function slideShow () { $('.sub-list').each(function () { var self = $(this); if (self.children('.item').hasClass('active')) { self.siblings('.item').addClass('active select'); } else { self .slideUp('fast', function () { self.siblings('.sub-list-heading').removeClass('select'); }) .siblings('.sub-list-heading').removeClass('active'); } }); } /** * 读取用户 */ function loadUser () { account.get() .then(function (user) { scope.user = user; }, function () { scope.$emit('notification', { type: 'danger', message: '读取用户失败' }); }); account.auths() .then(function (auths) { scope.auths = auths; }, function () { scope.$emit('notification', { type: 'danger', message: '读取权限失败' }); }); } loadUser(); /** * 退出登录 */ scope.signOut = function () { $http.put('/api/account/sign-out') .then(function () { // 清空账户缓存 account.reset(); $state.go('signIn'); }, function () { scope.$emit('notification', { type: 'danger', message: '退出登录失败' }); }); }; /** * 读取栏目列表 */ function loadCategories () { $http.get('/api/categories') .then(function (res) { var data = res.data; scope.categories = $filter('filter')(data, function (value) { if (value.type !== 'channel' && value.type !== 'link') { return true; } }); if (!_.find(data, { type: 'page', mixed: { isEdit: true } })) { scope.notFoundPages = true; } else { scope.notFoundPages = false; } if (!_.find(data, { type: 'column' })) { scope.notFoundContents = true; } else { scope.notFoundContents = false; } $timeout(function () { slideShow(); }); }); } loadCategories(); /** * 接收路由状态变更消息 */ $rootScope.$on('$stateChangeSuccess', function () { $timeout(function () { slideShow(); }); }); /** * 接收分类更新消息 */ $rootScope.$on('mainCategoriesUpdate', function () { loadCategories(); }); /** * 接收用户更新消息 */ $rootScope.$on('mainUserUpdate', function () { account.reset(); loadUser(); }); /** * 滑动门 */ $('.navigation').on('click', '.sub-list-heading', function () { var self = $(this); if (self.hasClass('select')) { self.siblings('.sub-list').slideUp('fast', function () { $(this).siblings('.sub-list-heading').removeClass('select'); }); } else { self.siblings('.sub-list').slideDown('fast', function () { $(this).siblings('.sub-list-heading').addClass('select'); }); } $('.sub-list:visible').not(self.siblings('.sub-list')).slideUp('fast', function () { $(this).siblings('.sub-list-heading').removeClass('select'); }); }); } } } ]);
JavaScript
0.000001
@@ -654,24 +654,59 @@ deShow () %7B%0A + $timeout(function () %7B%0A $( @@ -741,32 +741,34 @@ ) %7B%0A + + var self = $(thi @@ -764,32 +764,34 @@ elf = $(this);%0A%0A + if ( @@ -831,24 +831,26 @@ active')) %7B%0A + @@ -905,32 +905,34 @@ ');%0A + %7D else %7B%0A @@ -916,32 +916,34 @@ %7D else %7B%0A + se @@ -961,16 +961,18 @@ + .slideUp @@ -986,32 +986,34 @@ , function () %7B%0A + @@ -1092,11 +1092,15 @@ + + %7D)%0A + @@ -1169,33 +1169,51 @@ ');%0A + -%7D + %7D%0A %7D); %0A %7D);%0A
2531721001c9803831522312de485c876d03d830
fix typo in migratorInterface
lib/interface/migratorInterface.js
lib/interface/migratorInterface.js
function MigratorInterface() { } MigratorInterface.prototype = { checkDBMS: function() { arguments[arugments.length - 1]('not implemented'); }, createDatabase: function() { arguments[arugments.length - 1]('not implemented'); }, switchDatabase: function() { arguments[arugments.length - 1]('not implemented'); }, dropDatabase: function() { arguments[arugments.length - 1]('not implemented'); }, bindForeignKey: function() { arguments[arugments.length - 1]('not implemented'); }, createTable: function() { arguments[arugments.length - 1]('not implemented'); }, dropTable: function() { arguments[arugments.length - 1]('not implemented'); }, renameTable: function() { arguments[arugments.length - 1]('not implemented'); }, addColumn: function() { arguments[arugments.length - 1]('not implemented'); }, removeColumn: function() { arguments[arugments.length - 1]('not implemented'); }, renameColumn: function() { arguments[arugments.length - 1]('not implemented'); }, changeColumn: function() { arguments[arugments.length - 1]('not implemented'); }, addIndex: function() { arguments[arugments.length - 1]('not implemented'); }, insert: function() { arguments[arugments.length - 1]('not implemented'); }, removeIndex: function() { arguments[arugments.length - 1]('not implemented'); }, addForeignKey: function() { arguments[arugments.length - 1]('not implemented'); }, removeForeignKey: function() { arguments[arugments.length - 1]('not implemented'); }, runSql: function() { arguments[arugments.length - 1]('not implemented'); } }; module.exports = MigratorInterface;
JavaScript
0.000007
@@ -97,34 +97,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -192,34 +192,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -286,34 +286,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -378,34 +378,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -472,34 +472,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -563,34 +563,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -652,34 +652,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -743,34 +743,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -832,34 +832,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -924,34 +924,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -1016,34 +1016,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -1108,34 +1108,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -1196,34 +1196,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -1282,34 +1282,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -1373,34 +1373,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -1466,34 +1466,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -1562,34 +1562,34 @@ arguments%5Bar -u g +u ments.length - 1 @@ -1660,10 +1660,10 @@ s%5Bar -u g +u ment @@ -1708,22 +1708,60 @@ %7D;%0A%0A -module.exports +%0Aexports.extending = %7B%0A%7D;%0A%0Aexports.MigratorInterface = M
5b17408af31ef24321331cc4dfef0a348558eb48
Fix example for edit-form
tests/dummy/app/controllers/components-examples/flexberry-objectlistview/on-edit-form/suggestion.js
tests/dummy/app/controllers/components-examples/flexberry-objectlistview/on-edit-form/suggestion.js
import Ember from 'ember'; import BaseEditFormController from 'ember-flexberry/controllers/edit-form'; import EditFormControllerOperationsIndicationMixin from 'ember-flexberry/mixins/edit-form-controller-operations-indication'; import { Query } from 'ember-flexberry-data'; export default BaseEditFormController.extend(EditFormControllerOperationsIndicationMixin, { /** Route name for transition after close edit form. @property parentRoute @type String @default 'ember-flexberry-dummy-suggestion-list' */ parentRoute: 'components-examples/flexberry-objectlistview/on-edit-form', /** Name of model.comments edit route. @property commentsEditRoute @type String @default 'ember-flexberry-dummy-comment-edit' */ commentsEditRoute: 'ember-flexberry-dummy-comment-edit', folvModelName: 'ember-flexberry-dummy-localized-suggestion-type', folvProjection: 'LocalizedSuggestionTypeE', /** Method to get type and attributes of a component, which will be embeded in object-list-view cell. @method getCellComponent. @param {Object} attr Attribute of projection property related to current table cell. @param {String} bindingPath Path to model property related to current table cell. @param {DS.Model} modelClass Model class of data record related to current table row. @return {Object} Object containing name & properties of component, which will be used to render current table cell. { componentName: 'my-component', componentProperties: { ... } }. */ getCellComponent(attr, bindingPath, model) { let cellComponent = this._super(...arguments); if (Ember.isNone(model)) { return cellComponent; } if (attr.kind === 'belongsTo') { switch (`${model.modelName}+${bindingPath}`) { case 'ember-flexberry-dummy-vote+author': cellComponent.componentProperties = { choose: 'showLookupDialog', remove: 'removeLookupValue', displayAttributeName: 'name', required: true, relationName: 'author', projection: 'ApplicationUserL', autocomplete: true, }; break; case 'ember-flexberry-dummy-comment+author': cellComponent.componentProperties = { choose: 'showLookupDialog', remove: 'removeLookupValue', displayAttributeName: 'name', required: true, relationName: 'author', projection: 'ApplicationUserL', autocomplete: true, }; break; } } else if (attr.kind === 'attr') { switch (`${model.modelName}+${bindingPath}`) { case 'ember-flexberry-dummy-vote+author.eMail': cellComponent.componentProperties = { readonly: true, }; } } return cellComponent; }, customFolvContentObserver: Ember.observer('model', 'model.type', 'perPage', 'page', 'sorting', 'filter', 'filters', function() { let _this = this; Ember.run(function() { Ember.run.once(_this, 'getCustomContent'); }); }), objectListViewLimitPredicate: function(options) { let methodOptions = Ember.merge({ modelName: undefined, projectionName: undefined, params: undefined }, options); if (methodOptions.modelName === this.get('folvModelName') && methodOptions.projectionName === this.get('folvProjection')) { let id = this.get('model.type.id'); let limitFunction = new Query.SimplePredicate('suggestionType', Query.FilterOperator.Eq, id); return limitFunction; } return undefined; }, });
JavaScript
0.998397
@@ -2867,253 +2867,8 @@ %7D,%0A%0A - customFolvContentObserver: Ember.observer('model', 'model.type', 'perPage', 'page', 'sorting', 'filter', 'filters', function() %7B%0A let _this = this;%0A%0A Ember.run(function() %7B%0A Ember.run.once(_this, 'getCustomContent');%0A %7D);%0A %7D),%0A%0A ob @@ -3392,13 +3392,224 @@ ed;%0A %7D, +%0A%0A customFolvContentObserver: Ember.observer('model', 'model.type', 'perPage', 'page', 'sorting', 'filter', 'filters', function() %7B%0A%0A Ember.run.scheduleOnce('afterRender', this, this.getCustomContent);%0A %7D), %0A%7D);%0A
32a4c17868122e5106903f47c39d77256090f4b9
purge local functions in sellingReduced() and shiftedIntoDirichletDomain()
src/geometry/lattices.js
src/geometry/lattices.js
import { floatMatrices } from '../arithmetic/types'; const ops = floatMatrices; const eps = Math.pow(2, -50); const trim = x => Math.abs(x) < eps ? 0 : x; const lift = op => (...args) => args.reduce((a, b) => op(a, b)); const sum = lift(ops.plus); const gaussReduced = (u, v, dot = ops.times) => { const vs = [u, v]; const norm = v => dot(v, v); while (true) { const [i, j] = ops.lt(norm(vs[0]), norm(vs[1])) ? [0, 1] : [1, 0]; const t = ops.round(ops.div(dot(vs[0], vs[1]), norm(vs[i]))); vs[j] = ops.minus(vs[j], ops.times(t, vs[i])); if (ops.ge(norm(vs[j]), ops.times(norm(vs[i]), 1-eps))) break; } if (ops.gt(dot(vs[0], vs[1]), 0)) vs[1] = ops.negative(vs[1]); return vs; }; const sellingReduced = (u, v, w, dot = ops.times) => { const vs = [u, v, w, ops.negative(sum(u, v, w))]; const _sellingStep = () => { for (let i = 0; i < 3; ++i) { for (let j = i+1; j < 4; ++j) { if (ops.gt(dot(vs[i], vs[j]), eps)) { for (let k = 0; k < 4; ++k) { if (k != i && k != j) { vs[k] = sum(vs[k], vs[i]); } } vs[i] = ops.negative(vs[i]); return true; } } } }; while (_sellingStep()) { } return vs.slice(0, 3); }; const dirichletVectors = (basis, dot = ops.times) => { switch (basis.length) { case 0: case 1: return basis; case 2: { const vs = gaussReduced(...basis, dot); return [vs[0], vs[1], sum(vs[0], vs[1])]; } case 3: { const vs = sellingReduced(...basis, dot); return [ vs[0], vs[1], vs[2], sum(vs[0], vs[1]), sum(vs[0], vs[2]), sum(vs[1], vs[2]), sum(vs[0], vs[1], vs[2]) ] } } }; const reducedLatticeBasis = (vs, dot = ops.times) => { const abs = v => v.map(x => Math.abs(x)); const dif = (v, w) => (v > w) - (v < w); const cmp = (v, w) => ops.minus(dot(v, v), dot(w, w)) || dif(abs(w), abs(v)); const dim = vs[0].length; const tmp = dirichletVectors(vs, dot).sort(cmp); const A = []; for (let k = 0, i = 0; i < dim; ++i) { while (k < tmp.length) { let w = tmp[k++]; if (w < ops.times(0, w)) w = ops.negative(w); if (i > 0 && ops.gt(dot(A[0], w), 0)) w = ops.negative(w); A[i] = w.map(trim); if (ops.rank(A) > i) break; } } return A; }; const shiftedIntoDirichletDomain = (pos, dirichletVecs, dot = ops.times) => { let p = pos; const _step = () => { let changed = false; for (const v of dirichletVecs) { const t = ops.div(dot(p, v), dot(v, v)); if (t <= -0.5 || t > 0.5+eps) { p = ops.minus(p, ops.times(ops.round(t), v)); changed = true; } } return changed; }; while (_step()) { } return p; }; if (require.main == module) { Array.prototype.toString = function() { return '[ ' + this.map(x => x.toString()).join(', ') + ' ]'; }; console.log(reducedLatticeBasis([[16,3], [5,1]])); console.log(reducedLatticeBasis([[1,0,0], [1,1,0], [1,1,1]])); console.log(shiftedIntoDirichletDomain([3.2, -1.4], [[1,0],[0,1],[1,1]])); }
JavaScript
0
@@ -835,39 +835,52 @@ )%5D;%0A -%0A -const _sellingStep = () =%3E %7B +let changed;%0A%0A do %7B%0A changed = false;%0A %0A @@ -1130,22 +1130,25 @@ i%5D);%0A%09 -return +changed = true;%0A%09 @@ -1166,28 +1166,24 @@ %7D%0A %7D -;%0A%0A while ( _selling @@ -1178,29 +1178,17 @@ le ( -_sellingStep()) %7B%0A %7D +changed); %0A%0A @@ -2390,41 +2390,35 @@ os;%0A -%0A -const _step = () =%3E +let changed;%0A%0A do %7B%0A -let chan @@ -2649,58 +2649,28 @@ %7D%0A -%0A return changed;%0A %7D;%0A%0A while (_step()) %7B%0A %7D + %7D while (changed); %0A%0A
1a9ed008420563c396ce3bf6cbb5699e64516d20
improve coverage for Image (#4673)
src/js/components/Image/__tests__/Image-test.js
src/js/components/Image/__tests__/Image-test.js
import React from 'react'; import renderer from 'react-test-renderer'; import 'jest-styled-components'; import 'jest-axe/extend-expect'; import 'regenerator-runtime/runtime'; import { cleanup, render } from '@testing-library/react'; import { axe } from 'jest-axe'; import { Grommet } from '../../Grommet'; import { Image } from '..'; const opacityTypes = ['weak', 'medium', 'strong', '0.3', true, false]; const SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAABGdBTUEAALGPC/xhBQAAAA1JREFUCB1jYGBg+A8AAQQBAB5znEAAAAAASUVORK5CYII='; // eslint-disable-line max-len test('image should have no violations', async () => { const { container } = render( <Grommet> <Image src={SRC} a11yTitle="Alt Text" /> </Grommet>, ); const results = await axe(container); expect(results).toHaveNoViolations(); cleanup(); }); test('Image renders', () => { const component = renderer.create( <Grommet> <Image src={SRC} /> </Grommet>, ); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); test('Image renders with aria-label', () => { const component = renderer.create( <Grommet> <Image a11yTitle="aria-label-text" src={SRC} /> </Grommet>, ); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); test('Image fit renders', () => { const component = renderer.create( <Grommet> <Image fit="cover" src={SRC} /> <Image fit="contain" src={SRC} /> </Grommet>, ); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); opacityTypes.forEach(opacity => { test(`Image opacity of ${opacity} renders`, () => { const component = renderer.create( <Grommet> <Image opacity={opacity} src={SRC} /> </Grommet>, ); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); test('Image fillProp renders', () => { const component = renderer.create( <Grommet> <Image fill src={SRC} /> <Image fill={false} src={SRC} /> <Image fill="horizontal" src={SRC} /> <Image fill="vertical" src={SRC} /> </Grommet>, ); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); });
JavaScript
0
@@ -177,16 +177,21 @@ import %7B + act, cleanup @@ -191,16 +191,27 @@ cleanup, + fireEvent, render @@ -2196,28 +2196,330 @@ ree).toMatchSnapshot();%0A%7D);%0A +%0Atest('Image onError', () =%3E %7B%0A const onError = jest.fn();%0A const %7B getByAltText %7D = render(%0A %3CGrommet%3E%0A %3CImage alt=%22test%22 onError=%7BonError%7D /%3E%0A %3C/Grommet%3E,%0A );%0A%0A act(() =%3E %7B%0A fireEvent(getByAltText('test'), new Event('error'));%0A %7D);%0A%0A expect(onError).toHaveBeenCalledTimes(1);%0A%7D);%0A
41966ae3b6495e75b820280d92c8e7626a4d5cdc
remove log, spell correctly
guide/buildpages.js
guide/buildpages.js
var Handlebars = require('handlebars') var fs = require('fs') var glob = require('glob') var layout = fs.readFileSync(__dirname + '/layout.hbs').toString() var thefiles = [] var lang = process.argv[2] // I can probably use glob better to avoid // finding the right files within the files var rawFiles = __dirname + (lang ? '/raw-content-' + lang + '/' : '/raw-content/') var builtContent = __dirname + (lang ? '/chalenges-' + lang + '/' : '/challenges/') console.log(rawFiles, builtContent) glob("*.html", {cwd: rawFiles}, function (err, files) { thefiles = files if (err) return console.log(err) // var matches = files.map(function(file) { // if (file.match('guide/raw-content/')) { // return file // } // }) buildPage(files) }) function buildPage(files) { files.forEach(function(file) { // shouldn't have to do this if my // mapping were correct if (!file) return var content = { header: buildHeader(file), footer: buildFooter(file), body: fs.readFileSync(rawFiles + file).toString() } var shortname = makeShortname(file) var template = Handlebars.compile(layout) var final = template(content) fs.writeFileSync(builtContent + shortname + 'html', final) }) // hard coded right now because, reasons console.log("Built!") } function makeShortname(filename) { // FROM guide/raw-content/10_merge_tada.html // TO merge_tada. return filename.split('/').pop().split('_') .slice(1).join('_').replace('html', '') } function makeTitleName(filename) { var short = makeShortname(filename).split('_') .join(' ').replace('.', '') return grammarize(short) } function buildHeader(filename) { var num = filename.split('/').pop().split('_')[0] var title = makeTitleName(filename) var source = fs.readFileSync(__dirname + '/partials/header.html').toString() var template = Handlebars.compile(source) var content = {challengetitle: title, challengenumber: num } return template(content) } function grammarize(name) { var correct = name var wrongWords = ['arent', 'githubbin', 'its'] var rightWords = ["aren't", "GitHubbin", "it's"] wrongWords.forEach(function(word, i) { if (name.match(word)) { correct = name.replace(word, rightWords[i]) } }) return correct } function buildFooter(file) { var num = file.split('/').pop().split('_')[0] var data = getPrevious(num) data.lang = lang ? '-' + lang : '' var source = fs.readFileSync(__dirname + '/partials/footer.html').toString() var template = Handlebars.compile(source) // console.log(data) // console.log(template(data)) return template(data) } function getPrevious(num) { var pre = parseInt(num) - 1 var next = parseInt(num) + 1 var preurl = '' var prename = '' var nexturl = '' var nextname = '' thefiles.forEach(function(file) { if (pre === 0) { prename = "All Challenges" preurl = "../index.html" } else if (file.match(pre)) { prename = makeTitleName(file) var getridof = pre + '_' preurl = file.replace(getridof, '') } if (next === 12) { nextname = "Done!" nexturl = '../index.html' } else if (file.match(next)) { nextname = makeTitleName(file) var getridof = next + '_' nexturl = file.replace(getridof, '') } }) return {prename: prename, preurl: preurl, nextname: nextname, nexturl: nexturl} }
JavaScript
0.000003
@@ -411,16 +411,17 @@ ? '/chal +l enges-' @@ -2563,64 +2563,8 @@ ce)%0A - // console.log(data)%0A // console.log(template(data))%0A re
a20ee920da212df682267ccfd24ead81d6037e33
Add GTM environments support (#114)
addon/metrics-adapters/google-tag-manager.js
addon/metrics-adapters/google-tag-manager.js
import Ember from 'ember'; import canUseDOM from '../utils/can-use-dom'; import objectTransforms from '../utils/object-transforms'; import BaseAdapter from './base'; const { assert, get, set, $, getWithDefault, String: { capitalize } } = Ember; const assign = Ember.assign || Ember.merge; const { compact } = objectTransforms; export default BaseAdapter.extend({ dataLayer: 'dataLayer', toStringExtension() { return 'GoogleTagManager'; }, init() { const config = get(this, 'config'); const { id } = config; const dataLayer = getWithDefault(config,'dataLayer', 'dataLayer'); assert(`[ember-metrics] You must pass a valid \`id\` to the ${this.toString()} adapter`, id); set(this, 'dataLayer', dataLayer); if (canUseDOM) { /* jshint ignore:start */ (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script',get(this, 'dataLayer'),id); /* jshint ignore:end */ } }, trackEvent(options = {}) { const compactedOptions = compact(options); const dataLayer = get(this, 'dataLayer'); const gtmEvent = {'event': compactedOptions['event']}; delete compactedOptions['event']; for (let key in compactedOptions) { const capitalizedKey = capitalize(key); gtmEvent[`event${capitalizedKey}`] = compactedOptions[key]; } if (canUseDOM) { window[dataLayer].push(gtmEvent); } return gtmEvent; }, trackPage(options = {}) { const compactedOptions = compact(options); const dataLayer = get(this, 'dataLayer'); const sendEvent = { event: compactedOptions['event'] || 'pageview' }; const pageEvent = assign(sendEvent, compactedOptions); if (canUseDOM) { window[dataLayer].push(pageEvent); } return pageEvent; }, willDestroy() { if (canUseDOM) { $('script[src*="gtm.js"]').remove(); delete window.dataLayer; } } });
JavaScript
0
@@ -525,16 +525,27 @@ nst %7B id +, envParams %7D = con @@ -593,16 +593,17 @@ (config, + 'dataLay @@ -620,16 +620,77 @@ Layer'); +%0A const envParamsString = envParams ? %60&$%7BenvParams%7D%60: ''; %0A%0A as @@ -847,40 +847,8 @@ ) %7B%0A - /* jshint ignore:start */%0A @@ -865,31 +865,58 @@ n(w, + d, + s, + l, + i) -%7B + %7B%0A w%5Bl%5D -= + = w%5Bl%5D + %7C%7C + %5B%5D; +%0A w%5Bl%5D @@ -922,16 +922,27 @@ %5D.push(%7B +%0A 'gtm.sta @@ -945,22 +945,16 @@ .start': -%0A new Dat @@ -971,22 +971,34 @@ e(), +%0A event: + 'gtm.js' %7D);v @@ -997,17 +997,37 @@ .js' -%7D); +%0A %7D);%0A var f -= + = d.ge @@ -1062,10 +1062,18 @@ + -j= + j = d.cr @@ -1091,14 +1091,32 @@ (s), -dl=l!= +%0A dl = l !== 'dat @@ -1126,45 +1126,66 @@ yer' -? + ? '&l=' -+l:''; + + l : '';%0A j.async -= + = true; -j.src= %0A + j.src = 'ht @@ -1230,14 +1230,45 @@ id=' -+i+dl; + + i + dl + envParamsString;%0A f.pa @@ -1291,16 +1291,17 @@ efore(j, + f);%0A @@ -1312,16 +1312,17 @@ (window, + document @@ -1322,16 +1322,17 @@ ocument, + 'script' @@ -1332,16 +1332,17 @@ script', + get(this @@ -1360,43 +1360,14 @@ r'), + id);%0A - /* jshint ignore:end */%0A
de03e40d7da979937fc0ad991e82349abadcbb35
fix formatting
src/components/rows/presentation/Subtotal.js
src/components/rows/presentation/Subtotal.js
import React from 'react' import { TableRow, TableRowColumn } from 'material-ui/Table' const Subtotal = ({style, salary, kiwisaver, depreciation, phoneContribution}) => { const sum = +salary + +kiwisaver + +depreciation + +phoneContribution return ( <TableRow> <TableRowColumn> <h3>Subtotal</h3> </TableRowColumn> <TableRowColumn> <p style={style.outputNumbers}> { !isNaN(sum) && '$' + sum.toFixed(2) } </p> </TableRowColumn> </TableRow> ) } export default Subtotal
JavaScript
0.001459
@@ -180,17 +180,16 @@ t sum = -+ salary + @@ -189,17 +189,16 @@ alary + -+ kiwisave @@ -201,17 +201,16 @@ saver + -+ deprecia @@ -216,17 +216,16 @@ ation + -+ phoneCon
15c1ddfe1896850e2f8af6a024c9966eec965cbe
update script
kptalks.js
kptalks.js
var img_source = 'http://unlimited.kptaipei.tw/images/kp.png', api_source = 'http://api.kptaipei.tw/v1/category/40?accessToken=kp53f568e77303e9.28212837', kp_height = 450, // 圖片高度 kp_width = Math.ceil(kp_height*30/29), kp_left_distance = '-130px', // 滑入後的 left kp_slide_speed = 100, // 滑入、滑出速度 default_text = '你好,我是柯文哲', posts = {}, kp_says, kp = '<div id="kp_come_container" style="width:'+kp_width+'; height:'+kp_height+'px; position:fixed; left:-'+kp_width+'px; bottom:0;"><img src="'+img_source+'" style="width:100%; height:100%;"><div id="kp_popup" style="padding: 20px; width: 300px; height:140px; position: absolute;left:'+(kp_width*0.8)+'px;top:'+(kp_height*0.28)+'px;-webkit-border-radius: 5px;-moz-border-radius: 5px;border-radius: 5px;-webkit-box-shadow: rgba(0,0,0,.4) 0px 1px 5px -1px;box-shadow: rgba(0,0,0,.4) 0px 1px 5px -1px; background-color:beige;display:none;"><div id="kp_says" style="text-align:center;font-size:18px;line-height:26px;">'+default_text+'</div><div style="width: 0px;height: 0px;border-top-width: 15px;border-top-style: solid;border-top-color: transparent;border-bottom-width: 15px;border-bottom-style: solid;border-bottom-color: transparent;border-right-width: 40px;border-right-style: solid;border-right-color: rgba(0,0,0,.4);position: absolute;left: -40px;top:30%;"></div><div style="width: 0px;height: 0px;border-top-width: 15px;border-top-style: solid;border-top-color: transparent;border-bottom-width: 15px;border-bottom-style: solid;border-bottom-color: transparent;border-right-width: 42px;border-right-style: solid;border-right-color: beige;position: absolute;left: -40px;top:29.8%;"></div></div></div><style>html,body{height:100%;}#kp_come_container #kp_popup{-webkit-box-sizing: initial;-moz-box-sizing: initial;box-sizing: initial;}#kp_come_container #kp_says {height:140px;overflow-y:auto;text-algin:center;-webkit-box-sizing: initial;-moz-box-sizing: initial;box-sizing: initial;}#kp_come_container #kp_says p,#kp_come_container #kp_says span {padding:0;margin:0;font-size:18px;line-height:26px;}#kp_come_container #kp_say_hi{padding:0;margin:0;font-size:18px;line-height:26px;padding-bottom:5px;display:block;}#kp_come_container #kp_says #kp_say_bighi{font-size:22px;font-weight:bold;line-height:32px;}</style>'; $('body').append(kp); $.get(api_source,function(results){ var i = 0; $.each(results.data,function(ind,item){ posts[i] = item; i++; }); var post = posts[Math.floor(Math.random()*(i-1))], post_title = post.title, post_content = post.content, post_url = post.url, kp_link = '<a href="'+post_url+'" target="_blank" style="color:brown;padding-top:10px;display:block;">了解更多柯文哲的政見</a>'; post_title = post_title.replace(/【柯p新政】/g,""); post_content = post_content .replace(/柯文哲/g,"我") .replace(/台北市長參選人/g,"") .replace(/我表示/g,"我認為") .replace(/我指出/g,"我認為"); post_content = post_content.split('</p>'); if(post_content[1] == undefined) kp_says = '<p id="kp_say_bighi">您好,我是柯文哲<br>我提出<br>「'+post_title.substring(2)+'」</p>'+kp_link; else kp_says = '<p id="kp_say_hi">您好,我是柯文哲</p>'+post_content[1]+'...'+kp_link+'</p>'; $('#kp_says').html(kp_says).promise().done(function(){ $('p').removeAttr("style"); $('span').removeAttr("style"); }); }); $(window).scroll(function(){ var scroll = $(window).scrollTop(); var window_h = $(window).height(); var page_h = $(document).height(); if((scroll+window_h) > (page_h*0.8)) { if($('#kp_come_container').css('left') == '-'+kp_width+'px') { $('#kp_come_container').animate({ left: kp_left_distance }, kp_slide_speed, function() { $('#kp_popup').show(); }); } } else { if($('#kp_come_container').css('left') == kp_left_distance) { $('#kp_popup').hide(); $('#kp_come_container').animate({ left: '-'+kp_width+'px' }, kp_slide_speed, function() { }); } } }); $('#kp_come_container img').click(function(){ $('#kp_popup').hide(); $('#kp_come_container').animate({ left: '-'+kp_width+'px' }, kp_slide_speed, function() { }); });
JavaScript
0.000001
@@ -3490,20 +3490,14 @@ ) %3E -( page_h -*0.8) ) %7B%0A
1b1b08c3d88984b3c8cef3fc40afb3425b0df5a6
Add the simplest of simple `alert` error handling
editorsnotes_app/js/views/save_item_mixin.js
editorsnotes_app/js/views/save_item_mixin.js
"use strict"; var saveRow = require('../templates/save_row.html')(); module.exports = { events: { 'click .save-item': '_handleSave' }, render: function () { this.$el.append(saveRow) }, toggleLoaders: function (state) { this.$('.save-item').prop('disabled', state); this.$('.loader').toggle(state); }, _handleSave: function () { if (this.saveItem) { this.saveItem(); } else { this.defaultSave(); } }, defaultSave: function () { var that = this; this.toggleLoaders(true); this.model.save() .always(this.toggleLoaders.bind(this, false)) .done(function () { window.location.href = that.model.url().replace('\/api\/', '/'); }); } }
JavaScript
0.007722
@@ -451,16 +451,102 @@ %7D%0A %7D,%0A + handleError: function (errorObj) %7B%0A alert(window.JSON.stringify(errorObj));%0A %7D,%0A defaul @@ -791,16 +791,121 @@ , '/');%0A + %7D)%0A .fail(function (jqXHR, textStatus, error) %7B%0A that.handleError(jqXHR.responseJSON);%0A %7D)
2b6c5419aa7befeb0a425ec54746864b8bba75a1
Fix scan time ordering for tests
custom/uth/_design/views/uth_lookup/map.js
custom/uth/_design/views/uth_lookup/map.js
function(doc) { if (doc.type === "child" && doc.scan_status !== 'scan_complete' && doc.domain === "uth-rhd") { emit([doc.domain, 'VH014466XK', doc.exam_number, doc.date], doc._id); } }
JavaScript
0.000001
@@ -173,11 +173,16 @@ doc. -dat +scan_tim e%5D,
a32cb24145cfaac60363f6fa6d7826609a410c6d
Add a gulp task to build only styles (css + type)
gulpfile.js
gulpfile.js
'use strict'; // Dependencies var gulp = require('gulp'); var del = require('del'); var gutil = require('gulp-util'); var zip = require('gulp-zip'); var sass = require('gulp-sass'); var minifyCss = require('gulp-minify-css'); var browserify = require('browserify'); var babelify = require('babelify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var header = require('gulp-header'); var sourcemaps = require('gulp-sourcemaps'); var runSequence = require('run-sequence'); var banner = { theme: '/* \n' + 'Theme Name: Katherine Anne \n' + 'Theme URI: \n' + 'Description: Katherine Anne Porter Correspondence Theme \n' + 'Author: Trevor Muñoz <[email protected]> \n' + 'Author URI: http://www.trevormunoz.com \n' + 'Template: twentyfifteen \n' + 'Version: 0.1.0 \n' + 'License: MIT \n' + 'License URI: http://opensource.org/licenses/MIT \n' + 'Text Domain: katherine-anne \n' + '*/ \n\n' }; gulp.task('clean', function(callback) { return del(['./dist', './katherine-anne.zip'], callback); }); gulp.task('build:css', function() { return gulp.src('src/scss/**/*.scss') .pipe(sass().on('error', gutil.log)) .pipe(minifyCss({compatibility: 'ie8'})) .pipe(header(banner.theme)) .pipe(gulp.dest('dist/')); }); gulp.task('typography', function() { return gulp.src(['src/js/typography.js']) .pipe(gulp.dest('dist/js')); }); gulp.task('build:es6', function() { return browserify({ entries: './src/js/main.js', debug: true }) .transform(babelify) .bundle() .pipe(source('kap.js')) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) .pipe(uglify()) .on('error', gutil.log) .pipe(sourcemaps.write('./')) .pipe(rename('kap.min.js')) .pipe(gulp.dest('dist/js')); }); gulp.task('zip', function() { return gulp.src(['dist/**/*', 'src/**/*.php', 'src/**/*.png']) .pipe(zip('katherine-anne.zip')) .pipe(gulp.dest('./')); }); gulp.task('default', function(callback) { return runSequence( 'clean', ['build:css', 'typography', 'build:es6'], 'zip', callback ); });
JavaScript
0
@@ -2099,32 +2099,167 @@ st('./'));%0A%7D);%0A%0A +gulp.task('styles-only', function(callback) %7B%0A return runSequence(%0A %5B'build:css', 'typography'%5D,%0A 'zip',%0A callback%0A );%0A%7D);%0A%0A gulp.task('defau
eca0e66e2363d1dd65ec15e906b41cac0bba47ac
Remove use of dynamic require to facilitate bundling (#960)
lib/index.js
lib/index.js
'use strict'; const Sharp = require('./constructor'); [ 'input', 'resize', 'composite', 'operation', 'colour', 'channel', 'output', 'utility' ].forEach(function (decorator) { require('./' + decorator)(Sharp); }); module.exports = Sharp;
JavaScript
0
@@ -52,171 +52,229 @@ ');%0A -%5B%0A 'input',%0A 'resize',%0A 'composite',%0A 'operation',%0A 'colour',%0A 'channel',%0A 'output',%0A 'utility'%0A%5D.forEach(function (decorator) %7B%0A require('./' + decorator +require('./input')(Sharp);%0Arequire('./resize')(Sharp);%0Arequire('./composite')(Sharp);%0Arequire('./operation')(Sharp);%0Arequire('./colour')(Sharp);%0Arequire('./channel')(Sharp);%0Arequire('./output')(Sharp);%0Arequire('./utility' )(Sh @@ -282,12 +282,8 @@ rp); -%0A%7D); %0A%0Amo
fb2600cd9e383a6cd82332bbf28f25915a65e9f7
fix prefs
src/gnome-shell/prefs.js
src/gnome-shell/prefs.js
/* * This file is part of GPaste. * * Copyright (c) 2010-2022, Marc-Antoine Perennou <[email protected]> */ imports.gi.versions.GPasteGtk = '4'; const ExtensionUtils = imports.misc.extensionUtils; const { GPasteGtk } = imports.gi; /** */ function init() { ExtensionUtils.initTranslations(); } /** * @returns {Gtk.Widget} - the prefs widget */ function buildPrefsWidget() { return GPasteGtk.preferences_widget.new (); }
JavaScript
0
@@ -410,17 +410,17 @@ asteGtk. -p +P referenc @@ -425,10 +425,9 @@ nces -_w +W idge
bb7a3a1d6b415d48fa71dd223677113d9466a27c
update to dont refind for new notifications if last check returns 403
files/public/we.notification.js
files/public/we.notification.js
/** * Notifications client side lib */ (function (we) { we.notification = { count: 0, countDisplay: null, link: null, init: function() { this.countDisplay = $('.main-menu-link-notification-count'); this.link = $('.main-menu-notification-link'); // only start if both elements is found if (this.countDisplay && this.link) this.getNewNotificationCount(); }, notificationsCountCheckDelay: 60000,// check every 1 min lastCheckData: null, registerNewCheck: function registerNewCheck() { setTimeout( this.getNewNotificationCount.bind(this), this.notificationsCountCheckDelay ); }, getNewNotificationCount: function getNewNotificationCount() { var self = this; $.ajax({ url: '/api/v1/current-user/notification-count' }).then(function (data){ self.count = Number(data.count); self.updateNotificationsDisplay(); // update last check time self.lastCheckData = new Date().toISOString(); }).fail(function (err) { console.error('we.notification.js:error in getNewNotificationCount:', err); }).always(function () { self.registerNewCheck(); }); }, updateNotificationsDisplay: function updateNotificationsDisplay() { if (this.count) { this.countDisplay.text(this.count); this.link.addClass('have-notifications'); } else { this.countDisplay.text(''); this.link.removeClass('have-notifications'); } } }; we.notification.init(); })(window.we);
JavaScript
0
@@ -120,16 +120,75 @@ k: null, +%0A notificationsCountCheckDelay: 60000,// check every 1 min %0A%0A init @@ -444,67 +444,9 @@ %7D,%0A%0A - notificationsCountCheckDelay: 60000,// check every 1 min %0A + la @@ -807,14 +807,43 @@ ion +onSuccessGetNewNotifications (data) + %7B%0A @@ -1010,37 +1010,187 @@ ();%0A - %7D).fail(function (err) %7B%0A +%0A self.registerNewCheck();%0A %7D).fail(function afterFailtInGetNewNotifications(err) %7B%0A // skip new checks if user is unAuthenticated%0A if (err.status != '403') %7B%0A @@ -1273,34 +1273,8 @@ ;%0A - %7D).always(function () %7B%0A @@ -1296,24 +1296,32 @@ NewCheck();%0A + %7D%0A %7D);%0A %7D,
356af3ffe0943858a9b828ba25fc21374c66aba9
check version
lib/check-version.js
lib/check-version.js
var axios = require('axios') var semver = require('semver') var chalk = require('chalk') var packageConfig = require('../package.json') module.exports = function (done) { axios .get('https://registry.npmjs.org/easy-mock-cli', { timeout: 1000 }) .then((res) => { if (res.status === 200) { var latestVersion = res.data['dist-tags'].latest var localVersion = packageConfig.version if (semver.lt(localVersion, latestVersion)) { console.log(chalk.yellow(' easy-mock-cli 有新版本更新建议升级.')) console.log() console.log(' 最新版本: ' + chalk.green(latestVersion)) console.log(' 本地版本: ' + chalk.red(localVersion)) console.log() } } done() }) }
JavaScript
0
@@ -247,9 +247,9 @@ ut: -1 +3 000%0A @@ -732,22 +732,26 @@ - done()%0A %7D +%7D)%0A .catch(done )%0A%7D%0A
788a746ea3a906c1d65e99b536e12307e1868ef3
Fix log level bug.
graphql/utils/logger.js
graphql/utils/logger.js
import config from '../config' const logLevels = {} logLevels.LOG = 'log' logLevels.DEBUG = 'debug' logLevels.INFO = 'info' logLevels.WARN = 'warn' logLevels.ERROR = 'error' logLevels.FATAL = 'fatal' const logLevelsOrder = [ logLevels.DEBUG, logLevels.LOG, logLevels.INFO, logLevels.WARN, logLevels.ERROR, logLevels.FATAL ] const LOG_LEVEL = ( logLevels[config.LOG_LEVEL] ? logLevels[config.LOG_LEVEL] : 'debug' ) // TODO: set up logging via Sentry. const logger = {} logger.log = (msg) => { log(msg, logLevels.LOG) } logger.debug = (msg) => { log(msg, logLevels.DEBUG) } logger.info = (msg) => { log(msg, logLevels.INFO) } logger.warn = (msg) => { log(msg, logLevels.WARN) } logger.error = (msg) => { log(msg, logLevels.ERROR) } logger.fatal = (msg) => { log(msg, logLevels.FATAL) } /* * Log the error, adding the error ID to the error message. * @param {object} err - The error. * @param {string} errId - The error ID * @return {null} */ export const logErrorWithId = (err, errId) => { err.message = `${err.message}: Error ID ${errId}` logger.error(err) } export const shouldLog = (logLevel, globalLogLevel) => { return ( logLevelsOrder.indexOf(logLevel) >= logLevelsOrder.indexOf(globalLogLevel) ) } const log = (msg, logLevel) => { if (!shouldLog(logLevel, LOG_LEVEL)) { return } console.log(msg) } export default logger
JavaScript
0
@@ -336,104 +336,8 @@ %0A%5D%0A%0A -const LOG_LEVEL = (%0A logLevels%5Bconfig.LOG_LEVEL%5D%0A ? logLevels%5Bconfig.LOG_LEVEL%5D%0A : 'debug'%0A)%0A %0A// @@ -1224,16 +1224,23 @@ gLevel, +config. LOG_LEVE
3e49354944cac9e5f4b87fa35f21659f7bea99f9
Fix typos
dist/notification.js
dist/notification.js
/* * This file is part of the Browser Notification package. * * (c) Dimgba Kalu <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ // notification body in an array var articles = [ ["ProJaro is recruiting","http://projaro.com"], ["Visit ProJaro's website for update","http://projaro.com"], ["ProJaro builds people, technology and products","http://projaro.com"] ]; // set time out for notification setTimeout(function(){ // randomly select number from 1 to 3 var randomNumber = Math.floor((Math.random() * 3) + 1); // get the title from the array articles var title = articles[randomNumber][0]; /* I used a fixed description. YOu can as well add it to the array add pass it like this var desc = articles[randomNumber][1]; */ var description = 'ProJaro is a talent accelartaion startup.'; // get the url of teh article var url = articles[randomNumber][1]; // call browser notification browserNotification(title,description,url); }, 5000); // add event listener document.addEventListener('DOMContentLoaded', function () { // check if permission is granted to show notification on desktop if (Notification.permission !== "granted") { // show notification Notification.requestPermission(); } document.querySelector("#desktopNotification").addEventListener("click", function(e) { // randomly select number from 1 to 3 var randomNumber = Math.floor((Math.random() * 3) + 1); // get the title from the array articles var title = articles[randomNumber][0]; /* I used a fixed description. YOu can as well add it to the array add pass it like this var desc = articles[randomNumber][1]; */ var description = 'ProJaro is a talent acceleration startup'; // get the url of teh article var url = articles[randomNumber][1]; // call browser notification browserNotification(title,description,url); // you all know who this guy is! e.preventDefault(); }); }); /* function to call the notification * checks if notification is avaliable on your browser * checks if permission is granted to show the notification * displays notification * removes notification */ function browserNotification(title,desc,url) { // check if notification is vaaliable if (!Notification) { // if not displays message on console console.log('Desktop notifications is not available in your browser..'); // bye return; } // if notification avaliable, check if user have granted permission if (Notification.permission !== "granted") { // if permission is not granted, then request for one Notification.requestPermission(); } else { // go ahead to show notification var notification = new Notification(title, { icon:'https://scontent-lhr3-1.xx.fbcdn.net/v/t1.0-9/13083284_490780627779286_4039618550099495940_n.png?oh=2e22e6270e67f2513af9da5eb5a4aaf1&oe=57F104B4', body: desc, }); // Remove the notification from Notification Center when clicked. notification.onclick = function () { window.open(url); }; // Callback function when the notification is closed. notification.onclose = function () { console.log('Notification closed'); }; } }
JavaScript
0.999999
@@ -727,33 +727,33 @@ d description. Y -O +o u can as well ad @@ -929,32 +929,33 @@ et the url of te +c h article%0A%09var u @@ -1638,17 +1638,17 @@ ption. Y -O +o u can as @@ -2103,26 +2103,26 @@ ation is ava -l i +l able on your @@ -2323,13 +2323,13 @@ is -vaali +avail able @@ -2513,18 +2513,18 @@ tion ava -l i +l able, ch @@ -3252,9 +3252,10 @@ %09%7D;%0A%0A%09%7D%0A - %7D +%0A
f88cde3eafc2e14ea0277366dbd15e5f85644497
Add docs
lib/index.js
lib/index.js
var fs = require('fs'); function Chidori(jsonFile) { this.jsonFile = jsonFile; this.object = {}; if (fs.existsSync(this.jsonFile)) { this.object = JSON.parse(fs.readFileSync(this.jsonFile, 'utf8')); } else { fs.writeFileSync(this.jsonFile, JSON.stringify(this.object)); } return Database.bind(this); } function Database(collection) { this.collection = collection || 'default'; return new Methods(this); } function Methods(context) { this.jsonFile = context.jsonFile; this.object = context.object; this.collection = context.collection; } Methods.prototype.getAll = function() { if (this.object[this.collection]) { return this.object[this.collection]; } this.object = JSON.parse(fs.readFileSync(this.jsonFile, 'utf8')); return this.object[this.collection]; }; Methods.prototype.get = function(key) { if (this.object[this.collection] && this.object[this.collection].hasOwnProperty(key)) { return this.object[this.collection][key]; } this.object = JSON.parse(fs.readFileSync(this.jsonFile, 'utf8')); if (!this.object[this.collection]) this.object[this.collection] = {}; return this.object[this.collection][key]; }; Methods.prototype.set = function(key, value) { this.object = JSON.parse(fs.readFileSync(this.jsonFile, 'utf8')); if (!this.object[this.collection]) this.object[this.collection] = {}; this.object[this.collection][key] = value; fs.writeFileSync(this.jsonFile, JSON.stringify(this.object)); return this.object[this.collection][key]; }; Methods.prototype.remove = function(key) { if (this.object[this.collection] && this.object[this.collection][key]) { delete this.object[this.collection][key]; return; } this.object = JSON.parse(fs.readFileSync(this.jsonFile, 'utf8')); delete this.object[this.collection][key]; fs.writeFileSync(this.jsonFile, JSON.stringify(this.object)); }; module.exports = Chidori;
JavaScript
0.000001
@@ -18,16 +18,85 @@ 'fs');%0A%0A +/**%0A * Create a Chidori Database.%0A *%0A * @param %7BString%7D jsonFile%0A */%0A function @@ -382,32 +382,128 @@ .bind(this);%0A%7D%0A%0A +/**%0A * Query for the collection and create methods for it.%0A *%0A * @param %7BString%7D collection%0A */%0A function Databas @@ -595,16 +595,113 @@ is);%0A%7D%0A%0A +/**%0A * Helper functions to query the database.%0A *%0A * @constructor%0A * @param %7BString%7D context%0A */%0A function @@ -831,16 +831,53 @@ ion;%0A%7D%0A%0A +/**%0A * Get the whole collection.%0A */%0A Methods. @@ -1098,24 +1098,109 @@ ction%5D;%0A%7D;%0A%0A +/**%0A * Get a key from the collection.%0A * %0A * @param %7BString%7D key%0A * @returns %7B*%7D%0A */%0A Methods.prot @@ -1548,32 +1548,145 @@ tion%5D%5Bkey%5D;%0A%7D;%0A%0A +/**%0A * Set a key to a value in the collection.%0A *%0A * @param %7BString%7D key%0A * @param %7B*%7D value%0A * @returns %7B*%7D%0A */%0A Methods.prototyp @@ -2013,16 +2013,85 @@ y%5D;%0A%7D;%0A%0A +/**%0A * Remove a key in the collection.%0A *%0A * @param %7BString%7D key%0A */%0A Methods.
fcbc38f1fba208d7de8dd9a67e220949dbacf14c
Remove done TODO.
dispatcher.js
dispatcher.js
var cadence = require('cadence') var dispatch = require('dispatch') var interrupt = require('interrupt').createInterrupter('bigeasy.inlet') var Operation = require('operation') var Reactor = require('reactor') var slice = [].slice function Dispatcher (options) { options.object || (options = { object: options }) this._dispatch = {} this._service = options.object this._logger = options.logger || function () {} this._reactor = new Reactor({ operation: { object: this, method: '_respond' }, Date: options.Date, workers: options.workers || 24, timeout: options.timeout }) this.turnstile = this._reactor.turnstile } Dispatcher.prototype.dispatch = function (pattern, method) { this._dispatch[pattern] = handle(this._reactor, new Operation({ object: this._service, method: method })) } Dispatcher.prototype.createDispatcher = function () { return dispatch(this._dispatch) } // TODO Create `inlet.wrapped`. Dispatcher.prototype.createWrappedDispatcher = function () { return require('connect')() .use(require('express-auth-parser')) .use(require('body-parser').json()) .use(this.createDispatcher()) } Dispatcher.prototype._timeout = cadence(function (async, request) { request.raise(503, 'Service Not Available') }) Dispatcher.prototype._respond = cadence(function (async, status, work) { var next = work.next var entry = { turnstile: this.turnstile.health, statusCode: 200, request: { method: work.request.method, header: work.request.headers, url: work.request.url } } work.request.raise = raise if (status.timedout) { work.operation = new Operation({ object: this, method: '_timeout' }) } var block = async([function () { async(function () { async([function () { work.operation.apply([ work.request ].concat(work.vargs, async())) }, function (error) { return interrupt.rescue('bigeasy.inlet.http', function (error) { var statusCode = entry.statusCode = error.statusCode var description = entry.description = error.description var headers = error.headers var body = new Buffer(JSON.stringify({ description: description })) headers['content-length'] = body.length headers['content-type'] = 'application/json' work.response.writeHead(statusCode, description, headers) work.response.end(body) return [ block.break ] })(error) }]) }, function (result, headers) { headers || (headers = {}) var body switch (typeof result) { case 'function': // todo: delta on response end. result(work.response) return case 'string': body = new Buffer(result) break default: headers['content-type'] = 'application/json' body = new Buffer(JSON.stringify(result)) break } headers['content-length'] = body.length work.response.writeHead(200, 'OK', headers) work.response.end(body) }) }, function (error) { entry.statusCode = 0 entry.stack = error.stack next(error) }], function () { this._logger('info', 'request', entry) return [ block.break ] })() }) module.exports = Dispatcher function handle (reactor, operation) { return function (request, response, next) { var vargs = slice.call(arguments, 3) reactor.push({ operation: operation, request: request, response: response, vargs: vargs, next: next }) } } function raise (statusCode, description, headers) { throw interrupt(new Error('http'), { statusCode: statusCode, headers: headers || {}, description: description || 'Unknown' }) } Dispatcher.resend = function (statusCode, headers, body) { return function (response) { var h = { 'content-type': headers['content-type'], 'content-length': body.length } response.writeHeader(statusCode, h) response.end(body) } }
JavaScript
0
@@ -940,40 +940,8 @@ %0A%7D%0A%0A -// TODO Create %60inlet.wrapped%60.%0A Disp
57da5124dbc8b58684b66f6a5498e3715da8aded
Remove ErrorComponent.
assets/js/components/dashboard/dashboard-app.js
assets/js/components/dashboard/dashboard-app.js
/** * DashboardApp component. * * Site Kit by Google, Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import Header from 'GoogleComponents/header'; import DateRangeSelector from 'GoogleComponents/date-range-selector'; import PageHeader from 'GoogleComponents/page-header'; import 'GoogleComponents/publisher-wins'; /** * WordPress dependencies */ import { Component } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ import DashboardMain from './dashboard-main'; import DashboardNotifications from './dashboard-notifications'; import ErrorHandler from 'GoogleComponents/ErrorHandler'; import ErrorComponent from 'GoogleComponents/ErrorHandler/ErrorComponent'; class DashboardApp extends Component { render() { return ( <ErrorHandler> <ErrorComponent /> <Header /> <DashboardNotifications /> <div className="googlesitekit-module-page"> <div className="googlesitekit-dashboard"> <div className="mdc-layout-grid"> <div className="mdc-layout-grid__inner"> <div className=" mdc-layout-grid__cell mdc-layout-grid__cell--span-10-desktop mdc-layout-grid__cell--span-6-tablet mdc-layout-grid__cell--span-2-phone "> <PageHeader className=" googlesitekit-heading-2 googlesitekit-dashboard__heading " title={ __( 'Site Overview', 'google-site-kit' ) } /> </div> <div className=" mdc-layout-grid__cell mdc-layout-grid__cell--span-2-desktop mdc-layout-grid__cell--span-2-tablet mdc-layout-grid__cell--span-2-phone mdc-layout-grid__cell--align-middle mdc-layout-grid__cell--align-right "> <DateRangeSelector /> </div> <DashboardMain /> </div> </div> </div> </div> </ErrorHandler> ); } } export default DashboardApp;
JavaScript
0
@@ -1212,83 +1212,8 @@ er'; -%0Aimport ErrorComponent from 'GoogleComponents/ErrorHandler/ErrorComponent'; %0A%0Acl @@ -1294,31 +1294,8 @@ er%3E%0A -%09%09%09%09%3CErrorComponent /%3E%0A %09%09%09%09
dad1e9db33029661441c191fabd8efa447aced4f
Remove comments
c/series_switch.js
c/series_switch.js
/** * Series switch box. * @constructor */ function series_switch(options){ this.on = false; this.dom_obj = {}; this.series_box = {}; this.series = []; this.cur_idx = 0; this.callback = function(){}; this.parent = {}; if (options && options.hasOwnProperty('parent')){ this.parent = options.parent; } this.init(); } series_switch.prototype.init = function(){ _debug('series_switch.init'); this.dom_obj = create_block_element('series_switch'); this.series_box = create_block_element('series_switch_input', this.dom_obj); //var series_switch_title = create_block_element('series_switch_title', this.dom_obj); //series_switch_title.innerHTML = word['player_series_uc']; this.continuously_box = create_block_element('continuously', this.dom_obj); this.continuously_box.innerHTML = word['series_by_one_play']; this.hide(); } series_switch.prototype.show = function(series, cur_series){ _debug('series_switch.show', series, cur_series); var cur_series = cur_series || "1"; this.series = series || []; if (this.series.indexOf(cur_series) < 0){ cur_series = this.series[0]; } this.cur_idx = this.series.indexOf(cur_series); _debug('cur_series', cur_series); _debug('this.cur_idx', this.cur_idx); this.update_series_box(); this.dom_obj.show(); this.on = true; if (this.parent && this.parent.on){ this.parent.on = false; } } series_switch.prototype.hide = function(){ _debug('series_switch.hide'); this.series = []; this.cur_idx = 0; this.callback = function(){}; this.dom_obj.hide(); this.on = false; if (this.parent){ this.parent.on = true; } } series_switch.prototype.set = function(){ _debug('series_switch.set'); this.callback(this.series[this.cur_idx]); this.hide(); } series_switch.prototype.shift = function(dir){ _debug('series_switch.shift', dir); if (dir>0){ if (this.cur_idx < this.series.length - 1){ this.cur_idx++; }else{ this.cur_idx = 0; } }else{ if (this.cur_idx > 0){ this.cur_idx--; }else{ this.cur_idx = this.series.length - 1; } } this.update_series_box(); } series_switch.prototype.vshift = function(dir){ _debug('series_switch.vshift', dir); if (stb && stb.player && stb.player.hasOwnProperty('play_continuously')){ if (stb.player.play_continuously === true){ stb.player.play_continuously = false; this.continuously_box.innerHTML = word['series_by_one_play']; }else{ stb.player.play_continuously = true; this.continuously_box.innerHTML = word['series_continuously_play']; } } } series_switch.prototype.update_series_box = function(){ _debug('series_switch.update_series_box'); this.series_box.innerHTML = this.series[this.cur_idx] + ' / ' + this.series.length; } series_switch.prototype.bind = function(){ _debug('series_switch.bind'); this.shift.bind(key.RIGHT, this, 1); this.shift.bind(key.LEFT, this, -1); this.vshift.bind(key.DOWN, this, 1); this.vshift.bind(key.UP, this, -1); this.set.bind(key.OK, this); this.hide.bind(key.EXIT, this); } loader.next();
JavaScript
0
@@ -610,168 +610,13 @@ j);%0A - //var series_switch_title = create_block_element('series_switch_title', this.dom_obj);%0A //series_switch_title.innerHTML = word%5B'player_series_uc'%5D;%0A %0A + @@ -773,32 +773,33 @@ this.hide();%0A%7D +; %0A%0Aseries_switch. @@ -912,12 +912,8 @@ -var cur_ @@ -1365,32 +1365,33 @@ = false;%0A %7D%0A%7D +; %0A%0Aseries_switch. @@ -1647,32 +1647,33 @@ = true;%0A %7D%0A%7D +; %0A%0Aseries_switch. @@ -1803,24 +1803,25 @@ is.hide();%0A%7D +; %0A%0Aseries_swi @@ -2237,24 +2237,25 @@ ies_box();%0A%7D +; %0A%0Aseries_swi @@ -2758,16 +2758,17 @@ %0A %7D%0A%7D +; %0A%0Aseries @@ -2958,16 +2958,17 @@ ength;%0A%7D +; %0A%0Aseries @@ -3290,17 +3290,18 @@ this);%0A - %7D +; %0A%0Aloader
3b8989f75b270b6e1ad596e3a8c7be8786301c85
save image from api.meetup.com
src/graphql/mutations.js
src/graphql/mutations.js
import { graphql, compose } from 'react-apollo'; import gql from 'graphql-tag'; import { pick, isArray } from 'lodash'; const createOrderQuery = gql` mutation createOrder($order: OrderInputType!) { createOrder(order: $order) { id, createdAt, createdByUser { id, }, fromCollective { id, slug } collective { id, slug } } } `; const createMemberQuery = gql` mutation createMember($member: CollectiveAttributesInputType!, $collective: CollectiveAttributesInputType!, $role: String!) { createMember(member: $member, collective: $collective, role: $role) { id createdAt member { id name image slug twitterHandle description } role } } `; const removeMemberQuery = gql` mutation removeMember($member: CollectiveAttributesInputType!, $collective: CollectiveAttributesInputType!, $role: String!) { removeMember(member: $member, collective: $collective, role: $role) { id } } `; const createCollectiveQuery = gql` mutation createCollective($collective: CollectiveInputType!) { createCollective(collective: $collective) { id slug } } `; const editCollectiveQuery = gql` mutation editCollective($collective: CollectiveInputType!) { editCollective(collective: $collective) { id type slug name image backgroundImage description longDescription website twitterHandle members { id role description } } } `; const editTiersQuery = gql` mutation editTiers($collectiveSlug: String!, $tiers: [TierInputType]!) { editTiers(collectiveSlug: $collectiveSlug, tiers: $tiers) { id, type, name, amount } } `; const deleteCollectiveQuery = gql` mutation deleteCollective($id: Int!) { deleteCollective(id: $id) { id } } `; export const addCreateOrderMutation = graphql(createOrderQuery, { props: ( { mutate }) => ({ createOrder: (order) => mutate({ variables: { order } }) }) }); export const addCreateMemberMutation = graphql(createMemberQuery, { props: ( { mutate }) => ({ createMember: (member, collective, role) => mutate({ variables: { member, collective, role } }) }) }); export const addRemoveMemberMutation = graphql(removeMemberQuery, { props: ( { mutate }) => ({ removeMember: (member, collective, role) => mutate({ variables: { member, collective, role } }) }) }); export const addEventMutations = compose(addCreateOrderMutation, addCreateMemberMutation, addRemoveMemberMutation); export const addCreateCollectiveMutation = graphql(createCollectiveQuery, { props: ( { mutate }) => ({ createCollective: async (collective) => { const CollectiveInputType = pick(collective, [ 'slug', 'type', 'name', 'description', 'longDescription', 'location', 'twitterHandle', 'website', 'tags', 'startsAt', 'endsAt', 'timezone', 'maxAmount', 'currency', 'quantity', 'HostCollectiveId', 'ParentCollectiveId', 'data' ]); CollectiveInputType.tiers = (collective.tiers || []).map(tier => pick(tier, ['type', 'name', 'description', 'amount', 'maxQuantity', 'maxQuantityPerUser'])); CollectiveInputType.location = pick(collective.location, ['name','address','lat','long']); return await mutate({ variables: { collective: CollectiveInputType } }) } }) }); export const addEditCollectiveMutation = graphql(editCollectiveQuery, { props: ( { mutate }) => ({ editCollective: async (collective) => { const CollectiveInputType = pick(collective, [ 'id', 'type', 'slug', 'name', 'company', 'description', 'longDescription', 'website', 'twitterHandle', 'location', 'startsAt', 'endsAt', 'timezone', 'maxAmount', 'currency', 'quantity', 'ParentCollectiveId', 'image', 'backgroundImage' ]); if (collective.paymentMethods && collective.paymentMethods.length > 0) { CollectiveInputType.paymentMethods = collective.paymentMethods.map(pm => pick(pm, ['id', 'name', 'token', 'data', 'monthlyLimitPerMember', 'currency'])); } else { CollectiveInputType.paymentMethods = []; // force removing existing payment methods } if (isArray(collective.tiers)) { CollectiveInputType.tiers = collective.tiers.map(tier => pick(tier, ['id', 'type', 'name', 'description', 'amount', 'interval', 'maxQuantity', 'maxQuantityPerUser', 'presets'])); } if (isArray(collective.members)) { CollectiveInputType.members = collective.members.map(member => { return { id: member.id, role: member.role, description: member.description, member: { name: member.member.name, email: member.member.email } } }); } CollectiveInputType.location = pick(collective.location, ['name','address','lat','long']); return await mutate({ variables: { collective: CollectiveInputType } }) } }) }); export const addEditTiersMutation = graphql(editTiersQuery, { props: ( { mutate }) => ({ editTiers: async (collectiveSlug, tiers) => { tiers = tiers.map(tier => pick(tier, ['id', 'type', 'name', 'description', 'amount', 'maxQuantity', 'maxQuantityPerUser', 'interval', 'endsAt'])); return await mutate({ variables: { collectiveSlug, tiers } }) } }) }); export const addDeleteCollectiveMutation = graphql(deleteCollectiveQuery, { props: ( { mutate }) => ({ deleteCollective: async (id) => { return await mutate({ variables: { id } }) } }) });
JavaScript
0
@@ -2901,32 +2901,49 @@ 'name',%0A + 'image',%0A 'descrip
7ee32efb70c904ca040eb56d52ad5bcc031e043a
add path for get subscribe list
notification_server/server.js
notification_server/server.js
const express = require('express') const bodyParser = require('body-parser') const mongoose = require('mongoose') const webpush = require('web-push') const cors = require('cors') const config = require('config') mongoose.connect(config.get('DB_URL')) const Schema = mongoose.Schema const subSchema = Schema({ userId: String, storeId: String, endpoint: String, publicKey: String, auth: String, }) const Subscribe = mongoose.model('Subscribe', subSchema) const app = express() app.use(bodyParser.json()) app.use(cors()) app.use(bodyParser.urlencoded({ extended: true })) const vapidKeys = { publicKey: config.get('PUBLIC_KEY'), privateKey: config.get('SECRET_KEY') } webpush.setVapidDetails( 'localhost:8000', vapidKeys.publicKey, vapidKeys.privateKey ) app.get('/status', (req, res) => { res.send('Server is running') }) app.post('/subscribe', (req, res) => { const newSubscriber = { endpoint: req.body.endpoint, keys: { p256dh: req.body.publicKey, auth: req.body.auth } } const { storeId, userId } = req.body Subscribe.update( { userId, storeId }, { storeId, userId, endpoint: req.body.endpoint, publicKey: req.body.publicKey, auth: req.body.auth }, { upsert: true } ) .then(() => { res.send({ success: true, message: 'add success' }) }) .catch(e => { res.send({ success: false, message: 'something worng' }) }) }) const PORT = process.env.PORT || 8080; app.listen(PORT, function () { console.log(`push_server listening on port ${PORT}!`) })
JavaScript
0
@@ -841,16 +841,146 @@ g')%0A%7D)%0A%0A +app.get('/subscribe', (req, res) =%3E %7B%0A Subscribe.find(%7B%7D)%0A .then(data =%3E res.send(data))%0A .catch(error =%3E res.send(error))%0A%7D)%0A%0A app.post
f6bb6f7c21ba84fe8bb0978351508397d40b5c90
Translate "User's Documents" heading above search
public/javascripts/model/accounts.js
public/javascripts/model/accounts.js
// Account Model dc.model.Account = Backbone.Model.extend({ DISABLED : 0, ADMINISTRATOR : 1, CONTRIBUTOR : 2, REVIEWER : 3, FREELANCER : 4, ROLE_NAMES : ['disabled', 'administrator', 'contributor', 'reviewer', 'freelancer'], // NB: Indexed by role number. GRAVATAR_BASE : location.protocol + (location.protocol == 'https:' ? '//secure.' : '//www.') + 'gravatar.com/avatar/', DEFAULT_AVATAR : location.protocol + '//' + location.host + '/images/embed/icons/user_blue_32.png', defaults : { first_name : '', last_name : '', email : '', role : 2 }, initialize: function(options) { this.memberships = new Backbone.Collection(); if (this.get('memberships')) { this.memberships.reset(this.get('memberships')); } }, current_organization: function(){ return this.organization(); }, organization : function() { var default_membership = this.memberships.find(function(m){ return m.get('default'); }); return Organizations.get(default_membership.get('organization_id')); }, organization_ids: function() { return this.memberships.pluck('organization_id'); }, organizations: function() { var ids = this.organization_ids(); return new dc.model.OrganizationSet(Organizations.filter(function(org){ return _.contains(ids, org.get('id'));})); }, openDocuments : function(options) { options || (options = {}); var suffix = options.published ? ' filter: published' : ''; dc.app.searcher.search('account: ' + this.get('slug') + suffix); }, openOrganizationDocuments : function() { dc.app.searcher.search('group: ' + dc.account.organization().get('slug')); }, allowedToEdit: function(model) { return this.ownsOrOrganization(model) || this.collaborates(model); }, ownsOrOrganization: function(model) { return (model.get('account_id') == this.id) || (model.get('organization_id') == this.get('organization_id') && (this.isAdmin() || this.isContributor()) && _.contains([ dc.access.PUBLIC, dc.access.EXCLUSIVE, dc.access.ORGANIZATION, 'public', 'exclusive', 'organization' ], model.get('access'))); }, collaborates: function(model) { var docId = model.get('document_id') || model.id; var projectIds = model.get('project_ids'); for (var i = 0, l = Projects.length; i < l; i++) { var project = Projects.models[i]; if (_.contains(projectIds, project.get('id')) && !project.get('hidden')) { for (var j = 0, k = project.collaborators.length; j < k; j++) { var collab = project.collaborators.models[j]; if (collab.ownsOrOrganization(model)) return true; } } } return false; }, fullName : function(nonbreaking) { var name = this.get('first_name') + ' ' + this.get('last_name'); return nonbreaking ? name.replace(/\s/g, '&nbsp;') : name; }, documentsTitle : function() { return dc.inflector.possessivize(this.fullName()) + ' Documents'; }, isAdmin : function() { return this.attributes.role == this.ADMINISTRATOR; }, isContributor : function() { return this.attributes.role == this.CONTRIBUTOR; }, isReviewer : function() { return this.attributes.role == this.REVIEWER; }, isReal : function() { var role = this.attributes.role; return role == this.ADMINISTRATOR || role == this.CONTRIBUTOR || role == this.FREELANCER; }, isPending : function() { return !!this.get('pending'); }, searchUrl : function() { return "/#search/" + encodeURIComponent("account: " + this.get('slug')); }, gravatarUrl : function(size) { var hash = this.get('hashed_email'); var fallback = encodeURIComponent(this.DEFAULT_AVATAR); return this.GRAVATAR_BASE + hash + '.jpg?s=' + size + '&d=' + fallback; }, resendWelcomeEmail: function(options) { var url = '/accounts/' + this.id + '/resend_welcome'; $.ajax(_.extend(options || {}, {type : 'POST', dataType : 'json', url : url})); } }); // mixin the languages we support _.defaults( dc.model.Account.prototype, ModelWithLanguageMixin ); // Account Set dc.model.AccountSet = Backbone.Collection.extend({ model : dc.model.Account, url : '/accounts', comparator : function(account) { return (account.get('last_name') || '').toLowerCase() + ' ' + (account.get('first_name') || '').toLowerCase(); }, getBySlug : function(slug) { return this.detect(function(account) { return account.get('slug') === slug; }); }, getByEmail: function(email) { return this.detect(function(account){ return account.get('email') === email; }); }, getValidByEmail: function(email) { return this.detect(function(account){ return !account.invalid && account.get('email') === email; }); }, // Fetch the account of the logged-in journalist. current : function() { if (!dc.account) return null; return this.get(dc.account.id); }, // All accounts other than yours. others : function() { return this.filter(function(account) { return account.id !== dc.account.id; }); }, // If the contributor has logged-out of the workspace in a different tab, // force the logout here. forceLogout : function() { dc.ui.Dialog.alert('You are no longer logged in to DocumentCloud.', {onClose : function() { window.location = '/logout'; }}); } }); window.Accounts = new dc.model.AccountSet();
JavaScript
0.999996
@@ -3059,17 +3059,26 @@ ()) + ' -D +' + _.t('d ocuments @@ -3078,16 +3078,17 @@ cuments' +) ;%0A %7D,%0A%0A
995d021adcf0d19e4c934e2363c15c1c98e24123
add brackets to separate logic
src/javascript/binary/common_functions/currency.js
src/javascript/binary/common_functions/currency.js
const jpClient = require('./country_base').jpClient; const getLanguage = require('../base/language').get; const getPropertyValue = require('../base/utility').getPropertyValue; let currencies_config = ''; const formatMoney = (currency_value, amount, exclude_currency) => { const is_crypto = isCryptocurrency(currency_value); const is_jp = jpClient(); const decimal_places = getDecimalPlaces(currency_value); let money; if (amount) amount = String(amount).replace(/,/g, ''); if (typeof Intl !== 'undefined' && currency_value && !is_crypto && typeof amount !== 'undefined') { const options = exclude_currency ? { minimumFractionDigits: decimal_places, maximumFractionDigits: decimal_places } : { style: 'currency', currency: currency_value }; const language = getLanguage().toLowerCase(); money = new Intl.NumberFormat(language.replace('_', '-'), options).format(amount); } else { let updated_amount = amount, sign = ''; if (is_jp) { updated_amount = parseInt(amount); if (Number(updated_amount) < 0) { sign = '-'; } } updated_amount = addComma(updated_amount, decimal_places); if (exclude_currency) { money = updated_amount; } else { const symbol = map_currency[currency_value]; money = symbol ? sign + symbol + updated_amount : `${currency_value} ${updated_amount}`; } } return money; }; const addComma = (num, decimal_points, is_crypto) => { let number = String(num || 0).replace(/,/g, ''); if (typeof decimal_points !== 'undefined') { number = (+number).toFixed(decimal_points); } if (is_crypto) { number = parseFloat(+number); } return number.toString().replace(/(^|[^\w.])(\d{4,})/g, ($0, $1, $2) => ( $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, '$&,') )); }; const getDecimalPlaces = currency => ( getPropertyValue(currencies_config, [currency, 'fractional_digits']) || isCryptocurrency(currency) ? 8 : (jpClient() ? 0 : 2) ); // Taken with modifications from: // https://github.com/bengourley/currency-symbol-map/blob/master/map.js // When we need to handle more currencies please look there. const map_currency = { USD: '$', GBP: '£', AUD: 'A$', EUR: '€', JPY: '¥', BTC: '₿', ETH: 'Ξ', LTC: 'Ł', }; const setCurrencies = (website_status) => { currencies_config = website_status.currencies_config; }; const isCryptocurrency = currency => /crypto/i.test(getPropertyValue(currencies_config, [currency, 'type'])); module.exports = { formatMoney : formatMoney, formatCurrency : currency => map_currency[currency] || '', isCryptocurrency: isCryptocurrency, addComma : addComma, getDecimalPlaces: getDecimalPlaces, setCurrencies : setCurrencies, getCurrencies : () => currencies_config, };
JavaScript
0.000002
@@ -2057,16 +2057,17 @@ s'%5D) %7C%7C +( isCrypto @@ -2111,16 +2111,17 @@ ? 0 : 2) +) %0A);%0A%0A//
71b5b53c81b668485813c1b7feb4230557de13ef
Use int instead of string for parseInt radix.
content_scripts/dom.js
content_scripts/dom.js
window.DOM = { isSubmittable: function(element) { if (!element) { return false; } if (element.localName !== 'input') return false; if (element.hasAttribute('submit')) return true; while (element = element.parentElement) { if (element.localName === 'form') return true; } return false; }, isEditable: function(element) { if (!element) { return false; } if (element.localName === 'textarea' || element.hasAttribute('contenteditable')) return true; if (element.localName !== 'input') return false; var type = element.getAttribute('type'); switch (type) { case 'button': case 'checkbox': case 'color': case 'file': case 'hidden': case 'image': case 'radio': case 'reset': case 'submit': case 'week': return false; } return true; }, isTextElement: function(element) { if (!element) { return false; } if (element.localName === 'input' || element.localName === 'textarea') { return true; } while (element) { if (element.isContentEditable) { return true; } element = element.parentElement; } return false; }, nodeSelectorMatch: function(node, selector) { if (selector.indexOf('[') === -1 && selector.indexOf(' ') === -1) { switch (selector.charAt(0)) { case '.': return node.className === selector.slice(1).split('.').join(' '); case '#': return node.id === selector.slice(1); } } var fragment = document.createDocumentFragment(); fragment.appendChild(node.cloneNode(false)); return !!fragment.querySelector(selector); }, onTitleChange: function(callback) { waitForLoad(function() { var title = (document.getElementsByTagName('title') || [])[0]; if (!title) { return; } new MutationObserver(function() { callback(title.textContent); }).observe(title, { childList: true }); }); }, /** * Retrieves the proper boundingRect of an element if it is visible on-screen. * @return boundingRect or null (if element is not visible on-screen) */ getVisibleBoundingRect: function(node) { var i; var boundingRect = node.getClientRects()[0] || node.getBoundingClientRect(); if (boundingRect.width <= 1 && boundingRect.height <= 1) { var rects = node.getClientRects(); for (i = 0; i < rects.length; i++) { if (rects[i].width > rects[0].height && rects[i].height > rects[0].height) { boundingRect = rects[i]; } } } if (boundingRect === void 0) { return null; } if (boundingRect.top > innerHeight || boundingRect.left > innerWidth) { return null; } if (boundingRect.width <= 1 || boundingRect.height <= 1) { var children = node.children; var visibleChildNode = false; for (i = 0, l = children.length; i < l; ++i) { boundingRect = children[i].getClientRects()[0] || children[i].getBoundingClientRect(); if (boundingRect.width > 1 && boundingRect.height > 1) { visibleChildNode = true; break; } } if (visibleChildNode === false) { return null; } } if (boundingRect.top + boundingRect.height < 10 || boundingRect.left + boundingRect.width < -10) { return null; } var computedStyle = getComputedStyle(node, null); if (computedStyle.visibility !== 'visible' || computedStyle.display === 'none' || node.hasAttribute('disabled') || parseInt(computedStyle.width, '10') === 0 || parseInt(computedStyle.height, '10') === 0) { return null; } return boundingRect; }, /** * Checks if an element is visible (not necessarily on-screen) */ isVisible: function(element) { return element.offsetParent && !element.disabled && element.getAttribute('type') !== 'hidden' && getComputedStyle(element).visibility !== 'hidden' && element.getAttribute('display') !== 'none'; }, mouseEvent: function(type, element) { var events; switch (type) { case 'hover': events = ['mouseover', 'mouseenter']; break; case 'unhover': events = ['mouseout', 'mouseleave']; break; case 'click': events = ['mouseover', 'mousedown', 'mouseup', 'click']; break; } events.forEach(function(eventName) { var event = document.createEvent('MouseEvents'); event.initMouseEvent(eventName, true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null); element.dispatchEvent(event); }); } };
JavaScript
0
@@ -3649,20 +3649,18 @@ .width, -' 10 -' ) === 0 @@ -3705,12 +3705,10 @@ ht, -' 10 -' ) ==
75dd9fc2b760387da6125c61120948a7be14a6e0
Fix js action_save in ra.remote-form
app/assets/javascripts/rails_admin/ra.remote-form.js
app/assets/javascripts/rails_admin/ra.remote-form.js
/* * RailsAdmin remote form @VERSION * * License * * http://www.railsadmin.org * * Depends: * jquery.ui.core.js * jquery.ui.widget.js * jquery.ui.dialog.js */ (function($) { $.widget("ra.remoteForm", { _create: function() { var widget = this var dom_widget = widget.element; var edit_url = dom_widget.find('select').first().data('options') && dom_widget.find('select').first().data('options')['edit-url']; if(typeof(edit_url) != 'undefined' && edit_url.length) { dom_widget.on('dblclick', '.ra-multiselect option:not(:disabled)', function(e){ widget._bindModalOpening(e, edit_url.replace('__ID__', this.value)) }); } dom_widget.find('.create').unbind().bind("click", function(e){ var template_name = this.attributes['data-template-name'], template_value = this.attributes['data-template-value'], link = $(this).data('link'); if (template_name && template_name.value && template_value) { link = link.replace(template_name.value, template_value.value); } widget._bindModalOpening(e, link) }); dom_widget.find('.update').unbind().bind("click", function(e){ if(value = dom_widget.find('select').val()) { var template_name = this.attributes['data-template-name'], template_value = this.attributes['data-template-value'], link = $(this).data('link').replace('__ID__', value); if (template_name && template_name.value && template_value){ link = link.replace(template_name.value, template_value.value); } widget._bindModalOpening(e, link) } else { e.preventDefault(); } }); }, _bindModalOpening: function(e, url) { e.preventDefault(); widget = this; if($("#modal").length) return false; var dialog = this._getModal(); setTimeout(function(){ // fix race condition with modal insertion in the dom (Chrome => Team/add a new fan => #modal not found when it should have). Somehow .on('show') is too early, tried it too. $.ajax({ url: url, beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "text/javascript"); }, success: function(data, status, xhr) { dialog.find('.modal-body').html(data); widget._bindFormEvents(); }, error: function(xhr, status, error) { dialog.find('.modal-body').html(xhr.responseText); }, dataType: 'text' }); },200); }, _bindFormEvents: function() { var widget = this, dialog = this._getModal(), form = dialog.find("form"), saveButtonText = dialog.find(":submit[name=_save]").html(), cancelButtonText = dialog.find(":submit[name=_continue]").html(); dialog.find('.form-actions').remove(); form.attr("data-remote", true); dialog.find('.modal-header-title').text(form.data('title')); dialog.find('.cancel-action').unbind().click(function(){ dialog.modal('hide'); return false; }).html(cancelButtonText); dialog.find('.save-action').unbind().click(function(){ // Patch if ($(this).parents().find('.codemirrored').length > 0) { e.preventDefault(); form.trigger('dialog.submit'); form.submit(); return false; } else { form.submit(); return false; } }).html(saveButtonText); $(document).trigger('rails_admin.dom_ready', [form]) form.bind("ajax:complete", function(xhr, data, status) { if (status == 'error') { dialog.find('.modal-body').html(data.responseText); widget._bindFormEvents(); } else { var json = $.parseJSON(data.responseText); var option = '<option value="' + json.id + '" selected>' + json.label + '</option>'; var select = widget.element.find('select').filter(":hidden"); if(widget.element.find('.filtering-select').length) { // select input var input = widget.element.find('.filtering-select').children('.ra-filtering-select-input'); input.val(json.label); if (!select.find('option[value=' + json.id + ']').length) { // not a replace select.html(option).val(json.id); widget.element.find('.update').removeClass('disabled'); } } else { // multi-select input var input = widget.element.find('.ra-filtering-select-input'); var multiselect = widget.element.find('.ra-multiselect'); if (multiselect.find('option[value=' + json.id + ']').length) { // replace select.find('option[value=' + json.id + ']').text(json.label); multiselect.find('option[value= ' + json.id + ']').text(json.label); } else { // add select.append(option); multiselect.find('select.ra-multiselect-selection').append(option); } } widget._trigger("success"); dialog.modal("hide"); } }); }, _getModal: function() { var widget = this; if (!widget.dialog) { widget.dialog = $('<div id="modal" class="modal fade">\ <div class="modal-dialog">\ <div class="modal-content">\ <div class="modal-header">\ <a href="#" class="close" data-dismiss="modal">&times;</a>\ <h3 class="modal-header-title">...</h3>\ </div>\ <div class="modal-body">\ ...\ </div>\ <div class="modal-footer">\ <a href="#" class="btn cancel-action">...</a>\ <a href="#" class="btn btn-primary save-action">...</a>\ </div>\ </div>\ </div>\ </div>') .modal({ keyboard: true, backdrop: true, show: true }) .on('hidden.bs.modal', function(){ widget.dialog.remove(); // We don't want to reuse closed modals widget.dialog = null; }); } return this.dialog; } }); })(jQuery);
JavaScript
0.000003
@@ -3262,32 +3262,33 @@ .click(function( +e )%7B%0A // Pa
ddd9fcb7574938cc839294eebfd70c4fa6086738
Check devices.length >= 1.
blink1/color-picker.js
blink1/color-picker.js
(function() { var ui = { r: null, g: null, b: null }; var connection = -1; function initializeWindow() { for (var k in ui) { var id = k.replace(/([A-Z])/, '-$1').toLowerCase(); var element = document.getElementById(id); if (!element) { throw "Missing UI element: " + k; } ui[k] = element; } setGradients(); enableControls(false); ui.r.addEventListener('input', onColorChanged); ui.g.addEventListener('input', onColorChanged); ui.b.addEventListener('input', onColorChanged); enumerateDevices(); }; function enableControls(enabled) { ui.r.disabled = !enabled; ui.g.disabled = !enabled; ui.b.disabled = !enabled; }; function enumerateDevices() { chrome.hid.getDevices( { "vendorId": 10168, "productId": 493 }, onDevicesEnumerated); }; function onDevicesEnumerated(devices) { if (!devices) { console.warn("Unable to enumerate devices: " + chrome.runtime.lastError.message); return; } chrome.hid.connect(devices[0].deviceId, onDeviceConnected); }; function onDeviceConnected(connectInfo) { if (!connectInfo) { console.warn("Unable to connect to device: " + chrome.runtime.lastError.message); } connection = connectInfo.connectionId; enableControls(true); }; function fadeRGB(r, g, b, fade_ms, led) { // Send a fade command to the blink(1). The command protocol operates over // feature reports and is documented here: // // https://github.com/todbot/blink1/blob/master/docs/blink1-hid-commands.md var fade_time = fade_ms / 10; var th = (fade_time & 0xff00) >> 8; var tl = fade_time & 0x00ff; var data = new Uint8Array(8); data[0] = 'c'.charCodeAt(0); data[1] = r; data[2] = g; data[3] = b; data[4] = th; data[5] = tl; data[6] = led; chrome.hid.sendFeatureReport(connection, 1, data.buffer, function() { if (chrome.runtime.lastError) { console.warn("Unable to set feature report: " + chrome.runtime.lastError.message); } }); } function onColorChanged() { setGradients(); fadeRGB(ui.r.value, ui.g.value, ui.b.value, 250, 0); } function setGradients() { var r = ui.r.value, g = ui.g.value, b = ui.b.value; ui.r.style.background = 'linear-gradient(to right, rgb(0, ' + g + ', ' + b + '), ' + 'rgb(255, ' + g + ', ' + b + '))'; ui.g.style.background = 'linear-gradient(to right, rgb(' + r + ', 0, ' + b + '), ' + 'rgb(' + r + ', 255, ' + b + '))'; ui.b.style.background = 'linear-gradient(to right, rgb(' + r + ', ' + g + ', 0), ' + 'rgb(' + r + ', ' + g + ', 255))'; } window.addEventListener('load', initializeWindow); }());
JavaScript
0
@@ -1052,16 +1052,108 @@ %0A %7D%0A%0A + if (devices.length %3C 1) %7B%0A console.warn(%22No devices found.%22);%0A return;%0A %7D%0A%0A chro
bf79c49cf8da1adabccd552a9595462e139b3f55
Normalise weights by mean weight and keep better half
example/drummer/local_modules/mcbsp/index.js
example/drummer/local_modules/mcbsp/index.js
// Multi-channel binary predictor // const lib = require('./lib'); const binaryEntropy = require('./binaryEntropy'); const way = require('senseway'); exports.past = (hist, t, size) => { // Multi-channel past return way.before(hist, t, size) }; exports.future = (hist, t, size) => { // Multi-channel future return way.after(hist, t, size) }; exports.moment = (hist, t, pastSize, futureSize) => { // Multi-channel moment return { t: t, past: way.before(hist, t, pastSize), future: way.after(hist, t, futureSize) } }; exports.gain = binaryEntropy; exports.similarity = (a, b, apriori) => { // Similarity score between two multi-channel history slices. return way.reduce(a, (acc, aq, c, t) => { const bq = b[c][t]; // Alternatives for scoring: // 1 - Math.abs(aq - bq); // Math.min(aq, bq); const score = 1 - Math.abs(aq - bq); // Weight in the info gain. // Otherwise full ones or zeros will get huge weight. const p = apriori[c][0]; // Binary entropy function const gain = binaryEntropy(p); return acc + score * gain; }, 0); }; exports.predict = (hist, context, distance) => { // Assert hist.length === context.length const channels = context.length; const contextSize = context[0].length; const historySize = hist[0].length; const futureSize = distance; // No reason to include moments where the future is about to be predicted. const times = lib.range(Math.max(0, historySize - futureSize + 1)); var moments = times.map(t => { return exports.moment(hist, t, contextSize, futureSize); }); const apriori = way.mean(hist); var weights = moments.map(m => { var sim = exports.similarity(m.past, context, apriori); return sim * sim; }); let weightSum = lib.arraySum(weights); const accum = context.map(() => lib.zeros(futureSize)); let normalized = moments.reduce((pred, m, t) => { return way.add(pred, way.scale(m.future, weights[t] / weightSum)); }, accum); let maxLikelihood = way.map(normalized, q => Math.round(q)); return { moments, weights, probabilities: normalized, prediction: maxLikelihood }; };
JavaScript
0.000001
@@ -1632,19 +1632,19 @@ st);%0A%0A -var +let weights @@ -1743,14 +1743,169 @@ sim - * sim +;%0A %7D);%0A%0A const weightMean = lib.arrayMean(weights);%0A%0A // Pick weights above mean weight.%0A weights = weights.map(w =%3E %7B%0A return Math.max(0, w - weightMean) ;%0A
79dd015d323bedfbddddfcb280b01bdc99b28c75
Remove unused code.
gulp/tasks/watch.js
gulp/tasks/watch.js
var gulp = require('gulp'); var path = require('path'); var util = require('gulp-util'); var del = require('del'); var Glob = require('../glob.js'); // https://github.com/gulpjs/gulp/blob/master/docs/API.md#eventtype var WatchEventType = { Added: 'added', Changed: 'changed', Deleted: 'deleted' }; // Watch source files for changes. Run compile task when changes detected. gulp.task('watch', function(done) { var onFileChange = function(event) { // Write to log that change happened. util.log( util.colors.yellow(path.basename(event.path)) + util.colors.green(' was ' + event.type + ', recompiling...') ); // Clean-up deleted files manually by finding and removing their counterpart. if (event.type === WatchEventType.Deleted) { var compiledPath = ''; if (event.path.indexOf(Glob.Src) !== -1) { compiledPath = event.path.replace(Glob.Src, Glob.Compiled); } else if (event.path.indexOf(Glob.Jspm) !== -1) { // jspm's directory structure changes when moving into compiled. compiledPath = event.path.replace(Glob.Jspm, Glob.Compiled + '\\' + Glob.Jspm); } else { throw new Error('Unexpected path:' + event.path); } del(compiledPath); } }; gulp.watch(Glob.SrcFolder + Glob.AllFiles, ['compile:transformSrc']).on('change', onFileChange); gulp.watch([ Glob.JspmFolder + Glob.AllFiles, // It's too slow to watch jspm packages for changes. Increases watch task time by ~20s '!' + Glob.JspmFolder + Glob.JspmPackagesFolder + Glob.AllFiles ], ['compile:copyJspmFolder']).on('change', onFileChange); gulp.watch([ Glob.CompiledFolder + Glob.AllFiles, // It's too slow to watch jspm packages for changes. Increases watch task time by ~20s '!' + Glob.CompiledFolder + Glob.JspmFolder + Glob.JspmPackagesFolder + Glob.AllFiles ], ['connect:reloadCompiledFiles']); done(); });
JavaScript
0
@@ -814,13 +814,8 @@ Path - = '' ;%0D%0A%0D
aaa42ea552f9443fa8aacbf58defb3de2b52de2b
fix sample middleware order
webtasks.js
webtasks.js
/*jslint node: true */ 'use strict'; var express = require('express'), webtask = require('./lib/webtask'), app = module.exports = express(); webtask.init(app); /* istanbul ignore next */ if (!module.parent) { app.webtask('/', app.page('sample2')); app.webtask('/module/header', app.module('header')); app.webtask('/ajax/product', app.ajax('getProduct')); app.listen(3000); console.log('Webtasks started on port 3000'); }
JavaScript
0.000001
@@ -217,51 +217,8 @@ ) %7B%0A - app.webtask('/', app.page('sample2'));%0A @@ -324,24 +324,67 @@ Product'));%0A + app.webtask('/', app.page('sample2'));%0A app.list
5ec4001c3073e464e8c143aa040d7db7b48ba3e2
Create accurate gameStats array full of objects
server/serverHelpers.js
server/serverHelpers.js
var knex = require('knex')({ client: 'sqlite3', connection: { filename: './database.sqlite3' } }); exports.createGamesForTourney = function(tourneyId, playersInTourneyList) { // games array will be returned by this function var games = []; // while there is more than one player in the tourneyPlayersList, while (playersInTourneyList.length > 1) { // shift the first item off and hold it with our nextPlayer variable var nextPlayer = playersInTourneyList.shift(); // then forEach player left in there, create a game with the nextPlayer // and push that game into the games array playersInTourneyList.forEach(function(playerObj) { // this will be the object pushed into the games array var gameObj = {}; // set the needed values for the game object gameObj.player1_id = nextPlayer.id; gameObj.player2_id = playerObj.id; gameObj.tournament_id = tourneyId; // push into the games array games.push(gameObj); }); } // return games; }; exports.getTable = function(tourneyId) { // Output: // { // playerId: // gp: // won: // loss: // draw: // gd // } // Input: // Games and players // Created Players Array knex('players') .orderBy('id', 'asc') .then(function(data) { var playersArray = data.map(function(item) { return { id: item.id, wins: 0, losses: 0, draws: 0, gp: 0, gd: 0 } }) }); // if (tourneyId) { // knex('games') // .where('tournament_id', tourneyId) // .then(function(data) { // console.log(data); // }) // } };
JavaScript
0.000001
@@ -1078,150 +1078,168 @@ ) %7B%0A +%0A // -Output:%0A// +if (tourneyId) %7B%0A + // -playerId:%0A// gp:%0A// won:%0A// loss:%0A// draw:%0A// gd%0A// %7D%0A%0A// Input:%0A// Games and players%0A%0A// Created Players Array +knex('games')%0A // .where('tournament_id', tourneyId)%0A // .then(function(data) %7B%0A // console.log(data);%0A // %7D)%0A // %7D%0A%0A %0Akne @@ -1463,136 +1463,1492 @@ %7D)%0A -%7D);%0A%0A%0A%0A%0A // if (tourneyId) %7B%0A // knex('games')%0A // .where('tournament_id', tourneyId)%0A // .then(function(data) %7B%0A // +%0A knex('games')%0A .then(function(data) %7B%0A data.forEach(function(item) %7B%0A var diff = Math.abs(item.player1_score - item.player2_score);%0A var winner;%0A var loser;%0A var draw1;%0A var draw2;%0A %0A if(item.player1_score === item.player2_score) %7B%0A draw1 = item.player1_id;%0A draw2 = item.player2_id;%0A %0A playersArray.forEach(function(item) %7B%0A if(item.id === draw1 %7C%7C item.id === draw2) %7B%0A item.draws += 1;%0A item.gp += 1;%0A %7D%0A %7D) %0A %7D%0A else if(item.player1_score %3E item.player2_score) %7B%0A winner = item.player1_id;%0A loser = item.player2_id;%0A %0A playersArray.forEach(function(item) %7B%0A if(item.id === winner) %7B%0A item.wins++;%0A item.gp++;%0A item.gd += diff;%0A %7D %0A if(item.id === loser) %7B%0A item.losses++;%0A item.gp++;%0A item.gd -= diff;%0A %7D%0A %0A %7D)%0A %0A %7D else %7B%0A winner = item.player2_id;%0A loser = item.player1_id;%0A %0A playersArray.forEach(function(item) %7B%0A if(item.id === winner) %7B%0A item.wins++;%0A item.gp++;%0A item.gd += diff;%0A %7D %0A if(item.id === loser) %7B%0A item.losses++;%0A item.gp++;%0A item.gd -= diff;%0A %7D%0A %7D)%0A %7D%0A %0A %0A %0A %7D);%0A @@ -2963,32 +2963,37 @@ log( -data +playersArray );%0A - // %7D) +;%0A %0A -// %7D%0A +%7D); %0A%7D;%0A
cdbd66c0b6ed2739f5543e88a03ca17558d91a3d
Fix loading of single files
penelope.js
penelope.js
#!/usr/bin/env node /*! csstool v0.0.0 - MIT license */ 'use strict'; /** * Module dependencies */ var _ = require('underscore'), Penelope = require('./lib/Penelope'), CliController = require('./lib/CliController'), metrics = require('./metrics/All'), formatters = require('./lib/Formatters'), argv = require('minimist')(process.argv.slice(2)), fs = require('fs'), async = require('async'), path = require('path'), info = require('./lib/Info'); var cliController = new CliController(); cliController.on('runPaths', function (filePaths) { var stylesheets = []; async.each(filePaths, function (filePath, onAllLoad) { var onFileLoad = function (err, data) { stylesheets.push(data); }; if (!fileIsStylesheet(filePath)) { readDirectory(filePath, onFileLoad, onAllLoad); } else { readFile(filePath, function (err, data) { onFileLoad(err, data); onAllLoad();}); } }, function (err) { runReport(stylesheets, metrics); }); }); cliController.on('runStdin', function () { process.stdin.resume(); process.stdin.setEncoding('utf8'); var stdinData = ''; process.stdin.on('data', function(chunk) { stdinData += chunk; }); process.stdin.on('end', function() { runReport(stdinData, metrics); }); }); cliController.on('showVersion', function () { info.version(); process.exit(); }); cliController.on('showHelp', function () { info.help(); process.exit(); }); cliController.on('setFormat', function (format) { formatter = formatters[format]; if (!formatter) { console.error('Unknown output format: %s', argv.format); console.error(' available: ' + Object.keys(formatters).join(' ')); process.exit(1); } }); cliController.on('showNumericOnly', function () { metrics = _.filter(metrics, function (metric) { return metric.format == 'number'; }); }); var readDirectory = function (directoryPath, onFileLoad, onAllLoad) { fs.readdir(directoryPath, function (err, files) { async.each(files, function (file, fileDone) { if (!fileIsStylesheet(file)) { return fileDone(); } readFile(path.join(directoryPath, file), function(err, fileData) { onFileLoad(err, fileData); fileDone(); }); }, onAllLoad); }); }; var readFile = function (filePath, onLoad) { fs.readFile(filePath, {encoding: 'utf8'}, function (err, fileData) { onLoad(err, fileData); }); }; var fileIsStylesheet = function (filePath) { return filePath.indexOf('.css') !== -1; }; var runReport = function (stylesheets, metrics) { var results = penelope.run(stylesheets); console.log(formatter(metrics, results)); }; if (module.parent) { module.exports = Penelope; } else { var penelope = new Penelope(metrics), formatter = formatters['human']; cliController.dispatch(argv); }
JavaScript
0.000001
@@ -2705,16 +2705,17 @@ dexOf('. +s css') !=
ff42975541efddd2d80e74e1428d5693c2569947
fix yo yui3:handlebars
handlebars/index.js
handlebars/index.js
'use strict'; var util = require('util'); var yeoman = require('yeoman-generator'); var fs = require("fs"); var Handlebars = require('yui/handlebars').Handlebars; var path = require("path"); var HandlebarsGenerator = module.exports = function HandlebarsGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); }; util.inherits(HandlebarsGenerator, yeoman.generators.Base); HandlebarsGenerator.prototype.setPaths = function setPaths() { this.rootPath = process.cwd(); this.templatesPath = path.join(this.rootPath, "./templates"); this.jsPath = path.join(this.rootPath, "./js"); }; HandlebarsGenerator.prototype.actions = function actions() { var files = fs.readdirSync(this.templatesPath), i, fileLength = files.length, fileName, matches, templateFileRaw; for (i = 0; i < fileLength; i++) { fileName = files[i]; matches = fileName.match(/^([^\.]*)\.handlebars.html$/); if (matches) { templateFileRaw = this.readFileAsString(path.join(this.templatesPath, fileName)); var content = "Y.namespace('templates')['" + matches[1] + "'] = " + Handlebars.precompile(templateFileRaw) + ";\n" this.write(path.join(this.templatesPath, matches[1] + ".js"), content); } } };
JavaScript
0.000117
@@ -972,25 +972,24 @@ (matches) %7B%0A -%0A @@ -1146,16 +1146,38 @@ + %22'%5D = +Y.Handlebars.template( %22 + Hand @@ -1214,16 +1214,17 @@ Raw) + %22 +) ;%5Cn%22%0A
ef08e970848ec9746c8e76e73140dc3280757734
Switch to using 'localhost' for API endpoint when making requests for combined feed
src/handlers/collator.js
src/handlers/collator.js
import goodGuyHttp from 'good-guy-http'; const goodGuy = goodGuyHttp({ // defaultCaching: { // timeToLive: 300000, // }, // headers: { // 'User-Agent': 'Department of Commerce Intranet - request', // }, // proxy: process.env.HTTP_PROXY, timeout: 15000, }); exports.combinedNews = async function collateAllNews(request, reply) { // console.dir(request); // console.dir(request.connection.server.info); // console.dir(server.info); const endpointProto = request.connection.server.info.protocol; // console.log(endpointProto); const endpointPort = request.connection.server.info.port; // console.log(endpointPort); const checkHost = request.connection.server.info.host; // console.log(checkHost); let endpointHost = ''; if (checkHost.indexOf('local') > 0) { // console.log('localhost fired'); endpointHost = 'localhost'; } else { // console.log('remote host fired'); endpointHost = checkHost; } const endpointUrl = `${endpointProto}://${endpointHost}:${endpointPort}`; // console.log('endpoint url:', endpointUrl); const news = []; let flattened = []; try { const commerceNews = await goodGuy(`${endpointUrl}/api/v1/statements/commerce`); const ministerials = await goodGuy(`${endpointUrl}/api/v1/statements/ministerials`); const governmentNews = await goodGuy(`${endpointUrl}/api/v1/statements/government`); const dmirsTweets = await goodGuy(`${endpointUrl}/api/v1/tweets/dmirs`); const combined = news.concat( JSON.parse(commerceNews.body.toString()), JSON.parse(ministerials.body.toString()), JSON.parse(governmentNews.body.toString()), JSON.parse(dmirsTweets.body.toString()) ); flattened = combined.reduce((a, b) => a.concat(b), []); console.log('items count =', flattened.length); } catch (error) { console.error('Error building combined feed:', error); throw error; } // console.dir(news); // reply('testing'); // reply(combined); reply(flattened); };
JavaScript
0
@@ -347,116 +347,8 @@ ) %7B%0A - // console.dir(request);%0A // console.dir(request.connection.server.info);%0A // console.dir(server.info);%0A co @@ -412,41 +412,8 @@ ol;%0A - // console.log(endpointProto);%0A co @@ -476,37 +476,8 @@ // - console.log(endpointPort);%0A con @@ -536,34 +536,8 @@ // - console.log(checkHost);%0A let @@ -557,16 +557,19 @@ = '';%0A + // if (che @@ -603,48 +603,12 @@ ) %7B%0A - // - console.log('localhost fired');%0A e @@ -635,16 +635,19 @@ host';%0A + // %7D else @@ -652,52 +652,55 @@ e %7B%0A - // -console.log('remote host fired');%0A + endpointHost = checkHost;%0A // %7D%0A const end @@ -715,22 +715,20 @@ t = -checkHost;%0A %7D +'localhost'; %0A c
60641e726a545943fd1079fd69ce37ca762ae689
Rename parameter graph to pie
cabdriver.js
cabdriver.js
#!/usr/bin/env node var Program = require('commander'); var SemanticDate = require('semantic-date'); var Moment = require('moment-timezone'); var Async = require('async'); var Pad = require('pad'); var _ = require('underscore'); var auth = require('./lib/auth'); var slack_auth = require('./lib/slack_auth'); var calendar = require('./lib/calendar'); var mail = require('./lib/mail'); var slack = require('./lib/slack'); var git = require('./lib/git'); var pkg = require('./package.json'); exports.getStartAndEndDate = getStartAndEndDate; function dashed(val) { var splitted = val.split('-'); return _.map(splitted, function(elem) { return elem.trim(); }); } function getStartAndEndDate(dateStr) { var dates = { 'startDate': null, 'endDate': null }; if (SemanticDate.validate(dateStr)) { var parsed = SemanticDate.convert(dateStr); dates['startDate'] = Moment.tz(parsed.start, 'Europe/Zurich'); dates['endDate'] = Moment.tz(parsed.end, 'Europe/Zurich'); } else { var dateArr = dashed(dateStr); var startStr = dateArr[0]; var endStr = ''; if (dateArr.length > 1) { endStr = dateArr[1]; } if (startStr && Moment(startStr, 'DD.MM.YYYY').isValid()) { dates['startDate'] = Moment.tz(startStr, 'DD.MM.YYYY', 'Europe/Zurich'); } if (endStr && Moment(endStr, 'DD.MM.YYYY').isValid()) { dates['endDate'] = Moment.tz(endStr, 'DD.MM.YYYY', 'Europe/Zurich'); } } dates['endDate'] = dates['endDate'] ? dates['endDate'].toISOString() : Moment(dates['startDate']).endOf('day').toISOString(); dates['startDate'] = dates['startDate'] ? dates['startDate'].toISOString() : Moment().tz('Europe/Zurich').endOf('day').toISOString(); return dates; } Program .version(pkg.version) .option('-n, --number [number of events]', 'number of events to show [250]', 250) .option('-d, --date <date>', 'date for query [today]', 'today') .option('-c, --calendar [cal_id]', 'determine which calendar you want to use [primary]', 'primary') .option('-m, --mail', 'use mail as source') .option('-s, --slack', 'use slack as source') .option('-g, --git [path]', 'use git as a source') .option('-p, --pie', 'print pie chart instead of text') .option('-v, --verbose', 'more verbose output [false]', false) .parse(process.argv); var dates = getStartAndEndDate(Program.date); Moment.suppressDeprecationWarnings = true; if (!Moment(dates['endDate']).isValid() || !Moment(dates['startDate']).isValid()) { console.error("Please enter a valid date range"); process.exit(1); } if (Program.verbose) { console.log('Start date: %s', Moment.tz(dates['startDate'], 'Europe/Zurich').format('DD.MM.YYYY')); console.log('End date: %s', Moment.tz(dates['endDate'], 'Europe/Zurich').format('DD.MM.YYYY')); console.log('Calendar: %s', Program.calendar); console.log('Mail: %s', Program.mail); console.log('Slack: %s', Program.slack); console.log('Git: %s', Program.git); console.log('Graph: %s', Program.graph); console.log('Count: %s', Program.number); } auth.getAuth(function(auth) { Async.series([ function(callback) { // Google Calendar calendar.listEvents(callback, auth, Program.number, dates['startDate'], dates['endDate'], Program.calendar); }, function(callback) { // Google Mail if (Program.mail) { mail.listMessages(callback, auth, Program.number, dates['startDate'], dates['endDate']); } else { callback(null, []); } }, function(callback) { if (Program.slack) { slack_auth.getAuth(function(auth) { slack.dailyStats(callback, auth, Program.number, dates['startDate'], dates['endDate'], Program.graph); }); } else { callback(null, []); } }, function(callback) { if (Program.git) { git.getCommits(callback, Program.git, dates['startDate'], dates['endDate']); } else { callback(null, []); } } ], function(err, results) { results = _.flatten(results); results = _.groupBy(results, 'timestamp'); //order the resulting object based on timestamp var orderedResults = {}; Object.keys(results).sort().forEach(function(key) { orderedResults[key] = results[key]; }); //print a section for each day separated by type _.each(orderedResults, function(msgs, timestamp) { var day = Moment.unix(timestamp).tz('Europe/Zurich'); var allProjects = _.keys(_.groupBy(msgs, 'project')); var maxProjectLength = allProjects.reduce(function (a, b) { return a.length > b.length ? a : b; }).length; var padding = Math.max(5, maxProjectLength + 1); msgs = _.groupBy(msgs, 'type'); console.log(''); console.log('%s # %s', day.format('DD/MM/YYYY'), day.format('dddd')); _.each(msgs, function(msgs, type) { console.log('# ' + type); _.each(msgs, function(msg) { if (_.has(msg, 'raw') && msg.raw) { console.log(msg.raw); } else { var text = Pad(msg.project, padding); if (msg.time) { text += msg.time + ' '; } text += msg.text; if (msg.comment) { text = '# ' + text; } console.log(text); } }); }); }); }); });
JavaScript
0.001286
@@ -3087,13 +3087,17 @@ og(' -Graph +Pie chart : %25s @@ -3103,29 +3103,27 @@ s', Program. -graph +pie );%0A conso @@ -3911,13 +3911,11 @@ ram. -graph +pie );%0A
57f587ca457c86d9452146aeeda2d3b820a0811a
append slash in regular restangular api
onedegree/static/admin/app.js
onedegree/static/admin/app.js
define([ 'angular' , './namespace' // add necessary app as you wish , '../common/namespace' , './tag/namespace' // , './account/namespace' // , './contact/namespace' // , './search/namespace' // , './group/namespace' // , './common/namespace' // , './quanquan/namespace' // would be entity for diff app entity c-tor //, './tag/entity' // migrate to constant, a constant is an IIFE complex object with method init // for the convenience of invocation , 'ng-admin' , '../common/module.require' , './tag/module.require' // , './account/module.require' // , './contact/module.require' // , './search/module.require' // , './group/module.require' // , './common/module.require' // , './quanquan/module.require' ], function (angular, namespace , commonNamespace , tagNamespace ) { /* Admin official entry point */ 'use strict'; var app = angular.module(namespace, ['ng-admin' , 'ngJsTree' //, 'ct.ui.router.extras.future', 'ct.ui.router.extras.statevis' // this two should be manually added //, 'angularMoment' // below enable those namespace to be injected , commonNamespace , tagNamespace // , contactNamespace, searchNamespace // , groupNamespace, commonNamespace // , quanquanNamespace ]) .config(['NgAdminConfigurationProvider' , 'RestangularProvider' , 'tag.entities' , function(NgAdminConfigurationProvider , RestangularProvider , tagModuleEntities) { var nga = NgAdminConfigurationProvider; var baseApiUrl = '/api/v1/admin'; var admin = nga.application('One Degree Admin Site', true) // application main title and debug disabled .baseApiUrl(baseApiUrl); // main API endpoint // this form is commonjs pattern // and commonjs is not designated to cater web browser // var tag = require('tag'); // then I need to resolve menu item modulization... // in a simple way, entityMap sounds fine // each module's init method defines its menu(with nested menu items defined) // and entity definitions within // the cross-module entity dependency order might as well be // maintained by the developer for the sake of simplicity var rootMenuItem = nga.menu(), entityMap = {}; // init methods have no return value, only edit the content of below references tagModuleEntities.init(nga, admin, rootMenuItem, baseApiUrl, entityMap); admin.menu(rootMenuItem); nga.configure(admin); RestangularProvider .setBaseUrl(baseApiUrl) //.setBaseUrl(baseApiUrl) .addFullRequestInterceptor(function(element, operation, what, url, headers, params, httpConfig) { if (operation == 'getList') { // filtering settings if (params._filters) { for (var filter in params._filters) { params[filter] = params._filters[filter]; if (filter == 'q'){ params[filter] = '@' + params[filter]; // fulltext search MySql supported only } } delete params._filters; } // pagination settings if(params._page){ params.page = params._page; delete params._page; } if(params._perPage){ params.page_size = params._perPage; delete params._perPage; } //ordering/sort settings if(params._sortField){ // this sorting field on treetag is lft since it's mptt default behavior params.ordering = params._sortField || 'id'; if (params._sortDir == 'DESC'){ params.ordering = '-' + params.ordering; } delete params._sortField; } delete params._sortDir; } return { params: params }; }) .addResponseInterceptor(function(data, operation, what, url, response, deferred) { // .. to look for getList operations if (operation === "getList") { // add totalCount according to doc. // refer to https://github.com/marmelab/ng-admin/blob/master/doc/API-mapping.md#total-number-of-results response.totalCount = data.count; return data.results; // so return data.result will suite our requirement } console.log('response, interceptor'); return data; }) .setRequestSuffix('/'); }]) .run(function () { }) return app; });
JavaScript
0.000002
@@ -2947,32 +2947,29 @@ %09 -// .set -BaseUrl(baseApiUrl +RequestSuffix('/' )%0A @@ -3459,14 +3459,8 @@ r%5D = - '@' + par @@ -3475,48 +3475,8 @@ er%5D; -%09// fulltext search MySql supported only %0A @@ -5124,120 +5124,34 @@ %09 -console.log('response, interceptor');%0A %09return data;%0A %7D)%0A .setRequestSuffix('/' +return data;%0A %7D );%0A
4876620028a134fb32c9c06e3616f36a27f31571
Remove get receipt override for given providers
src/wallets/web3-provider/providers/given-provider.js
src/wallets/web3-provider/providers/given-provider.js
import { Manager as Web3RequestManager } from 'web3-core-requestmanager'; import MiddleWare from '../middleware'; import { ethSendTransaction, ethSign, ethSignTransaction, ethGetTransactionCount, ethGetTransactionReceipt } from '../methods'; class GivenProvider { constructor(host, options, store, eventHub) { this.givenProvider = Object.assign({}, host); const requestManager = new Web3RequestManager(host); options = options ? options : null; if (this.givenProvider.sendAsync) { this.givenProvider.send = this.givenProvider.sendAsync; delete this.givenProvider.sendAsync; } this.givenProvider.send_ = this.givenProvider.send; delete this.givenProvider.send; this.givenProvider.send = (payload, callback) => { const req = { payload, store, requestManager, eventHub }; const middleware = new MiddleWare(); middleware.use(ethSendTransaction); middleware.use(ethSignTransaction); middleware.use(ethGetTransactionCount); middleware.use(ethGetTransactionReceipt); middleware.use(ethSign); middleware.run(req, callback).then(() => { this.givenProvider.send_(payload, callback); }); }; return this.givenProvider; } } export default GivenProvider;
JavaScript
0.000001
@@ -199,36 +199,8 @@ ount -,%0A ethGetTransactionReceipt %0A%7D f @@ -1011,56 +1011,8 @@ t);%0A - middleware.use(ethGetTransactionReceipt);%0A
c50a8f81b4f612e73a02866dfe1c9b4ef1f99d6b
Add ability to remove progressbar
src/lib/sherlockphotography/ss-event-log-widget.js
src/lib/sherlockphotography/ss-event-log-widget.js
YUI.add('ss-event-log-widget', function(Y, NAME) { var EventLogEntry = Y.Base.create( 'ss-event-log-entry', Y.Base, [], { _progressBar: null, _logTypeToClassname: function(type) { var classname; switch (type) { case 'error': case 'warning': classname = type; break; default: classname = 'info'; } return 'log-' + classname; }, _uiSetProgress: function() { var progress = this.get('progress'); if (progress) { if (!this._progressBar) { if (progress.total > 0) { this._progressBar = new Y.SherlockPhotography.ProgressBar(progress); this._progressBar.render(this.get('element')); } } else { this._progressBar.set('total', progress.total); this._progressBar.set('completed', progress.completed); } } }, _uiSetMessage: function() { this.get('element').one('> .message').set('text', this.get('message')); }, render: function() { element = Y.Node.create('<li class="' + (this.get('type') == 'error' ? 'alert-danger' : '') + '"><span class="message"></span></li>'); this.set('element', element); this._uiSetMessage(); this._uiSetProgress(); return element; }, initializer: function(cfg) { var self = this; this.after({ progressChange: function(e) { self._uiSetProgress(); }, messageChange: function(e) { self._uiSetMessage(); }, elementChange: function(e) { if (e.prevVal) { e.prevVal.replace(e.newVal); } } }); this.render(); } }, { ATTRS: { element : { value: null }, type: {}, message: {}, progress: { value: null } } } ); var EventLogWidget = Y.Base.create( NAME, Y.Widget, [], { _list: null, renderUI: function() { var contentBox = this.get("contentBox"); this._list = Y.Node.create('<ul class="list-unstyled"></ul>'); contentBox.append(this._list); }, clear: function() { this._list.get('childNodes').remove(); }, appendLog: function(type, message) { if (type != 'info') { //As soon as something goes wrong, log everything this.set('maximumInfoHistory', 1000); } if (this._list.get('children').size() >= this.get('maximumInfoHistory')) { this._list.one('*').remove(); } var entry = new EventLogEntry({type:type, message:message}); this._list.append(entry.get('element')); this._list.getDOMNode().scrollTop = this._list.getDOMNode().scrollHeight; return entry; } }, { ATTRS : { /** * Only bother keeping a set number of Info level entries in a row. */ maximumInfoHistory: { value: 1 } } } ); Y.namespace("SherlockPhotography").EventLogEntry = EventLogEntry; Y.namespace("SherlockPhotography").EventLogWidget = EventLogWidget; }, '0.0.1', { requires : ['base', 'widget', 'escape'] });
JavaScript
0.000001
@@ -839,24 +839,129 @@ ed);%0A%09%09%09%09%09%7D%0A +%09%09%09%09%7D else if (this._progressBar) %7B%0A%09%09%09%09%09this._progressBar.destroy(true);%0A%09%09%09%09%09this._progressBar = null;%0A %09%09%09%09%7D%0A%09%09%09%7D,%0A @@ -1829,24 +1829,29 @@ essage: %7B%7D,%0A +%09%09%09%09%0A %09%09%09%09progress
265a51b0e4608ea9451421fe4caf1f00b5d95f0a
Fix bad hard coding of tile sizes
webtiles.js
webtiles.js
// url: url to JSON in format { tiles : [[1,2,3],[3,2,1]] } // where tiles[x][y] = $number, such that there is a valid ".wt-$number" css class // [0][0] is lower left // all columns tiles[$i] should be equal length // grid: id of the div to populate with tiles function webtiles_load($, grid, url) { $(document).ready(function(){ $("#" + grid).addClass("webtiles-grid"); $.getJSON(url, function(result){ var tiles = result.tiles; // console.log(result); for(var y=tiles[0].length - 1; y>= 0; y--){ var row = $("<div></div>"); row.addClass("webtiles-row"); for(var x=0; x < tiles.length; x++){ var tile = $("<div></div>"); tile.addClass("webtile"); tile.addClass("wt-" + tiles[x][y]); row.append(tile); } $("#grid").append(row); } }); }); } function webtiles_generate_tileset_css($, output_css_pre_id, output_html_pre_id, image_ids, tile_width, tile_height) { // window load to wait for images to load $(window).on("load", function(){ var out_css = $("#" + output_css_pre_id); var out_html = $("#" + output_html_pre_id); // css prelude out_css.append(".webtiles-grid div {\n"); out_css.append(" min-width: 32px;\n"); out_css.append(" width: 32px;\n"); out_css.append(" height: 32px;\n"); out_css.append("}\n"); out_css.append("\n"); out_css.append(".webtile {\n"); out_css.append(" line-height: 32px;\n"); out_css.append("}\n"); function output_tile(i,x_offset,y_offset,img_url) { //background: url(house.png); //background-position: -32px -128px; out_css.append(".wt-" + i + " {\n"); out_css.append(" background: url(" + img_url + ") " + x_offset + "px " + y_offset + "px;\n"); out_css.append("}\n"); out_html.append(document.createTextNode(" <div class=\"webtile wt-" + i +"\">" + i +"</div>\n")); } var tile_id = 0; $.each(image_ids, function(i, img_id) { var img = document.getElementById(img_id); var w = img.width; var h = img.height; var src = img.src; console.log("img id: " + img_id); console.log("img url: " + src); console.log("img width: " + w); console.log("img height: " + h); if( w == 0 || h == 0 || (w % tile_width != 0) || (h % tile_height != 0)){ console.log("Warning: non compatible images for w=" + tile_width + " and h=" + tile_height + ": " + src); } var num_x = w / tile_width; var num_y = h / tile_height; out_html.append(document.createTextNode("<!-- img " + src + " -->\n")); for(var y=0; y < num_y; y++){ out_html.append(document.createTextNode("<div class=\"webtiles-row\">\n")); for(var x=0; x < num_x; x++){ var ox = -x * tile_width; var oy = -y * tile_height; out_css.append("/* " + src + " (" + x + ", " + y + ") */\n"); output_tile(tile_id++,ox,oy,src); } out_html.append(document.createTextNode("</div>\n")); } }); }); }
JavaScript
0.000013
@@ -1295,26 +1295,42 @@ min-width: -32 +%22 + tile_width + %22 px;%5Cn%22);%0A @@ -1354,18 +1354,34 @@ width: -32 +%22 + tile_width + %22 px;%5Cn%22); @@ -1402,34 +1402,50 @@ ppend(%22 height: -32 +%22 + tile_width + %22 px;%5Cn%22);%0A out @@ -1563,18 +1563,35 @@ height: -32 +%22 + tile_height + %22 px;%5Cn%22);
5806b51eb352690bc8a4869899c7a4809720042b
Mark raven-shim as an ES module
vendor/raven-shim.js
vendor/raven-shim.js
define('raven', [], function() { "use strict"; var Raven = window.Raven.noConflict(); return { 'default': Raven }; });
JavaScript
0.000001
@@ -10,16 +10,25 @@ aven', %5B +'exports' %5D, funct @@ -31,16 +31,23 @@ unction( +exports ) %7B%0A %22u @@ -65,77 +65,123 @@ %0A%0A -var Raven = window.Raven.noConflict();%0A%0A return %7B 'default': Raven %7D +Object.defineProperty(exports, %22__esModule%22, %7B%0A value: true%0A %7D);%0A%0A exports.default = window.Raven.noConflict() ;%0A%7D)
84d083fb329cd22be922e6c89251862f2c10c82b
normalize branch protection response (`restrictions.apps_url`)
lib/normalize/branch-protection.js
lib/normalize/branch-protection.js
module.exports = branchProtection const get = require('lodash/get') const normalizeTeam = require('./team') const normalizeUser = require('./user') const setIfExists = require('../set-if-exists') const temporaryRepository = require('../temporary-repository') // https://developer.github.com/v3/repos/branches/#response-2 function branchProtection (scenarioState, response) { // normalize temporary repository setIfExists(response, 'url', url => url.replace(temporaryRepository.regex, '$1')) setIfExists(response, 'required_status_checks.url', url => url.replace(temporaryRepository.regex, '$1')) setIfExists(response, 'required_status_checks.contexts_url', url => url.replace(temporaryRepository.regex, '$1')) setIfExists(response, 'required_pull_request_reviews.url', url => url.replace(temporaryRepository.regex, '$1')) setIfExists(response, 'required_pull_request_reviews.dismissal_restrictions.url', url => url.replace(temporaryRepository.regex, '$1')) setIfExists(response, 'required_pull_request_reviews.dismissal_restrictions.users_url', url => url.replace(temporaryRepository.regex, '$1')) setIfExists(response, 'required_pull_request_reviews.dismissal_restrictions.teams_url', url => url.replace(temporaryRepository.regex, '$1')) setIfExists(response, 'enforce_admins.url', url => url.replace(temporaryRepository.regex, '$1')) setIfExists(response, 'restrictions.url', url => url.replace(temporaryRepository.regex, '$1')) setIfExists(response, 'restrictions.users_url', url => url.replace(temporaryRepository.regex, '$1')) setIfExists(response, 'restrictions.teams_url', url => url.replace(temporaryRepository.regex, '$1')) // normalize users const dismissalRestrictionsUsers = get(response, 'required_pull_request_reviews.dismissal_restrictions.users') || [] const dismissalRestrictionsTeams = get(response, 'required_pull_request_reviews.dismissal_restrictions.teams') || [] const restrictionsUsers = get(response, 'restrictions.users') || [] const restrictionsTeams = get(response, 'restrictions.teams') || [] dismissalRestrictionsUsers.concat(restrictionsUsers).forEach(normalizeUser.bind(null, scenarioState)) dismissalRestrictionsTeams.concat(restrictionsTeams).forEach(normalizeTeam.bind(null, scenarioState)) }
JavaScript
0
@@ -1652,16 +1652,118 @@ , '$1')) +%0A setIfExists(response, 'restrictions.apps_url', url =%3E url.replace(temporaryRepository.regex, '$1')) %0A%0A // n
5b500a625b802673526926453b1f8040cb97d237
Add more debug logging to findfeed
src/handlers/findFeed.js
src/handlers/findFeed.js
const cheerio = require('cheerio') const normalizeUrl = require('normalize-url') const { parseFromString, parseFromQuery } = require('./feed') const request = require('../request') const normalizeOptions = { removeTrailingSlash: false } module.exports = async function findFeed({ url }) { const normalizedUrl = normalizeUrl(url, normalizeOptions) let response = null let content try { response = await request(normalizedUrl) content = response.text } catch (error) { return [] } if ( /application\/(rss|atom)/.test(response.contentType) || /(application|text)\/xml/.test(response.contentType) ) { const { title } = await parseFromString({ content }) return [{ title, link: normalizedUrl }] } const dom = cheerio.load(response.text) if (dom('rss')) { try { const { title } = await parseFromString({ content }) return [{ title, link: normalizedUrl }] } catch (error) { if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') { console.log(error) // eslint-disable-line no-console } } } const $linkTags = dom('link[rel="alternate"][type="application/rss+xml"]').add( 'link[rel="alternate"][type="application/atom+xml"]' ) const urls = $linkTags .map((index, $linkTag) => { const link = $linkTag.attribs.href return normalizeUrl(/^\//.test(link) ? url + link : link, normalizeOptions) }) .toArray() return (await Promise.all( urls.map(async url => { try { const { title } = await parseFromQuery({ url }) return { title, link: url } } catch (error) { if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') { console.log(error) // eslint-disable-line no-console } } }) )).filter(item => item !== undefined && item !== null) }
JavaScript
0
@@ -479,24 +479,173 @@ h (error) %7B%0A + if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') %7B%0A console.log(error) // eslint-disable-line no-console%0A %7D%0A return %5B @@ -777,24 +777,36 @@ Type)%0A ) %7B%0A + try %7B%0A const %7B @@ -850,24 +850,26 @@ tent %7D)%0A + return %5B%7B ti @@ -896,16 +896,199 @@ dUrl %7D%5D%0A + %7D catch (error) %7B%0A if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') %7B%0A console.log(error) // eslint-disable-line no-console%0A %7D%0A %7D%0A %7D%0A%0A c
7db66f75c10c4a49bab7242b013eca06a8da4562
change conditional to count participants
app/assets/javascripts/channels/gameView.js
app/assets/javascripts/channels/gameView.js
function renderGamePage(gameState) { var team1 = gameState.teams[0]; var team2 = gameState.teams[1]; var userdata = $("#live[data-userid]").data() var user_id = !!userdata ? userdata.userid : null; var isCluegiver = (user_id === gameState.cluegiver.id); var isCreator = (user_id === gameState.creator.id); // Universal View function getTimerHTML(){ return ` <div id='timer' class="fbCountdown" data-start-time='TBD' data-run-time='60'> <p>00:30</p> </div>`; }; function getTitleHTML(){ return ` <h3>${gameState.game.name}</h3> <div id='round-container'> <p>Current Round: ${gameState.current_round.type}</p> </div>`; }; // Waiting-to-Start-Game View function getWaitingHTML(){ if(gameState.game_started){ return "" } var allPlayers = '' gameState.participants.forEach(function(participant){ allPlayers += `<li class='player-name'>${participant.display_name}</li>` }) return ` <div class='waiting-game'> <h4>Participants</h4> <ul class='player-names-list'> ${allPlayers} </ul> <div id='create-card-form'> <form id="new_card" class="action-form" action="/cards" accept-charset="UTF-8" method="post"> <input type="text" name="card[concept]" id="card_concept" /> <input type="hidden" name="game_id" id="game_id" value="${gameState.game.id}" /> <input type="submit" name="commit" value="Add Card" data-disable-with="Add Card" /> </form> </div> ${startGameFormHTML()} </div> `; } function startGameFormHTML(){ if(!isCreator) { return "" } else if(!gameState.ready) { return ` <div class='game-not-ready'> <span>Waiting for at least 4 players...</span> </div> ` } return ` <form id="start-game" class="action-form" action="/games/${gameState.game.name}/start" method="post"> <input class="waves-effect waves-light btn-large teal" type="submit" value="Start Game!"> </form> ` } // Waiting-to-Round-Game View function getTeamsHTML(){ if(!gameState.game_started || gameState.round_started){ return "" } var team1Players = '' var team2Players = '' team1.players.forEach(function(player) { team1Players += ('<li>' + player.display_name + '</li>') }) team2.players.forEach(function(player) { team2Players += ('<li>' + player.display_name + '</li>') }) return `<h4>Teams:</h4> <div> <h5>${team1.name}</h5> <h5>${team1.score} points</h5> <ul> ${team1Players} </ul> <h5>${team2.name}</h5> <h5>${team2.score} points</h5> <ul> ${team2Players} </ul> </div> `; } function startRoundFormHTML(){ if(!isCreator){ return "" } if(!gameState.game_started || gameState.round_started){ return "" } return ` <form class="action-form" action="/games/${gameState.game.name}/start_round" method="post"> <input class="waves-effect waves-light btn-large teal" type="submit" value="START ROUND"> </form> ` } // Cluegiver View function getCluegiverHTML() { if(!gameState.round_started || !isCluegiver){ return "" } return ` <div id="cluegiver-container"> ${getCardHTML()} ${getCluegiverButtonsHTML()} </div> `; } function getCardHTML(){ return `<h1>${gameState.card}</h1>`; } function getCluegiverButtonsHTML(){ return `<div class="actions"> <form class="action-form" action="/games/${gameState.game.name}/pass" method="post"> <input class="waves-effect waves-light btn-large red" type="submit" value="pass"> </form> <form class="action-form" action="/games/${gameState.game.name}/win_card" method="post"> <input class="waves-effect waves-light btn-large teal" type="submit" value="got it!"> </form> <form class="action-form" action="/games/${gameState.game.name}/pause" method="post"> <input class="waves-effect waves-light btn-large orange" type="submit" value="pause"> </form> </div>`; }; // Observer View function getObserverHTML() { if(!gameState.round_started || isCluegiver){ return "" } return ` <div id="observer-container"> <h1>${gameState.cluegiver.display_name}s Turn</h1> </div> `; } // Results View function showResults() { var winningTeam = team1.score > team2.score ? team1 : team2; var losingTeam = gameState.teams.find(function(team) { return team != winningTeam }); return ` <div class='results-container'> <div class='winners'> <h4>${winningTeam.name} win!</h4> <h5>${winningTeam.score}</h5> </div> <div class='losers'> <h5>${losingTeam.name}</h5> <h5>${losingTeam.score}</h5> </div> </div> ` } function nextTurnButton() { if(!isCreator || !gameState.round_started){ return "" } return ` <form class="action-form" action="/games/${gameState.game.name}/next_turn" method="post"> <input class="waves-effect waves-light btn-large green" type="submit" value="NEXT TURN"> </form> ` } var gameHTML; if(gameState.is_over){ gameHTML = showResults() } else { gameHTML = ` ${getTimerHTML()} ${getTitleHTML()} ${getWaitingHTML()} ${getTeamsHTML()} ${startRoundFormHTML()} ${getCluegiverHTML()} ${getObserverHTML()} ${nextTurnButton()} ` } $('#live').html(gameHTML) }
JavaScript
0
@@ -1682,25 +1682,24 @@ %7D else if( -! gameState.re @@ -1696,21 +1696,32 @@ meState. -ready +participants %3C 4 ) %7B%0A
6bc8e870109854f915e8a553281a863562522537
add error handler with hacker news api
server/src/resolvers.js
server/src/resolvers.js
const axios = require('axios') // constants ====== const HACKER_NEWS_TOP_STORIES_URI = 'https://hacker-news.firebaseio.com/v0/topstories.json' const HACKER_NEWS_ITEM_URI = 'https://hacker-news.firebaseio.com/v0/item/' // handlers ======= const user = (rootValue, _, { user }) => { if (user) return user return null } const topStories = async (root, { first, after, reload }, { session }) => { let data if (!session.storyIds || reload) { const res = await axios.get(HACKER_NEWS_TOP_STORIES_URI) session.storyIds = res.data data = res.data } else { data = session.storyIds } const stories = data.slice(after, after + first).map(async storyId => { const res = await axios.get(`${HACKER_NEWS_ITEM_URI}${storyId}.json`) const { id, title, url, score, descendants, kids, time } = res.data return { id, title, url, score, numComments: descendants, commentsIds: kids, creationDate: time, } }) if (stories.length === 0) session.storyIds = undefined return stories } const comments = async (root, { id }) => { let storyId if (root) storyId = root.id else storyId = id const res = await axios.get(`${HACKER_NEWS_ITEM_URI}${storyId}.json`) const ids = res.data.kids if (!ids) return [] return ids.map(async commentId => { const res = await axios.get(`${HACKER_NEWS_ITEM_URI}${commentId}.json`) const { id, by, text, kids, time } = res.data return { id, author: by, text, hasKids: !!kids, creationDate: time, } }) } // ================ const resolverMap = { Query: { user, topStories, storyComments: comments, }, Story: { comments }, Comment: { comments }, } // ================ module.exports = resolverMap
JavaScript
0
@@ -215,16 +215,340 @@ item/'%0A%0A +// helpers ========%0Aconst fetchData = async url =%3E %7B%0A let res%0A try %7B%0A res = await axios.get(url)%0A %7D catch (error) %7B%0A if (error.code === 'ETIMEDOUT') %7B%0A try %7B%0A res = await axios.get(url)%0A %7D catch (error) %7B%0A throw new Error(error)%0A %7D%0A %7D else throw new Error(error)%0A %7D%0A return res%0A%7D%0A%0A // handl @@ -584,17 +584,20 @@ tValue, -_ +args , %7B user @@ -792,25 +792,25 @@ = await -axios.get +fetchData (HACKER_ @@ -1019,33 +1019,33 @@ res = await -axios.get +fetchData (%60$%7BHACKER_N @@ -1505,33 +1505,33 @@ res = await -axios.get +fetchData (%60$%7BHACKER_N @@ -1673,25 +1673,25 @@ = await -axios.get +fetchData (%60$%7BHACK
534176bab84ae668dd9b394464c09f7e5ca091bf
update tests according to #16
packages/svg-baker-runtime/test/utils.test.js
packages/svg-baker-runtime/test/utils.test.js
/* eslint-disable max-len */ import { parse, stringify, wrapInSvgString, updateUrls, selectAttributes, objectToAttrsString, dispatchCustomEvent, getUrlWithoutFragment, moveGradientsOutsideSymbol } from '../src/utils'; function wrapInSvgAndParse(content) { return parse(wrapInSvgString(content)); } function createTestFactory(func) { return ({ input, expected, args, selector, wrap = true }) => { const doc = typeof input === 'string' ? parse(wrap ? wrapInSvgString(input) : input) : input; const nodes = selector ? doc.querySelectorAll(selector) : doc; const opts = [nodes].concat(args || []); func(...opts); const ex = wrap ? wrapInSvgString(expected) : expected; const actual = stringify(doc); if (ex !== actual) { const err = new Error('Expected !== actual'); err.expected = ex; err.actual = actual; err.showDiff = true; throw err; } // stringify(doc).should.be.equal(ex); }; } describe('svg-baker-runtime/utils', () => { describe('dispatchCustomEvent()', () => { it('should dispatch', (done) => { const eventName = 'qwe'; const eventDetail = { a: 1, b: 2 }; window.addEventListener(eventName, (e) => { e.detail.should.be.deep.equal(eventDetail); done(); }); dispatchCustomEvent(eventName, eventDetail); }); }); describe('getUrlWithoutFragment()', () => { it('should work', () => { getUrlWithoutFragment('http://www.example.com/#qwe') .should.be.equal('http://www.example.com/'); }); it('should return current URL if no arg provided', () => { window.location.hash = '#qwe'; getUrlWithoutFragment().should.be.equal(window.location.href.split('#')[0]); window.location.hash = ''; }); }); describe('moveGradientsOutsideSymbol()', () => { const test = createTestFactory(moveGradientsOutsideSymbol); it('should work', () => { test({ input: '<defs><symbol><pattern></pattern></symbol></defs>', expected: '<defs><pattern></pattern><symbol></symbol></defs>' }); }); it('should support custom selector', () => { test({ input: '<defs><symbol><mask /><pattern></pattern></symbol></defs>', expected: '<defs><mask></mask><symbol><pattern></pattern></symbol></defs>', args: ['mask'] }); }); }); describe('objectToAttrString()', () => { it('should properly serialize object to attributes string', () => { objectToAttrsString({ fill: 'url("#id")', styles: 'color: #f0f' }) .should.be.equal('fill="url(&quot;#id&quot;)" styles="color: #f0f"'); }); }); describe('parse()', () => { it('should return Element instance', () => { parse(wrapInSvgString('<path/>')).should.be.instanceOf(Element); }); }); describe('selectAttributes()', () => { it('should work', () => { const doc = wrapInSvgAndParse('<path d="" class="q" fill="red" />'); const result = selectAttributes(doc.querySelectorAll('path'), ({ value }) => value === 'red'); result.should.be.lengthOf(1); result[0].value.should.be.equal('red'); }); }); describe('stringify()', () => { it('should properly serialize DOM nodes', () => { let input; input = wrapInSvgString('<defs><symbol id="foo"></symbol></defs><use xlink:href="#foo"></use>'); stringify(parse(input)).should.be.equal(input); input = wrapInSvgString('<path id="p1"></path><path id="p2"></path><path id="p3"></path>'); stringify(parse(input)).should.be.equal(input); }); }); describe('updateUrls()', () => { const test = createTestFactory(updateUrls); it('should replace URLs in attributes and references', () => { const input = '<linearGradient id="id"></linearGradient><path fill="url(#id)" style="fill:url(#id);"></path><use xlink:href="#id"></use>'; const expected = '<linearGradient id="id"></linearGradient><path fill="url(/prefix#id)" style="fill:url(/prefix#id);"></path><use xlink:href="/prefix#id"></use>'; const doc = wrapInSvgAndParse(input); test({ input: doc, expected, args: [ doc.querySelectorAll('use'), '#', '/prefix#' ] }); }); it('should not modify non matched attributes and references', () => { const input = '<linearGradient id="id"></linearGradient><path fill="url(#id)" style="fill:url(#id);"></path><use xlink:href="#id"></use>'; const doc = wrapInSvgAndParse(input); test({ input: doc, expected: input, args: [ doc.querySelectorAll('use'), '#qwe', '/prefix#qwe' ] }); }); it('should handle special chars properly', () => { const input = '<linearGradient id="id"></linearGradient><path fill="url(#id)" style="fill:url(#id);"></path><use xlink:href="#id"></use>'; const expected = '<linearGradient id="id"></linearGradient><path fill="url(inbox/33%28popup:compose%29#id)" style="fill:url(inbox/33%28popup:compose%29#id);"></path><use xlink:href="inbox/33%28popup:compose%29#id"></use>'; const doc = wrapInSvgAndParse(input); test({ input: doc, expected, args: [ doc.querySelectorAll('use'), '#', 'inbox/33(popup:compose)#' ] }); }); }); });
JavaScript
0.000001
@@ -5046,35 +5046,33 @@ ll=%22url(inbox/33 -%2528 +( popup:compose%2529 @@ -5064,27 +5064,37 @@ opup:compose -%2529 +)?q=123%257B%257D #id)%22 style= @@ -5103,35 +5103,33 @@ ill:url(inbox/33 -%2528 +( popup:compose%2529 @@ -5125,19 +5125,29 @@ :compose -%2529 +)?q=123%257B%257D #id);%22%3E%3C @@ -5181,11 +5181,9 @@ x/33 -%2528 +( popu @@ -5195,11 +5195,21 @@ pose -%2529 +)?q=123%257B%257D #id%22 @@ -5418,16 +5418,24 @@ compose) +?q=123%7B%7D #'%0A
206843b91961f72aeab0c52ba3174953f0573269
Allows spaces between commands
dist/index.js
dist/index.js
'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.parseText = exports.parseFile = exports.parseStream = exports.GCodeParser = undefined; var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _stream = require('stream'); var _stream2 = _interopRequireDefault(_stream); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var streamify = function streamify(text) { var s = new _stream2.default.Readable(); s.push(text); s.push(null); return s; }; var stripComments = function stripComments(s) { var re1 = /^\s+|\s+$/g; // Strip leading and trailing spaces var re2 = /\s*[#;].*$/g; // Strip everything after # or ; to the end of the line, including preceding spaces return s.replace(re1, '').replace(re2, ''); }; var GCodeParser = (function (_Transform) { _inherits(GCodeParser, _Transform); function GCodeParser(options) { _classCallCheck(this, GCodeParser); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(GCodeParser).call(this, _lodash2.default.extend({}, options, { objectMode: true }))); _this.options = options || {}; return _this; } _createClass(GCodeParser, [{ key: '_transform', value: function _transform(chunk, encoding, next) { var _this2 = this; // decode binary chunks as UTF-8 encoding = encoding || 'utf8'; if (Buffer.isBuffer(chunk)) { if (encoding === 'buffer') { encoding = 'utf8'; } chunk = chunk.toString(encoding); } var lines = chunk.split(/\r\n|\r|\n/g); _lodash2.default.each(lines, function (line) { line = _lodash2.default.trim(stripComments(line)) || ''; if (line.length === 0) { return; } var n = undefined; var words = []; var list = line.match(/([a-zA-Z][^\s]*)/igm) || []; _lodash2.default.each(list, function (word) { var r = word.match(/([a-zA-Z])([^\s]*)/) || []; var letter = (r[1] || '').toUpperCase(); var argument = _lodash2.default.isNaN(parseFloat(r[2])) ? r[2] : Number(r[2]); if (letter === 'N' && typeof n === 'undefined') { // Line (block) number in program n = Number(argument); return; } words.push([letter, argument]); }); _this2.push({ line: line, N: n, words: words }); }); next(); } }, { key: '_flush', value: function _flush(done) { done(); } }]); return GCodeParser; })(_stream.Transform); var parseStream = function parseStream(stream, callback) { var results = []; callback = callback || function (err) {}; try { stream.pipe(new GCodeParser()).on('data', function (data) { results.push(data); }).on('end', function () { callback(null, results); }).on('error', callback); } catch (err) { callback(err); return; } return stream; }; var parseFile = function parseFile(file, callback) { file = file || ''; var s = _fs2.default.createReadStream(file, { encoding: 'utf8' }); s.on('error', callback); return parseStream(s, callback); }; var parseText = function parseText(text, callback) { var s = streamify(text); return parseStream(s, callback); }; exports.GCodeParser = GCodeParser; exports.parseStream = parseStream; exports.parseFile = parseFile; exports.parseText = parseText;
JavaScript
0.892042
@@ -2378,24 +2378,108 @@ 2, '');%0A%7D;%0A%0A +var removeSpaces = function removeSpaces(s) %7B%0A return s.replace(/%5Cs+/g, '');%0A%7D;%0A%0A var GCodePar @@ -3487,22 +3487,16 @@ s(line)) - %7C%7C '' ;%0A @@ -3671,20 +3671,34 @@ list = +removeSpaces( line +) .match(/ @@ -3708,18 +3708,22 @@ -zA-Z%5D%5B%5E -%5Cs +a-zA-Z %5D*)/igm) @@ -3845,18 +3845,22 @@ A-Z%5D)(%5B%5E -%5Cs +a-zA-Z %5D*)/) %7C%7C @@ -4737,30 +4737,8 @@ ) %7B%0A - var results = %5B%5D;%0A @@ -4775,24 +4775,25 @@ n (err) %7B%7D;%0A +%0A try %7B%0A @@ -4790,16 +4790,73 @@ try %7B%0A + (function () %7B%0A var results = %5B%5D;%0A @@ -4927,16 +4927,20 @@ + results. @@ -4951,16 +4951,20 @@ (data);%0A + @@ -4994,32 +4994,36 @@ ) %7B%0A + + callback(null, r @@ -5031,32 +5031,36 @@ sults);%0A + + %7D).on('error', c @@ -5065,24 +5065,38 @@ callback);%0A + %7D)();%0A %7D catch
c3616218aabb1055d0e7da592c3840724a097b51
Add Array `findIndex` support
app/assets/javascripts/commons/polyfills.js
app/assets/javascripts/commons/polyfills.js
// ECMAScript polyfills import 'core-js/fn/array/find'; import 'core-js/fn/array/from'; import 'core-js/fn/array/includes'; import 'core-js/fn/object/assign'; import 'core-js/fn/promise'; import 'core-js/fn/string/code-point-at'; import 'core-js/fn/string/from-code-point'; import 'core-js/fn/symbol'; // Browser polyfills import './polyfills/custom_event'; import './polyfills/element';
JavaScript
0
@@ -49,16 +49,54 @@ /find';%0A +import 'core-js/fn/array/find-index';%0A import '
054f3574bb0c1b51791fa03804aa5729a7f642f2
Fix iphone xr rendering issue
scripts/apply_fixes.js
scripts/apply_fixes.js
/* Usage: npm run-script apply-fixes */ const fs = require('fs') // Fix an issue with Android default text color const TEXT_FIX_PATH = './node_modules/react-native/Libraries/Text/Text.js' const TEXT_ERR = 'if \\(this.context.isInAParentText\\)' const TEXT_FIX = 'newProps = {...newProps, style: [{color: \'black\'}, this.props.style] }\n if (this.context.isInAParentText)' const makeReplacements = (FILE_PATH, REPLACEMENTS) => { fs.readFile(FILE_PATH, 'utf8', (readErr, data) => { if (readErr) { return console.log(readErr) } else { for (let i = 0; REPLACEMENTS.length > i; i++) { data = data.replace(new RegExp(REPLACEMENTS[i].initial, 'g'), REPLACEMENTS[i].fixed) } fs.writeFile(FILE_PATH, data, 'utf8', (writeErr) => { if (writeErr) { return console.log(writeErr) } else { console.log('SUCCESS: File ' + FILE_PATH + ' updated with fixed value.') } }) } }) } makeReplacements(TEXT_FIX_PATH, [ { initial: TEXT_ERR, fixed: TEXT_FIX } ])
JavaScript
0.000001
@@ -373,16 +373,552 @@ Text)'%0A%0A +// Set correct safe area for iPhone XR%0Aconst XR_FIX_PATH = './node_modules/react-native-safe-area-view/index.js'%0Aconst XR_FIX_REPL1 = 'const X_HEIGHT = 812;'%0Aconst XR_FIX_REPL1_FIX = 'const X_HEIGHT = 812;const XSMAX_WIDTH = 414;const XSMAX_HEIGHT = 896;'%0Aconst XR_FIX_REPL2 = '%5C%5C(D_HEIGHT === X_WIDTH && D_WIDTH === X_HEIGHT%5C%5C)%5C%5C)'%0Aconst XR_FIX_REPL2_FIX = '%5C(D_HEIGHT === X_WIDTH && D_WIDTH === X_HEIGHT%5C)%5C) %7C%7C %5C(%5C(D_HEIGHT === XSMAX_HEIGHT && D_WIDTH === XSMAX_WIDTH%5C) %7C%7C %5C(D_HEIGHT === XSMAX_WIDTH && D_WIDTH === XSMAX_HEIGHT%5C)%5C)'%0A%0A const ma @@ -1525,8 +1525,149 @@ IX %7D%0A%5D)%0A +%0AmakeReplacements(XR_FIX_PATH, %5B%0A%09%7B initial: XR_FIX_REPL1, fixed: XR_FIX_REPL1_FIX %7D,%0A%09%7B initial: XR_FIX_REPL2, fixed: XR_FIX_REPL2_FIX %7D%0A%5D)%0A
40dbe9a97b628b494d1c23a4df0b78160c13222e
Update __name__.js helper blueprint to remove unnecessary semicolon.
blueprints/helper/files/app/helpers/__name__.js
blueprints/helper/files/app/helpers/__name__.js
import Ember from 'ember'; export function <%= camelizedModuleName %>(input) { return input; }; export default Ember.Handlebars.makeBoundHelper(<%= camelizedModuleName %>);
JavaScript
0.000001
@@ -90,17 +90,16 @@ input;%0A%7D -; %0A%0Aexport
3856d65b4143ee1d64f2a08527fcfa200378804b
Change packaging name
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var electronPackager = require('electron-packager'); var appVersion = require('./package.json').version; var platform = process.platform; var packagePaths = undefined; var defaultOptions = { 'dir': '.', 'arch': 'x64', 'name': 'frontend-builder', 'platform': platform, 'version': '0.36.10', 'asar': true, 'out': 'dist', 'ignore': 'dist', 'overwrite': true, 'app-version': appVersion }; var variations = { darwin: { 'asar': false, 'icon': 'app/icon/icon.icns', 'app-category-type': 'public.app-category.developer-tools' }, linux: {}, win32: { 'arch': 'all', 'icon': 'app/icon/icon.ico' } }; gulp.task('build:packaging', function (done) { electronPackager(Object.assign(defaultOptions, variations[platform]), function (err, result) { packagePaths = result; done(err); }); }); gulp.task('build:darwin', ['build:packaging'], function (done) { done(); }); gulp.task('build:linux', ['build:packaging'], function () { return gulp.src('app/icon/icon.png') .pipe(gulp.dest(packagePaths + '/resources')); }); gulp.task('build:win32', ['build:packaging'], function (done) { done(); }); gulp.task('build', ['build:' + platform]);
JavaScript
0.000002
@@ -78,26 +78,30 @@ ');%0Avar -appVersion +projectPackage = requi @@ -124,16 +124,8 @@ on') -.version ;%0A%0Av @@ -251,26 +251,27 @@ e': -'frontend-builder' +projectPackage.name ,%0A%09' @@ -404,12 +404,24 @@ n': -appV +projectPackage.v ersi
f21b87cb7155d72880c6b464c8425bbe6ba3195b
Update strategy.js
lib/passport-vkontakte/strategy.js
lib/passport-vkontakte/strategy.js
/** * Module dependencies. */ var parse = require('./profile').parse , util = require('util') , url = require('url') , OAuth2Strategy = require('passport-oauth2') , InternalOAuthError = require('passport-oauth2').InternalOAuthError , VkontakteAuthorizationError = require('./errors/vkontakteauthorizationerror') , VkontakteTokenError = require('./errors/vkontaktetokenerror') , VkontakteAPIError = require('./errors/vkontakteapierror'); /** * `Strategy` constructor. * * The VK.com authentication strategy authenticates requests by delegating to * VK.com using the OAuth 2.0 protocol. * * Applications must supply a `verify` callback which accepts an `accessToken`, * `refreshToken` and service-specific `profile`, and then calls the `done` * callback supplying a `user`, which should be set to `false` if the * credentials are not valid. If an exception occured, `err` should be set. * * Options: * - `clientID` your VK.com application's App ID * - `clientSecret` your VK.com application's App Secret * - `callbackURL` URL to which VK.com will redirect the user after granting authorization * - `profileFields` array of fields to retrieve from VK.com * - `apiVersion` version of VK API to use * * Examples: * * passport.use(new VKontakteStrategy({ * clientID: '123-456-789', * clientSecret: 'shhh-its-a-secret' * callbackURL: 'https://www.example.net/auth/facebook/callback' * }, * function(accessToken, refreshToken, profile, done) { * User.findOrCreate(..., function (err, user) { * done(err, user); * }); * } * )); * * @param {Object} options * @param {Function} verify * @api public */ function Strategy(options, verify) { options = options || {}; options.authorizationURL = options.authorizationURL || 'https://oauth.vk.com/authorize'; options.tokenURL = options.tokenURL || 'https://oauth.vk.com/access_token'; options.scopeSeparator = options.scopeSeparator || ','; OAuth2Strategy.call(this, options, verify); this.name = 'vkontakte'; this._profileURL = options.profileURL || 'https://api.vk.com/method/users.get'; this._profileFields = options.profileFields || []; this._apiVersion = options.apiVersion || '5.0'; this._https = options.https || 0; } /** * Inherit from `OAuth2Strategy`. */ util.inherits(Strategy, OAuth2Strategy); /** * Authenticate request by delegating to a service provider using OAuth 2.0. * * Since VK.com API is brain-dead and doesn't allow getting user info just * by its OAuth access token, this method uses a hack around this limitation. * * @param {Object} req * @api protected */ Strategy.prototype.authenticate = function(req, options) { options = options || {}; if (req.query && req.query.error) { return this.error(new VkontakteAuthorizationError(req.query.error_description, req.query.error, req.query.error_reason)); } OAuth2Strategy.prototype.authenticate.call(this, req, options); }; /** * Return extra parameters to be included in the authorization request. * * Options: * - `display` Display mode to render dialog, { `page`, `popup`, `mobile` }. * * @param {Object} options * @return {Object} * @api protected */ Strategy.prototype.authorizationParams = function (options) { var params = {}; // http://vk.com/dev/auth_mobile if (options.display) { params.display = options.display; } return params; }; /** * Retrieve user profile from Vkontakte. * * This function constructs a normalized profile, with the following properties: * * - `provider` always set to `vkontakte` * - `id` the user's VK.com ID * - `displayName` the user's full name * - `name.familyName` the user's last name * - `name.givenName` the user's first name * - `gender` the user's gender: `male` or `female` * - `photos` array of `{ value: 'url' }` * * @param {String} accessToken * @param {Function} done * @api protected */ Strategy.prototype.userProfile = function(accessToken, done) { var url = this._profileURL; var fields = [ 'uid' , 'first_name' , 'last_name' , 'screen_name' , 'sex' , 'photo' ]; this._profileFields.forEach(function(f) { if (fields.indexOf(f) < 0) fields.push(f); }); url += '?fields=' + fields.join(',') + '&v='+this._apiVersion + '&https=' + this._https; this._oauth2.getProtectedResource(url, accessToken, function (err, body, res) { if (err) { return done(new InternalOAuthError('failed to fetch user profile', err)); } try { var json = JSON.parse(body); if (json.error) throw new VkontakteAPIError(json.error.error_msg, json.error.error_code); json = json.response[0]; var profile = parse(json); profile.provider = 'vkontakte'; profile._raw = body; profile._json = json; done(null, profile); } catch(e) { done(e); } }); } /** * Parse error response from Vkontakte OAuth 2.0 token endpoint. * * @param {String} body * @param {Number} status * @return {Error} * @api protected */ Strategy.prototype.parseErrorResponse = function(body, status) { var json = JSON.parse(body); if (json.error && typeof json.error == 'object') { return new VkontakteTokenError(json.error.error_msg, json.error.error_code); } return OAuth2Strategy.prototype.parseErrorResponse.call(this, body, status); }; /** * Expose `Strategy`. */ module.exports = Strategy;
JavaScript
0.000001
@@ -2281,17 +2281,18 @@ n %7C%7C '5. -0 +64 ';%0A thi
5168662c04347d705e55a94d9e0ee48d72e9b2e2
Reset modal btns on show
frontend/js/profile-updating.js
frontend/js/profile-updating.js
var toastr = require('toastr'); require('../libraries/jquery.cropit.js'); // profile modifications $('.js-profile-add-adult').on('click touchstart', function () { $.ajax({ 'type': 'GET', 'url': '/add/adults', 'cache': false }).then(function (data) { $('.js-profile-adult-container').append(data); }) }) $('.js-profile-add-children').on('click touchstart', function () { $.ajax({ 'type': 'GET', 'url': '/add/children', 'cache': false }).then(function (data) { $('.js-profile-children-container').append(data); }) }) $('.profile-container').on('click', '.js-remove-adult, .js-remove-child', function () { console.log("removing") $(this).closest('.js-option-existing').remove(); }) $(function () { $('[data-toggle="popover"]').popover() }) // profile completion function computeCompletion() { var total = 6; var found = 0; // at most +1 if ($('.js-children-pref input:checked').length) { found += 1; } if ($('.js-residence-about input[type="text"]:checked').length) { found += 1; } // at most +4 found += $('.js-residence-about input[type="text"]').filter(function () { return this.value.length > 0 }).length; // at most +1 if ($('.js-profile-children-container .js-option-existing').children().length) { found += 1; } // at most +1 if ($('.js-profile-adult-container .js-option-existing').children().length) { found += 1; } var completness = Math.min((found / total * 100).toFixed(0), 100); $('.js-profile-completeness').attr('aria-valuenow', completness).css("width", completness + "%").text(completness + "%") } computeCompletion(); // Avatar $(function () { var $imageCropper = $('.image-editor').cropit({ smallImage: 'stretch', maxZoom: 2, imageState: { // src: 'http://lorempixel.com/500/400/', }, onImageError: function () { toastr.error("Please use an image that's at least " + $(".cropit-image-preview").outerWidth() + "px in width and " + $(".cropit-image-preview").outerHeight() + "px in height."), $(".cropit-image-preview") $(".cropit-image-preview").removeClass("has-error") } }); $('.js-avatar-update').on('click touchstart', function () { $("#avataredit .modal-footer button").addClass("hidden"); $("#avataredit #avatar_loading_msg").fadeIn(); // have to use formData inorder for multi-part to work var data = new FormData(); if ($imageCropper.cropit('imageSrc').trim() == '') { toastr.error('Choose Image first') return; } data.append('avatar', $('.image-editor').cropit('export')); var update = $.ajax({ 'type': 'POST', contentType: false, processData: false, data: data, 'url': '/avatar', 'cache': false, }) update.then(function () { // Display a success toast, with a title toastr.info('Avatar Updated') window.setTimeout(function () { location.reload(); }, 2000); }) }); $('.js-avatar-delete').on('click touchstart', function(){ $("#avataredit .modal-footer button").addClass("hidden"); $("#avataredit #avatar_loading_msg").fadeIn(); var deletePromise = $.ajax({ 'type': 'DELETE', 'url': '/avatar', 'cache': false }) deletePromise.then(function () { // Display a success toast, with a title toastr.info('Avatar Deleted'); window.setTimeout(function(){ location.reload(); },1000); }) }); }); $('#updateprofile').on('submit', function (e) { e.preventDefault(); $.ajax({ 'type': 'POST', 'url': 'ajaxupdate', data: $(this).serialize(), 'cache': false }).then(function (data) { toastr.success("Profile Updated"); }) }); $('.profile-container').on('click', '.js-profile-editing-cancel', function(e){ e.preventDefault(); e.stopPropagation(); $(this).closest('.profile-editing-info').remove(); })
JavaScript
0
@@ -4344,21 +4344,219 @@ -info').remove();%0A%7D) +;%0A%0A$('#avataredit').on('show.bs.modal', function (event) %7B%0A console.log(%22123%22);%0A $(%22#avataredit .modal-footer button%22).removeClass(%22hidden%22);%0A $(%22#avataredit #avatar_loading_msg%22).hide();%0A%7D); %0A
e5c8a47cbb39dddb0855c1ddfa505f083fff0c78
fix monaco editor config to ensure service workers are not loaded from cross-domain origins
app/assets/javascripts/ide/monaco_loader.js
app/assets/javascripts/ide/monaco_loader.js
import monacoContext from 'monaco-editor/dev/vs/loader'; monacoContext.require.config({ paths: { vs: `${__webpack_public_path__}monaco-editor/vs`, // eslint-disable-line camelcase }, }); // eslint-disable-next-line no-underscore-dangle window.__monaco_context__ = monacoContext; export default monacoContext.require;
JavaScript
0
@@ -190,16 +190,343 @@ %7D,%0A%7D);%0A%0A +// ignore CDN config and use local assets path for service worker which cannot be cross-domain%0Aconst relativeRootPath = (gon && gon.relative_url_root) %7C%7C '';%0Aconst monacoPath = %60$%7BrelativeRootPath%7D/assets/webpack/monaco-editor/vs%60;%0Awindow.MonacoEnvironment = %7B getWorkerUrl: () =%3E %60$%7BmonacoPath%7D/base/worker/workerMain.js%60 %7D;%0A%0A // eslin
c119c1bd45d1f8eb0d2925bfcbff71e0841f065e
fix database name in createUser (#2998)
mongosrc.js
mongosrc.js
use dashboarddb db.createUser( { user: "dashboarduser", pwd: "1qazxSw2", roles: [ {role: "readWrite", db: "dashboard"} ] }) db.dummmyCollection.insert({x: 1});
JavaScript
0
@@ -149,16 +149,18 @@ ashboard +db %22%7D%0A
d47c22db1669fc487f56ae626f9aeb9afdf3d759
Add space to title variable in Javascript
scripts/ariaCurrent.js
scripts/ariaCurrent.js
function setAriaCurrent() { var title = document.title; if title== "Comunidad hispanohablante de NVDA" { var id = "inicio" } document.getElementById(id).removeAttribute("accesskey"); document.getElementById(id).setAttribute("aria-current", "page"); } setAriaCurrent();
JavaScript
0.000011
@@ -96,16 +96,17 @@ de NVDA + %22 %7B%0A%09%09va
6f85de4ff92f28859957276d2fa392a418af4429
Replace mnemonic require with a relative one
packages/truffle-core/lib/commands/develop.js
packages/truffle-core/lib/commands/develop.js
const emoji = require("node-emoji"); const mnemonicInfo = require("truffle-core/lib/mnemonics/mnemonic"); const command = { command: "develop", description: "Open a console with a local development blockchain", builder: { log: { type: "boolean", default: false } }, help: { usage: "truffle develop", options: [] }, runConsole: (config, ganacheOptions, done) => { const Console = require("../console"); const { Environment } = require("truffle-environment"); const commands = require("./index"); const excluded = ["console", "develop", "unbox", "init"]; const availableCommands = Object.keys(commands).filter( name => !excluded.includes(name) ); const consoleCommands = availableCommands.reduce( (acc, name) => Object.assign({}, acc, { [name]: commands[name] }), {} ); Environment.develop(config, ganacheOptions) .then(() => { const c = new Console( consoleCommands, config.with({ noAliases: true }) ); c.start(done); c.on("exit", () => process.exit()); }) .catch(err => done(err)); }, run: (options, done) => { const Config = require("truffle-config"); const { Develop } = require("truffle-environment"); const config = Config.detect(options); const customConfig = config.networks.develop || {}; const { mnemonic, accounts, privateKeys } = mnemonicInfo.getAccountsInfo( customConfig.accounts || 10 ); const onMissing = () => "**"; const warning = ":warning: Important :warning: : " + "This mnemonic was created for you by Truffle. It is not secure.\n" + "Ensure you do not use it on production blockchains, or else you risk losing funds."; const ipcOptions = { log: options.log }; const ganacheOptions = { host: customConfig.host || "127.0.0.1", port: customConfig.port || 9545, network_id: customConfig.network_id || 5777, total_accounts: customConfig.accounts || 10, default_balance_ether: customConfig.defaultEtherBalance || 100, blockTime: customConfig.blockTime || 0, fork: customConfig.fork, mnemonic, gasLimit: customConfig.gas || 0x6691b7, gasPrice: customConfig.gasPrice || 0x77359400, noVMErrorsOnRPCResponse: true }; if (customConfig.hardfork !== null && customConfig.hardfork !== undefined) { ganacheOptions["hardfork"] = customConfig.hardfork; } function sanitizeNetworkID(network_id) { if (network_id !== "*") { if (!parseInt(network_id, 10)) { const error = `The network id specified in the truffle config ` + `(${network_id}) is not valid. Please properly configure the network id as an integer value.`; throw new Error(error); } return network_id; } else { // We have a "*" network. Return the default. return 5777; } } ganacheOptions.network_id = sanitizeNetworkID(ganacheOptions.network_id); Develop.connectOrStart(ipcOptions, ganacheOptions, started => { const url = `http://${ganacheOptions.host}:${ganacheOptions.port}/`; if (started) { config.logger.log(`Truffle Develop started at ${url}`); config.logger.log(); config.logger.log(`Accounts:`); accounts.forEach((acct, idx) => config.logger.log(`(${idx}) ${acct}`)); config.logger.log(); config.logger.log(`Private Keys:`); privateKeys.forEach((key, idx) => config.logger.log(`(${idx}) ${key}`)); config.logger.log(); config.logger.log(`Mnemonic: ${mnemonic}`); config.logger.log(); config.logger.log(emoji.emojify(warning, onMissing)); config.logger.log(); } else { config.logger.log( `Connected to existing Truffle Develop session at ${url}` ); config.logger.log(); } if (!options.log) { command.runConsole(config, ganacheOptions, done); } }); } }; module.exports = command;
JavaScript
0.999798
@@ -64,24 +64,10 @@ re(%22 -truffle-core/lib +.. /mne
12157b5c2f8354986dc2bfbdd3e527fef97e1677
change :checked to prop
app/geobox/web/static/js/widgets/thematicalvector.js
app/geobox/web/static/js/widgets/thematicalvector.js
var thematicalVectorLabels = { 'legend': OpenLayers.i18n('Legend'), 'settings': OpenLayers.i18n('Settings'), 'active': OpenLayers.i18n('Active'), 'list': OpenLayers.i18n('List') } gbi.widgets = gbi.widgets || {}; gbi.widgets.ThematicalVector = function(editor, options) { var self = this; var defaults = { "element": "thematical-vector", "changeAttributes": true, "components": { configurator: true, legend: true, list: true } }; self.options = $.extend({}, defaults, options); self.element = $('#' + self.options.element); self.editor = editor; self.activeLayer = self.editor.layerManager.active(); self.active = false; $(gbi).on('gbi.layermanager.layer.active', function(event, layer) { if(layer != self.activeLayer) { if(self.activeLayer) { self.activeLayer.deactivateHover(); self.activeLayer.deactivateFeatureStylingRule(); } self.activeLayer = layer; self.active = false; self.render(); } }); self.components = {}; if(self.options.components.list) { self.components["list"] = new gbi.widgets.ThematicalVectorAttributeList(self, { 'element': 'thematical-feature-list', featurePopup: 'hover', initOnly: true }); } if(self.options.components.configurator) { self.components["configurator"] = new gbi.widgets.ThematicalVectorConfigurator(self, { 'element': 'thematical-settings-element', initOnly: true }); } if(self.options.components.legend) { if(self.options.changeAttributes) { self.components["legend"] = new gbi.widgets.ThematicalVectorLegendChangeAttributes(self, { 'element': 'thematical-legend-element', 'featureList': self.components.list, initOnly: true }); } else { self.components["legend"] = new gbi.widgets.ThematicalVectorLegend(self, { 'element': 'thematical-legend-element', 'featureList': self.components.list, initOnly: true }); } } self.render(); }; gbi.widgets.ThematicalVector.prototype = { CLASS_NAME: 'gbi.widgets.ThematicalVectorConfigurator', render: function() { var self = this; self.element.empty(); self.element.append(tmpl(gbi.widgets.ThematicalVector.template, {active: self.active})); $.each(self.components, function(name, component) { component.render(); }); self.element.find('#tabs a').click(function (e) { e.preventDefault(); $(self).tab('show'); }); self.element.find('#thematical-map-active').change(function() { self.active = $(this).is(':checked'); if(self.activeLayer) { if(self.active) { self.activeLayer.activateFeatureStylingRule(); self.activeLayer.activateHover(); } else { self.activeLayer.deactivateFeatureStylingRule(); self.activeLayer.deactivateHover(); } } self.render(); }); }, showListView: function() { $('#thematical-list-tab').tab('show'); }, showSettings: function() { $('#thematical-settings-tab').tab('show'); } }; gbi.widgets.ThematicalVector.template = '\ <label for="thematical-map-active" class="checkbox">\ <input type="checkbox" <% if(active) {%>checked="checked"<% } %> id="thematical-map-active" />\ ' + thematicalVectorLabels.active + '\ </label>\ <% if(active) { %>\ <ul id="tabs" class="nav nav-tabs">\ <li class="active">\ <a href="#thematical-legend" id="thematical-legend-tab" data-toggle="tab">' + thematicalVectorLabels.legend + '</a>\ </li>\ <li>\ <a href="#thematical-list" id="thematical-list-tab" data-toggle="tab">' + thematicalVectorLabels.list + '</a>\ </li>\ <li>\ <a href="#thematical-settings" id="thematical-settings-tab" data-toggle="tab">' + thematicalVectorLabels.settings + '</a>\ </li>\ </ul>\ <div class="tab-content">\ <div class="tab-pane fade in active" id="thematical-legend">\ <h4>' + thematicalVectorLabels.legend + '</h4>\ <div id="thematical-legend-element"></div>\ </div>\ <div class="tab-pane fade" id="thematical-list">\ <h4>' + thematicalVectorLabels.list + '</h4>\ <div id="thematical-feature-list"></div>\ </div>\ <div class="tab-pane fade" id="thematical-settings">\ <div id="thematical-settings-element"></div>\ </div>\ </div>\ <% } %>\ ';
JavaScript
0
@@ -2925,13 +2925,14 @@ is). -is +prop (' -: chec
a5404c02c68d55f1fc55d243b198d10be47c9f1a
revert back to the old hotline
bot/modules/hotline.js
bot/modules/hotline.js
var bot = require('../bot'); const m2e = require('./../lib/message2embed'); let messageDB = { data: [] }; bot.on('message', message => { if (message.author.bot == true) return; // prevent loop let attach = ''; if (message.attachments.size > 0) { attach = message.attachments.first().url; } if (message.channel.id == '271350052188979201') { bot.channels.get('271349742099759104').send(attach, { embed: m2e(message, true) }) .then(msg => messageDB.data.push({ oldMessage: message.id, newMessage: msg.id, channel: msg.channel.id })); } else if (message.channel.id == '271349742099759104') { bot.channels.get('271350052188979201').send(attach, { embed: m2e(message, true) }) .then(msg => messageDB.data.push({ oldMessage: message.id, newMessage: msg.id, channel: msg.channel.id })); } }); bot.on('messageUpdate', (oldMessage, newMessage) => { if (newMessage.author.bot == true) return; // prevent double messages console.log("executing"); let attach = ''; if (newMessage.attachments.size > 0) { attach = newMessage.attachments.first().url; } let m = messageDB.data.find(function (messageObj) { if (messageObj.oldMessage === oldMessage.id) return messageObj; }); if (m) { //console.log(m); bot.channels.get(m.channel).fetchMessage(m.newMessage).edit(attach, { files: [attach], embed: m2e(newMessage, true) });; } }); bot.on('messageDelete', message => { if (message.author.bot == true) return; // prevent double messages console.log("executing"); let m = messageDB.data.find(function (messageObj) { if (messageObj.oldMessage === message.id) return messageObj; }); if (m) { //console.log(m); bot.channels.get(m.channel).fetchMessage(m.newMessage).then(msg => msg.delete()).then(messageDB.data.splice(messageDB.data.indexOf(m), 1)).catch(console.log); } });
JavaScript
0.000001
@@ -26,55 +26,8 @@ ');%0A -const m2e = require('./../lib/message2embed');%0A let @@ -216,16 +216,23 @@ attach = + '%5Cn' + message @@ -368,46 +368,87 @@ send -(attach, %7B embed: m2e(message, true) %7D +Message(%22**%22 + message.author.username + %22:** %22 + message.cleanContent + attach )%0A @@ -681,46 +681,87 @@ send -(attach, %7B embed: m2e(message, true) %7D +Message(%22**%22 + message.author.username + %22:** %22 + message.cleanContent + attach )%0A @@ -1122,16 +1122,23 @@ attach = + '%5Cn' + newMess @@ -1427,67 +1427,86 @@ dit( -attach, %7B files: %5Battach%5D, embed: m2e(newMessage, true) %7D); +%22**%22 + oldMessage.author.username + %22:** %22 + newMessage.cleanContent + attach) ;%0A @@ -2012,9 +2012,8 @@ %7D%0A%7D);%0A -%0A
a867e051e3eae976f59ccd86b98894304a5ba900
check instance cache before loading the composition
lib/client/engine.js
lib/client/engine.js
var Flow = require('./flow'); var Instance = require('./instance'); // client flag engine.client = true; // extend engine with flow emitter engine = Flow(engine); // listen to core engine events engine.mind('C', {call: '@/C'}).mind('M', {call: '@/M'}); // data handlers engine.handlers = { transform: require('./transform') }; /** * Create server module instances */ engine.load = function (name, callback) { // ensure callback callback = callback || function () {}; // get composition engine.flow('C').data(function (err, composition) { if (err) { return callback(err); } // require module require(composition.module, function (module) { if (err) { return callback(err); } // create instance Instance(module, composition, callback); }); }).write(null, name); }; /** * Empties all caches and reloads the modules. * * @public * @param {boolean} Don't remove the DOM nodes. * @todo be aware of memory leaks */ engine.reload = function (keepDom) { // .. }; // load entrypoint engine.load();
JavaScript
0
@@ -486,24 +486,153 @@ () %7B%7D;%0A %0A + // check instance chache%0A if (engine.instances%5Bname%5D) %7B%0A return callback(null, engine.instances%5Bname%5D);%0A %7D%0A %0A // get c
91ff16f9e795e5e2b3a5f0b53b88fa5bd5adba80
update AdditionalInputInfo component to fix propTypes error
storybook-utilities/components/AdditionalInputInfo.js
storybook-utilities/components/AdditionalInputInfo.js
import React from 'react'; import PropTypes from 'prop-types'; import SprkList from '../../react/src/base/lists/SprkList'; import SprkListItem from '../../react/src/base/lists/SprkListItem'; import { getStorybookInstance } from '../getStorybookInstance'; const AdditionalInputInfo = (props) => { const { additionalHeaderClasses, additionalListClasses, additionalListItemClasses, headerElement, listElement, listVariant, } = props; const storybookInstance = getStorybookInstance(); const isHTMLStorybook = (storybookInstance === 'html'); const TagName = headerElement; return ( <> <TagName className={additionalHeaderClasses} > Additional Input Information </TagName> <SprkList element={listElement} additionalClasses={additionalListClasses} variant={listVariant} > <SprkListItem additionalClasses={additionalListItemClasses} > By default, Spark does not provide validation or formatting. </SprkListItem> <SprkListItem additionalClasses={additionalListItemClasses} > Special characters used in formatting (like the hyphens in the SSN field) are not automatically removed from the field value and may need to be manually removed. </SprkListItem> <SprkListItem additionalClasses={additionalListItemClasses} > Each input element&apos;s id should be unique on the page. </SprkListItem> <SprkListItem additionalClasses={additionalListItemClasses} > The <code> type </code> attribute for an Input should be the most appropriate value that semantically matches your use case. </SprkListItem> <SprkListItem additionalClasses={additionalListItemClasses} > The <code> data-id </code> property is provided as a hook for automated tools. If you have multiple instances of the same variant of a component on the same page, make sure each instance has a unique <code> data-id </code> property (&quot;input-text-1&quot;, &quot;input-text-2&quot;, &quot;input-date-1&quot;, etc). </SprkListItem> {isHTMLStorybook && ( <> <SprkListItem additionalClasses={additionalListItemClasses} > In Vanilla JS applications, if an input is required only, meaning that no validation is needed aside from a value being supplied, you can add the <code> data-sprk-required-only </code> attribute to the input container. The values that are available are &apos;text&apos;, &apos;select&apos;, and &apos;tick&apos;. Text is for any input that accepts text as a value, Select is only for select inputs, and Tick is for radio buttons or checkboxes. </SprkListItem> <SprkListItem additionalClasses={additionalListItemClasses} > You should be providing your own validation for Inputs, not relying on the browser validation. Be sure to add the <code> novalidate </code> attribute to your form element to disable the browser implementation. </SprkListItem> <SprkListItem additionalClasses={additionalListItemClasses} > The Input Label <code> for </code> attribute must match the <code> id </code> attribute of the corresponding Input. </SprkListItem> <SprkListItem additionalClasses={additionalListItemClasses} > The value set in <code> aria-describedby </code> must match the <code> id </code> attribute on the error container. </SprkListItem> </> )} </SprkList> </> ); }; AdditionalInputInfo.defaultProps = { headerElement: 'h4', listElement: 'ul', }; AdditionalInputInfo.PropTypes = { /** * A space-separated string of classes to * add to the header. */ additionalHeaderClasses: PropTypes.string, /** * A space-separated string of classes to * add to the list. */ additionalListClasses: PropTypes.string, /** * A space-separated string of classes to * add to the list items. */ additionalListItemClasses: PropTypes.string, /** * Determines the type of header element * that will be rendered. */ headerElement: PropTypes.string, /** * Determines the type of header element * that will be rendered. */ listElement: PropTypes.oneOf(['ol', 'ul']), /** * Will cause the appropriate list variant * type to render. */ listVariant: PropTypes.oneOf(['indented', 'bare']), }; export default AdditionalInputInfo;
JavaScript
0
@@ -4277,17 +4277,17 @@ putInfo. -P +p ropTypes
ec10606a7e7012ed7f55df397a6f7910c6f2c096
change user agent regex to also catch iPad webapp mode
pics2pdf.js
pics2pdf.js
/* ======================================================================== * pics2pdf.js v1.0.5 * https://flesser.github.io/pics2pdf * ======================================================================== * Copyright 2015 Florian Eßer * * 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. * ======================================================================== */ function fitImage(img, maxLong, maxShort) { maxShort = maxShort || maxLong; if (img.width > img.height) { if (img.width <= maxLong && img.height <= maxShort) { // no resizing necessary return [img.width, img.height]; } var widthRatio = maxLong / img.width; var heightRatio = maxShort / img.height; } else { if (img.height <= maxLong && img.width <= maxShort) { // no resizing necessary return [img.width, img.height]; } var widthRatio = maxShort / img.width; var heightRatio = maxLong / img.height; } var resizeRatio = Math.min(widthRatio, heightRatio); return [img.width * resizeRatio, img.height * resizeRatio]; } /**********************************************************************************************************************/ function handleFileSelect(evt) { var files = evt.target.files; for (var i = 0; i < files.length; i++) { var f = files[i]; if (!f.type.match('image.*')) continue; var imageContainer = $('<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 center-block image-container"></div>'); var thumbnail = $('<div class="thumbnail text-center"></div>').appendTo(imageContainer); var buttons = $('<div class="image-overlay image-buttons"></div>').appendTo(thumbnail); thumbnail.append($('<p class="image-caption">' + f.name + '</p>')); thumbnail.spin(); var deleteButton = $('<button class="btn btn-danger image-button-remove">' + '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>' + ' remove</button>').appendTo(buttons); deleteButton.click(function() { $(this).parent().parent().parent().fadeOut('', function() { $(this).next('.clear').remove(); // remove clear helper $(this).remove(); // remove image if ($(".thumbnail").length == 0) { $('#pdfbutton').addClass('disabled'); $('#welcome').fadeIn(); } }); }); $('#image-row').append(imageContainer); $('#image-row').append($('<div class="clear"></div>')); thumbnail.data('filesize', f.size); var reader = new FileReader(); reader.onload = (function(thumbnail) { return function(e) { var img = document.createElement('img'); img.src = e.target.result; thumbnail.data('imagedata', e.target.result); img.onload = function() { var canvas = document.createElement('canvas'); var dimensions = fitImage(this, 500); canvas.width = dimensions[0]; canvas.height = dimensions[1]; canvas.getContext("2d").drawImage(this, 0, 0, canvas.width, canvas.height); var dataurl = canvas.toDataURL("image/jpeg"); thumbnail.children('.image-caption').addClass('image-overlay'); thumbnail.append($('<img class="img-responsive" src="' + dataurl + '" title="drag to reorder"/>')); thumbnail.spin(false); } delete this; }; })(thumbnail); reader.readAsDataURL(f); } // reset file input evt.target.value = null; var pageCount = $(".thumbnail").length; if (pageCount > 0) { $('#welcome').slideUp(); $('#pdfbutton').removeClass('disabled'); } $('#status-pagecount').text(pageCount + ' pages'); var totalSize = 0; $(".thumbnail").each(function() { totalSize += $(this).data('filesize'); }); totalSize /= 1024*1024; $('#status-filesize').text('ca. ' + totalSize.toFixed(1) + ' MB'); } /**********************************************************************************************************************/ function createPDF() { var dpi = 300; // TODO: maybe make this an option var pdf = jsPDF('l', 'in', 'a4'); pdf.deletePage(1); var title = $('#pdfTitle').val(); var filename = (title || 'output') + '.pdf'; pdf.setProperties({ title: title, subject: $('#pdfSubject').val(), author: $('#pdfAuthor').val(), creator: 'flesser.github.io/pics2pdf' }); var doResize = ($('input[name="resizeRadios"]:checked').val() == 1); if (doResize) { var maxSize = parseInt($('#maxImageSize').val()); if (!maxSize) { // TODO: maybe nicer looking error modal? alert('Invalid pixel value for image size reduction!\nPlease check again under "Edit PDF Options".'); return; } } var thumbnailCount = $(".thumbnail").length; $(".thumbnail").each(function(i) { var imageData = $(this).data('imagedata'); var img = document.createElement('img'); img.onload = function() { if (doResize) { var canvas = document.createElement('canvas'); var dimensions = fitImage(this, maxSize); canvas.width = dimensions[0]; canvas.height = dimensions[1]; canvas.getContext("2d").drawImage(this, 0, 0, canvas.width, canvas.height); imageData = canvas.toDataURL("image/jpeg"); } else { var dimensions = [this.width, this.height]; } var pageWidth = dimensions[0] / dpi; var pageHeight = dimensions[1] / dpi; pdf.addPage([pageWidth, pageHeight]); var imageFormat = imageData.substr(0, 16).split('/')[1].split(';')[0]; pdf.addImage(imageData, imageFormat, 0, 0, pageWidth, pageHeight); if (i == thumbnailCount - 1) { // last one: save PDF var isSafari = /^((?!chrome).)*safari/i.test(navigator.userAgent); if (isSafari) { // download doesn't work in Safari, see https://github.com/MrRio/jsPDF/issues/196 // open inline instead pdf.output('dataurl'); } else { // create a nice download with file name pdf.save(filename); } } } img.src = imageData; }); } /**********************************************************************************************************************/ $(document).ready(function() { $('#image-input').bind('change', handleFileSelect); $('#image-row').sortable({ items: "> .image-container", helper: 'clone', placeholder: 'col-xs-6 col-sm-4 col-md-3 col-lg-2 center-block image-container', start: function(e, ui) { // remove old clearfix helper ui.item.next().next('.clear').remove(); }, stop: function(e, ui) { // create new clearfix helper if(ui.item.prev('.clear').length > 0) { // dropped after clearfix helper --> create new one after ui.item.after($('<div class="clear"></div>')); } else if(ui.item.next('.clear').length > 0) { // dropped before clearfix helper --> create new one before ui.item.before($('<div class="clear"></div>')); } } }); $('#pdfbutton').click(function() { if (!$(this).hasClass('disabled')) { createPDF(); } }); });
JavaScript
0
@@ -6846,14 +6846,29 @@ ).)* +(( safari +)%7C(mobile%5C/)) /i.t
994ade980953520e4026bffd6c2172f40550e655
Add slight right margin to lists on mobile view
frontend/src/Lists/ListsView.js
frontend/src/Lists/ListsView.js
import React, { Component } from "react"; import { Row } from "../SharedComponents.js"; import Loading from "../loading.js"; import List from "./List.js"; import CreateList from "./CreateList.js"; import Notes from "./Notes.js"; class ListsView extends Component { render() { const { user, lists, loading } = this.props; if (loading) { return <Loading />; } return ( <MainContainer> <ListContainer numberOfLists={lists.length}> {lists.map((list, i) => ( <List key={list.id} list={list} user={user} inactive={i < lists.length - 1} /> ))} </ListContainer> {user.isAdmin && <CreateList />} <Notes /> </MainContainer> ); } } const ListContainer = Row.extend` margin-left: -${props => (props.numberOfLists - 2) * 20}em; align-self: ${props => (props.numberOfLists > 1 ? "flex-end" : "center")}; width: ${props => props.numberOfLists * 20}em; margin-bottom: 2em; transition: ${props => props.numberOfLists > 1 ? "all" : "margin-left"} 1000ms; `; const MainContainer = Row.extend` @media (min-width: 900px) { flex-direction: row; justify-content: space-around; } @media (max-width: 900px) { flex-direction: column; align-items: center; } `; export default ListsView;
JavaScript
0
@@ -1125,16 +1125,131 @@ 1000ms; +%0A%0A @media (min-width: 900px) %7B%0A margin-right: 0em;%0A %7D%0A @media (max-width: 900px) %7B%0A margin-right: 1em;%0A %7D %0A%60;%0A%0Acon
8097973aba0aecc2073893842c37dc41d044fc36
remove warnings
server/user-provider.js
server/user-provider.js
/* Copyright 2015 and Scott Weinstein and Krzysztof Daniel. 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.*/ var config = { userProvider : 'stormpath' }; try { config = require('../config.json'); } catch (ex) { } module.exports = function(app) { if (config.userProvider === 'stormpath') { var stormpathconfig = require('./config/stormpathconfig').stormpathconfig; var googleauth = require('./config/googleauth').googleauth; var stormpath = require('express-stormpath'); var user = new require('./user')(); app.use(stormpath.init(app, { apiKeyId : stormpathconfig.getApiKeyId(), apiKeySecret : stormpathconfig.getApiKeySecret(), secretKey : stormpathconfig.getSecretKey(), application : stormpathconfig.getApplication(), postRegistrationHandler : function(account, res, next) { user.processLoginInfo(account, res, next); }, enableGoogle : true, social : { google : { clientId : googleauth.getClientID(), clientSecret : googleauth.getClientSecret(), }, }, expandProviderData : true, expandCustomData : true })); return stormpath; } if (config.userProvider === 'os') { console.log('WARNING : development mode'); console.log('WARNING : auth disabled'); function osUserMiddleware(req, res, next) { req.user = { href : process.env.USER || process.env.USERNAME }; next(); } osUserMiddleware.loginRequired = function(req, res, next) { next(); } app.use(osUserMiddleware); return osUserMiddleware; } var someOtherProvider = require(config.userProvider); app.use(someOtherProvider); return someOtherProvider; }
JavaScript
0.000002
@@ -2213,32 +2213,33 @@ ext();%0A %7D +; %0A app.use @@ -2419,9 +2419,10 @@ vider;%0A%7D +; %0A
8392cf175c3dd01933afc975064191e9bd27af9d
add tempdata.keep function
cms/node/mvcTempData.js
cms/node/mvcTempData.js
/* * mvcTempData * author: ronglin * create date: 2014.7.1 */ 'use strict'; var utils = require('./utilities'); var fmKey = function(key) { return utils.trim(key).toLowerCase(); }; var CONST_SessionStateKey = '__ControllerTempData'; var sessionProvider = { loadTempData: function(httpContext) { var session = httpContext.request.session; if (session) { var values = session[CONST_SessionStateKey]; if (values) { delete session[CONST_SessionStateKey]; return values; } } return {}; }, saveTempData: function(httpContext, values) { var session = httpContext.request.session; if (session) { if (values && utils.propCount(values) > 0) { session[CONST_SessionStateKey] = values; return true; } else { delete session[CONST_SessionStateKey]; } } return false; } }; var mvcTempData = function(set) { utils.extend(this, set); this.newData = {}; this.oldData = {}; if (!this.provider) { this.provider = sessionProvider; } }; mvcTempData.prototype = { provider: null, newData: null, oldData: null, constructor: mvcTempData, className: 'mvcTempData', set: function(key, val) { key = fmKey(key); this.newData[key] = val; return this; }, get: function(key) { key = fmKey(key); if (key in this.newData) { return this.newData[key]; } else { return this.oldData[key]; } }, remove: function(key) { key = fmKey(key); delete this.newData[key]; delete this.oldData[key]; return this; }, exists: function(key) { key = fmKey(key); return (key in this.newData || key in this.oldData); }, save: function(httpContext) { this.provider.saveTempData(httpContext, this.newData); }, load: function(httpContext) { this.oldData = this.provider.loadTempData(httpContext); } }; mvcTempData.sessionProvider = sessionProvider; module.exports = mvcTempData;
JavaScript
0.000002
@@ -1609,24 +1609,368 @@ %7D%0A %7D,%0A%0A + keep: function(key) %7B%0A if (key === undefined) %7B%0A for (var k in this.oldData) %7B%0A this.keep(k);%0A %7D%0A %7D else %7B%0A key = fmKey(key);%0A if (key in this.oldData && !(key in this.newData)) %7B%0A this.newData%5Bkey%5D = this.oldData%5Bkey%5D;%0A %7D%0A %7D%0A %7D,%0A%0A remove:
a82bbe685040ee6dc913104de9ae90f35e660826
Remove props param to get current mobilization selector
app/modules/widgets/containers/settings-container.js
app/modules/widgets/containers/settings-container.js
import React, { PropTypes } from 'react' import { connect } from 'react-redux' // Global module dependencies import { SettingsPageLayout } from '../../../components/Layout' // Parent module dependencies import * as MobilizationSelectors from '../../mobilizations/selectors' // Current module dependencies import * as WidgetSelectors from '../selectors' export const SettingsContainer = ({ children, ...rest }) => ( <SettingsPageLayout> {children && React.cloneElement(children, {...rest})} </SettingsPageLayout> ) SettingsContainer.propTypes = { children: PropTypes.object, mobilization: PropTypes.object.isRequired, widget: PropTypes.object.isRequired, widgets: PropTypes.array.isRequired } const mapStateToProps = (state, props) => ({ mobilization: MobilizationSelectors.getCurrent(state, props), widget: WidgetSelectors.getWidget(state, props), widgets: WidgetSelectors.getList(state) }) export default connect(mapStateToProps)(SettingsContainer)
JavaScript
0
@@ -802,31 +802,24 @@ urrent(state -, props ),%0A widget:
c40386ee3a25fdce7809232cfca51d4d2565988c
update js for personal message toggler to match html change
assets/javascripts/personal_message_toggler.js
assets/javascripts/personal_message_toggler.js
$(document).ready(function() { $switcherFieldGroup = $("#request_personal_switch"); $formSubmitButton = $("#request_form input[type='submit']")[0]; personalRequestClass = "personal_request_switcher_focused"; if ($switcherFieldGroup.length) { // If an error is showing or the subject has been filled then // they must have selected 'no' already // so set this and don't hide the form. if ($(".errorExplanation").length || $("#request_header_subject input")[0].value) { $("#request_personal_switch_no").prop("checked", true); } else { $switcherFieldGroup.addClass(personalRequestClass); $formSubmitButton.disabled = true; } $("#request_personal_switch_no").click(function(e) { $switcherFieldGroup.removeClass(personalRequestClass); $formSubmitButton.disabled = false; }); $("#request_personal_switch_yes").click(function(e) { $switcherFieldGroup.addClass(personalRequestClass); $formSubmitButton.disabled = true; }); } });
JavaScript
0
@@ -455,15 +455,8 @@ est_ -header_ subj
0eb4fef9f1dd4c1336e80bd54eb7547d16d6ab57
Fix 404 for empty send method
packages/strapi/lib/configuration/hooks/core/responses/policy.js
packages/strapi/lib/configuration/hooks/core/responses/policy.js
'use strict'; /** * Module dependencies */ // Public node modules. const _ = require('lodash'); const Boom = require('boom'); const delegate = require('delegates'); // Local utilities. const responses = require('./responses/index'); // Custom function to avoid ctx.body repeat const createResponses = ctx => { return _.merge( responses, _.mapValues(_.omit(Boom, ['create']), fn => (...rest) => { ctx.body = fn(...rest); }) ); }; /** * Policy used to add responses in the `this.response` object. */ module.exports = async function(ctx, next) { const delegator = delegate(ctx, 'response'); _.forEach(createResponses(ctx), (value, key) => { // Assign new error methods to context.response ctx.response[key] = value; // Delegate error methods to context delegator.method(key); }); try { // App logic. await next(); } catch (error) { // Log error. strapi.log.error(error); // Wrap error into a Boom's response. ctx.status = error.status || 500; ctx.body = _.get(ctx.body, 'isBoom') ? ctx.body || error && error.message : Boom.wrap(error, ctx.status, ctx.body || error.message); } // Empty body is considered as `notFound` response. if (!ctx.body) { ctx.notFound(); } // Format `ctx.body` and `ctx.status`. ctx.status = ctx.body.isBoom ? ctx.body.output.statusCode : ctx.status; ctx.body = ctx.body.isBoom ? ctx.body.output.payload : ctx.body; // Call custom responses. if (_.isFunction(_.get(strapi.config, `responses.${ctx.status}`))) { await strapi.config.responses[ctx.status].call(this, ctx); } };
JavaScript
0.000002
@@ -1236,46 +1236,231 @@ if ( -!ctx.body) %7B%0A ctx.notFound();%0A %7D%0A%0A +_.isUndefined(ctx.body) && _.isUndefined(ctx.status)) %7B%0A return ctx.notFound();%0A %7D%0A%0A if (_.isObject(ctx.body)) %7B%0A if (ctx.body.isBoom && ctx.body.data) %7B%0A ctx.body.output.payload.data = ctx.body.data;%0A %7D%0A%0A // @@ -1496,16 +1496,18 @@ tatus%60.%0A + ctx.st @@ -1572,16 +1572,18 @@ status;%0A + ctx.bo @@ -1640,16 +1640,20 @@ tx.body; +%0A %7D %0A%0A // C
55604f0669ff8692695163d041e9eb64309263e0
Initialise component state in init() instead of constructor
js/forum/src/components/AutocompleteDropdown.js
js/forum/src/components/AutocompleteDropdown.js
import Component from 'flarum/Component'; export default class AutocompleteDropdown extends Component { constructor(...args) { super(...args); this.active = false; this.index = 0; this.keyWasJustPressed = false; } view() { return ( <ul className="Dropdown-menu MentionsDropdown"> {this.props.items.map(item => <li>{item}</li>)} </ul> ); } show(left, top) { this.$().show().css({ left: left + 'px', top: top + 'px' }); this.active = true; } hide() { this.$().hide(); this.active = false; } navigate(e) { if (!this.active) return; switch (e.which) { case 40: case 38: // Down/Up this.keyWasJustPressed = true; this.setIndex(this.index + (e.which === 40 ? 1 : -1), true); clearTimeout(this.keyWasJustPressedTimeout); this.keyWasJustPressedTimeout = setTimeout(() => this.keyWasJustPressed = false, 500); e.preventDefault(); break; case 13: case 9: // Enter/Tab this.$('li').eq(this.index).find('button').click(); e.preventDefault(); break; case 27: // Escape this.hide(); e.stopPropagation(); e.preventDefault(); break; default: // no default } } setIndex(index, scrollToItem) { if (this.keyWasJustPressed && !scrollToItem) return; const $dropdown = this.$(); const $items = $dropdown.find('li'); let rangedIndex = index; if (rangedIndex < 0) { rangedIndex = $items.length - 1; } else if (rangedIndex >= $items.length) { rangedIndex = 0; } this.index = rangedIndex; const $item = $items.removeClass('active').eq(rangedIndex).addClass('active'); if (scrollToItem) { const dropdownScroll = $dropdown.scrollTop(); const dropdownTop = $dropdown.offset().top; const dropdownBottom = dropdownTop + $dropdown.outerHeight(); const itemTop = $item.offset().top; const itemBottom = itemTop + $item.outerHeight(); let scrollTop; if (itemTop < dropdownTop) { scrollTop = dropdownScroll - dropdownTop + itemTop - parseInt($dropdown.css('padding-top'), 10); } else if (itemBottom > dropdownBottom) { scrollTop = dropdownScroll - dropdownBottom + itemBottom + parseInt($dropdown.css('padding-bottom'), 10); } if (typeof scrollTop !== 'undefined') { $dropdown.stop(true).animate({scrollTop}, 100); } } } }
JavaScript
0.000001
@@ -104,51 +104,16 @@ %7B%0A -constructor(...args) %7B%0A super(...args);%0A +init() %7B %0A
91ccc288b6967ed0f35784f0b73f9615c7ec55cf
Update gulp file
gulpfile.js
gulpfile.js
(function () { 'use strict'; var gulp = require('gulp'), connect = require('gulp-connect'), open = require('gulp-open'), del = require('del'), shell = require('gulp-shell'), autoprefixer = require('gulp-autoprefixer'), sass = require('gulp-sass'), minifyCss = require('gulp-minify-css'), runSequence = require('run-sequence'); var paths = { dest: 'dist', temp: '_tmp' }; gulp.task('sass', function () { gulp.src('app/scss/app.scss') .pipe(sass()) .pipe(autoprefixer(['> 1%', 'last 2 versions'], { cascade: true })) .pipe(minifyCss({ keepBreaks: true })) .pipe(gulp.dest(paths.temp + '/css')); }); gulp.task('connect', ['sass'], function() { connect.server({ root: ['app', paths.temp], port: 1336, livereload: true }); }); gulp.task('html', ['sass'], function() { gulp.src('./app/*.html').pipe(connect.reload()); }); gulp.task('watch', function() { gulp.watch(['app/*.html', 'app/scss/**/*'], ['html']); }); gulp.task('open', ['connect', 'watch'], function(){ gulp.src('app/index.html') .pipe(open('', { url: 'http://localhost:1336' })); }); gulp.task('clean', function () { del([paths.dest, paths.temp]); }); gulp.task('copy_css_to_dist', ['sass'], function(){ gulp.src(['_tmp/css/app.css']) .pipe(gulp.dest(paths.dest + '/css')); }); gulp.task('copy_app_to_dist', function(){ gulp.src(['app/index.html', 'app/images/**/*', 'app/favicon.ico'], { base: 'app/' }) .pipe(gulp.dest(paths.dest)); }); gulp.task('deploy', ['build'], shell.task([ 'rsync -rvz dist/ pi:walktocircle.com', 'echo world' ])); gulp.task('build', function() { runSequence('clean', ['copy_app_to_dist', 'copy_css_to_dist']); }); gulp.task('serve', ['open']); gulp.task('default', ['build']); })();
JavaScript
0.000001
@@ -1578,32 +1578,35 @@ dest));%0A %7D);%0A%0A + // gulp.task('depl @@ -1635,16 +1635,19 @@ task(%5B%0A + // 'rsyn @@ -1681,16 +1681,148 @@ e.com',%0A + // 'echo world'%0A // %5D));%0A%0A gulp.task('deploy', %5B'build'%5D, shell.task(%5B%0A 'rsync -rvz dist/ arvixe:public_html/evgenii.com',%0A 'ech
a1afdf70d9ce6f2e04f5f87fe56ffe425411462d
fix comments in credentials.js
browser/credentials.js
browser/credentials.js
/* The values here are used as credentials. This file is present in the marklogic/marklogic-samplestack repository, but credentials are not supplied, and changes to the file are ignored. As such, you may enter and save your own credentials, or you can set environment variables to read them dynamically. If a non-null value is supplied, the environment variable will be ignored. */ module.exports = { // Use your SauceLabs credentials or create a new account under the // open-source licensing model at https://saucelabs.com/opensauce sauce: { // replace with your sauce username or set 'ML_SS_SAUCEUSER' env. variable user: null, // e.g. // user: 'my-sauce-account' // replace with your sauce username or set 'ML_SS_SAUCETOKEN' env. variable accessToken: null // e.g. // accessToken: '05fa46d0-a6df-4a08-a345-c3d3e2f24a61' } };
JavaScript
0.000004
@@ -577,32 +577,39 @@ r sauce username +%0A // or set 'ML_SS_S @@ -636,24 +636,8 @@ ble%0A - user: null,%0A @@ -675,16 +675,32 @@ account' +%0A user: null, %0A%0A // @@ -724,24 +724,35 @@ r sauce -username +access token%0A // or set @@ -788,30 +788,8 @@ ble%0A - accessToken: null%0A @@ -855,15 +855,37 @@ f24a61'%0A + accessToken: null%0A %7D%0A%7D;%0A
9ed7aedfa92553782f7ea472d3e913835a85841a
Fix typo.
app/scripts/components/issues/issue-comments-list.js
app/scripts/components/issues/issue-comments-list.js
import template from './issue-comments-list.html'; export const issueCommentsList = { template, bindings: { issue: '<' }, controller: class IssueCommentsListController { constructor(issueCommentsService, usersService, $rootScope) { this.issueCommentsService = issueCommentsService; this.usersService = usersService; this.$rootScope = $rootScope; } $onInit() { this.unlisten = this.$rootScope.$on('refreshCommentsList', () => { this.issueCommentsService.clearAllCacheForCurrentEndpoint(); this.refresh(); }); this.refresh(); } $onDestroy() { this.unbind(); } refresh() { this.loading = true; this.loadComments().then(comments => { this.comments = comments; }).catch(() => { this.erred = true; }).finally(() => { this.loading = false; }); } loadComments() { return this.usersService.getCurrentUser().then(user => { let query = { issue_uuid: this.issue.uuid }; if (!user.is_staff && !user.is_support) { query.is_public = true; } return this.issueCommentsService.getAll(query); }); } } };
JavaScript
0.001604
@@ -634,20 +634,22 @@ this.un -bind +listen ();%0A
28011c60e13daa4347139380c2650482b3b58926
remove test function
algorithms/mutations.js
algorithms/mutations.js
/* Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array. */ function mutation(arr) { var baseLine = arr[0].toLowerCase(); var checkString = arr[1].toLowerCase(); for(var i = 0; i < checkString.length; i++) { if(baseLine.indexOf(checkString[i]) === -1) { return false; } } return true; } console.log(mutation(["hello", "hey"]));
JavaScript
0.000424
@@ -395,45 +395,4 @@ ;%0A%7D%0A -%0Aconsole.log(mutation(%5B%22hello%22, %22hey%22%5D));
aeafd5141c0fbd29162e7be9c68da45526312e80
Remove TODO.
src/ExpandableSection.js
src/ExpandableSection.js
import './ExpandablePanel.js'; import './SeamlessButton.js'; import { merge } from './updates.js'; import * as symbols from './symbols.js' import * as template from './template.js'; import OpenCloseMixin from './OpenCloseMixin.js'; import ReactiveElement from './ReactiveElement.js'; const Base = OpenCloseMixin( ReactiveElement ); /** * A document section with a header that can be used to expand or collapse * * @inherits ReactiveElement * @mixes OpenCloseMixin */ class ExpandableSection extends Base { componentDidMount() { if (super.componentDidMount) { super.componentDidMount(); } this.$.headerBar.addEventListener('click', () => { this.toggle(); }); // HACK this.$.headerBar.$.inner.style.display = 'flex'; } get updates() { const collapseIcon = this.$.collapseIcon; const expandIcon = this.$.expandIcon; // TODO: Default header content pulls text from aria-label. const opened = this.opened; return merge( super.updates, { attributes: { 'aria-expanded': opened }, $: { headerBar: { }, panel: { opened } }, }, collapseIcon && { $: { collapseIcon: { style: { display: opened ? 'block' : 'none' } } } }, expandIcon && { $: { expandIcon: { style: { display: opened ? 'none' : 'block' } } } } ); } get [symbols.template]() { // TODO: Roles // Default expand/collapse icons from Google's Material Design collection. return template.html` <style> :host { display: block; } #headerBar { display: flex; } #headerBar:hover { opacity: 0.66; } #headerBar > * { align-self: center; } #headerContainer { flex: 1; text-align: start; } #toggleContainer { margin: 0.5em; } </style> <elix-seamless-button id="headerBar"> <div id="headerContainer"> <slot name="headerSlot"></slot> </div> <div id="toggleContainer"> <slot name="toggleSlot"> <svg id="collapseIcon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"> <path d="M12 8l-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z"/> </svg> <svg id="expandIcon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"> <path d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"/> </svg> </slot> </div> </elix-seamless-button> <elix-expandable-panel id="panel" role="none"> <slot></slot> </elix-expandable-panel> `; } } customElements.define('elix-expandable-section', ExpandableSection); export default ExpandableSection;
JavaScript
0
@@ -876,72 +876,8 @@ n;%0A%0A - // TODO: Default header content pulls text from aria-label.%0A
94de9accfba4db8c37869f0514a800b04c1a6694
Enable test
test/function/export-from-no-local-binding/_config.js
test/function/export-from-no-local-binding/_config.js
var assert = require( 'assert' ); module.exports = { description: 'export from does not create a local binding', error: function ( err ) { assert.ok( false, 'TODO: assertion is skipped because it is not used... we need to implement something like /*rollup: include */') }, skip: true }; // test copied from https://github.com/esnext/es6-module-transpiler/tree/master/test/examples/export-from
JavaScript
0.000001
@@ -1,39 +1,4 @@ -var assert = require( 'assert' );%0A%0A modu @@ -75,187 +75,8 @@ ing' -,%0A%0A%09error: function ( err ) %7B%0A%09%09assert.ok( false, 'TODO: assertion is skipped because it is not used... we need to implement something like /*rollup: include */')%0A%09%7D,%0A%0A%09skip: true %0A%7D;%0A
fcc8157dcfbc56cff3d760ef0fb0820a4696eb3a
Replace placeholder countries with real service call
src/main/webapp/scripts/services/CountryService.js
src/main/webapp/scripts/services/CountryService.js
'use strict'; mldsApp.factory('CountryService', ['$http', '$log', '$q', function($http, $log, $q){ return { getCountries: function() { return $q.when([ { isoCode2: 'DK', isoCode3: 'DNK', commonName: 'Denmark' }, { isoCode2: 'FR', isoCode3: 'FRA', commonName: 'France' }, { isoCode2: 'UA', isoCode3: 'URE', commonName: 'United Arab Emirates' }, { isoCode2: 'GB', isoCode3: 'GBP', commonName: 'United Kingdom' }, { isoCode2: 'US', isoCode3: 'USA', commonName: 'United States' } ]); //FIXME retrieve countries from server //return $http.get('/app/countries'); }, }; }]);
JavaScript
0.001584
@@ -98,635 +98,601 @@ )%7B%0A%09 -%09return %7B%0A%09%09%09getCountries: function() %7B%0A%09%09%09%09return $q.when(%5B%0A%09%09%09%09%09%7B +%0A%09%09var countriesListQ = $http.get('/app/rest/countries')%0A%09%09%09.then(function(d)%7Breturn d.data;%7D);%0A%09%09var service = %7B%7D; %0A%09%09 +%0A %09%09 -%09%09isoCode2: 'DK',%0A%09%09%09%09%09%09isoCode3: 'DNK',%0A%09%09%09%09%09%09commonName: 'Denmark'%0A%09%09%09%09%09%7D,%0A%09%09%09%09%09%7B%0A%09%09%09%09%09%09isoCode2: 'FR',%0A%09%09%09%09%09%09isoCode3: 'FRA',%0A%09%09%09%09%09%09commonName: 'France'%0A%09%09%09%09%09%7D,%0A%09%09%09%09%09%7B%0A%09%09%09%09%09%09isoCode2: 'UA',%0A%09%09%09%09%09%09isoCode3: 'URE',%0A%09%09%09%09%09%09commonName: 'United Arab Emirates'%0A%09%09%09%09%09%7D,%0A%09%09%09%09%09%7B%0A%09%09%09%09%09%09isoCode2: 'GB',%0A%09%09%09%09%09%09isoCode3: 'GBP',%0A%09%09%09%09%09%09commonName: 'United Kingdom'%0A%09%09%09%09%09%7D,%0A%09%09%09%09%09%7B%0A%09%09%09%09%09%09isoCode2: 'US',%0A%09%09%09%09%09%09isoCode3: 'USA',%0A%09%09%09%09%09%09commonName: 'United States'%0A%09%09%09%09%09%7D%0A%09%09%09%09%5D);%0A%09%09%09%09//FIXME retrieve countries from server +service.countries = %5B%5D;%0A%09%09service.countriesByCode = %7B%7D;%0A%09%09%0A%09%09service.getCountries = function getCountries() %7B%0A%09%09%09return countriesListQ;%0A%09%09%7D;%0A%09%09%0A%09%09countriesListQ.then(function(countries)%7B%0A%09%09%09// append to countries list%0A%09%09%09Array.prototype.push.apply(service.countries,countries);%0A%09%09%09%0A%09%09%09// fill countriesByCode map%0A%09%09%09service.countries.map(function(c)%7B%0A%09%09%09%09service.countriesByCode%5Bc.isoCode2%5D = c;%0A%09%09%09%7D);%0A%09%09%09%0A%09%09%09$log.log('CountryService', service);%0A%09%09%7D); %0A%09%09 +%0A %09%09 -// return -$http.get('/app/countries');%0A%09%09%09%7D,%0A%09%09%7D +service ;%0A%09%09
ca6bdf333fd0ac85a850e0fba08fd39a03de3362
Improve gulpfile
gulpfile.js
gulpfile.js
/*vim: fileencoding=utf8 tw=100 expandtab ts=4 sw=4 */ /*jslint indent: 4, maxlen: 100, node: true */ /*global require*/ (function () { 'use strict'; var concat = require('gulp-concat'), babel = require('gulp-babel'), gulp = require('gulp'), plumber = require('gulp-plumber'), uglify = require('gulp-uglify'), less = require('gulp-less'), glob = require('glob'), LessPluginCleanCSS = require('less-plugin-clean-css'), LessPluginAutoPrefix = require('less-plugin-autoprefix'), cleancss = new LessPluginCleanCSS({advanced: true}), autoprefix = new LessPluginAutoPrefix({browsers: ['last 3 versions']}); gulp.task('build:app', function () { gulp.src('dev/shareSelectedText.js') .pipe(plumber()) .pipe(babel()) .pipe(concat('shareSelectedText.js')) .pipe(gulp.dest('dist')); return gulp.src('dev/shareSelectedText.js') .pipe(plumber()) .pipe(babel()) .pipe(uglify()) .pipe(concat('shareSelectedText.min.js')) .pipe(gulp.dest('dist')); }); gulp.task('build:less:demo', function () { return gulp.src('demo/demo.less') .pipe(plumber({ handleError: function (err) { console.log(err); this.emit('end'); } })) .pipe(less({ plugins: [autoprefix, cleancss] })) .pipe(concat('demo.min.css')) .pipe(gulp.dest('demo')); }); gulp.task('build:less:app', function () { return gulp.src('dev/shareSelectedText.less') .pipe(plumber({ handleError: function (err) { console.log(err); this.emit('end'); } })) .pipe(less({ plugins: [autoprefix, cleancss] })) .pipe(concat('shareSelectedText.min.css')) .pipe(gulp.dest('dist')); }); gulp.task('build:all', ['build:app', 'build:less:app', 'build:less:demo']); gulp.task('watch', function () { gulp.watch('dev/shareSelectedText.js', ['build:app']); gulp.watch('**/*.less', ['build:less:app', 'build:less:demo']); }); gulp.task('default', ['build:all', 'watch']); }());
JavaScript
0.000005
@@ -100,27 +100,8 @@ */%0A%0A -/*global require*/%0A (fun @@ -394,16 +394,65 @@ 'glob'), +%0A sourcemaps = require('gulp-sourcemaps'), %0A%0A @@ -1697,32 +1697,54 @@ return gulp.src( +%5B'dev/sst_icons.css', 'dev/shareSelect @@ -1751,24 +1751,25 @@ edText.less' +%5D )%0A @@ -2125,32 +2125,163 @@ st'));%0A %7D);%0A%0A + gulp.task('build:copy:fonts', function () %7B%0A return gulp.src(%5B'dev/fonts/**/*'%5D).pipe(gulp.dest('dist/fonts'));%0A %7D);%0A%0A gulp.task('b @@ -2336,24 +2336,44 @@ d:less:demo' +, 'build:copy:fonts' %5D);%0A%0A gul
357decdd53a91f4f050f425d95de3c9f00932aed
Revert "Edit index for new sag icons"
lib/tag-images/index.js
lib/tag-images/index.js
/** * Export images dictionary */ module.exports = { 'culture':{ name:'culture', url: '/lib/tag-images/images/culture.svg' }, 'economy': { name: 'economy', url: '/lib/tag-images/images/economy.svg' }, 'education': { name: 'education', url: '/lib/tag-images/images/education.svg' }, 'health': { name: 'health', url: '/lib/tag-images/images/health.svg' }, 'housing': { name: 'housing', url: '/lib/tag-images/images/housing.svg' }, 'immigration': { name: 'immigration', url: '/lib/tag-images/images/immigration.svg' }, 'infosociety': { name: 'infosociety', url: '/lib/tag-images/images/infosociety.svg' }, 'lgbt': { name: 'lgbt', url: '/lib/tag-images/images/lgbt.svg' }, 'participation': { name: 'participation', url: '/lib/tag-images/images/participation.svg' }, 'security': { name: 'security', url: '/lib/tag-images/images/security.svg' }, 'work': { name: 'work', url: '/lib/tag-images/images/work.svg' } };
JavaScript
0
@@ -49,16 +49,784 @@ rts = %7B%0A + 'arts': %7B%0A name: 'arts',%0A url: '/lib/tag-images/images/arts.svg'%0A %7D,%0A 'scale': %7B%0A name: 'scale',%0A url: '/lib/tag-images/images/scale.svg'%0A %7D,%0A 'police': %7B%0A name: 'police',%0A url: '/lib/tag-images/images/police.svg'%0A %7D,%0A 'signs': %7B%0A name: 'signs',%0A url: '/lib/tag-images/images/signs.svg'%0A %7D,%0A 'transportation': %7B%0A name: 'transportation',%0A url: '/lib/tag-images/images/transportation.svg'%0A %7D,%0A 'people': %7B%0A name: 'people',%0A url: '/lib/tag-images/images/people.svg'%0A %7D,%0A 'parks': %7B%0A name: 'parks',%0A url: '/lib/tag-images/images/parks.svg'%0A %7D,%0A 'agora': %7B%0A name: 'agora',%0A url: '/lib/tag-images/images/agora.svg'%0A %7D,%0A 'internet': %7B%0A name: 'internet',%0A url: '/lib/tag-images/images/internet.svg'%0A %7D,%0A 'cultu
a5cb55ddce162109791e731d0c486731ce9bf20a
Move disabled selector to child and AlertMessage out
troposphere/static/js/components/modals/instance/launch/components/Image.react.js
troposphere/static/js/components/modals/instance/launch/components/Image.react.js
import React from 'react'; import Backbone from 'backbone'; import stores from 'stores'; import moment from 'moment'; import Tags from 'components/common/tags/ViewTags.react'; import Gravatar from 'components/common/Gravatar.react'; export default React.createClass({ displayName: "Image", getInitialState: function(){ let image = this.props.image; let versionList = null; let active = false; if (image) { versionList = image.get('versions'); if (versionList.length > 0) { active = true; } } return { active } }, propTypes: { image: React.PropTypes.instanceOf(Backbone.Model).isRequired, onClick: React.PropTypes.func }, handleClick: function () { if (this.state.active) { this.props.onSelectImage(this.props.image); } }, renderTags: function () { var tags = stores.TagStore.getAll(); var activeTags = stores.TagStore.getImageTags(this.props.image); return ( <Tags tags={tags} activeTags={activeTags} renderLinks={false}/> ); }, render: function () { var image = this.props.image, type = stores.ProfileStore.get().get('icon_set'), imageCreationDate = moment(image.get('start_date')).format("MMM D, YYYY hh:mm a"), iconSize = 67, icon; let fullDescription = image.get('description'); let renderDescription = fullDescription.length < 150 ? fullDescription : (fullDescription.substring(0,150) + " ..."); // always use the Gravatar icons icon = ( <Gravatar hash={image.get('uuid_hash')} size={iconSize} type={type}/> ); let inactiveClass = !this.state.active ? "disabled" : ""; return ( <li className={`media card ${inactiveClass}`} onClick={this.handleClick}> <div className="media__img"> {icon} </div> <div className="media__content"> <div className="row"> <div className="col-md-3 t-wordBreaker"> <h2 className="t-body-1" style={{margin: "0 0 5px"}}>{image.get('name')}</h2> <hr style={{margin: "0 0 5px" }}/> <time>{imageCreationDate}</time> by <strong>{image.get('created_by').username}</strong> </div> <p className="media__description col-md-5"> {renderDescription} </p> <div className="col-md-4"> {this.renderTags()} </div> </div> </div> </li> ) } });
JavaScript
0
@@ -1690,17 +1690,16 @@ %0A );%0A -%0A let @@ -1718,139 +1718,1437 @@ s = -!this.state.active ? %22disabled%22 : %22%22;%0A%0A return (%0A %3Cli className=%7B%60media card $%7BinactiveClass%7D%60%7D onClick=%7Bthis.handleClick +%22%22;%0A let alertMessage = () =%3E null;%0A%0A if (!this.state.active) %7B%0A inactiveClass = %22media--disabled%22;%0A if (this.state.showAlert) %7B%0A alertMessage = () =%3E %7B%0A return (%0A %3Cdiv%0A style=%7B%7B%0A position: %22absolute%22,%0A display: %22inline-block%22,%0A width: %22250px%22,%0A top: %2225%25%22, %0A right: %220%22,%0A left: %220%22,%0A margin: %22auto%22,%0A padding: %225px 10px%22,%0A background: %22#F15757%22,%0A boxShadow: %220 1px 2px rgba(0,0,0,.4)%22,%0A color: %22white%22,%0A textAlign: %22center%22,%0A cursor: %22no-drop !important%22%0A %7D%7D%0A %3E%0A %3Ci className=%22glyphicon glyphicon-exclamation-sign%22/%3E%0A %7B%22 Image Disabled - No Versions%22%7D%0A %3C/div%3E%0A )%0A %7D%0A %7D%0A %7D%0A return (%0A %3Cli %0A style=%7B%7Bposition: %22relative%22 %7D%7D %0A className=%22media card%22%0A onClick=%7Bthis.handleClick%7D%0A %3E%0A %3Cdiv className=%7B%60clearfix $%7BinactiveClass%7D%60 %7D%3E%0A @@ -4030,32 +4030,80 @@ %3C/div%3E%0A + %3C/div%3E%0A %7BalertMessage()%7D%0A %3C/li%3E%0A
15f31929f23e163924f1e217e064eeac23de5276
improve the report location for report-message-format
lib/rules/report-message-format.js
lib/rules/report-message-format.js
/** * @fileoverview enforce a consistent format for rule report messages * @author Teddy Katz */ 'use strict'; const utils = require('../utils'); // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: 'enforce a consistent format for rule report messages', category: 'Rules', recommended: false, }, fixable: null, schema: [ { type: 'string' }, ], }, create (context) { const pattern = new RegExp(context.options[0] || ''); let contextIdentifiers; // ---------------------------------------------------------------------- // Public // ---------------------------------------------------------------------- return { Program (node) { contextIdentifiers = utils.getContextIdentifiers(context, node); }, CallExpression (node) { if ( node.callee.type === 'MemberExpression' && contextIdentifiers.has(node.callee.object) && node.callee.property.type === 'Identifier' && node.callee.property.name === 'report' ) { if (node.arguments.length === 1 && node.arguments[0].type !== 'ObjectExpression') { return; } const message = node.arguments.length === 1 ? node.arguments[0].properties.find(prop => (prop.key.type === 'Literal' && prop.key.value === 'message') || (prop.key.type === 'Identifier' && prop.key.name === 'message') ).value : node.arguments[1]; if ( (message.type === 'Literal' && typeof message.value === 'string' && !pattern.test(message.value)) || (message.type === 'TemplateLiteral' && message.quasis.length === 1 && !pattern.test(message.quasis[0].value.cooked)) ) { context.report({ node, message: "Report message does not match the pattern '{{pattern}}'.", data: { pattern: context.options[0] || '' }, }); } } }, }; }, };
JavaScript
0.000003
@@ -1997,16 +1997,25 @@ node +: message ,%0A
08f79d50e7aa5358ca9de89fe0cbc3a5b9fe0e20
change menu width on smaller screens
src/container/footer.js
src/container/footer.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { deleteCity } from '../actions/index'; import Modal from 'react-modal'; import MaterialIcon from 'material-icons-react'; import { saveState } from '../manageLocalStorage'; import Option from '../components/option'; class Footer extends Component { constructor(props) { super(props); this.state = { modalIsOpen: false }; this.optionsList = [ { option: 'useSwipeToDelete', text: 'Use Swipe to Delete' }, { option: 'showFetched', text: 'Show Fetched' }, { option: 'showUpdated', text: 'Show Updated' }, { option: 'showCelcius', text: 'Show Celcius' }, { option: 'showFahrenheit', text: 'Show Fahrenheit' }, { option: 'showHumidity', text: 'Show Humidity' }, { option: 'showSunrise', text: 'Show Sunrise' }, { option: 'showSunset', text: 'Show Sunset' } ]; this.openModal = this.openModal.bind(this); this.closeModal = this.closeModal.bind(this); this.deleteAllCities = this.deleteAllCities.bind(this); } openModal() { this.setState({ modalIsOpen: true }); } closeModal() { this.setState({ modalIsOpen: false }); } deleteAllCities() { this.setState({ modalIsOpen: false }); this.props.cities.map(city => { this.props.deleteCity(city.id); }); saveState(); } render() { return ( <div className="row row--footer"> <div className="col"> <Modal isOpen={this.state.modalIsOpen} onRequestClose={this.closeModal} contentLabel="Delete all cities" appElement={document.getElementById('app')} className="modal--delete" > <h3>Delete All Cities?</h3> <button className="btn btn-danger" onClick={this.deleteAllCities}> Delete </button> <button className="btn btn-light" onClick={this.closeModal}> Cancel </button> </Modal> <div className="settings-menu"> <button className="icon-settings"> <MaterialIcon icon="settings" size="medium" /> </button> <div className="settings-menu__content"> <button className="btn btn-link" onClick={this.openModal}> Delete All Cities </button> {this.optionsList.map(option => ( <Option text={option.text} key={option.option} isChecked={this.props.checkBoxChecked[option.option]} updateCheckbox={this.props.updateCheckbox} /> ))} </div> </div> </div> </div> ); } } function mapStateToProps(state) { return { cities: state.weather }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ deleteCity }, dispatch); } export default connect( mapStateToProps, mapDispatchToProps )(Footer);
JavaScript
0
@@ -2292,16 +2292,42 @@ _content + col-12 col-sm-12 col-md-3 %22%3E%0A
5b310f8b449b1cb9098e94b4ca0bd0140d4fc4bf
fix content is null
wsy-dice.js
wsy-dice.js
(function(Plugin) { 'use strict'; var winston = require('winston'), seedrandom = require('seedrandom'); var constant = require('./plugin/constants.js'); var parser = require('./plugin/parser.js'); var tempInfo = {}; function RandomStr() { var rng = seedrandom(); var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'; var maxPos = $chars.length; var strRet = ''; for (var i = 0; i < 32; i++) { strRet += $chars.charAt(Math.floor(rng() * maxPos)); } return strRet; } //winston.info("load plugin dice"); Plugin.hooks = { parse: function(payload, callback) { winston.info("hooks.parse==================================") //TODO:change roll formula to roll result, use saved random result if there is any winston.info(payload); var seeds = payload.postData.content.match(constant.REG_DICE_SEED); if (seeds != null) { var seed = seeds[seeds.length - 1].replace(constant.REG_DICE_SEED, "$2"); var rng = seedrandom(seed); payload.postData.content = payload.postData.content.replace(constant.REG_DICE_FORMULA, function(formula){ return parser.parse(formula, rng); }); } //cut seed tail payload.postData.content = payload.postData.content.replace(constant.REG_DICE_SEED, ""); winston.info(payload); winston.info("============================================="); callback(null, payload); }, edit: function(payload, callback) { winston.info("hooks.edit==================================="); winston.info(payload); winston.info(tempInfo); //add saved random seed to end of the content if (tempInfo[payload.post.pid] !== undefined) { winston.info("add seed back"); payload.post.content += tempInfo[payload.post.pid]; tempInfo[payload.post.pid] = undefined; } else { var seed = RandomStr(); payload.post.content += "\n[diceseed]" + seed + "[/diceseed]"; } winston.info(payload); winston.info("============================================="); callback(null, payload); }, create: function(payload, callback) { winston.info("hooks.create================================="); winston.info(payload); //TODO:add a random seed to end of the content var seed = RandomStr(); payload.post.content += "\n[diceseed]" + seed + "[/diceseed]"; winston.info("add dice seed"); winston.info(payload.post.content); winston.info("============================================="); callback(null, payload); }, get: function(payload, callback) { winston.info("hooks.get===================================="); winston.info(payload); //save the random seed at the end of the content var ret = payload.content.match(constant.REG_DICE_SEED); if (ret !== null) { tempInfo[payload.pid] = ret[ret.length - 1]; } winston.info(payload); winston.info("============================================="); callback(null, payload); }, getFields: function(payload, callback) { winston.info("hooks.getFields=============================="); //cut saved random seed at the end of the content winston.info(payload); for (var i = 0; i < payload.posts.length; ++i) { var data = payload.posts[i]; winston.info(data); if (data.content !== undefined) { winston.info("cut dice seed:" + data.content); data.content = data.content.replace(constant.REG_DICE_SEED, ""); } } winston.info(payload); winston.info("============================================="); callback(null, payload); } }; })(module.exports);
JavaScript
0.999945
@@ -3933,32 +3933,57 @@ nt !== undefined + && data.content !== null ) %7B%0A
f56b0fcf1d4d735dae025c3285d0c093f383338d
Disable reset password link for now
src/components/Dialogs/LoginDialog/LoginForm.js
src/components/Dialogs/LoginDialog/LoginForm.js
import * as React from 'react'; import { translate } from 'react-i18next'; import EmailIcon from 'material-ui/svg-icons/communication/email'; import PasswordIcon from 'material-ui/svg-icons/action/lock'; import Loader from '../../Loader'; import Form from '../../Form'; import FormGroup from '../../Form/Group'; import TextField from '../../Form/TextField'; import Button from '../../Form/Button'; @translate() export default class LoginForm extends React.Component { static propTypes = { t: React.PropTypes.func.isRequired, error: React.PropTypes.object, onLogin: React.PropTypes.func, onOpenResetPasswordDialog: React.PropTypes.func }; state = { busy: false }; componentWillReceiveProps() { this.setState({ busy: false }); } handleSubmit = (event) => { event.preventDefault(); this.setState({ busy: true }); this.props.onLogin({ email: this.email.value, password: this.password.value }); }; handleResetPassword = (event) => { event.preventDefault(); this.props.onOpenResetPasswordDialog(); }; refEmail = (email) => { this.email = email; }; refPassword = (password) => { this.password = password; }; render() { const { t, error } = this.props; const { busy } = this.state; return ( <Form className="LoginForm" onSubmit={this.handleSubmit}> {error && <FormGroup>{error.message}</FormGroup>} <FormGroup> <TextField ref={this.refEmail} className="LoginForm-field" type="email" placeholder={t('login.email')} icon={<EmailIcon color="#9f9d9e" />} autoFocus /> </FormGroup> <FormGroup> <TextField ref={this.refPassword} className="LoginForm-field" type="password" placeholder={t('login.password')} icon={<PasswordIcon color="#9f9d9e" />} /> </FormGroup> <FormGroup> <Button className="LoginForm-submit" disabled={busy} > {busy ? <div className="Button-loading"><Loader size="tiny" /></div> : t('login.login')} </Button> </FormGroup> <FormGroup> <a href onClick={this.handleResetPassword} className="LoginForm-forgot"> Forgot Password? </a> </FormGroup> </Form> ); } }
JavaScript
0
@@ -2229,32 +2229,44 @@ %3C/FormGroup%3E%0A%0A + %7B/*%0A %3CFormGro @@ -2413,24 +2413,36 @@ /FormGroup%3E%0A + */%7D%0A %3C/Form
6c0c6bc5c49c3cc1518e1d18ba1f0ebdcda86231
remove OTP (#4055)
packages/xo-server/src/recover-account-cli.js
packages/xo-server/src/recover-account-cli.js
import appConf from 'app-conf' import pw from 'pw' import Xo from './xo' import { generateToken } from './utils' const recoverAccount = async ([name]) => { if (name === undefined || name === '--help' || name === '-h') { return ` xo-server-recover-account <user name or email> If the user does not exist, it is created, if it exists, updates its password and resets its permission to Admin. ` } let password = await new Promise(resolve => { process.stdout.write('Password (leave empty for random): ') pw(resolve) }) if (password === '') { password = await generateToken(10) console.log('The generated password is', password) } const xo = new Xo( await appConf.load('xo-server', { ignoreUnknownFormats: true, }) ) const user = await xo.getUserByName(name, true) if (user !== null) { await xo.updateUser(user.id, { password, permission: 'admin' }) console.log(`user ${name} has been successfully updated`) } else { await xo.createUser({ name, password, permission: 'admin' }) console.log(`user ${name} has been successfully created`) } } export { recoverAccount as default }
JavaScript
0
@@ -363,16 +363,43 @@ password +, remove any configured OTP and res @@ -904,16 +904,22 @@ er.id, %7B +%0A passwor @@ -912,32 +912,38 @@ %0A password, +%0A permission: 'ad @@ -938,32 +938,71 @@ mission: 'admin' +,%0A preferences: %7B otp: null %7D,%0A %7D)%0A console.
9e01d44ef5b4f160f69f981359b1af494814a338
Fix bug that was blocking JSON support, closes #4
lib/config-plugin.js
lib/config-plugin.js
var _ = require("lodash") var path = require("path") // Load configuration file function loadFile(dir, filename) { if (filename == null) return {} filename = path.join(dir, filename) try { return require(filename) } catch(e) { return {} } } module.exports = Config function Config(options) { this.options = options this._config = null if (this.options.environment == null) { this.options.environment = process.env.NODE_ENV || "development" } } Config.prototype.getConfig = function () { if (!this._config) { this._config = _.merge({}, loadFile(this.options.dir, "default"), loadFile(this.options.dir, this.options.environment), loadFile(this.options.dir, "local") ) } return this._config } Config.prototype.apply = function(compiler) { // Build the configuration object var options = this.options var config = this.getConfig() compiler.plugin('compilation', (compilation) => { // Setup a resolver to faux-resolve a request for "config" compilation.resolvers.normal.plugin("module", function(request, next) { if (request.request !== "config") { // This plugin only resolves for the explicit module "config" return next() } return next(null, { // No actual source is needed here path: path.join(options.dir, "default.js"), resolved: true }) }) }) // Setup a module-factory to direct the flow to the loader ( // which outputs the configuration JSON) compiler.plugin("normal-module-factory", function(nmf) { nmf.plugin("after-resolve", function(data, next) { if (data.rawRequest !== "config") { // This plugin only resolves for the explicit module "config" return next(null, data) } // console.log(data) // NOTE: Parameters are passed via query string to the loader // at `this.query` data.loaders = [ path.join(__dirname, "./config-loader.js") + "?" + JSON.stringify(config) ] return next(null, data) }) }) }
JavaScript
0
@@ -836,37 +836,8 @@ ect%0A - var options = this.options%0A va @@ -898,16 +898,24 @@ ation', +function (compila @@ -923,11 +923,8 @@ ion) - =%3E %7B%0A @@ -1207,15 +1207,9 @@ %7D%0A - %0A + @@ -1245,38 +1245,68 @@ // -No actual source is needed her +This path is not actually used but must be set to a real fil e%0A @@ -1321,44 +1321,22 @@ th: +%22 pa -th.join(options.dir, %22default.js%22) +ckage.json%22 ,%0A
83730a2766eca7b8807f194453204cb63485eab3
use glob instead of loader
lib/tasks/base/files.js
lib/tasks/base/files.js
'use strict'; var path = require('path'); var utils = require('../../utils'); module.exports = function(app, base) { base.create('files', { renameKey: function (key) { return path.basename(key); } }); var glob = base.get('argv.files'); if (glob) { glob = glob.split(','); } else { glob = ['*', 'lib/*', 'bin/*']; } return function(cb) { base.files(glob, {dot: true, ignore: ['.DS_Store']}); base.emit('loaded', base.files); cb(); }; };
JavaScript
0.000002
@@ -8,16 +8,40 @@ rict';%0A%0A +var fs = require('fs');%0A var path @@ -376,88 +376,227 @@ %0A%0A -return function(cb) %7B%0A base.files(glob, %7Bdot: true, ignore: %5B'.DS_Store'%5D +var opts = %7Bdot: true, realpath: true, ignore: %5B'**/.DS_Store', '**/.git'%5D%7D;%0A%0A return function(cb) %7B%0A utils.glob.sync(glob, opts).forEach(function(fp) %7B%0A base.file(fp, %7Bcontent: fs.readFileSync(fp)%7D);%0A %7D);%0A +%0A