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
aeaec88314eaca20b1f56ce85a9cd3575555cdcc
fix unused var (jslint)
editor/directives/edit.js
editor/directives/edit.js
/*jslint node:true, browser:true */ 'use strict'; /* Copyright 2015 Enigma Marketing Services Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ module.exports = function (app) { var Directive = function (Restangular, $timeout, $q) { var deep = require('deep-get-set'), directive = {}, pendingRequests = [], completeRequests = {}; deep.p = true; //hack to create empty objects directive.restrict = 'A'; directive.scope = {}; directive.controller = function ($scope) { var self = this; // expose the local scope so it can be shared on // the directives that require this one // check directives/var.js self.$scope = $scope; self.parseName = function (name) { var opts = {}, parts = name.split('.'); opts.name = name; opts.entity = parts[0]; opts.id = parts[1]; opts.property = parts.slice(2).join('.'); return opts; }; self.getData = function (name) { var opts = self.parseName(name), Entity = Restangular.all(opts.entity), isRequestPending = (pendingRequests.indexOf(opts.entity + '.' + opts.id) !== -1), hasBeenRequested = $scope[opts.entity]; if (!hasBeenRequested && !isRequestPending) { //add to pending requests pendingRequests.push(opts.entity + '.' + opts.id); // get data from API Entity .get(opts.id) .then(function (data) { // remove from pending requests pendingRequests.splice(pendingRequests.indexOf(opts.entity + '.' + opts.id), 1); $timeout(function () { $scope.$apply(function () { var value; // add the API response to the $scope deep($scope, opts.entity + '.' + opts.id, data); // cache in complete requests so we can quicly access it completeRequests[opts.entity] = $scope[opts.entity]; // if the requested property is missing // create it value = deep($scope, opts.name); if (value === undefined) { deep($scope, opts.name, ''); } }); }); }, function (err) { self.$scope.$emit('error', err); }); } return $scope; }; self.saveAll = function () { var promisses = []; Object.keys(completeRequests).forEach(function (entity) { var Entity = completeRequests[entity]; Object.keys(Entity).forEach(function (id) { var item = Entity[id]; promisses.push(item.save()); }); }); $q.all(promisses).then(function (data) { self.$scope.$emit('saved'); }, function (err) { self.$scope.$emit('error', err); }); }; // iterates the $scope obj and applies as get to all // restangular objects self.reloadAll = function () { var promisses = []; Object.keys(completeRequests).forEach(function (entity) { var Entity = completeRequests[entity]; Object.keys(Entity).forEach(function (id) { var item = Entity[id], promise; promise = item.get().then(function (data) { $timeout(function () { $scope.$apply(function () { // add the API response to the $scope deep($scope, entity + '.' + id, data); }); }); }); promisses.push(promise); }); }); $q.all(promisses).then(function (data) { self.$scope.$emit('reloaded'); }, function (err) { self.$scope.$emit('error', err); }); }; }; return directive; }; app.directive('lkEdit', ['Restangular', '$timeout', '$q', Directive]); return app; };
JavaScript
0
@@ -4037,36 +4037,32 @@ .then(function ( -data ) %7B%0A @@ -5248,36 +5248,32 @@ .then(function ( -data ) %7B%0A
db866be02ea791a73120f41f95280331cfe2329b
Fix extraneous subscription bug
packages/redux-components/src/makeSelectorObservable.js
packages/redux-components/src/makeSelectorObservable.js
import createBehaviorSubject from 'observable-utils/lib/createBehaviorSubject' // Make a selector on a ReduxComponentInstance into an ES7 Observable. export default function makeSelectorObservable(componentInstance, selector) { var observerCount = 0 var subscription = undefined var lastSeenValue = undefined // Make the selector a Subject. var subj = createBehaviorSubject({ onObserversChanged: function(observers) { observerCount = observers.length if (observerCount === 0) { // No subscribers left; remove upstream subscription. if(subscription) subscription.unsubscribe() subscription = undefined } else if (observerCount === 1) { // This closure will observe and select from the store. // Selectors expect to receive valid states, not undefined, so only call // the selector when the state is fully realized. var observeState = function() { var store = componentInstance.store if (!store) return var state = store.getState() if (state !== undefined) { var val = selector(state) if (val !== lastSeenValue) { lastSeenValue = val; subj.next(val) } } } subscription = componentInstance.__getSubject().subscribe({ next: observeState }) observeState() } } }) Object.assign(selector, subj) return selector }
JavaScript
0
@@ -416,16 +416,31 @@ bservers +, observerAdded ) %7B%0A%09%09%09o @@ -669,16 +669,33 @@ nt === 1 + && observerAdded ) %7B%0A%09%09%09%09
202da675c1ca9e4730d8f51f52d46c788a0a330b
Fix bug
src/redux/modules/board.js
src/redux/modules/board.js
export const INITIAL_WIDTH = 40 export const INITIAL_HEIGHT = 20 const setCellActionHandler = (state, action) => { const {x, y, live} = action.payload const cells = state.cells.slice() cells[x] = cells[x].slice() cells[x][y] = live const newState = { ...state, cells: cells } return newState } const randomizeActionHandler = (state, action) => { const newState = { ...state, cells: makeCells(state.width, state.height) } for (let x = 0; x < state.width; x++) { for (let y = 0; y < state.height; y++) { newState.cells[x][y] = Math.random() > 0.8 } } return newState } const clearActionHandler = (state, action) => { return { ...state, cells: makeCells(state.width, state.height) } } const stepActionHandler = (state, action) => { const board = state const {width, height} = board const newCells = makeCells(width, height) for (let x = 0; x < width; x++) { for (let y = 0; y < width; y++) { newCells[x][y] = shouldLiveInNextGeneration(board, x, y) } } const newBoard = {...board, cells: newCells} return newBoard } export const makeCells = (width, height) => { const cells = [] for (let x = 0; x < width; x++) { const row = [] cells.push(row) for (let y = 0; y < height; y++) { row.push(false) } } return cells } const shouldLiveInNextGeneration = (board, x, y) => { const alive = board.cells[x][y] const neighbourCount = neighbours(board, x, y) return alive ? (neighbourCount >= 2 && neighbourCount <= 3) : (neighbourCount === 3) } export const neighbours = (board, x, y) => { return aliveCellsAt(board, x-1, y-1) + aliveCellsAt(board, x, y-1) + aliveCellsAt(board, x+1, y-1) + aliveCellsAt(board, x-1, y) + aliveCellsAt(board, x+1, y) + aliveCellsAt(board, x-1, y+1) + aliveCellsAt(board, x, y+1) + aliveCellsAt(board, x+1, y+1) } const aliveCellsAt = (board, x, y) => { if (x < 0 || x >= board.width) { return 0 } if (y < 0 || y >= board.height) { return 0 } return board.cells[x][y] ? 1 : 0 } const resizeActionHandler = (state, action) => { const {width, height} = action.payload const cells = makeCells(width, height) const copyWidth = Math.min(width, state.width) const copyHeight = Math.min(height, state.height) for (let x = 0; x < copyWidth; x++) { for (let y = 0; y < copyHeight; y++) { cells[x][y] = state.cells[x][y] } } const newState = {...state, cells: cells, width: width, height: height} return newState } const initialState = () => { return { cells: makeCells(INITIAL_WIDTH, INITIAL_HEIGHT), width: INITIAL_WIDTH, height: INITIAL_HEIGHT } } const ACTION_HANDLERS = { SET_CELL: setCellActionHandler, RANDOMIZE: randomizeActionHandler, STEP: stepActionHandler, RESIZE: resizeActionHandler, CLEAR: clearActionHandler } // ------------------------------------ // Reducer // ------------------------------------ export default function counterReducer (state, action) { if (state === undefined) { state = initialState() } const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state }
JavaScript
0.000001
@@ -920,21 +920,22 @@ 0; y %3C -width +height ; y++) %7B
38f9ccb1fa5152a8540117c31c3ffe1a5a9be9e3
Add prescriber page info
src/pages/dataTableUtilities/getPageInfoColumns.js
src/pages/dataTableUtilities/getPageInfoColumns.js
/* eslint-disable dot-notation */ /** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2016 */ import { pageInfoStrings, programStrings, tableStrings } from '../../localization'; import { MODAL_KEYS, formatDate } from '../../utilities'; import { ROUTES } from '../../navigation/constants'; import { PageActions } from './actions'; /** * PageInfo rows/columns for use with the PageInfo component. * * * To add a page, add the pages routeName (see: pages/index.js) * and a 2d array of page info rows to PER_PAGE_INFO_COLUMNS, * of the desired pageinfo rows needed on the page. * * To use in the new page: use the usePageReducer hook. * usePageReducer will inject a your pages reducer with a field * pageInfo - a function returned by getPageInfo. Passing * this function the particular pages base object - i.e, * transaction, requisition or stock and it's dispatch will return the * required pageInfo columns for the page. */ const PER_PAGE_INFO_COLUMNS = { [ROUTES.CUSTOMER_INVOICE]: [ ['entryDate', 'confirmDate', 'enteredBy'], ['customer', 'theirRef', 'transactionComment'], ], [ROUTES.SUPPLIER_INVOICE]: [ ['entryDate', 'confirmDate'], ['otherParty', 'theirRef', 'transactionComment'], ], [ROUTES.SUPPLIER_REQUISITION]: [ ['entryDate', 'enteredBy'], ['otherParty', 'editableMonthsToSupply', 'requisitionComment'], ], [ROUTES.SUPPLIER_REQUISITION_WITH_PROGRAM]: [ ['program', 'orderType', 'entryDate', 'enteredBy'], ['period', 'otherParty', 'monthsToSupply', 'requisitionComment'], ], [ROUTES.STOCKTAKE_EDITOR]: [['stocktakeName', 'stocktakeComment']], [ROUTES.STOCKTAKE_EDITOR_WITH_REASONS]: [['stocktakeName', 'stocktakeComment']], [ROUTES.CUSTOMER_REQUISITION]: [ ['monthsToSupply', 'entryDate'], ['customer', 'requisitionComment'], ], [ROUTES.PRESCRIPTION]: [['entryDate', 'enteredBy'], ['customer', 'transactionComment']], stocktakeBatchEditModal: [['itemName']], stocktakeBatchEditModalWithReasons: [['itemName']], }; const PAGE_INFO_ROWS = (pageObject, dispatch, route) => ({ entryDate: { title: `${pageInfoStrings.entry_date}:`, info: formatDate(pageObject.entryDate) || 'N/A', }, confirmDate: { title: `${pageInfoStrings.confirm_date}:`, info: formatDate(pageObject.confirmDate), }, enteredBy: { title: `${pageInfoStrings.entered_by}:`, info: pageObject.enteredBy && pageObject.enteredBy.username, }, customer: { title: `${pageInfoStrings.customer}:`, info: pageObject.otherPartyName, }, theirRef: { title: `${pageInfoStrings.their_ref}:`, info: pageObject.theirRef, onPress: () => dispatch(PageActions.openModal(MODAL_KEYS.THEIR_REF_EDIT, route)), editableType: 'text', }, transactionComment: { title: `${pageInfoStrings.comment}:`, info: pageObject.comment, onPress: () => dispatch(PageActions.openModal(MODAL_KEYS.TRANSACTION_COMMENT_EDIT, route)), editableType: 'text', }, stocktakeComment: { title: `${pageInfoStrings.comment}:`, info: pageObject.comment, onPress: () => dispatch(PageActions.openModal(MODAL_KEYS.STOCKTAKE_COMMENT_EDIT, route)), editableType: 'text', }, requisitionComment: { title: `${pageInfoStrings.comment}:`, info: pageObject.comment, onPress: () => dispatch(PageActions.openModal(MODAL_KEYS.REQUISITION_COMMENT_EDIT, route)), editableType: 'text', }, otherParty: { title: `${pageInfoStrings.supplier}:`, info: pageObject.otherPartyName, }, program: { title: `${programStrings.program}:`, info: pageObject.program && pageObject.program.name, }, orderType: { title: `${programStrings.order_type}:`, info: pageObject.orderType, }, editableMonthsToSupply: { title: `${pageInfoStrings.months_stock_required}:`, info: pageObject.monthsToSupply, onPress: () => dispatch(PageActions.openModal(MODAL_KEYS.SELECT_MONTH, route)), editableType: 'selectable', }, period: { title: `${programStrings.period}:`, info: pageObject.period && pageObject.period.toInfoString(), }, monthsToSupply: { title: `${pageInfoStrings.months_stock_required}:`, info: pageObject.monthsToSupply, }, stocktakeName: { title: `${pageInfoStrings.stocktake_name}:`, info: pageObject.name, onPress: () => dispatch(PageActions.openModal(MODAL_KEYS.STOCKTAKE_NAME_EDIT, route)), editableType: 'text', }, itemName: { title: `${tableStrings.item_name}`, info: pageObject.itemName, onPress: null, }, }); const getPageInfoColumns = page => { const pageInfoColumns = PER_PAGE_INFO_COLUMNS[page]; if (!pageInfoColumns) return null; return (pageObjectParameter, dispatch, route) => { const pageInfoRows = PAGE_INFO_ROWS(pageObjectParameter, dispatch, route); return pageInfoColumns.map(pageInfoColumn => pageInfoColumn.map(pageInfoKey => pageInfoRows[pageInfoKey]) ); }; }; export default getPageInfoColumns;
JavaScript
0
@@ -1843,16 +1843,21 @@ TION%5D: %5B +%0A %5B'entryD @@ -1875,16 +1875,20 @@ redBy'%5D, +%0A %5B'custo @@ -1909,25 +1909,43 @@ tionComment' -%5D +, 'prescriber'%5D,%0A %5D,%0A stockta @@ -4549,16 +4549,196 @@ l,%0A %7D,%0A + prescriber: %7B%0A title: 'Prescriber',%0A info: pageObject?.prescriber?.firstName,%0A onPress: () =%3E dispatch(PageActions.openModal(MODAL_KEYS.SELECT_PRESCRIBER, route)),%0A %7D,%0A %7D);%0A%0Acon
72304e4cf05f3cf2a4a2268bcfeae6ea7eaac1fb
fix delete closure in role
lib/api/controllers/securityController.js
lib/api/controllers/securityController.js
var ResponseObject = require('../core/models/responseObject'); module.exports = function SecurityController (kuzzle) { /** * Get a specific role according to the given id * @param {RequestObject} requestObject * @returns {Promise} */ this.getRole = function (requestObject) { kuzzle.pluginsManager.trigger('data:getRole', requestObject); return kuzzle.repositories.role.loadRole( kuzzle.repositories.role.getRoleFromRequestObject(requestObject) ) .then(role => { if (role.closures) { delete role.closures; } return Promise.resolve(new ResponseObject(requestObject, role || {})); }); }; /** * Return a list of roles that specify a right for the given indexes * @param {RequestObject} requestObject * @returns {Promise} */ this.searchRoles = function (requestObject) { kuzzle.pluginsManager.trigger('data:searchRole', requestObject); return kuzzle.repositories.role.searchRole(requestObject) .then((response) => { if (requestObject.data.body.hydrate && response.data.body && response.data.body.hits) { response.data.body.hits = response.data.body.hits.map(role => { var parsedRole = {}; parsedRole._id = role._id; parsedRole._source = {indexes: role.indexes}; return parsedRole; }); } return Promise.resolve(response); }); }; /** * Create or update a Role * @param {RequestObject} requestObject * @returns {Promise} */ this.putRole = function (requestObject) { kuzzle.pluginsManager.trigger('data:putRole', requestObject); return kuzzle.repositories.role.validateAndSaveRole( kuzzle.repositories.role.getRoleFromRequestObject(requestObject) ) .then(result => { return Promise.resolve(new ResponseObject(requestObject, result)); }); }; /** * Remove a role according to the given id * @param {RequestObject} requestObject * @returns {Promise} */ this.deleteRole = function (requestObject) { kuzzle.pluginsManager.trigger('data:deleteRole', requestObject); return kuzzle.repositories.role.deleteRole( kuzzle.repositories.role.getRoleFromRequestObject(requestObject) ); }; };
JavaScript
0.000001
@@ -515,24 +515,32 @@ if (role + && role .closures) %7B
eecadcd151300feddf9e7252d0a02bcdc90ff4f0
Fix incorrect permission resolveable
src/commands/Roles/LeaveRole.js
src/commands/Roles/LeaveRole.js
'use strict'; const Command = require('../../Command.js'); /** * Get a role from the matching string * @param {string} string String to use to search for role * @param {Message} message originating message * @returns {Role|null} Role */ function getRoleForString(string, message) { const trimmedString = string.trim(); const roleFromId = message.guild.roles.get(trimmedString); let roleFromName; if (typeof roleFromId === 'undefined') { roleFromName = message.guild.roles .find(item => item.name.toLowerCase() === trimmedString.toLowerCase()); } return roleFromId || roleFromName || null; } /** * Add a joinable role */ class LeaveRole extends Command { constructor(bot) { super(bot, 'settings.leaveRole', 'leave'); this.usages = [ { description: 'Show instructions for leaving roles', parameters: [] }, { description: 'Leave a role', parameters: ['Role/Role id to leave'] }, ]; this.regex = new RegExp(`^${this.call}\\s(.*)?`, 'i'); this.allowDM = false; } /** * Run the command * @param {Message} message Message with a command to handle, reply to, * or perform an action based on parameters. */ run(message) { const stringRole = message.strippedContent.replace(`${this.call} `, ''); if (!stringRole) { this.sendInstructionEmbed(message); } else { const role = getRoleForString(stringRole, message); if (!role) { this.sendInstructionEmbed(message); } else { this.bot.settings.getRolesForGuild(message.guild) .then((roles) => { const filteredRoles = roles.filter(storedRole => role.id === storedRole.id); const roleRemoveable = filteredRoles.length > 0 && message.member.roles.get(role.id) && message.channel.permissionsFor(this.bot.client.user.id).hasPermission('MANAGE_ROLES'); if (roleRemoveable) { message.member.removeRole(role.id) .then(() => this.sendLeft(message, role)) .catch(this.logger.error); } else { this.sendCantLeave(message); } }) .catch(this.logger.error); } } } sendLeft(message, role) { this.messageManager.embed(message, { title: 'Left Role', type: 'rich', color: 0x779ECB, fields: [ { name: '_ _', value: role.name, inline: true, }, ], }, true, true); } sendCantLeave(message) { this.messageManager.embed(message, { title: 'Invalid Role', type: 'rich', color: 0x779ECB, fields: [ { name: '_ _', value: 'You can\'t leave that role.', inline: true, }, ], }, true, true); } sendInstructionEmbed(message) { const embed = { title: 'Usage', type: 'rich', color: 0x779ECB, fields: [ { name: '_ _', value: 'Role or role id to join.', }, { name: 'Possible role values:', value: '_ _', }, ], }; this.bot.settings.getChannelPrefix(message.channel) .then((prefix) => { embed.fields[0].name = `${prefix}${this.call} <role or role id>`; return this.bot.settings.getRolesForGuild(message.guild); }) .then((roles) => { embed.fields[1].value = roles.map(role => role.name).join('; '); this.messageManager.embed(message, embed, true, false); }) .catch(this.logger.error); } } module.exports = LeaveRole;
JavaScript
0.0003
@@ -1917,16 +1917,31 @@ GE_ROLES +_OR_PERMISSIONS ');%0A
120c44b01e5e6e20f576e0dff1e4aa30e549d35d
Implement blockFunction.fail
blockFunction.js
blockFunction.js
/* Block a function from being called by adding and removing any number of blocks. Excellent for waiting on parallel asynchronous operations. A blocked function starts out with exactly one block Example usage: http.createServer(function(req, res) { var sendResponse = blockFunction(function() { res.writeHead(204) res.end() }) var queries = parseQueries(req.url) for (var i=0; i<queries.length; i++) { sendResponse.addBlock() handleQuery(queries[i]; function() { sendResponse.removeBlock() }) } }) */ module.exports = function blockFunction(fn) { var numBlocks = 0 return { addBlock:function() { numBlocks++ return this }, removeBlock:function() { if (!fn) { throw new Error("Block removed after function was unblocked") } if (!numBlocks) { throw new Error("Tried to remove a block that was never added") } if (--numBlocks) { return } fn() delete fn return this } } }
JavaScript
0.999996
@@ -897,16 +897,91 @@ %7D%0A%09%09%09fn( +null)%0A%09%09%09delete fn%0A%09%09%09return this%0A%09%09%7D,%0A%09%09fail:function(error) %7B%0A%09%09%09fn(error )%0A%09%09%09del
dc55355016d2a5562b1a0523f95aa35df808e621
Add stocktake editor initial reducer
src/pages/dataTableUtilities/reducer/getReducer.js
src/pages/dataTableUtilities/reducer/getReducer.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ /** * Method using a factory pattern variant to get a reducer * for a particular page or page style. * * For a new page - create a constant object with the * methods from reducerMethods which are composed to create * a reducer. Add to PAGE_REDUCERS. * * Each key value pair in a reducer object should be in the form * action type: reducer function, returning a new state object * */ import { filterData, focusNextCell, selectRow, deselectRow, deselectAll, focusCell, sortData, openBasicModal, closeBasicModal, addMasterListItems, addItem, editTheirRef, editComment, deleteRecordsById, refreshData, createAutomaticOrder, hideOverStocked, showOverStocked, editField, selectAll, hideStockOut, showStockOut, selectItems, editName, } from './reducerMethods'; /** * Used for actions that should be in all pages using a data table. */ const BASE_TABLE_PAGE_REDUCER = { focusNextCell, focusCell, sortData, }; const customerInvoice = { ...BASE_TABLE_PAGE_REDUCER, filterData, editField, selectRow, deselectRow, deselectAll, openBasicModal, closeBasicModal, addMasterListItems, addItem, editTheirRef, editComment, deleteRecordsById, refreshData, }; const customerInvoices = { ...BASE_TABLE_PAGE_REDUCER, filterData, selectRow, deselectRow, deselectAll, openBasicModal, closeBasicModal, deleteRecordsById, }; const supplierInvoice = { ...BASE_TABLE_PAGE_REDUCER, filterData, selectRow, deselectRow, deselectAll, closeBasicModal, openBasicModal, editTheirRef, editComment, refreshData, addItem, editField, deleteRecordsById, }; const supplierRequisition = { ...BASE_TABLE_PAGE_REDUCER, filterData, selectRow, deselectRow, deselectAll, openBasicModal, closeBasicModal, editTheirRef, editComment, refreshData, addMasterListItems, addItem, createAutomaticOrder, hideOverStocked, showOverStocked, editField, deleteRecordsById, }; const programSupplierRequisition = { ...BASE_TABLE_PAGE_REDUCER, filterData, selectRow, deselectRow, deselectAll, openBasicModal, closeBasicModal, editTheirRef, editComment, refreshData, addMasterListItems, addItem, createAutomaticOrder, hideOverStocked, showOverStocked, editField, }; const supplierRequisitions = { sortData, filterData, selectRow, deselectRow, openBasicModal, closeBasicModal, refreshData, }; const stocktakes = { openBasicModal, closeBasicModal, filterData, selectRow, deselectAll, deselectRow, sortData, }; const stocktakeManager = { selectRow, deselectAll, deselectRow, sortData, filterData, selectAll, hideStockOut, showStockOut, selectItems, editName, }; const PAGE_REDUCERS = { customerInvoice, customerInvoices, supplierInvoice, supplierRequisitions, supplierRequisition, programSupplierRequisition, stocktakes, stocktakeManager, }; const getReducer = page => { const reducer = PAGE_REDUCERS[page]; return (state, action) => { const { type } = action; if (!reducer[type]) return state; return reducer[type](state, action); }; }; export default getReducer;
JavaScript
0
@@ -2811,24 +2811,125 @@ itName,%0A%7D;%0A%0A +const stocktakeEditor = %7B%0A ...BASE_TABLE_PAGE_REDUCER,%0A sortData,%0A filterData,%0A editComment,%0A%7D;%0A%0A const PAGE_R @@ -3109,16 +3109,35 @@ anager,%0A + stocktakeEditor,%0A %7D;%0A%0Acons
f0dd47e9c61569755ac7eb1a7ca03dfb23ae1f05
set hash when sorting list
js/content-filter.js
js/content-filter.js
MLS.contentFilter = (function () { var $cf = $jQ('#content-filter'), hashLoaded = false, options = { endpoint: null, callback: function () {}, container: null }, pub = { /*============================ = Init = ============================*/ init: function (o) { options = $jQ.extend(options, o); // endpoint = endpoint ? endpoint : (ep || MLS.ajax.endpoints.PRODUCT_LISTING); // callback = c || contentGrid.reInit; $cf = $jQ('#content-filter'); var $collapsible = $cf.find('.collapsible'), $facets = $cf.find('.facet'); // collapse all but first dimension $collapsible.find('.facet-list').slideToggle('slow'); // load content on load (if hash) !hashLoaded && pub.loadFromHash(); hashLoaded = true; /*========== bind click events ==========*/ // dimension (expansion/collapse) $collapsible.find('.dimension-header').on('click', pub.dimensionClick); $facets.on('click', pub.facetClick); $jQ('.filter-panels li').on('click', pub.sort); /* mobile option */ // remove filter $jQ('#filter-selections').find('a').on('click', pub.removeFilter); // compability services $jQ('.compatibility-filter').children('select').on('change', pub.compabilitySelect); // type ahead (searc) $jQ('.compatibility-filter').children('input.type-ahead').on('keyup', pub.compabilitySearch); // sort links $jQ('#sort-options').find('li').on('click', pub.sort); $jQ('#mobile-sort-filter li.sort-option').on('click', pub.sort); }, /*----- End of Init ------*/ /*================================================ = Finalize (unbind events) = =================================================*/ finalize: function () { $cf = $jQ('#content-filter'); var $collapsible = $cf.find('.collapsible'), $facets = $cf.find('.facet'); /*========== bind click events ==========*/ // dimension (expansion/collapse) $collapsible.find('.dimension-header').unbind('click', pub.dimensionClick); $facets.unbind('click', pub.facetClick); $jQ('.filter-panels li').unbind('click', pub.sort); /* mobile option */ // remove filter $jQ('#clear-selections').find('li').find('a').unbind('click', pub.removeFilter); // compability services $jQ('.compatibility-filter').children('select').unbind('change', pub.compabilitySelect); // type ahead (searc) $jQ('.compatibility-filter').children('input.type-ahead').unbind('keyup', pub.compabilitySearch); // sort links $jQ('#sort-options').find('li').on('click', pub.sort); $jQ('#mobile-sort-filter li.sort-option').on('click', pub.sort); }, /*----- End of Finalize (unbind events) ------*/ /*============================================ = Reinit: on ajax load = ============================================*/ reInit: function () { MLS.contentFilter.finalize(); MLS.contentFilter.init(); }, /*----- End of Reinit: on ajax load ------*/ /*====================================== = Load from Hash = ======================================*/ // If the url contains paramaters in the hash when it // is first loaded then request content loadFromHash: function () { var hash = window.location.hash, params = {}; if (hash !== '') { // we have a hash params = MLS.util.getParamsFromUrl(hash); if (!$jQ.isEmptyObject(params)) { pub.processRequest(params); } } }, /*----- End of Load from Hash ------*/ /*======================================= = Listing sorting = =======================================*/ sort: function (e) { e.preventDefault(); var $elem = $jQ(this), href = $elem.find('a').attr('href'), params = MLS.util.getParamsFromUrl(href); pub.processRequest(params); }, /*----- End of Listing sorting ------*/ /*======================================= = dimension click = =======================================*/ dimensionClick: function (e) { e.preventDefault(); $jQ(this).toggleClass('active').promise().done(function () { $jQ(this).next().slideToggle('slow'); }); }, /*----- End of dimension click ------*/ /*========================================== = Compability search = ==========================================*/ compabilitySearch: function (e) { var $elem = $jQ(this), params = {search: $elem.val()}; if (e.keyCode === 13) { pub.processRequest(params); } }, compabilitySelect: function () { var $elem = $jQ(this), href = $elem.find('option:selected').attr('value'), params; // update hash window.location.hash = MLS.util.setHash(href); params = MLS.util.getParamsFromUrl(href); pub.processRequest(params); }, facetClick: function (e) { e.preventDefault(); var $elem = $jQ(this),//e.currentTarget, href = $elem.find('a').attr('href'), params; // update hash window.location.hash = MLS.util.setHash(href); params = MLS.util.getParamsFromUrl(href); pub.processRequest(params); }, /*----- End of Compability search ------*/ /*============================================= = Remove selected facet = =============================================*/ removeFilter: function (e) { e.preventDefault(); var $elem = $jQ(this), href = $elem.attr('href'), params = MLS.util.getParamsFromUrl(href); window.location.hash = MLS.util.setHash(href); pub.processRequest(params); }, /*----- End of remove facet ------*/ /*======================================= = process request = =======================================*/ processRequest: function (params) { // make request MLS.ajax.sendRequest( options.endpoint, params, pub.updateResults ); }, /*----- End of process request ------*/ /*=================================== = update grid = ===================================*/ updateResults : function (data) { if (data.hasOwnProperty('success')) { // update results... options.container.html(data.success.responseHTML); // ... and result count ... $jQ('#content-filter-count').find('strong').text(data.success.count); // ... and filters $cf.replaceWith(data.success.filtersHTML); // ... and even the sort by $jQ('#sort-options').find('ul').replaceWith(data.success.sortByHTML); options.callback(); pub.reInit(); } else { options.container.html(data.error.responseHTML); } }, /*----- End of update grid ------*/ }; return pub; }());
JavaScript
0.000002
@@ -4951,32 +4951,95 @@ FromUrl(href);%0A%0A + window.location.hash = MLS.util.setHash(href);%0A
a865bcf957042157032fbc15805140662c000c55
fix missing dataTables.css in watch
scripts/calfwatch.js
scripts/calfwatch.js
import del from 'rollup-plugin-delete'; import rollupCalf from './rollupCalf'; import serve from 'rollup-plugin-serve'; const fs = require('fs'); const port = require('./config.json').port; const outPath = 'dist/watch/'; const options = rollupCalf( outPath, '[name].js', { _BETA: true, _CSSPATH: `https://localhost:${port}/${outPath}`, _DEV: true }); options.treeshake = false; options.watch = {include: 'src/**'}; options.plugins.push(serve({ contentBase: '', headers: {'Access-Control-Allow-Origin': '*'}, https: { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.crt') }, port })); options.plugins.push(del({ targets: [ `${outPath}*`, `!${outPath}fallenswordhelper.user.js` ] })); export default options;
JavaScript
0.0006
@@ -691,16 +691,49 @@ ath%7D*%60,%0A + %60!$%7BoutPath%7DdataTables.css%60,%0A %60!$%7B
cb8089dec35a495f63bb101d61a65ac9a9ba15ba
Set the focus appropriately when asking the user for an access code.
remoting/webapp/ui_mode.js
remoting/webapp/ui_mode.js
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * Functions related to controlling the modal UI state of the app. UI states * are expressed as HTML attributes with a dotted hierarchy. For example, the * string 'host.shared' will match any elements with an associated attribute * of 'host' or 'host.shared', showing those elements and hiding all others. * Elements with no associated attribute are ignored. */ 'use strict'; /** @suppress {duplicate} */ var remoting = remoting || {}; /** @enum {string} */ // TODO(jamiewalch): Move 'in-session' to a separate web-page so that the // 'home' state applies to all elements and can be removed. remoting.AppMode = { HOME: 'home', UNAUTHENTICATED: 'home.auth', HOST: 'home.host', HOST_WAITING_FOR_CODE: 'home.host.waiting-for-code', HOST_WAITING_FOR_CONNECTION: 'home.host.waiting-for-connection', HOST_SHARED: 'home.host.shared', HOST_SHARE_FAILED: 'home.host.share-failed', HOST_SHARE_FINISHED: 'home.host.share-finished', CLIENT: 'home.client', CLIENT_UNCONNECTED: 'home.client.unconnected', CLIENT_PIN_PROMPT: 'home.client.pin-prompt', CLIENT_CONNECTING: 'home.client.connecting', CLIENT_CONNECT_FAILED_IT2ME: 'home.client.connect-failed.it2me', CLIENT_CONNECT_FAILED_ME2ME: 'home.client.connect-failed.me2me', CLIENT_SESSION_FINISHED_IT2ME: 'home.client.session-finished.it2me', CLIENT_SESSION_FINISHED_ME2ME: 'home.client.session-finished.me2me', HISTORY: 'home.history', CONFIRM_HOST_DELETE: 'home.confirm-host-delete', ASK_PIN: 'home.ask-pin', IN_SESSION: 'in-session' }; /** * @param {Element} element The element to check. * @param {string} attr The attribute on the element to check. * @param {string} mode The mode to check for. * @return {boolean} True if |mode| is found within the element's |attr|. */ remoting.hasModeAttribute = function(element, attr, mode) { return element.getAttribute(attr).match( new RegExp('(\\s|^)' + mode + '(\\s|$)')) != null; }; /** * Update the DOM by showing or hiding elements based on whether or not they * have an attribute matching the specified name. * @param {string} mode The value against which to match the attribute. * @param {string} attr The attribute name to match. * @return {void} Nothing. */ remoting.updateModalUi = function(mode, attr) { var modes = mode.split('.'); for (var i = 1; i < modes.length; ++i) modes[i] = modes[i - 1] + '.' + modes[i]; var elements = document.querySelectorAll('[' + attr + ']'); for (var i = 0; i < elements.length; ++i) { var element = /** @type {Element} */ elements[i]; var hidden = true; for (var m = 0; m < modes.length; ++m) { if (remoting.hasModeAttribute(element, attr, modes[m])) { hidden = false; break; } } element.hidden = hidden; } }; /** * @type {remoting.AppMode} The current app mode */ remoting.currentMode = remoting.AppMode.HOME; /** * Change the app's modal state to |mode|, determined by the data-ui-mode * attribute. * * @param {remoting.AppMode} mode The new modal state. */ remoting.setMode = function(mode) { remoting.updateModalUi(mode, 'data-ui-mode'); console.log('App mode: ' + mode); remoting.currentMode = mode; if (mode == remoting.AppMode.IN_SESSION) { document.removeEventListener('keydown', remoting.ConnectionStats.onKeydown, false); } else { document.addEventListener('keydown', remoting.ConnectionStats.onKeydown, false); } if (mode == remoting.AppMode.HOME) { var display = function() { remoting.hostList.display(); }; remoting.hostList.refresh(display); } }; /** * Get the major mode that the app is running in. * @return {string} The app's current major mode. */ remoting.getMajorMode = function() { return remoting.currentMode.split('.')[0]; };
JavaScript
0.000065
@@ -3004,16 +3004,171 @@ hidden;%0A + if (!hidden) %7B%0A var autofocusNode = element.querySelector('%5Bautofocus%5D');%0A if (autofocusNode) %7B%0A autofocusNode.focus();%0A %7D%0A %7D%0A %7D%0A%7D;%0A%0A
2e23beb2a3df26ecd216d7640c0a1bb8c967bf59
Update math.js
lib/assets/javascripts/do/helpers/math.js
lib/assets/javascripts/do/helpers/math.js
// least common multiple Math.lcm = function() { var _factors = []; // arguments returns the arguments of js function for(var i in arguments) { if( arguments.hasOwnProperty(i) ){ _factors.push(parseInt(arguments[i])); } } return _factors.gcd(); } Array.prototype.lcm = function() { } // Considerar algumas propriedades para o algorítmo ficar mais rápido e não precisar fazer conta, exemplos: // Para apenas dois números o Algorítmo de Euclides é mais rápido // Se dois ou mais valores forem múltiplos entre si, então o MDC será o menor dentre eles; // Seja n a quantidade de termos a ser calculado o MDC, se n <= 3, e se um dos termos for primo, então o MDC será 1 // Se dois termos forem primos, então o MDC também será 1, visto que dois números primos distintos nunca serão múltiplos // MDC de valores iguais // greatest common divisor Math.gcd = function() { var _factors = []; // arguments returns the arguments of js function for(var i in arguments) { if( arguments.hasOwnProperty(i) ){ _factors.push(parseInt(arguments[i])); } } return _factors.gcd(); } Array.prototype.gcd = function() { var _factors = [], smallerFactorsHash = {}, factor = 2, dividend = 1, count = 1, smallerCommonProduct = 1, _arr = this, powFactor = null ; _arr.map(function(item) { if(item < 0){ item *= -1; } dividend = item; while ( dividend > 1 ) { factor = dividend.firstMultiple(); dividend = dividend/dividend.firstMultiple(); // guard sum of the same divisor if( dividend.firstMultiple() === factor ) { count++; } else { _factors.push(factor); // map smaller factors powFactor = Math.pow( factor, count ); if( factor in smallerFactorsHash ) { if( powFactor < smallerFactorsHash[factor] ) { smallerFactorsHash[factor] = powFactor; } } else { smallerFactorsHash[factor] = powFactor; } count = 1; } } }); // check common factors _factors = _factors.sort(); _factors.map(function(n, i) { if( n === _factors[i+1] ) { count++; } else { if( count === _arr.length ) { smallerCommonProduct *= smallerFactorsHash[n]; } count = 1; } }); return smallerCommonProduct; }
JavaScript
0.000002
@@ -88,32 +88,33 @@ turns the argume +g nts of js functi @@ -248,35 +248,35 @@ return _factors. -gcd +lcm ();%0A%7D%0A%0AArray.pro
67638baa1c94e18f145ae8579b5eb676a523a8d0
fix ext
app/templates/_Gruntfile.js
app/templates/_Gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ sass: { dist: { files: [ { expand: true, cwd: "<%= src_dir %>/css", src: ["*.scss"], dest: "<%= dest_dir %>/css", ext: ".css" } ] } }, connect: { server: { options: { port: <%= port %>, hostname: "*", base: "<%= dest_dir %>" } } }, watch: { sass: { files: ["<%= src_dir %>/css/*.sass"], tasks: ["sass:dist"] }, livereload: { files: ["<%= dest_dir %>/css/*.css", "<%= dest_dir %>/css/**/*.css"], options: { livereload: true } } } }); grunt.loadNpmTasks("grunt-contrib-connect"); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-contrib-sass"); grunt.registerTask("livereload", ["connect:server", "watch"]); grunt.registerTask("default", []); };
JavaScript
0.000047
@@ -532,17 +532,17 @@ /css/*.s -a +c ss%22%5D,%0A
3598e8b3a76765ffc473f33c79d574324e7f2df1
set width only for first-child labels
src/code.js
src/code.js
'use strict' const AudioContext=require('./audio-context') const Loader=require('./loader') const AudioGraph=require('./audio-graph') const Canvas=require('./canvas') const Lines=require('crnx-base/lines') const JsLines=require('crnx-base/js-lines') const InterleaveLines=require('crnx-base/interleave-lines') const NoseWrapLines=require('crnx-base/nose-wrap-lines') const BaseWebCode=require('crnx-base/web-code') class Code extends BaseWebCode { constructor(options,i18n) { super() this.i18n=i18n this.featureContext={} this.features=[ new AudioContext(options.api), new Loader(options.loader), new AudioGraph(options.graph), new Canvas(options.canvas), ] // possible feature context flags: // alignedInputs = all input labels have to be the same width; requested by equalizer // audioContext = // AudioContext has to assign the audio context to var ctx // AudioGraph has to output the js // media elements of AudioGraph have to have crossorigin enabled // canvas = Canvas has to output <canvas> element and create var canvas and var canvasContext // canvasVolumeGradient = Canvas has to create var canvasVolumeGradient // loader = Loader has to provide loadSample() function // loaderOnError = loadSample() caller has to pass the error handler // maxLogFftSize = max log(fft size) of all analysers // maxLogFftSizeNodeJsName = name of analyser node with max log(fft size); if set, Canvas has to allocate analyserData array // visualization functions, either undefined or set to VisFunction object: // visualizeWaveformFn // visualizeFrequencyBarsFn // visualizeFrequencyOutlineFn // visualizeVolumeFn // counters: // canvasVolumeMeterCounter = number of volume meters, for communication between volume vis fns // helpers: // getConnectAssignJsLines = set by AudioContext for (const feature of this.features) { feature.requestFeatureContext(this.featureContext) } this.isInteresting=!!this.featureContext.audioContext } get basename() { return 'webaudio' } get lang() { return this.i18n.lang } get title() { return this.i18n('code.title') } get styleLines() { const a=Lines.b() if (this.featureContext.alignedInputs) { a( "label {", " display: inline-block;", " width: 10em;", " text-align: right;", " line-height: 0.8em;", "}", ".min {", " display: inline-block;", " width: 5em;", " text-align: right;", "}", ".max {", " display: inline-block;", " width: 5em;", " text-align: left;", "}" ) } if (this.featureContext.canvas) { a( "canvas {", " border: 1px solid;", "}" ) } return a.e() } get bodyLines() { return Lines.bae( ...this.features.map(feature=>feature.getHtmlLines(this.featureContext,this.i18n)) ) } get scriptLines() { return InterleaveLines.bae( ...this.features.map(feature=>feature.getInitJsLines(this.featureContext,this.i18n)), NoseWrapLines.b( JsLines.bae( "function visualize() {" ), JsLines.bae( " requestAnimationFrame(visualize);", "}", "requestAnimationFrame(visualize);" ) ).ae( ...this.features.map(feature=>feature.getPreVisJsLines(this.featureContext,this.i18n)), ...this.features.map(feature=>feature.getVisJsLines(this.featureContext,this.i18n)) ) ) } } module.exports=Code
JavaScript
0.000001
@@ -2228,16 +2228,28 @@ %09%09%22label +:first-child %7B%22,%0A%09%09%09
a860a544772f9ab06b866cbfe3e493229b6a514a
store promises in content type cache
packages/data/addon/services/cardstack-data.js
packages/data/addon/services/cardstack-data.js
import Service from '@ember/service'; import { inject } from '@ember/service'; import { camelize } from '@ember/string'; import { defaultBranch } from '@cardstack/plugin-utils/environment'; import { singularize, pluralize } from 'ember-inflector'; import DS from 'ember-data'; const noFields = '___no-fields___'; function getType(record) { return record.get('type') || record.constructor.modelName; } export default Service.extend({ store: inject(), init() { this._super(); this._loadedRecordsCache = {}; this._contentTypeCache = {}; }, async load(branch, type, id, format) { branch = branch || defaultBranch; let store = this.get('store'); let contentType = await this._getContentType(type); let fieldset = contentType.get(`fieldsets.${format}`); if (!fieldset) { return await store.findRecord(singularize(type), id, { branch }); } let include = fieldset.map(i => i.field).join(',') || noFields; // note that ember data ignores an empty string includes, so setting to nonsense field let record = await store.findRecord(type, id, { include, branch }); await this._loadRelatedRecords(branch, record, format); return record; }, // caching the content types to more efficiently deal with parallel content type lookups async _getContentType(type) { if (this._contentTypeCache[type]) { return await this._contentTypeCache[type]; } this._contentTypeCache[type] = await this.get('store').findRecord('content-type', pluralize(type)); return await this._contentTypeCache[type]; }, async _loadRelatedRecords(branch, record, format) { if (!record || !getType(record)) { return; } let contentType = await this._getContentType(getType(record)); let fieldset = contentType.get(`fieldsets.${format}`); if (!fieldset || !fieldset.length) { return; } // record is already loaded, you are all done let recordLoadPromises = []; for (let fieldItem of fieldset) { let fieldRecord = await record.get(camelize(fieldItem.field)); if (!fieldRecord) { continue; } if (fieldRecord instanceof DS.ManyArray) { for (let fieldRecordItem of fieldRecord.toArray()) { recordLoadPromises.push(this._recurseRecord(branch, fieldRecordItem, fieldItem.format)); } } else { recordLoadPromises.push(this._recurseRecord(branch, fieldRecord, fieldItem.format)); } } await Promise.all(recordLoadPromises); }, async _recurseRecord(branch, record, format) { let loadedRecord = await this._loadRecord(branch, getType(record), record.id, format); if (!loadedRecord) { return; } await this._loadRelatedRecords(branch, loadedRecord, format); }, async _loadRecord(branch, type, id, format) { let store = this.get('store'); let fieldRecordType = await this._getContentType(type); let fieldset = fieldRecordType.get(`fieldsets.${format}`); if (!fieldset) { return; } let include = fieldset.map(i => i.field).join(',') || noFields; // note that ember data ignores an empty string includes, so setting to nonsense field let cacheKey = `${branch}/${type}/${id}:${include}`; if (this._loadedRecordsCache[cacheKey]) { await this._loadedRecordsCache[cacheKey]; return; // no need to process any further, as it has this record already been loaded into the store } // we need to specify `reload` in order to allow the included resources to be added to the store. // otherwise, if the primary resource is already in the store, ember data is skipping adding the // included resources into the store. this._loadedRecordsCache[cacheKey] = store.findRecord(type, id, { include, reload: true, branch }); return await this._loadedRecordsCache[cacheKey]; } });
JavaScript
0.000001
@@ -1452,22 +1452,16 @@ %5Btype%5D = - await this.ge @@ -3317,15 +3317,8 @@ as -it has this @@ -3325,16 +3325,20 @@ record +has already
567b6eb2851a882a31b9f1621587aef20336a029
Fix problem with osm map, OpenLayers.Control.MouseDefaults() was removed in OpenLayers 2.12
modules/freifunk/htdocs/luci-static/resources/osm.js
modules/freifunk/htdocs/luci-static/resources/osm.js
var map; var layer_mapnik; var layer_tah; var layer_markers; var PI = Math.PI; var latfield = ''; var lonfield = ''; var latfield_id=''; var lonfield_id=''; var centerlon = 10; var centerlat = 52; var zoom = 6; function lon2merc(lon) { return 20037508.34 * lon / 180; } function lat2merc(lat) { lat = Math.log(Math.tan( (90 + lat) * PI / 360)) / PI; return 20037508.34 * lat; } function merc2lon(lon) { return lon*180/20037508.34; }; function merc2lat(lat) { return Math.atan(Math.exp(lat*PI/20037508.34))*360/PI-90; }; OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, { defaultHandlerOptions: { 'single': true, 'double': false, 'pixelTolerance': 0, 'stopSingle': false, 'stopDouble': false }, initialize: function(options) { this.handlerOptions = OpenLayers.Util.extend( {}, this.defaultHandlerOptions ); OpenLayers.Control.prototype.initialize.apply( this, arguments ); this.handler = new OpenLayers.Handler.Click( this, { 'click': this.trigger }, this.handlerOptions ); }, trigger: function(e) { var lonlat = map.getLonLatFromViewPortPx(e.xy); lat=merc2lat(lonlat.lat); lon=merc2lon(lonlat.lon); if(parent.document.getElementById(latfield_id)==null){ latfield=document.getElementById('osmlat'); }else{ latfield=parent.document.getElementById(latfield_id); } if(parent.document.getElementById(lonfield_id)==null){ lonfield=document.getElementById('osmlon'); }else{ lonfield=parent.document.getElementById(lonfield_id); } latfield.value = lat; lonfield.value = lon; } }); function init(){ var field = window.name.substring(0, window.name.lastIndexOf(".")); if(parent.document.getElementById(field+".latfield")!=null){ latfield_id = parent.document.getElementById(field+".latfield").value; document.getElementById('osm').style.display="none"; } if(parent.document.getElementById(field+".lonfield")!=null){ lonfield_id = parent.document.getElementById(field+".lonfield").value; } if(parent.document.getElementById(field+".centerlat")!=null){ centerlat =parseFloat(parent.document.getElementById(field+".centerlat").value); } if(parent.document.getElementById(field+".centerlon")!=null){ centerlon = parseFloat(parent.document.getElementById(field+".centerlon").value); } if(parent.document.getElementById(field+".zoom")!=null){ zoom = parseFloat(parent.document.getElementById(field+".zoom").value); } } function drawmap() { OpenLayers.Lang.setCode('de'); mapdiv=document.getElementById('map'); mapdiv.style.height=window.innerHeight+"px"; mapdiv.style.width=window.innerWidth+"px"; map = new OpenLayers.Map('map', { projection: new OpenLayers.Projection("EPSG:900913"), displayProjection: new OpenLayers.Projection("EPSG:4326"), controls: [ new OpenLayers.Control.MouseDefaults(), new OpenLayers.Control.PanZoomBar()], maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34, 20037508.34, 20037508.34), numZoomLevels: 18, maxResolution: 156543, units: 'meters' }); layer_mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik"); map.addLayers([layer_mapnik]); var y =lat2merc(centerlat); var x =lon2merc(centerlon); map.setCenter(new OpenLayers.LonLat(x, y), zoom); // Check for geolocation support if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(function(position){ var y =lat2merc(position.coords.latitude); var x =lon2merc(position.coords.longitude); map.setCenter(new OpenLayers.LonLat(x, y), '17'); }); } var click = new OpenLayers.Control.Click(); map.addControl(click); click.activate(); }
JavaScript
0.000001
@@ -2826,21 +2826,18 @@ rol. -MouseDefaults +Navigation (),%0A
f23dd7150f270c843707f1a06ac12a6af63b7320
Remove unused wheel event detection in isEventSupported (#11822)
packages/react-dom/src/events/isEventSupported.js
packages/react-dom/src/events/isEventSupported.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'; let useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if ( !ExecutionEnvironment.canUseDOM || (capture && !('addEventListener' in document)) ) { return false; } const eventName = 'on' + eventNameSuffix; let isSupported = eventName in document; if (!isSupported) { const element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } export default isEventSupported;
JavaScript
0
@@ -248,355 +248,8 @@ ';%0A%0A -let useHasFeature;%0Aif (ExecutionEnvironment.canUseDOM) %7B%0A useHasFeature =%0A document.implementation &&%0A document.implementation.hasFeature &&%0A // always returns true in newer browsers as per the standard.%0A // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature%0A document.implementation.hasFeature('', '') !== true;%0A%7D%0A%0A /**%0A @@ -1190,235 +1190,8 @@ %7D%0A%0A - if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') %7B%0A // This is the only way to test support for the %60wheel%60 event in IE9+.%0A isSupported = document.implementation.hasFeature('Events.wheel', '3.0');%0A %7D%0A%0A re
a561a245258626c90a77ff4216a2620ecfc383be
Update app.js
bootstrap/app.js
bootstrap/app.js
/** * * Load the global `app` Object which will be used as reference throughout the project. By default the only thing that * will automatically be loaded is the current environment configuration. * * @author Salvatore Garbesi <[email protected]> * @module bootstrap/app * **/ module.exports = !function(global) { 'use strict'; // The application namespace. global.app = {}; }(global);
JavaScript
0.000002
@@ -5,12 +5,14 @@ *%0A* -Load +Define the @@ -54,16 +54,18 @@ used as +a referenc
ee11d8f1361d3df1b231b21c4327dab3eb59639e
Update index.js
test/assets/js/index.js
test/assets/js/index.js
var accessToken = "db6b486f323c410a82d597f2e1ad6a5c", subscriptionKey = "878cd060684e45099834389e8de74e63", baseUrl = "https://api.api.ai/v1/", $speechInput, // The input element, the speech box $recBtn, // Toggled recording button value recognition, // Used for accessing the HTML5 Speech Recognition API messageRecording = " я слушаю...", messageCouldntHear = "я не слышу", messageInternalError = "пока я немогу говорить, сначала надо набратся ума", messageSorry = "даже и сказать нечего"; $(document).ready(function() { $speechInput = $("#speech"); $recBtn = $("#rec"); $speechInput.keypress(function(event) { if (event.which == 13) { event.preventDefault(); send(); } }); $recBtn.on("click", function(event) { switchRecognition(); }); $(".debug__btn").on("click", function() { $(this).next().toggleClass("is-active"); return false; }); }); function switchRecognition() { if (recognition) { stopRecognition(); } else { startRecognition(); } } function startRecognition() { recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimResults = false; recognition.onstart = function(event) { respond(messageRecording); updateRec(); }; recognition.onresult = function(event) { recognition.onend = null; var text = ""; for (var i = event.resultIndex; i < event.results.length; ++i) { text += event.results[i][0].transcript; } setInput(text); stopRecognition(); }; recognition.onend = function() { respond(messageCouldntHear); stopRecognition(); }; recognition.lang = "ru-RUS"; recognition.start(); } function stopRecognition() { if (recognition) { recognition.stop(); recognition = null; } updateRec(); } function setInput(text) { $speechInput.val(text); send(); } function updateRec() { $recBtn.html(recognition ? "<i class='fa fa-square'>" : "<i class='fa fa-circle'>"); } function send() { var text = $speechInput.val(); $.ajax({ type: "POST", url: baseUrl + "query/", contentType: "application/json; charset=utf-8", dataType: "json", headers: { "Authorization": "Bearer " + accessToken, "ocp-apim-subscription-key": subscriptionKey }, data: JSON.stringify({q: text, lang: "en", sessionId: "somerandomthing"}), success: function(data) { prepareResponse(data); }, error: function() { respond(messageInternalError); } }); } function prepareResponse(val) { var spokenResponse = val.result.speech; // actionResponse = val.result.action; // respond() respond(spokenResponse); var debugJSON = JSON.stringify(val, undefined, 2); debugRespond(debugJSON); // Print JSON to Debug window } function debugRespond(val) { $("#response").text(val); } function respond(val) { if (val == "") { val = messageSorry; } if (val !== messageRecording) { var msg = new SpeechSynthesisUtterance(); msg.voiceURI = "native"; msg.text = val; msg.lang = "en-US"; window.speechSynthesis.speak(msg); } $("#spokenResponse").addClass("is-active").find(".spoken-response__text").html(val); $("#spokenResponse").style('opacity:1;'); }
JavaScript
0.000002
@@ -3242,50 +3242,121 @@ l);%0A - $(%22#spokenResponse%22).style('opacity:1;') +%7D%0Afunction r() %7B%0A document.getElementById(%22demo%22).innerHTML = %22%3Ci class=%22fa fa-times%22 aria-hidden=%22true%22%3E%3C/i%3E%22 ;%0A%7D%0A
b834c208584853e65709751534e73bad92e536df
fix page_size in plot.js
daiquiri/query/static/query/js/services/plot.js
daiquiri/query/static/query/js/services/plot.js
app.factory('PlotService', ['$resource', '$q', '$filter', function($resource, $q, $filter) { /* get the base url */ var baseurl = angular.element('meta[name="baseurl"]').attr('content'); /* configure resources */ var resources = { rows: $resource(baseurl + 'serve/api/rows/') } var service = { params: { page_size: 10000, }, columns: null, values: {}, errors: {}, labels: {}, ready: false }; service.init = function(rows_url, params, columns) { service.ready = false; angular.extend(service.params, params); service.columns = columns; if (angular.isDefined(service.columns[0])) { service.values.x = service.columns[0].name; } else { service.values.x = null; } if (angular.isDefined(service.columns[1])) { service.values.y = service.columns[1].name; } else { service.values.y = null; } service.update(); }; service.update = function() { service.clear(); if (service.values.x) { var x_column = $filter('filter')(service.columns, {name: service.values.x}, true)[0]; if (['int', 'long', 'float', 'double'].indexOf(x_column.datatype) > -1) { service.errors.x = null; service.labels.x = x_column.name; if (x_column.unit && x_column.unit.length > 0) { service.labels.x += ' [' + x_column.unit + ']'; } } else { service.errors.x = [interpolate(gettext('Columns of the type %s can not be plotted'), [x_column.datatype])]; } } else { service.errors.x = [gettext('No column selected')]; } if (service.values.y) { var y_column = $filter('filter')(service.columns, {name: service.values.y}, true)[0]; if (['int', 'long', 'float', 'double'].indexOf(y_column.datatype) > -1) { service.errors.y = null; service.labels.y = y_column.name; if (y_column.unit && y_column.unit.length > 0) { service.labels.y += ' [' + y_column.unit + ']'; } } else { service.errors.y = [interpolate(gettext('Columns of the type %s can not be plotted'), [y_column.datatype])]; } } else { service.errors.y = [gettext('No column selected')]; } if (service.errors.x === null && service.errors.y === null) { service.fetch().then(function() { service.draw(); service.ready = true; }); } else { service.ready = true; } }; service.clear = function() { $('#canvas').empty(); } service.fetch = function() { var x_params = angular.extend({}, service.params, { column: service.values.x, page_size: service.page_size }); var y_params = angular.extend({}, service.params, { column: service.values.y, page_size: service.page_size }); return $q.all([ resources.rows.paginate(x_params).$promise, resources.rows.paginate(y_params).$promise ]).then(function(results) { service.source = new Bokeh.ColumnDataSource({ data: { x: results[0].results, y: results[1].results } }); }); }; service.draw = function() { var xmin = Math.min.apply(null, service.source.data.x), xmax = Math.max.apply(null, service.source.data.x), ymin = Math.min.apply(null, service.source.data.y), ymax = Math.max.apply(null, service.source.data.y); if (!isNaN(xmin) && !isNaN(xmax) && !isNaN(ymin) && !isNaN(ymax)) { // compute a 1% padding around the data var xpad, ypad; if (xmax == xmin) { xpad = 0.001 * xmax; } else { xpad = 0.01 * (xmax - xmin); } if (ymax == ymin) { ypad = 0.001 * ymax; } else { ypad = 0.01 * (ymax - ymin); } // create some ranges for the plot var x_range = new Bokeh.Range1d({ start: xmin - xpad, end: xmax + xpad }); var y_range = new Bokeh.Range1d({ start: ymin - ypad, end: ymax + ypad }); // make the plot var tools = "pan,crosshair,wheel_zoom,box_zoom,reset,save"; var figure = new Bokeh.Plotting.figure({ height: 840, height: 500, x_range: x_range, y_range: y_range, plot_width: $('.col-md-9').width(), tools: tools, // output_backend: 'webgl', background_fill_color: '#f5f5f5' }); figure.xaxis.axis_label = service.labels.x; figure.xaxis.axis_label_text_font = 'DroidSans' figure.yaxis.axis_label = service.labels.y; figure.yaxis.axis_label_text_font = 'DroidSans' figure.toolbar.active_scroll = figure.toolbar.wheel_zoom; figure.outline_line_color = '#dddddd'; figure.toolbar.logo = null; var circles = figure.circle({ x: { field: "x" }, y: { field: "y" }, source: service.source, fill_alpha: 0.5 }); Bokeh.Plotting.show(figure, $('#canvas')); $('.bk-button-bar-list[type="scroll"] .bk-toolbar-button').click(); $('.bk-button-bar-list[type="inspectors"] .bk-toolbar-button').click(); } } return service; }]);
JavaScript
0.000004
@@ -3009,50 +3009,8 @@ es.x -,%0A page_size: service.page_size %0A @@ -3118,50 +3118,8 @@ es.y -,%0A page_size: service.page_size %0A @@ -4952,19 +4952,16 @@ - // output_
bb9e0da5bf14fe2a164b8c623b671eb3b2ae10b8
Update script.js
js/script.js
js/script.js
(function(window, document, undefined) { window.onload = init; function init() { //create an empty map var map = new Array(960); for(var i = 0; i < 960; i++) { map[i] = new Array(540); } //get the canvas var canvas = document.getElementById("mapcanvas"); var c = canvas.getContext("2d"); c.imageSmoothingEnabled = false; var imgData = c.createImageData(1, 1); var i; for (i = 0; i < imgData.data.length; i += 4) { imgData.data[i+0] = 255; imgData.data[i+1] = 0; imgData.data[i+2] = 0; imgData.data[i+3] = 255; } function ncount(i,j) { var i1 = i+1; var i2 = i-1; var j1 = j+1; var j2 = j-1; var neighbors = 0; if(i1 < 960 && i2 >=0 && j1 < 540 && j2 >=0){ if(map[i1][j1] == 1){ neighbors++; } if(map[i][j1] == 1){ neighbors++; } if(map[i2][j1] == 1){ neighbors++; } if(map[i1][j] == 1){ neighbors++; } if(map[i2][j] == 1){ neighbors++; } if(map[i1][j2] == 1){ neighbors++; } if(map[i][j2] == 1){ neighbors++; } if(map[i2][j2] == 1){ neighbors++; } } return neighbors; } //when we click, assign values and then paint document.getElementById("startbtn").onclick = test; function test() { for(j = 0; j <canvas.width; j++){ for(k = 0; k<canvas.height; k++){ if(Math.random() < .45){ c.putImageData(imgData, j, k); } } } } var it = 1; function paint() { if(it == 1){ //fill the values for(var i = 0; i< 960; i++) { for(var j = 0; j < 540; j++) { if(Math.random() < .45){ map[i][j] = 1; } else { map[i][j] = 0; } } } } else { for(var i = 0; i< 960; i++) { for(var j = 0; j < 540; j++){ var nc = ncount(i,j); switch(nc){ case 4: break; case 5: map[i][j] = 1; break; case 6: map[i][j] = 1; break; case 7: map[i][j] = 1; break; case 8: map[i][j] = 1; break; default: map[i][j] = 0; } } } } //paint the map for(var i = 0; i < 960; i++) { for(var j = 0; j< 540; j++){ if(map[i][j] == 1){ c.putImageData(imgData, i, j); }else { } } } it++; document.getElementById("iter").innerHTML = it; } } })(window, document, undefined);
JavaScript
0.000002
@@ -390,37 +390,27 @@ c. -imageSmoothingEnabled = false +translate(0.5, 0.5) ;%0A
9384e89b35c2f11acb21455cf5f1a05421bd69e7
add imagemin task to scss watch refs #35
app/templates/_gruntfile.js
app/templates/_gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { options: { livereload: true, spawn: false }, // Styling scss: { files: 'components/**/*.scss', tasks: ['compass:development', 'csslint'] }, // Scripting js: { files: ['components/app/**/*.js', '!components/app/_deferred/**/*.js'], tasks: ['requirejs:development', 'jshint'], }, js_deferred: { files: ['components/app/_deferred/**/*.js'], tasks: ['uglify:deferred', 'jshint'], }, js_bower: { files: ['components/bower/**/*.js'], tasks: ['uglify:external', 'requirejs:development'], }, // HTML html: { files: ['**/*.html', '!components/bower/**/*.html', '!build/**/*.html'], tasks: ['replace:development'], }, // Images img_content: { files: 'img/**/*.{png,gif,jpg,svg}', tasks: ['imagemin:content'], }, img_background: { files: 'components/**/*.{png,gif,jpg,svg}', tasks: ['clean:css', 'imagemin:backgrounds' , 'compass:development', 'clean:development', 'csslint'], } }, compass: { options: { // banner: "/* <%= pkg.author %>, Version: <%= pkg.version %> */", // httpPath: "/build", // imagesPath: 'assets/img', // specify: '*.scss' asset_cache_buster: false, cssDir: 'build/assets/css', httpImagesPath: '/assets/img', imagesDir: 'build/assets/img', noLineComments: true, sassDir: 'components' }, development: { options: { environment: 'development' } }, production: { options: { httpPath: "/", // . = relative environment: 'production' } } }, replace: { modules: { options: { patterns: [ { match: /{app:{(.+)}}/g, replacement: function (match, placeholder) { return grunt.file.read('components/app/' + placeholder + '/' + placeholder + '.html'); } }, { match: /{deferred:{(.+)}}/g, replacement: function (match, placeholder) { return grunt.file.read('components/app/_deferred/' + placeholder + '/' + placeholder + '.html'); } } ] }, files: [ { expand: true, flatten: true, src: ['*.html'], dest: 'build/' } ] } }, requirejs: { development: { options: { // baseUrl: "modules", useStrict: true, mainConfigFile: "components/<%= _.slugify(ProjectName) %>.js", name: "<%= _.slugify(ProjectName) %>", optimize: 'none', out: "build/assets/js/<%= _.slugify(ProjectName) %>.js" } } }, uglify: { deferred: { options: { beautify: true }, files: [{ expand: true, flatten: true, cwd: 'components/app/_deferred', src: ['**/*.js'], dest: 'build/assets/js/deferred' }] }, external: { options: { beautify: true }, files: { <% if (includeModernizr) { %>'build/assets/js/libs/modernizr.js': ['components/bower/modernizr-shim/modernizr.min.js'],<% } %> 'build/assets/js/libs/require.js': ['components/bower/requirejs/require.js'] } } }, imagemin: { content: { files: [{ flatten: true, expand: true, cwd: 'img', src: ['**/*.{png,jpg,gif,svg}'], dest: 'build/img' }] }, backgrounds: { files: [{ flatten: true, expand: true, cwd: 'components/app', src: ['**/*.{jpg,gif,png,svg}'], dest: 'build/assets/img' }] } }, jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: ['components/app/**/*.js'] }, csslint: { options: { csslintrc: '.csslintrc', import: false }, lax: { src: ['build/assets/css/**/*.css'] } }, accessibility: { options : { accessibilityLevel: 'WCAG2<%= WCAG2 %>', outputFormat: 'txt', domElement: true }, development : { files: [{ expand : true, cwd : 'build/', src : ['*.html'], dest : 'build/WCAG2-reports/', ext : '-report.txt' }] } }, clean: { development: { src: ["build/assets/img/**/*.svg"] }, css: { src: ["build/assets/css/**/*.css"] } } }); grunt.loadNpmTasks('grunt-accessibility'); // grunt.loadNpmTasks('grunt-bower-requirejs'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.loadNpmTasks('grunt-contrib-csslint'); grunt.loadNpmTasks('grunt-contrib-imagemin'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-requirejs'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-replace'); grunt.registerTask('default', ['replace', 'imagemin', 'compass:development', 'requirejs:development', 'uglify', 'clean:development', 'csslint', 'jshint', 'accessibility:development']); };
JavaScript
0
@@ -266,24 +266,36 @@ tasks: %5B +'imagemin', 'compass:dev
5d606318d21b335fef86c0a0600e1981e117b266
Edit screen was not loading correctly after going to review screen.
src/main/web/florence/js/functions/_viewWorkspace.js
src/main/web/florence/js/functions/_viewWorkspace.js
function viewWorkspace(path) { window.intIntervalTime = 100; var workspace_menu_main = '<nav class="fl-panel fl-panel--menu">' + ' <ul class="fl-main-menu">' + ' <li class="fl-main-menu__item fl-main-menu__item--browse">' + ' <a href="#" class="fl-main-menu__link">Browse</a>' + ' </li>' + ' <li class="fl-main-menu__item fl-main-menu__item--create">' + ' <a href="#" class="fl-main-menu__link">Create</a>' + ' </li>' + ' <li class="fl-main-menu__item fl-main-menu__item--edit">' + ' <a href="#" class="fl-main-menu__link">Edit</a>' + ' </li>' + ' <li class="fl-main-menu__item fl-main-menu__item--review">' + ' <a href="#" class="fl-main-menu__link">Review</a>' + ' </li>' + ' </ul>' + '</nav>' + '<section class="fl-panel fl-panel--sub-menu">' + '</section>'; var workspace_menu_review = '<section class="fl-panel">' + ' <div class="fl-review-list-holder"></div>' + ' <button class="fl-button fl-button--big fl-button--center fl-review-page-edit-button" style="display: none;">Edit this page</button>' + ' <button class="fl-button fl-button--big fl-button--center fl-review-page-review-button" style="display: none;">Happy with this send to content owner</button>' + '</section>'; var currentPath = ''; if (path) { currentPath = path; } var workspace_preview = '<section class="fl-panel fl-panel--preview">' + ' <div class="fl-panel--preview__inner">' + ' <iframe src="/index.html#!' + currentPath + '" class="fl-panel fl-panel--preview__content"></iframe>' + ' </div>' + '</section>'; //build view $('.fl-view').html(workspace_menu_main + workspace_preview); enablePreview(); var collectionName = localStorage.getItem("collection"); localStorage.removeItem("pageurl"); var pageurl = $('.fl-panel--preview__content').contents().get(0).location.href; localStorage.setItem("pageurl", pageurl); //click handlers $('.fl-main-menu__link').click(function () { $('.fl-panel--sub-menu').empty(); $('.fl-main-menu__link').removeClass('fl-main-menu__link--active'); $('.fl-main-menu__link').removeClass('fl-main-menu__link--active'); $(this).addClass('fl-main-menu__link--active'); // setupFlorenceWorkspace($(this)); if ($(this).parent().hasClass('fl-main-menu__item--browse')) { enablePreview(); } else if ($(this).parent().hasClass('fl-main-menu__item--create')) { disablePreview(); loadCreateBulletinScreen(collectionName); } else if ($(this).parent().hasClass('fl-main-menu__item--edit')) { viewWorkspace(path); clearInterval(window.intervalID); enablePreview(); window.intervalID = setInterval(function () { checkForPageChanged(function () { loadPageDataIntoEditor(collectionName, true); }); }, window.intIntervalTime); } else if ($(this).parent().hasClass('fl-main-menu__item--review')) { $('.fl-panel--sub-menu').html(workspace_menu_review); enablePreview(); //$('.fl-panel--preview__inner').addClass('fl-panel--preview__inner--active'); loadReviewScreen(collectionName); clearInterval(window.intervalID); window.intervalID = setInterval(function () { checkForPageChanged(function () { updateReviewScreen(collectionName); }); }, window.intIntervalTime); } else { //browse } }); $('.fl-main-menu__link').removeClass('fl-main-menu__link--active'); $('.fl-main-menu__item--browse .fl-main-menu__link').addClass('fl-main-menu__link--active'); //removePreviewColClasses(); //removeSubMenus(); //$(this).addClass('fl-main-menu__link--active'); $('.fl-panel--preview').addClass('col--7'); //$('.fl-panel--sub-menu').show(); }
JavaScript
0
@@ -2172,81 +2172,8 @@ e'); -%0A%0A $('.fl-main-menu__link').removeClass('fl-main-menu__link--active'); %0A @@ -2586,34 +2586,59 @@ %7B%0A -viewWorkspace(path +loadPageDataIntoEditor(collectionName, true );%0A
d3e95bb46397c7da260ae0a303b18a5898d6411e
Use rnw view instead of div
packages/reddio-ui/src/components/PostListSort.js
packages/reddio-ui/src/components/PostListSort.js
import React from "react"; import { Picker } from "react-native"; import { withRouter } from "react-router-dom"; import first from "lodash/first"; import last from "lodash/last"; import dropRight from "lodash/dropRight"; const sortTypes = { hot: "hot", top: "top", new: "new" }; export function getSortType(location) { const { pathname } = location; if (pathname === "/") { return sortTypes.hot; } const pathParts = pathname.split("/"); const pathNamedParts = pathParts.filter(Boolean); const lastPart = last(pathNamedParts); if (sortTypes[lastPart.toLowerCase()]) { return sortTypes[lastPart.toLowerCase()]; } // Return the default sortType of hot if we don't know return sortTypes.hot; } export function getSortRange(location) { // TODO } export function resolveSortTypePath(location, newSort) { const { pathname, search } = location; // Depending on if we're on a subreddit or a multireddit // We could have differing number of parts in our path. const pathParts = pathname.split("/"); const pathNamedParts = pathParts.filter(Boolean); // Handle root case, where currently the user is at the root path const atRoot = pathNamedParts.length <= 1; if (atRoot) { if (pathname === "/" && newSort === "hot") { return { pathname, search }; } const newPathname = `/${newSort}`; return { pathname: newPathname, search }; } // Handle subreddits and multireddits // If we're at the root and we're trying to navigate to a hot sort type // We want to preserve the existing path instead of tacking on /hot const atListingRoot = first(pathNamedParts) === "r" && pathNamedParts.length === 2; if (atListingRoot && newSort === "hot") { return { pathname, search }; } const hasSortType = sortTypes[last(pathNamedParts)]; let newParts; if (hasSortType) { newParts = dropRight(pathParts).concat(newSort); } else { newParts = pathParts.concat(newSort); } return { pathname: newParts.join("/"), search }; } export function resolveSortRangePath(location, newRange) { const { pathname, search } = location; return { pathname, search }; } export function PostListSort(props) { const { location } = props; return ( <div className="PostListSort"> <Picker selectedValue={getSortType(location)} onValueChange={sortType => { const nextPath = resolveSortTypePath(location, sortType); props.history.push(nextPath); }} > <Picker.Item label="Hot" value={sortTypes.hot} /> <Picker.Item label="New" value={sortTypes.new} /> <Picker.Item label="Top" value={sortTypes.top} /> </Picker> </div> ); } export default withRouter(PostListSort);
JavaScript
0
@@ -29,22 +29,40 @@ mport %7B -Picker +View, Picker, StyleSheet %7D from @@ -2245,24 +2245,28 @@ %3C -div className=%22P +View style=%7Bstyles.p ostL @@ -2272,17 +2272,17 @@ ListSort -%22 +%7D %3E%0A @@ -2699,11 +2699,12 @@ %3C/ -div +View %3E%0A @@ -2705,24 +2705,102 @@ ew%3E%0A );%0A%7D%0A%0A +const styles = StyleSheet.create(%7B%0A postListSort: %7B%0A padding: 16%0A %7D%0A%7D);%0A%0A export defau
57cba3d511329ada111939d9a15fd91d5b5b139b
Fix comment
lib/cartodb/api/overviews_metadata_api.js
lib/cartodb/api/overviews_metadata_api.js
function OverviewsMetadataApi(pgQueryRunner) { this.pgQueryRunner = pgQueryRunner; } module.exports = OverviewsMetadataApi; // TODO: share this with QueryTablesApi? ... or maintain independence? var affectedTableRegexCache = { bbox: /!bbox!/g, scale_denominator: /!scale_denominator!/g, pixel_width: /!pixel_width!/g, pixel_height: /!pixel_height!/g }; function prepareSql(sql) { return sql .replace(affectedTableRegexCache.bbox, 'ST_MakeEnvelope(0,0,0,0)') .replace(affectedTableRegexCache.scale_denominator, '0') .replace(affectedTableRegexCache.pixel_width, '1') .replace(affectedTableRegexCache.pixel_height, '1') ; } OverviewsMetadataApi.prototype.getOverviewsMetadata = function (username, sql, callback) { // FIXME: Currently using internal function parsed_table // CDB_Overviews should provide the schema information directly. var query = 'SELECT *, _cdb_schema_name(base_table)' + ' FROM CDB_Overviews(CDB_QueryTablesText($windshaft$' + prepareSql(sql) + '$windshaft$))'; this.pgQueryRunner.run(username, query, function handleOverviewsRows(err, rows) { if (err){ callback(err); return; } var metadata = {}; rows.forEach(function(row) { var table = row.base_table; var schema = row._cdb_schema_name; var table_metadata = metadata[table]; if ( !table_metadata ) { table_metadata = metadata[table] = {}; } table_metadata[row.z] = { table: row.overview_table }; table_metadata.schema = schema; }); return callback(null, metadata); }); };
JavaScript
0
@@ -821,19 +821,23 @@ ion -parsed_tabl +_cdb_schema_nam e%0A
6aa3c9b10eb13aea5a4786a41671034edd1ce3d2
remove excess of validation (doesn't make any sense..)
packages/nova-newsletter/lib/server/methods.js
packages/nova-newsletter/lib/server/methods.js
import Campaign from "./campaign.js"; import MailChimpList from "./mailchimp.js"; Meteor.methods({ sendCampaign: function () { if(Users.is.adminById(this.userId)) return Campaign.scheduleNextWithMailChimp(false); }, testCampaign: function () { if(Users.is.adminById(this.userId)) return Campaign.scheduleNextWithMailChimp(true); }, 'newsletter.addUser'(user){ if (!user || !Users.can.editById(this.userId, user)) { throw new Meteor.Error(601, __('sorry_you_cannot_edit_this_user')); } try { return MailChimpList.add(user, false); } catch (error) { throw new Meteor.Error(500, error.message); } }, 'newsletter.removeUser'(user) { if (!user || !Users.can.editById(this.userId, user)) { throw new Meteor.Error(601, __('sorry_you_cannot_edit_this_user')); } try { return MailChimpList.remove(user); } catch (error) { throw new Meteor.Error(500, error.message); } }, 'newsletter.addEmail'(email) { if(Users.is.adminById(this.userId)) { try { return MailChimpList.add(email, true); } catch (error) { throw new Meteor.Error(500, error.message); } } } });
JavaScript
0
@@ -1015,52 +1015,8 @@ ) %7B%0A - if(Users.is.adminById(this.userId)) %7B%0A @@ -1023,26 +1023,24 @@ try %7B%0A - return MailC @@ -1062,26 +1062,24 @@ ail, true);%0A - %7D catch @@ -1090,26 +1090,24 @@ or) %7B%0A - throw new Me @@ -1142,16 +1142,8 @@ e);%0A - %7D%0A
f189dcb04ceb281ac6b134368d74786f89039df7
rename instanceId to id
src/core.js
src/core.js
var $ = require('jquery'); var BaseComponent = require('./component.js'); /** * Web container for all components and services. */ var core = core || (function() { 'use strict'; return { /** * Registered services * @property services * @private */ services: {}, /** * Registered components * @property components * @private */ components: {}, /** * Started components * @property componentInstances * @private */ componentInstances: {}, /** * Defines a new service * @params {String} name * @params {Object} service * @return {Object} this */ registerService: function(name, Service) { if (!this.services[name]) { this.services[name] = Service; } return this; }, /** * Get the service by name * @params {String} name * @return {Object} service instance */ getService: function(name) { var Service = this.services[name] || null; if (typeof Service === 'function') { Service = this.services[name] = new Service(this); } return Service; }, /** * Extend from the base component class and store the reference * @param {String} name - Component blueprint * @param {Object} protoProps - Properties of our defined component * @return {Object} this */ registerComponent: function(name, protoProps) { var parent = BaseComponent; var component, Surrogate; component = function() { parent.apply(this, arguments); }; $.extend(component, parent); Surrogate = function() { this.constructor = component; }; Surrogate.prototype = parent.prototype; component.prototype = new Surrogate(); $.extend(component.prototype, protoProps); component.__super__ = parent.prototype; this.components[name] = component; return this; }, /** * Stats a new component from the component blueprint and returns the reference * @param {String} name * @param {String} instanceId * @param {Object} options * @return {Object} component instance */ startComponent: function(name, instanceId, options) { options = options || {}; var Component = this.components[name]; var instance; if (!!Component) { instance = new Component(instanceId, options, this); this.componentInstances[instanceId] = instance; } else { throw new Error('Component with the type: ' + name + ' is not defined.'); } return instance; }, /** * Stats a new component from the component blueprint and returns the reference * @param {Array} components * @return {Object} component instance */ startComponents: function(components) { var instances = []; $.each(components, function(index, component) { try { instances[index] = this.startComponent(component.name, component.instanceId, component.options); } catch(e) { console.error('Start of component failed: ' + component.instanceId); console.error(e); } }.bind(this)); return instances; }, /** * Get a Component instance by instanceId * @param {String} instanceId - component instance identifier defined with the "startComponent" method * @return {Object} component instance */ getComponent: function(instanceId) { return this.componentInstances[instanceId] || null; }, /** * Facade for destroying a component * @param {Object|String} component Could be an instance or the component id * @return {Object} */ removeComponent: function(component) { if (typeof component === 'string') { this.destroyComponent(component); } else { this.destroyComponent(component.id); } return this; }, /** * Destroys a component and removes its DOM element * @param {String} instanceId * @private */ destroyComponent: function(instanceId) { var instance = this.componentInstances[instanceId]; if (!!instance) { instance.destroy.call(instance); delete this.componentInstances[instanceId]; } return this; } }; })(); module.exports = core;
JavaScript
0.999993
@@ -2428,32 +2428,24 @@ m %7BString%7D i -nstanceI d%0A * @@ -2568,24 +2568,16 @@ (name, i -nstanceI d, optio @@ -2769,24 +2769,16 @@ ponent(i -nstanceI d, optio @@ -2829,24 +2829,16 @@ tances%5Bi -nstanceI d%5D = ins @@ -3455,24 +3455,16 @@ ponent.i -nstanceI d, compo @@ -3584,24 +3584,16 @@ ponent.i -nstanceI d);%0A @@ -3765,24 +3765,16 @@ nce by i -nstanceI d%0A @@ -3795,24 +3795,16 @@ tring%7D i -nstanceI d - comp @@ -3957,32 +3957,24 @@ : function(i -nstanceI d) %7B%0A @@ -4010,24 +4010,16 @@ tances%5Bi -nstanceI d%5D %7C%7C nu @@ -4587,24 +4587,16 @@ tring%7D i -nstanceI d%0A @@ -4657,24 +4657,16 @@ nction(i -nstanceI d) %7B%0A @@ -4710,32 +4710,24 @@ tInstances%5Bi -nstanceI d%5D;%0A @@ -4849,16 +4849,8 @@ es%5Bi -nstanceI d%5D;%0A
f35b8ec8c22956e7461846944260d94d79ae772b
Copy only the required fonts when building
brunch-config.js
brunch-config.js
// Brunch configuration // See http://brunch.io for documentation. 'use strict'; module.exports = { files: { javascripts: { joinTo: { 'scripts/main.js': ['app/scripts/**/*.js', /^node_modules/] } }, stylesheets: { joinTo: { 'styles/main.css': ['app/styles/main.scss'] } } }, modules: { autoRequire: { 'scripts/main.js': ['scripts/main'] } }, paths: { // Exclude test files from compilation watched: ['app'] }, plugins: { copycat: { fonts: ['node_modules/typeface-ubuntu/files'], verbose: false, onlyChanged: true }, postcss: { processors: [ require('autoprefixer')({ browsers: ['> 0.1%'] }) ] }, swPrecache: { swFileName: 'service-worker.js', options: { cacheId: 'connect-four', staticFileGlobs: ['public/**/!(*map*)'], stripPrefix: 'public', replacePrefix: '/connect-four' } } } };
JavaScript
0
@@ -536,16 +536,25 @@ fonts: %5B +%0A 'node_mo @@ -580,17 +580,249 @@ tu/files -' +/ubuntu-latin-400.woff2',%0A 'node_modules/typeface-ubuntu/files/ubuntu-latin-400.woff',%0A 'node_modules/typeface-ubuntu/files/ubuntu-latin-400.eot',%0A 'node_modules/typeface-ubuntu/files/ubuntu-latin-400.svg'%0A %5D,%0A
966f99fa76d3d7a13af6524a9b2c659dc0bddd8f
Remove onFormSubmit
src/components/Budgets/index.js
src/components/Budgets/index.js
import * as BudgetsActions from '../../actions/budgets'; import Form from './Item/Form'; import List from './List'; import * as search from 'searchtabular'; import React, { Component } from 'react'; import Table from './Table'; import { connect } from 'react-redux'; import { Route, Link } from 'react-router-dom'; import { compose } from 'redux'; import { multiInfix } from '../../helpers/utils'; class Budgets extends Component { constructor(props) { super(); this.state = { filter: { field: 'summary', value: '', }, }; this.filterItems = this.filterItems.bind(this); this.onAdd = this.onAdd.bind(this); this.onDelete = this.onDelete.bind(this); this.onEdit = this.onEdit.bind(this); this.onFilter = this.onFilter.bind(this); this.onFormSubmit = this.onFormSubmit.bind(this); this.renderList = this.renderList.bind(this); this.renderTable = this.renderTable.bind(this); this.search = this.search.bind(this); this.toggleColumn = this.toggleColumn.bind(this); } componentDidMount() { this.props.dispatch(BudgetsActions.subscribe()); } filterItems(items, query) { const rows = this.props.items; const columns = this.props.fields.map((field) => ({ property: field.name, header: { label: field.label, }, filterType:field.filterType, })); const searchExecutor = search.multipleColumns({ columns, query, strategy: multiInfix }); const visibleItems = compose(searchExecutor)(rows); return visibleItems; } onFilter({ field = this.state.filter.field, value = this.state.filter.value }) { this.setState({ filter: { field, value, }, }); const newQuery = { ...this.props.query, [field]: value, }; this.props.dispatch(BudgetsActions.search({ query: newQuery })); } onFormSubmit(item) { this.onAdd(item); } onAdd(item) { this.props.dispatch(BudgetsActions.addItem({ item })); } onDelete(itemId) { this.props.dispatch(BudgetsActions.removeItem({ itemId })); } onEdit(updatedItem) { this.props.dispatch(BudgetsActions.updateItem({ updatedItem })); } renderList() { return ( <List items={this.props.items} filter={this.state.filter} filterItems={this.filterItems} fields={this.props.fields} onFilter={this.onFilter} onEdit={this.onEdit} onDelete={this.onDelete} query={this.props.query} /> ); } renderTable() { return ( <Table fields={this.props.fields} filterItems={this.filterItems} items={this.props.items} query={this.props.query} search={this.search} toggleColumn={this.toggleColumn} userColumns={this.props.userColumns} /> ); } search(query) { this.props.dispatch(BudgetsActions.search({ query })); } toggleColumn(payload){ this.props.dispatch(BudgetsActions.toggleColumn({ columnName: payload.columnName })); } render() { return ( <div> <div className="panel-uc panel panel-default"> <div className="panel-uc__heading panel-heading clearfix"> <h4>Budget Tool</h4> </div> </div> <div className="row panel-body"> <div className="panel-body projects__wrapper"> <Form onSubmit={this.onFormSubmit} fields={this.props.fields} /> <h3>View Selection</h3> <ul> <li> <Link to={this.props.match.url + '/list'}>List</Link> </li> <li> <Link to={this.props.match.url + '/table'}>Table</Link> </li> </ul> <Route exact path={this.props.match.url} render={this.renderList} /> <Route path={this.props.match.url + '/list'} render={this.renderList} /> <Route path={this.props.match.url + '/table'} render={this.renderTable} /> </div> </div> </div> ); } } const mapStateToProps = state => ({ items: state.budgets.items, fields: state.budgets.fields, query: state.budgets.query, userColumns: state.budgets.userColumns, }) export default connect(mapStateToProps)(Budgets);
JavaScript
0
@@ -796,62 +796,8 @@ s);%0A - this.onFormSubmit = this.onFormSubmit.bind(this);%0A @@ -1864,58 +1864,8 @@ %7D%0A%0A - onFormSubmit(item) %7B%0A this.onAdd(item);%0A %7D%0A%0A on @@ -3388,18 +3388,11 @@ s.on -FormSubmit +Add %7D%0A
d6f1d8719b837629b5052541ee1f87a3aab653d3
Use CSM RP registration API for website and VSO in XplatCLI
lib/commands/arm/group/group.template._js
lib/commands/arm/group/group.template._js
/** * Copyright (c) Microsoft. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var fs = require('fs'); var request = require('request'); var util = require('util'); var profile = require('../../../util/profile'); var utils = require('../../../util/utils'); var groupUtils = require('./groupUtils'); var $ = utils.getLocaleString; var azure = require('azure'); exports.init = function(cli) { profile.addKnownResourceNamespace('successbricks.cleardb', 'microsoft.insights'); profile.addKnownProvider('website', 'visualstudio.account', 'sqlserver'); var log = cli.output; var group = cli.category('group'); var groupTemplate = group.category('template') .description($('Commands to manage your local or gallery resource group template')); groupTemplate.command('list') .description($('Lists gallery resource group templates')) .option('-c --category [category]', $('the category of the templates to list')) .option('-p --publisher [publisher]', $('the publisher of the templates to list')) .option('--subscription <subscription>', $('the Azure subscription to run against')) .execute(function (options, _) { var client = createGalleryClient(profile.current.getSubscription(options.subscription)); var filters = []; if (options.publisher) { filters.push(util.format('Publisher eq \'%s\'', options.publisher)); } if (options.category) { filters.push(util.format('CategoryIds/any(c: c eq \'%s\')', options.category)); } var result = cli.interaction.withProgress($('Listing gallery resource group templates'), function (log, _) { return client.items.list(filters.length === 0 ? null : { filter: filters.join(' and ') }, _); }, _); cli.interaction.formatOutput(result.items, function (data) { if (data.length === 0) { log.info($('No gallery resource group templates')); } else { var validItems = data.filter(function (c) { return !utils.stringEndsWith(c.version, '-placeholder', true); }); var sortedItems = validItems.sort(function (left, right) { return left.publisher.localeCompare(right.publisher); }); log.table(sortedItems, function (row, item) { row.cell($('Publisher'), item.publisher); row.cell($('Name'), item.identity); }); } }); }); groupTemplate.command('show [name]') .description($('Shows a gallery resource group template')) .usage('[options] <name>') .option('-n --name <name>', $('the name of template to show')) .option('--subscription <subscription>', $('the Azure subscription to run against')) .execute(function (name, options, _) { if (!name) { return cli.missingArgument('name'); } var client = createGalleryClient(profile.current.getSubscription(options.subscription)); var result = cli.interaction.withProgress($('Showing a gallery resource group template'), function (log, _) { return client.items.get(name, _); }, _); cli.interaction.formatOutput(result.item, function (data) { log.data($('Name: '), data.identity); log.data($('Publisher: '), data.publisher); log.data($('Version: '), data.version); log.data($('Url: '), groupUtils.getTemplateDownloadUrl(data)); log.data($('Summary: '), data.summary); log.data($('Description: '), data.description); }); }); groupTemplate.command('download [name] [file]') .description($('Downloads a gallery resource group template')) .usage('[options] [name] [file]') .option('-n --name <name>', $('the name of the template to download')) .option('-f --file <file>', $('the name of the destination directory or file')) .option('-q --quiet', $('quiet mode (do not prompt for overwrite if output file exists)')) .option('--subscription <subscription>', $('the Azure subscription to run against')) .execute(function (name, file, options, _) { if (!name) { return cli.missingArgument('name'); } var confirm = cli.interaction.confirm.bind(cli.interaction); var downloadFileName = groupUtils.normalizeDownloadFileName(name, file, options.quiet, confirm, _); if (!downloadFileName) { // overwrite not confirmed, stop return; } var client = createGalleryClient(profile.current.getSubscription(options.subscription)); var result = cli.interaction.withProgress( util.format($('Getting gallery resource group template %s'), name), function (log, _) { return client.items.get(name, _); }, _); var downloadUrl = groupUtils.getTemplateDownloadUrl(result.item); var waitForDownloadEnd = function (stream, callback) { stream.on('close', function () { callback(null); }); stream.on('error', function (ex) { callback(ex); }); }; return waitForDownloadEnd(request(downloadUrl).pipe(fs.createWriteStream(downloadFileName)), _); }); groupTemplate.command('validate [resource-group]') .description($('Validates a template to see whether it\'s using the right syntax, resource providers, resource types, etc.')) .usage('[options] <resource-group>') .option('-g --resource-group <resource-group>', $('the name of the resource group')) .option('-y --gallery-template <gallery-template>', $('the name of the template in the gallery')) .option('-f --template-file <template-file>', $('the path to the template file in the file system')) .option('--template-uri <template-uri>', $('the uri to the remote template file')) //TODO: comment out till ARM supports contentHash //.option('--template-hash <template-hash>', $('the content hash of the template')) //.option('--template-hash-algorithm <template-hash-algorithm>', $('the algorithm used to hash the template content')) .option('--template-version <template-version>', $('the content version of the template')) .option('-s --storage-account <storage-account>', $('the storage account where we will upload the template file')) //TODO: comment out till ARM supports validation mode //.option('-m --mode <mode>', $('the mode of the template deployment. Valid values are Replace, New and Incremental')) .option('-p --parameters <parameters>', $('a JSON-formatted string containing parameters')) .option('-e --parameters-file <parametersFile>', $('a file containing parameters')) //TODO: comment out till ARM supports contentHash //.option('--parameters-hash <parameters-hash>', $('the content hash of the parameters')) //.option('--parameters-hash-algorithm <parameters-hash-algorithm>', $('the algorithm used to hash the parameters content')) //.option('--parameters-version <parameters-version>', $('the expected content version of the parameters')) .option('--subscription <subscription>', $('the subscription identifier')) .execute(function (resourceGroup, options, _) { if (!resourceGroup) { return cli.missingArgument('resourceGroup'); } groupUtils.validateTemplate(cli, resourceGroup, options, _); }); }; function createGalleryClient(subscription) { return utils.createClient('createGalleryClient', new azure.AnonymousCloudCredentials(), subscription.galleryEndpointUrl); }
JavaScript
0
@@ -960,16 +960,59 @@ mespace( +'microsoft.web', 'microsoft.visualstudio', 'success @@ -1092,32 +1092,8 @@ te', - 'visualstudio.account', 'sq
61c0fc5236bfc20480b37475ee3331d91e8858c5
Use the useTemplate
core/app/assets/javascripts/backbone/views/facts_view.js
core/app/assets/javascripts/backbone/views/facts_view.js
window.FactsView = Backbone.View.extend({ tagName: "div", className: "facts", _loading: true, _timestamp: undefined, tmpl: $('#facts_tmpl').html(), _previousLength: 0, initialize: function(options) { var self = this; this.collection.bind('add', this.addFact, this); this.collection.bind('reset', this.resetFacts, this); //TODO split this into two views, one for channels, one for searchresults if(options.channel !== undefined ) { $(this.el).html(Mustache.to_html(this.tmpl,options.channel.toJSON())); } else { $(this.el).html(Mustache.to_html(this.tmpl)); } this.bindScroll(); }, render: function() { if (this.collection.length > 0) { this.resetFacts(); } return this; }, remove: function() { Backbone.View.prototype.remove.apply(this); this.unbindScroll(); }, addFact: function(fact) { var view = new FactView({ model: fact }); $(this.el).find('.facts').append(view.render().el); }, resetFacts: function(e) { var self = this; this.stopLoading(); if (this.collection.length === 0) { this.showNoFacts(); } else { this.collection.forEach(function(fact) { self.addFact(fact); }); } if ( this._previousLength === this.collection.length ) { this.hasMore = false; } else { this._previousLength = this.collection.length; } this.loadMore(); }, _moreNeeded: true, moreNeeded: function() { var bottomOfTheViewport = window.pageYOffset + window.innerHeight; var bottomOfEl = $(this.el).offset().top + $(this.el).outerHeight(); if ( this.hasMore ) { if ( bottomOfEl < bottomOfTheViewport ) { return true; } else if ($(document).height() - ($(window).scrollTop() + $(window).height()) < 700) { return true; } } return false; }, loadMore: function() { var self = this; var lastModel = self.collection.models[(self.collection.length - 1) || 0]; var new_timestamp = (lastModel ? lastModel.get('timestamp') : 0); if ( self.moreNeeded() && ! self._loading && self._timestamp !== new_timestamp ) { self.setLoading(); self._timestamp = new_timestamp; self.collection.fetch({ add: true, data: { timestamp: self._timestamp }, success: function() { self.stopLoading(); self.loadMore(); }, error: function() { self.stopLoading(); self.hasMore = false; } }); } }, hasMore: true, showNoFacts: function() { $(this.el).find('div.no_facts').show(); }, hideNoFacts: function() { $(this.el).find('div.no_facts').hide(); }, setLoading: function() { this._loading = true; $(this.el).find('div.loading').show(); }, stopLoading: function() { this._loading = false; $(this.el).find('div.loading').hide(); }, //TODO: Unbind on remove? bindScroll: function() { var self = this; $(window).bind('scroll.' + this.cid, function MCBiggah() { self.loadMore.apply(self); }); }, unbindScroll: function() { $(window).unbind('scroll.' + this.cid); } });
JavaScript
0.000001
@@ -122,41 +122,8 @@ ed,%0A - tmpl: $('#facts_tmpl').html(),%0A _p @@ -173,24 +173,77 @@ (options) %7B%0A + this.useTemplate(%22channels%22, %22_facts%22);%0A %0A var self @@ -556,16 +556,31 @@ toJSON() +, this.partials ));%0A @@ -636,16 +636,35 @@ his.tmpl +, %7B%7D, this.partials ));%0A
ee00205d992f03e9b4b4ac319fb8f4b5fb6abffd
add a transition to SVG lines
src/components/SvgLines.js
src/components/SvgLines.js
import {createElement} from 'react'; export default function SvgLines({lines = []}) { const inlines = []; for (let i = 0; i < lines.length; i++) { const [sP, eP] = lines[i]; const hD = (eP[0] - sP[0]) / 3; inlines.push( <path key={i} d={`M${sP[0]},${sP[1]} C${eP[0] - hD},${sP[1]} ${sP[0] + hD},${eP[1]} ${eP[0]},${eP[1]}`} stroke="black" fill="none" /> ); } return ( <svg width="100%" height="100%" shapeRendering="geometricPrecision"> {inlines} </svg> ); }
JavaScript
0
@@ -388,16 +388,85 @@ l=%22none%22 + style=%7B%7Btransition: 'all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms'%7D%7D /%3E%0A
308ebea5997f35f90c145033de86240288b4770f
add vertical padding to comment-field component
pkg/interface/publish/src/js/components/lib/comments.js
pkg/interface/publish/src/js/components/lib/comments.js
import React, { Component } from 'react' import { CommentItem } from './comment-item'; export class Comments extends Component { constructor(props){ super(props); this.state = { commentBody: '', disabled: false } this.commentSubmit = this.commentSubmit.bind(this); this.commentChange = this.commentChange.bind(this); } commentSubmit(evt){ let comment = { "new-comment": { who: this.props.ship.slice(1), book: this.props.book, note: this.props.note, body: this.state.commentBody } }; this.textArea.value = ''; window.api.setSpinner(true); this.setState({disabled: true}); let submit = window.api.action("publish", "publish-action", comment); submit.then(() => { window.api.setSpinner(false); this.setState({ disabled: false, commentBody: "" }); }) } commentChange(evt){ this.setState({ commentBody: evt.target.value, }) } render() { if (!this.props.enabled) { return null; } let commentArray = this.props.comments.map((com, i) => { return ( <CommentItem comment={com} key={i} contacts={this.props.contacts} /> ); }) let disableComment = ((this.state.commentBody === '') || (this.state.disabled === true)); let commentClass = (disableComment) ? "f9 pa2 bg-white br1 ba b--gray2 gray2" : "f9 pa2 bg-white br1 ba b--gray2 black pointer"; return ( <div> <div className="mt8"> <div> <textarea style={{resize:'vertical'}} ref={(el) => {this.textArea = el}} id="comment" name="comment" placeholder="Leave a comment here" className={"f9 db border-box w-100 ba b--gray3 pt3 ph3 pb8 br1 " + "mb2 focus-b--black"} aria-describedby="comment-desc" onChange={this.commentChange}> </textarea> </div> <button disabled={disableComment} onClick={this.commentSubmit} className={commentClass}> Add comment </button> </div> {commentArray} </div> ) } } export default Comments
JavaScript
0
@@ -1520,17 +1520,17 @@ sName=%22m -t +v 8%22%3E%0A
76e287c3754e5280acfe7531f42d3857d8ae5881
Remove basedir from cachebuster
build/cachebuster.js
build/cachebuster.js
module.exports = { cachebuster: { options: { basedir: 'dist/js/' }, files: { 'dist/hashed.json': ['dist/js/binary.min.js', 'dist/js/lib.min.js'], }, } };
JavaScript
0
@@ -53,49 +53,8 @@ s: %7B -%0A basedir: 'dist/js/'%0A %7D,%0A @@ -147,16 +147,43 @@ .min.js' +, 'dist/css/binary.min.css' %5D,%0A
ce9fb54d8f35ac57f716abe7ca4bfb9a5ce92830
Use actions directly rather than proxy through another func.
elements/create-column.js
elements/create-column.js
var h = require('virtual-dom/h') module.exports = CreateColumn function CreateColumn (props) { var name, type return h('div', [ h('h1', 'Create new column'), h('h2', 'Set the column name & type'), h('div', [ h('input.small', { type: 'text', name: 'column-name', onchange: function (e) { name = e.target.value } }) ]), h('div', [ h('select.small', { name: 'column-type', onchange: function (e) { type = e.target.options[e.target.selectedIndex].text } }, [ h('option', 'string'), h('option', 'number') ]) ]), h('div', [ h('button.button-blue', { onclick: function () { props.onsubmit(name, type) } }, 'Create column') ]) ]) }
JavaScript
0
@@ -90,16 +90,46 @@ rops) %7B%0A + var actions = props.actions%0A var na @@ -775,22 +775,25 @@ -props.onsubmit +actions.newColumn (nam
c438e05533f705b25868c8a902802516391e1520
change icon on dropown in select
packages/tocco-ui/src/Select/DropdownIndicator.js
packages/tocco-ui/src/Select/DropdownIndicator.js
import React from 'react' import PropTypes from 'prop-types' import {components} from 'react-select' import Ball from '../Ball' const DropdownIndicator = props => !props.immutable && <components.DropdownIndicator {...props}> <Ball icon="chevron-down" tabIndex={-1} /> </components.DropdownIndicator> DropdownIndicator.propTypes = { immutable: PropTypes.bool, openMenu: PropTypes.func.isRequired } export default DropdownIndicator
JavaScript
0.000001
@@ -237,17 +237,48 @@ icon= -%22 +%7Bprops.isOpen ? 'chevron-up' : ' chevron- @@ -285,9 +285,10 @@ down -%22 +'%7D %0A @@ -438,16 +438,42 @@ Required +,%0A isOpen: PropTypes.bool %0A%7D%0A%0Aexpo
afd0f75bb698b6a2ced0ca6d7d79d0274b30b676
add condition in ES6ModuleInfo
src/plugins/ES6ModuleInfo.js
src/plugins/ES6ModuleInfo.js
var esprima = require('esprima-fb'); module.exports = function () { return function (code, filename) { var ast = esprima.parse(code, {sourceType: 'module'}); var body = ast.body; var es6imports = body.filter(function (node) { return node.type == 'ImportDeclaration'; }).map(function (node) { return node.source.value; }); var requires = body.filter(function (node) { // TODO: this doesn't detect something like this: // var something = require('module')(somearguments); // only this: // var something = require('module'); if (node.type !== 'VariableDeclaration') return false; var init = node.declarations[0].init; if (init.type != 'CallExpression') return false; if (init.callee.name != 'require') return false; return true; }).map(function (node) { return node.declarations[0].init.arguments[0].value; }); return { name: filename, es6imports: es6imports, requires: requires, imports: es6imports.concat(requires) }; }; };
JavaScript
0
@@ -773,16 +773,69 @@ %5D.init;%0A + if (!init)%0A return false;%0A
2100d96e21ffea5825fe0d79bf3d9c88cbc42595
Remove redundant require('./hover') operations
src/components/fx/index.js
src/components/fx/index.js
/** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var d3 = require('d3'); var Lib = require('../../lib'); var dragElement = require('../dragelement'); var helpers = require('./helpers'); var layoutAttributes = require('./layout_attributes'); module.exports = { moduleType: 'component', name: 'fx', constants: require('./constants'), schema: { layout: layoutAttributes }, attributes: require('./attributes'), layoutAttributes: layoutAttributes, supplyLayoutGlobalDefaults: require('./layout_global_defaults'), supplyDefaults: require('./defaults'), supplyLayoutDefaults: require('./layout_defaults'), calc: require('./calc'), getDistanceFunction: helpers.getDistanceFunction, getClosest: helpers.getClosest, inbox: helpers.inbox, quadrature: helpers.quadrature, appendArrayPointValue: helpers.appendArrayPointValue, castHoverOption: castHoverOption, castHoverinfo: castHoverinfo, hover: require('./hover').hover, unhover: dragElement.unhover, loneHover: require('./hover').loneHover, multiHovers: require('./hover').multiHovers, loneUnhover: loneUnhover, click: require('./click') }; function loneUnhover(containerOrSelection) { // duck type whether the arg is a d3 selection because ie9 doesn't // handle instanceof like modern browsers do. var selection = Lib.isD3Selection(containerOrSelection) ? containerOrSelection : d3.select(containerOrSelection); selection.selectAll('g.hovertext').remove(); selection.selectAll('.spikeline').remove(); } // helpers for traces that use Fx.loneHover function castHoverOption(trace, ptNumber, attr) { return Lib.castOption(trace, ptNumber, 'hoverlabel.' + attr); } function castHoverinfo(trace, fullLayout, ptNumber) { function _coerce(val) { return Lib.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); } return Lib.castOption(trace, ptNumber, 'hoverinfo', _coerce); }
JavaScript
0.999993
@@ -392,16 +392,54 @@ butes'); +%0Avar hoverModule = require('./hover'); %0A%0Amodule @@ -1167,34 +1167,27 @@ hover: -require('./hover') +hoverModule .hover,%0A @@ -1236,34 +1236,27 @@ eHover: -require('./hover') +hoverModule .loneHov @@ -1276,34 +1276,27 @@ Hovers: -require('./hover') +hoverModule .multiHo
14e77f531c0e1517b2a71be5b1e428d03cc1dac2
Add support for default at same level of content
lib/core/filter/inRule/actions/default.js
lib/core/filter/inRule/actions/default.js
const { isFunction, validateSiblings, validateChild, getLatestFromNames, loadCurrentValue, saveCurrentValue } = require("../../util/ruleUtil"); const { CONTENT, CLEAN, TRANSFORM, FUNCTION, DEFAULT, TYPE, STRING, PROPERTIES, OPTIONAL, CAST_TO, MATCH, VALIDATE, MIN, MAX, NUMBER, ARRAY, OBJECT, BOOLEAN } = require("../../constant"); const depth = 1; const config = { body: { siblings: [ { name: PROPERTIES }, { name: TRANSFORM }, { name: OPTIONAL }, { name: VALIDATE }, { name: CONTENT }, { name: CLEAN }, { name: TYPE }, ], children: { types: [BOOLEAN, STRING, NUMBER, FUNCTION, ARRAY, OBJECT] }, }, userInput: { siblings: [ { name: OPTIONAL }, { name: TYPE }, { name: CAST_TO }, { name: MATCH }, { name: VALIDATE }, { name: TRANSFORM }, { name: MIN }, { name: MAX }, { name: PROPERTIES }, ], children: { types: [BOOLEAN, STRING, NUMBER, FUNCTION, ARRAY, OBJECT] }, }, }; module.exports = { name: DEFAULT, priority: 10, validate, execute, config, }; function execute({ rule, data }) { return new Promise(async (resolve, reject) => { loadCurrentValue(data); if (data.current.value === undefined) { if (isFunction(rule.current)) { try { data.current.value = await rule.current.value(rule.current.value); } catch (error) { return reject(error); } } else { data.current.value = rule.current.value; } } saveCurrentValue(data); resolve(true); }); } function validate({ current, parents, ruleConfig }) { const { siblings, children } = getLatestFromNames(config, parents, depth, DEFAULT); validateSiblings({ siblings, current, parents, ruleConfig }); const child = current; validateChild({ child, children, parents, current, ruleConfig }); return true; }
JavaScript
0
@@ -839,24 +839,46 @@ OPERTIES %7D,%0A +%09%09%09%7B name: CONTENT %7D,%0A %09%09%5D,%0A%09%09child
db4be268071ece9f4d0dcf9c836652d9ead1137a
Change theme added
scripts/listeners.js
scripts/listeners.js
$(document).ready(function () { var agreements = $('<div id="agreements"></div>'); var cookiesLink = '<a href="https://support.mozilla.org/en-US/kb/cookies-information-websites-store-on-your-computer" title="Cookies" target="_blank">Cookies</a>'; var FAQLink = '<a href="#" title="FAQ" target="_blank">FAQ</a>'; var acceptBtn = '<a id="accept-agreements" href="#" title="accept agreement">I agree</a>'; var paragraph = 'This site use &nbsp' + cookiesLink + '&nbsp ' + 'to store information on your computer.' + 'Please read our &nbsp' + FAQLink + '&nbsp&nbsp' + ' section.' + acceptBtn; agreements.append(paragraph); $('#fake-header').append(agreements); //CLICK LISTENER AGREEMENTS $('#accept-agreements').click(function () { $('#agreements').remove(); }); //CLICK LISTENER LOGIN $('#login-btn').click(function () { var formStatus = '<input id="form-status" type="hidden" name="status" value="submitted"/>'; var loginForm = $('#login-form'); loginForm.append(formStatus); if ($('#form-status').val() === 'submitted') { loginForm.submit(); } }); //MODAL LISTENER $("#modal_trigger").leanModal({top : 120, overlay : 0.6, closeButton: ".modal_close" }); });
JavaScript
0
@@ -1284,12 +1284,819 @@ ose%22 %7D); +%0A%0A //CHANGE CSS%0A function changeCSS(cssFile, cssLinkIndex) %7B%0A%0A var oldlink = document.getElementsByTagName(%22link%22).item(cssLinkIndex);%0A%0A var newlink = document.createElement(%22link%22);%0A newlink.setAttribute(%22rel%22, %22stylesheet%22);%0A newlink.setAttribute(%22type%22, %22text/css%22);%0A newlink.setAttribute(%22href%22, cssFile);%0A%0A document.getElementsByTagName(%22head%22).item(0).replaceChild(newlink, oldlink);%0A %7D%0A%0A $('#theme-choose').change(function() %7B%0A var element = $('#theme-choose');%0A%0A if (element.val() == 'dark') %7B%0A changeCSS('assets/styles/dark.css', 0);%0A %7D else if (element.val() == 'white') %7B%0A changeCSS('assets/styles/white.css', 0);%0A %7D else %7B%0A changeCSS('assets/styles/main.css', 0);%0A %7D%0A %7D) %0A%7D);
af170b915f90b01ee2ae6c027b42c0f89047d94b
Update listen.js
bot/listen.js
bot/listen.js
const refresh = require('./lib/refresh'); const bot = require('./bot.js'); const settings = require('./../settings.json'); const modules = require('./modules.js'); const Message = require('./../orm/Message') const commands = require('./commands'); const request = require('request-promise-native'); let lock = false; bot.on('error', (err) => { /** * Catch errors here */ console.log("Stack Trace: " + err.stack); }) process.on('unhandledRejection', (err) => { console.log("UNHANDLED REJECTION AT " + err.stack); if (err.toString().includes('Request to use token, but token was unavailable to the client')) process.exit();//restart }); process.on('uncaughtException', (err) => console.log("UNHANDLED EXCEPTION AT " + err.stack)); bot.on('message', (message) => { /** * if locked, reject everything except dm */ new Message({ messageID: message.id, channel: message.channel.id }).save(); if (message.author.bot) return; if (lock) { if (!settings.owners.includes(message.author.id)) // if (message.channel.guild) return;//not DM } /** * Listen to messages and convert into params */ if (message.content.startsWith(settings.identifier)) { /**Extracting params */ let params = message.content.substring(settings.identifier.length).trim(); params = params.split(settings.delimiter || ' '); let cmd = params.shift().trim(); commands.execute(cmd.toLowerCase(), params, message) } else if (message.isMentioned(bot.user)) { /**remove mentions and then get params */ let params = message.cleancontent.trim().replace(bot.user.toString(), "").trim(); params = params.split(settings.delimiter || ' '); let cmd = params.shift.trim(); commands.execute(cmd.toLowerCase(), params, message) } else { //ignore because normal message } }); bot.on('lock', () => { lock = true; }); bot.on('unlock', () => { lock = false; }); bot.on("guildMemberAdd", async function (member) { var user = member.user; if (member.guild.id === "184536578654339072") { if (member.user.bot) return console.log(member.user.tag + " is a bot who joined " + member.guild.name) user.send("Welcome to the Revive Network"); if (! await refresh(user)) { await member.addRole(bot.guilds.get("184536578654339072").roles.get("317854639431221248")); const ma = await bot.channels.get("317859245309689856").send(user.toString() + "Type `accept` to continue. You will be kicked if you don't type `accept` within 10 minutes"); ma.delete(); // Await !vote messages const filter = (message) => { if (message.author.id === member.user.id) { message.delete(); if (message.content.toLowerCase().includes("accept") && message.member.roles.get("317854639431221248")) { message.member.removeRole("317854639431221248"); return message; } } } // Errors: ['time'] treats ending because of the time limit as an error bot.channels.get("317859245309689856").awaitMessages(filter, { max: 1, time: 600000, errors: ['time'] }) .then(collected => { if (collected.size < 1) { member.kick(); } return collected; }) } } });/** bot.on('disconnect', function(event) { if (event.code === 0) return console.error(event); process.exit();//force restart });*/ bot.on('ready', () => { console.log("ReviveBot Ready"); }); bot.on("guildMemberUpdate", async function (member, newMem) { let user = member.user; if (member.guild && (member.guild.id === "184536578654339072")) { let oldMem = member; if (!oldMem.roles.has("273105185566359562") && newMem.roles.has("273105185566359562")) return; if (!oldMem.roles.has("275317218911322112") && newMem.roles.has("275317218911322112")) return; if ((!oldMem.roles.has("184684916833779712") && newMem.roles.has("184684916833779712")) || (!oldMem.roles.has("200849956796497920") && newMem.roles.has("200849956796497920")) || (!oldMem.roles.has("184676864630063104") && newMem.roles.has("184676864630063104")) || (!oldMem.roles.has("286646245198528523") && newMem.roles.has("286646245198528523"))) { await request('http://revive-bot-discord.revive.systems/v0/discord/reverse_link/' + user.id); } } });
JavaScript
0.000001
@@ -3450,16 +3450,68 @@ size %3C 1 + && !message.member.roles.get(%22317854639431221248%22) ) %7B%0A
d6a10def9b605d2cb3ce17f0b2ef08b21147be77
Allow setting a className to Loader
src/components/Loader/Loader.js
src/components/Loader/Loader.js
import React from 'react' import PropTypes from 'prop-types' import styles from './Loader.scss' const Loader = ({ loading, label = 'Chargement…', error, children }) => ( loading ? ( <div className={styles.wrapper}> <div className={styles.loader}> {label} </div> </div> ) : error ? ( <div className={styles.error}> Une erreur est survenue : {error.message}. </div> ) : children ) Loader.propTypes = { loading: PropTypes.bool.isRequired, label: PropTypes.string, error: PropTypes.oneOfType([ PropTypes.shape({ message: PropTypes.string.isRequired }), PropTypes.bool ]), children: PropTypes.node } export default Loader
JavaScript
0.000002
@@ -140,16 +140,33 @@ ement%E2%80%A6', + className = '', error, @@ -212,24 +212,27 @@ className=%7B +%60$%7B styles.wrapp @@ -234,16 +234,31 @@ wrapper%7D + $%7BclassName%7D%60%7D %3E%0A @@ -545,16 +545,48 @@ tring,%0A%0A + className: PropTypes.string,%0A%0A error:
5024a7be3c607ac2a6ec1284e49a0f78f9f952f1
Update the distribution js as well
js/button.js
js/button.js
/* ======================================================================== * Bootstrap: button.js v3.3.4 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.4' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state += 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function () { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked')) changed = false $parent.find('.active').removeClass('active') this.$element.addClass('active') } else if ($input.prop('type') == 'checkbox') { if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false this.$element.toggleClass('active') } $input.prop('checked', this.$element.hasClass('active')) if (changed) $input.trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) this.$element.toggleClass('active') } } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') Plugin.call($btn, 'toggle') if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault() }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery);
JavaScript
0
@@ -849,16 +849,15 @@ = ' -disabled +loading '%0A
8d815404e25b8a48386592293a681c47fbc973a4
remove date.now
bot/listen.js
bot/listen.js
const bot = require('./bot.js'); const settings = require('./../settings.json'); const modules = require('./modules.js'); const commands = require('./commands'); let lock = false; bot.on('error', (err) => { /** * Catch errors here */ console.log(new Date.now() + " - Error: " + err); console.log("Stack Trace: " + err.stack); }) process.on('unhandledRejection',(err)=>console.log("UNHANDLED REJECTION AT "+err.stack)); process.on('uncaughtException',(err)=>console.log("UNHANDLED EXCEPTION AT "+err.stack)); bot.on('message', (message) => { /** * if locked, reject everything except dm */ if (lock) { if (!settings.owners.includes(message.author.id)) if (message.channel.guild) return;//not DM } /** * Listen to messages and convert into params */ if (message.content.startsWith(settings.identifier)) { /**Extracting params */ let params = message.content.substring(settings.identifier.length).trim(); params = params.split(settings.delimiter || ' '); let cmd = params.shift().trim(); commands.execute(cmd.toLowerCase(), params, message) } else if (message.isMentioned(bot.user)) { /**remove mentions and then get params */ let params = message.cleancontent.trim().replace(bot.user.toString(), "").trim(); params = params.split(settings.delimiter || ' '); let cmd = params.shift.trim(); commands.execute(cmd.toLowerCase(), params, message) } else { //ignore because normal message } }); bot.on('lock', () => { lock = true; }); bot.on('unlock', () => { lock = false; }); bot.on("guildMemberAdd", (member) => { var user = member.user; if (member.guild.name.toLowerCase().includes('revive')) { user.sendMessage("Welcome to the Revive Network"); refresh(user); } }); bot.on('disconnect', function(event) { if (event.code === 0) return console.error(event); bot.destroy().then(() => bot.login()); });
JavaScript
0.999285
@@ -245,62 +245,8 @@ */%0A - console.log(new Date.now() + %22 - Error: %22 + err);%0A
3329230d14ed72b6099624c628dbf9988cf3885d
Fix <DatePicker/> calendar top position
source/TextInputComponent.js
source/TextInputComponent.js
import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import Input from './TextInputInput' import Label from './TextInputLabel' // `<input/>` and its `<label/>`. export default function TextInputComponent(props) { const { id, value, required, floatingLabel, label, placeholder, multiline, error, indicateInvalid, containerRef } = props const { icon: Icon, className, children, ...rest } = props return ( <div ref={containerRef} className={classNames('rrui__input', { 'rrui__input--multiline' : multiline, })}> {Icon && <Icon className="rrui__input-field__icon"/> } {/* `children` are placed before the `<input/>` so that they're above it when having `position: absolute`. */} {children} {/* `<input/>` */} <Input {...rest} className={classNames(className, { 'rrui__input-field--with-icon': Icon })}/> {/* Input `<label/>`. */} {/* It is rendered after the input to utilize the `input:focus + label` CSS selector rule */} {label && <Label aria-hidden inputId={id} value={value} required={required} invalid={indicateInvalid && error} floats={floatingLabel && !placeholder}> {label} </Label> } </div> ) } TextInputComponent.propTypes = { // Set to `true` to mark the field as required. required : PropTypes.bool.isRequired, // Labels float by default. floatingLabel : PropTypes.bool.isRequired, // `<input/>` icon. icon : PropTypes.func } TextInputComponent.defaultProps = { // Set to `true` to mark the field as required. required : false, // Labels float by default. floatingLabel : true }
JavaScript
0
@@ -669,144 +669,8 @@ %09%7D%0A%0A -%09%09%09%7B/* %60children%60 are placed before the %60%3Cinput/%3E%60%0A%09%09%09 so that they're above it when having %60position: absolute%60. */%7D%0A%09%09%09%7Bchildren%7D%0A%0A %09%09%09%7B @@ -1156,16 +1156,341 @@ el%3E%0A%09%09%09%7D +%0A%0A%09%09%09%7B/* %60children%60 are placed after the %60%3Cinput/%3E%60%0A%09%09%09 so that in cases when they're %60position: absolute%60%0A%09%09%09 then their default top position is right below the %60%3Cinput/%3E%60.%0A%09%09%09 For example, this is used in %60%3CDatePicker/%3E%60 so that%0A%09%09%09 the list of options is displayed right below the %60%3Cinput/%3E%60. */%7D%0A%09%09%09%7Bchildren%7D %0A%09%09%3C/div
9d80437de44280e3105645bb24a0d00b8a77caee
comment method
src/core.js
src/core.js
"use strict"; (function(window) { function Moon(opts) { var _el = opts.el; var _data = opts.data; var _methods = opts.methods; var directives = {}; var self = this; this.$el = document.querySelector(_el); this.components = opts.components; this.dom = {type: this.$el.nodeName, children: [], node: this.$el}; // Change state when $data is changed Object.defineProperty(this, '$data', { get: function() { return _data; }, set: function(value) { _data = value; this.build(this.dom.children); } }); /** * Converts attributes into key-value pairs * @param {Node} node * @return {Object} Key-Value pairs of Attributes */ var extractAttrs = function(node) { var attrs = {}; if(!node.attributes) return attrs; var rawAttrs = node.attributes; for(var i = 0; i < rawAttrs.length; i++) { attrs[rawAttrs[i].name] = rawAttrs[i].value } return attrs; } /** * Compiles a template with given data * @param {String} template * @param {Object} data * @return {String} Template with data rendered */ var compileTemplate = function(template, data) { var code = template, re = /{{([.]?\w+)}}/gi; code.replace(re, function(match, p) { code = code.replace(match, "` + data." + p + " + `"); }); var compile = new Function("data", "var out = `" + code + "`; return out"); return compile(data); } /** * Creates an object to be used in a Virtual DOM * @param {String} type * @param {Array} children * @param {String} val * @param {Object} props * @param {Node} node * @return {Object} Object usable in Virtual DOM */ this.createElement = function(type, children, val, props, node) { return {type: type, children: children, val: val, props: props, node: node}; } /** * Create Elements Recursively For all Children * @param {Array} children * @return {Array} Array of elements usable in Virtual DOM */ this.recursiveChildren = function(children) { var recursiveChildrenArr = []; for(var i = 0; i < children.length; i++) { var child = children[i]; recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child)); } return recursiveChildrenArr; } /** * Creates Virtual DOM * @param {Node} node */ this.createVirtualDOM = function(node) { var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node); this.dom = vdom; } /** * Turns Custom Components into their Corresponding Templates */ this.componentsToHTML = function() { for(var component in this.components) { var componentsFound = document.getElementsByTagName(component); for(var i = 0; i < componentsFound.length; i++) { componentsFound[i].outerHTML = this.components[component].template; } } } /** * Sets Value in Data * @param {String} key * @param {String} val */ this.set = function(key, val) { this.$data[key] = val; this.build(this.dom.children); } /** * Gets Value in Data * @param {String} key * @return {String} Value of key in data */ this.get = function(key) { return this.$data[key]; } /** * Makes an AJAX Request * @param {String} method * @param {String} url * @param {Object} params * @param {Function} cb */ this.ajax = function(method, url, params, cb) { var xmlHttp = new XMLHttpRequest(); method = method.toUpperCase(); if(typeof params === "function") { cb = params; } var urlParams = "?"; if(method === "POST") { http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); for(var param in params) { urlParams += param + "=" + params[param] + "&"; } } xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) cb(JSON.parse(xmlHttp.responseText)); } xmlHttp.open(method, url, true); xmlHttp.send(method === "POST" ? urlParams : null); } // Call a method defined in _methods this.method = function(method) { _methods[method](); } // Directive Initialization this.directive = function(name, action) { directives["m-" + name] = action; } // Default Directives directives["m-if"] = function(el, val, vdom) { var evaluated = new Function("return " + val); if(!evaluated()) { el.textContent = ""; } else { el.textContent = compileTemplate(vdom.val, self.$data); } } // Build the DOM with $data this.build = function(children) { for(var i = 0; i < children.length; i++) { var el = children[i]; if(el.type === "#text") { el.node.textContent = compileTemplate(el.val, this.$data); } else if(el.props) { for(var prop in el.props) { var propVal = el.props[prop]; var compiledProperty = compileTemplate(propVal, this.$data); var directive = directives[prop]; if(directive) { directive(el.node, compiledProperty, el); } el.node.setAttribute(prop, compiledProperty); } } this.build(el.children); } } // Initialize this.componentsToHTML(); this.createVirtualDOM(this.$el); this.build(this.dom.children); } window.Moon = Moon; window.$ = function(el) { el = document.querySelectorAll(el); return el.length === 1 ? el[0] : el; } })(window);
JavaScript
0.000004
@@ -4972,14 +4972,26 @@ / -/ +**%0A * Call +s a m @@ -4999,28 +4999,52 @@ thod - defined in _methods +%0A * @param %7BString%7D method%0A */ %0A
a65c50d9c471404478cdf8f67c8111e7ba128353
Add missing gettext
analytics_dashboard/static/js/performance-answer-distribution-main.js
analytics_dashboard/static/js/performance-answer-distribution-main.js
/** * This is the first script called by the performance answer distribution page. */ require(['vendor/domReady!', 'load/init-page'], function(doc, page) { 'use strict'; require(['underscore', 'views/data-table-view', 'views/discrete-bar-view'], function (_, DataTableView, DiscreteBarView) { var courseModel = page.models.courseModel, answerField = 'answer_value', answerColumn = {key: answerField, title: gettext('Answer'), type:'hasNull'}, tableColumns = [ answerColumn, {key: 'correct', title: gettext('Correct'), type: 'bool'}, {key: 'count', title: gettext('Submission Count'), type: 'number', className: 'text-right'} ]; // answers are stored either the numeric or string fields if (courseModel.get('answerType') === 'numeric') { answerColumn.type = 'number'; } // randomized problems have a random seeds field that differentiates rows if (courseModel.get('isRandom')) { // only show the variant column for randomized problems tableColumns.push({ key: 'variant', title: gettext('Variant'), type: 'number', className: 'text-right' }); } new DiscreteBarView({ el: '#performance-chart-view', model: courseModel, modelAttribute: 'answerDistributionLimited', dataType: 'count', truncateXTicks: true, trends: [{ title: function(index) { if (courseModel.get('answerDistributionLimited')[index].correct) { return 'Correct'; } else { return 'Incorrect'; } }, color: function (bar, index) { // green bars represent bars with the correct answer if (courseModel.get('answerDistributionLimited')[index].correct) { return '#4BB4FB'; } else { return '#CA0061'; } } }], x: { key: answerField }, y: { key: 'count' }, // Translators: <%=value%> will be replaced by a student response to a question asked in a course. interactiveTooltipHeaderTemplate: _.template(gettext('Answer: <%=value%>')) }); new DataTableView({ el: '[data-role=performance-table]', model: courseModel, modelAttribute: 'answerDistribution', columns: tableColumns, sorting: ['-count'], replaceZero: '-' }); }); });
JavaScript
0.999477
@@ -1921,16 +1921,24 @@ return +gettext( 'Correct @@ -1934,24 +1934,25 @@ xt('Correct' +) ;%0A @@ -2017,16 +2017,24 @@ return +gettext( 'Incorre @@ -2036,16 +2036,17 @@ correct' +) ;%0A
5ea36d9cb4bc252c432fb41ab7afd9ab25f88161
fix variable
src/plugins/geomuxp/index.js
src/plugins/geomuxp/index.js
var logger; const exec = require('child_process').exec; const fs = require('fs'); const path = require('path'); const respawn = require('respawn'); const io = require('socket.io-client'); const events = require('events'); var defaults = { port: 8099, wspath: '/geovideo' }; var geomux = function geomux(name, deps) { logger= deps.logger; logger.info('The geo-mux plugin.'); var self = this; this.deps = deps; this.services = {}; var emitter = new events.EventEmitter(); var global = deps.globalEventLoop; var cockpit = deps.cockpit; this.flag_experimentH264 = false; this._monitor = null; var videoServer = io.connect('http://localhost:' + defaults.port, { path: defaults.wspath, reconnection: true, reconnectionAttempts: Infinity, reconnectionDelay: 10 }); var cameras = {}; // ---------------------------- // Register all other listeners cockpit.on('plugin.geomuxp.command', function(camera, command, params) { // Forward to geo-video-server videoServer.emit('geomux.command', camera, command, params); }); global.withHistory.on('settings-change.videosettings',function(settings){ if ((flag_experimentH264!==settings.videosettings['use-geoserve']) && (_monitor !== null)){ this.stop(); this.start(); } flag_experimentH264=settings.videosettings['use-geoserve']; }); videoServer.on('video-deviceRegistration', function(update) { logger.debug('Got device update'); }); // Video endpoint announcement videoServer.on('geomux.video.announcement', function(camera, channel, info) { logger.debug('Announcement info: ' + JSON.stringify(info)); // Emit message on global event loop to register with the Video plugin self.deps.globalEventLoop.emit('CameraRegistration', { location: info.txtRecord.cameraLocation, videoMimeType: info.txtRecord.videoMimeType, resolution: info.txtRecord.resolution, framerate: info.txtRecord.framerate, wspath: info.txtRecord.wspath, relativeServiceUrl: info.txtRecord.relativeServiceUrl, sourcePort: info.port, sourceAddress: info.addresses[0], connectionType: 'socket.io' }); }); // Channel settings videoServer.on('geomux.channel.settings', function(camera, channel, settings) { UpdateCameraInfo(camera, channel); self.deps.cockpit.emit('plugin.geomuxp.' + camera + '_' + channel + '.settings', settings); }); // Channel health videoServer.on('geomux.channel.health', function(camera, channel, health) { UpdateCameraInfo(camera, channel); self.deps.cockpit.emit('plugin.geomuxp.' + camera + '_' + channel + '.health', health); }); // Channel api videoServer.on('geomux.channel.api', function(camera, channel, api) { UpdateCameraInfo(camera, channel); self.deps.cockpit.emit('plugin.geomuxp.' + camera + '_' + channel + '.api', api); }); // Channel status videoServer.on('geomux.channel.status', function(camera, channel, status) { UpdateCameraInfo(camera, channel); self.deps.cockpit.emit('plugin.geomuxp.' + camera + '_' + channel + '.status', status); }); // Channel error videoServer.on('geomux.channel.error', function(camera, channel, error) { UpdateCameraInfo(camera, channel); self.deps.cockpit.emit('plugin.geomuxp.' + camera + '_' + channel + '.error', error); }); // Upon connecting to video server, set up listeners videoServer.on('connect', function() { logger.info('Successfully connected to geo-video-server'); // Tell geo-video-server to start the daemons videoServer.emit('geomux.ready'); }); // Disconnection videoServer.on('disconnect', function() { logger.info('Disconnected from video server.'); }); // Error videoServer.on('error', function(err) { logger.error(err,'Video Server Connection Error'); }); // Reconnect attempt videoServer.on('reconnect', function() { logger.info('Attempting to reconnect'); }); // Helper function to update local store of cameras and channels function UpdateCameraInfo(camera, channel) { if (cameras[camera] === undefined) { // Create the camera cameras[camera] = {}; // Add the channel cameras[camera][channel] = {}; self.deps.cockpit.emit('plugin.geomuxp.cameraInfo', cameras); } else if (cameras[camera][channel] === undefined) { // Add the channel cameras[camera][channel] = {}; self.deps.cockpit.emit('plugin.geomuxp.cameraInfo', cameras); } } }; geomux.prototype.start = function stop() { logger.info('Stopping geomux program'); _monitor.stop(); _monitor = null; } // This gets called when plugins are started geomux.prototype.start = function start() { logger.info('Starting geomux program'); var geoprogram = ''; // Figure out which video server to use if( process.env.USE_MOCK == 'true' ) { if (process.env.MOCK_VIDEO_TYPE === "GEOMUX") { geoprogram = require.resolve('geo-video-simulator'); } else { return; } } else { // Find the geo-video-server app try { geoprogram = require.resolve('geo-video-server'); } catch (er) { logger.error('geo-video-server not installed'); return; } } var launch_options = []; if( process.env.USE_MOCK != 'true' ){ //Don't use platform specific nice in mock mode launch_options= launch_options.concat([ 'nice', '--19' ]) } if (this.flag_experimentH264){ launch_options = launch_options.concat([ 'geoserve' ]) } else { // Create all launch options launch_options = launch_options.concat([ 'node', geoprogram, '--p', defaults.port, '--w', defaults.wspath, '--c', 0, '--u', process.env.DEV_MODE === 'true' ? ':8099' : '' ]); } const infinite = -1; // Set up monitor with specified options var monitor = respawn(launch_options, { name: 'geomux', env: { 'DEBUG': 'app*,camera*,channel*' }, maxRestarts: infinite, sleep: 1000 }); monitor.on('exit', function(code, signal) { logger.error('Geo-video-server exited. Code: [' + code + '] Signal: [' + signal + ']'); }); monitor.on('stdout', function(data) { var msg = data.toString('utf-8'); logger.debug('geo-video-server STDOUT: ' + msg); }); monitor.on('stderr', function(data) { var msg = data.toString('utf-8'); logger.debug('geo-video-server STDERR: ' + msg); }); // Start the monitor monitor.start(); this._monitor = monitor; }; //Export provides the public interface module.exports = function(name, deps) { return new geomux(name, deps); };
JavaScript
0.000011
@@ -1222,16 +1222,21 @@ if (( +this. flag_exp @@ -1383,16 +1383,21 @@ +this. flag_exp
f59c7761ad471839d45ef381699a5dd40d83b9aa
Reboot bot
bot/listen.js
bot/listen.js
const bot = require('./bot.js'); const settings = require('./../settings.json'); const modules = require('./modules.js'); const commands = require('./commands'); let lock = false; bot.on('error', (err) => { /** * Catch errors here */ console.log("Stack Trace: " + err.stack); }) process.on('unhandledRejection',(err)=>{ console.log("UNHANDLED REJECTION AT "+err.stack); if(err.toString().includes('Request to use token, but token was unavailable to the client')) process.exit();//restart }); process.on('uncaughtException',(err)=>console.log("UNHANDLED EXCEPTION AT "+err.stack)); bot.on('message', (message) => { /** * if locked, reject everything except dm */ if (lock) { if (!settings.owners.includes(message.author.id)) if (message.channel.guild) return;//not DM } /** * Listen to messages and convert into params */ if (message.content.startsWith(settings.identifier)) { /**Extracting params */ let params = message.content.substring(settings.identifier.length).trim(); params = params.split(settings.delimiter || ' '); let cmd = params.shift().trim(); commands.execute(cmd.toLowerCase(), params, message) } else if (message.isMentioned(bot.user)) { /**remove mentions and then get params */ let params = message.cleancontent.trim().replace(bot.user.toString(), "").trim(); params = params.split(settings.delimiter || ' '); let cmd = params.shift.trim(); commands.execute(cmd.toLowerCase(), params, message) } else { //ignore because normal message } }); bot.on('lock', () => { lock = true; }); bot.on('unlock', () => { lock = false; }); bot.on("guildMemberAdd", (member) => { var user = member.user; if (member.guild.name.toLowerCase().includes('revive')) { user.sendMessage("Welcome to the Revive Network"); refresh(user); } }); bot.on('disconnect', function(event) { if (event.code === 0) return console.error(event); process.exit();//force restart });
JavaScript
0.000001
@@ -1966,32 +1966,35 @@ user);%0A %7D%0A%7D); +/** %0Abot.on('disconn @@ -2102,17 +2102,19 @@ orce restart%0A%7D); +*/ %0A
0e5f956f9231bd63f3d1a4393017832e1bffaba4
add script to go to the top
src/components/MenuBar/index.js
src/components/MenuBar/index.js
import React, { useState, useEffect } from 'react' import { Home } from '@styled-icons/entypo/Home' import { UpArrowAlt as Arrow } from '@styled-icons/boxicons-regular/UpArrowAlt' import { LightBulb as Light } from '@styled-icons/entypo/LightBulb' import { GridHorizontal as Grid } from '@styled-icons/boxicons-regular/GridHorizontal' import { ListUl as List} from '@styled-icons/boxicons-regular/ListUl' import * as S from './styled' const MenuBar = () => { const [theme, setTheme] = useState(null) const [display, setDisplay] = useState(null) const isDarkMode = theme === 'dark' const isListMode = display === 'list' useEffect(() => { setTheme(window.__theme) setDisplay(window.__display) window.__onThemeChange = () => setTheme(window.__theme) window.__onDisplayChange = () => setDisplay(window.__display) }, []) return ( <S.MenuBarWrapper> <S.MenuBarGroup> <S.MenuBarLink to="/" title="Go back to Home" cover direction="right" bg="#0e1218" duration={0.5} > <S.MenuBarItem><Home /></S.MenuBarItem> </S.MenuBarLink> </S.MenuBarGroup> <S.MenuBarGroup> <S.MenuBarItem title="Change theme" onClick={() => { window.__setPreferredTheme(isDarkMode ? 'light' : 'dark') }} className={theme} > <Light /> </S.MenuBarItem> <S.MenuBarItem title="Change visualization" onClick={() => { window.__setPreferredDisplay(isListMode ? 'grid' : 'list') }} className="display" > {isListMode ? <Grid /> : <List />} </S.MenuBarItem> <S.MenuBarItem title="Go to top"><Arrow /></S.MenuBarItem> </S.MenuBarGroup> </S.MenuBarWrapper> ) } export default MenuBar
JavaScript
0
@@ -1753,16 +1753,26 @@ uBarItem +%0A title=%22 @@ -1785,18 +1785,145 @@ top%22 -%3E%3CArrow /%3E +%0A onClick=%7B() =%3E %7B%0A window.scroll(%7B top: 0, behavior: 'smooth' %7D)%0A %7D%7D%0A %3E%0A %3CArrow /%3E%0A %3C/S.
0c723958cbdf1a2aa1320da63ed59ccf591b0f5a
Update config.js
samples/webrtc/peer-to-peer/config.js
samples/webrtc/peer-to-peer/config.js
var QBApp = { appId: 92, authKey: 'wJHdOcQSxXQGWx5', authSecret: 'BTFsj7Rtt27DAmT' }; var CONFIG = { chatProtocol: { active: 2, }, debug: true, webrtc: { answerTimeInterval: 25, dialingTimeInterval: 5 } }; var QBUsers = [ { id: 2436251, login: 'webrtc_user1', password: 'x6Bt0VDy5', full_name: 'User 1', colour: 'FD8209' }, { id: 2436254, login: 'webrtc_user2', password: 'x6Bt0VDy5', full_name: 'User 2', colour: '1765FB' }, { id: 2436257, login: 'webrtc_user3', password: 'x6Bt0VDy5', full_name: 'User 3', colour: 'F81480' }, { id: 2436258, login: 'webrtc_user4', password: 'x6Bt0VDy5', full_name: 'User 4', colour: '39A345' }, { id: 2436259, login: 'webrtc_user5', password: 'x6Bt0VDy5', full_name: 'User 5', colour: '921392' }, { id: 2436262, login: 'webrtc_user6', password: 'x6Bt0VDy5', full_name: 'User 6', colour: '6594C5' }, { id: 2436263, login: 'webrtc_user7', password: 'x6Bt0VDy5', full_name: 'User 7', colour: 'C1061E' }, { id: 2436265, login: 'webrtc_user8', password: 'x6Bt0VDy5', full_name: 'User 8', colour: '898989' }, { id: 2436266, login: 'webrtc_user9', password: 'x6Bt0VDy5', full_name: 'User 9', colour: 'C7B325' }, { id: 2436269, login: 'webrtc_user10', password: 'x6Bt0VDy5', full_name: 'User 10', colour: 'BDA0CA' } ];
JavaScript
0.000002
@@ -190,18 +190,18 @@ terval: -25 +60 ,%0A di
29146d7c89dc4f7ef72f223c343a6296d75723d1
fix community pages test #598
routes/admin/authenticated/external/community-new/page.spec.js
routes/admin/authenticated/external/community-new/page.spec.js
import React from 'react' import { shallow } from 'enzyme' import * as mock from '~client/utils/mock' import Page from '~routes/admin/authenticated/external/community-new/page' describe('routes/admin/authenticated/external/community-new/page', () => { const props = { fields: { name: {}, city: {} }, submitting: false, // Actions create: mock.noop } it('should render without crashed', () => { shallow(<Page {...props} />) }) })
JavaScript
0.000001
@@ -35,16 +35,24 @@ shallow +WithIntl %7D from @@ -56,14 +56,26 @@ om ' -enzyme +~root/intl/helpers '%0A%0Ai @@ -459,16 +459,24 @@ shallow +WithIntl (%3CPage %7B
4284f9c52e75deba38c4bbc9abe3252449629565
Allow links to open in html documents
src/components/contents/html.js
src/components/contents/html.js
// @flow import * as React from "react"; export default class HTMLView extends React.Component<*> { ifr: ?HTMLIFrameElement; shouldComponentUpdate() { return false; } render() { return ( <div style={{ position: "fixed", width: "100%", height: "100%" }} > <iframe title={`view of ${this.props.entry.path}`} sandbox="allow-scripts" style={{ width: "100%", height: "100%", border: "none", margin: "0", padding: "0", display: "block" }} srcDoc={this.props.entry.content} ref={f => { this.ifr = f; }} height="100%" width="100%" /> </div> ); } }
JavaScript
0
@@ -426,16 +426,47 @@ -scripts + allow-popups allow-same-origin %22%0A
e06b9b50e9c3fd22cd4921d745d6e6b086fcc087
Trim whitespace when getting password for Transifex.
brave/l10n/downloadLanguages.js
brave/l10n/downloadLanguages.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Environment Variables USERNAME - valid Transifex user name with read privileges PASSWORD - password for above username LANG [optional] - single language code to retrieve in xx-XX format (I.e. en-US) run: USERNAME=brave.dev PASSWORD=<pw> node downloadLanguages.js */ 'use strict' const path = require('path') const fs = require('fs') const request = require('request') // The names of the directories in the locales folder are used as a list of languages to retrieve var languages = [ "fr", "pl", "ru", "de", "zh", "zh_TW", "id_ID", "it", "ja", "ko_KR", "ms", "pt_BR", "es", "uk", "nb" ] // Support retrieving a single language if (process.env.LANG_CODE) { languages = [process.env.LANG_CODE] } // Setup the credentials var username = process.env.USERNAME var password = process.env.PASSWORD if (!(username && password)) { username = 'brave.dev' password = '' + fs.readFileSync(path.join(process.env.HOME, '.transifex-password')) if (!(username && password)) { throw new Error('The USERNAME and PASSWORD environment variables must be set to the Transifex credentials') } } // URI and resource list const TEMPLATE = 'https://www.transifex.com/api/2/project/brave-ios-browser-1/resource/RESOURCE_SLUG/translation/LANG_CODE/?file' console.log('languages ' + languages + '\n') // For each language / resource combination languages.forEach(function (languageCode) { // Build the URI var URI = TEMPLATE.replace('RESOURCE_SLUG', 'bravexliff') URI = URI.replace('LANG_CODE', languageCode) // Authorize and request the translation file request.get(URI, { 'auth': { 'user': username, 'pass': password, 'sendImmediately': true } }, function (error, response, body) { if (error) { // Report errors (often timeouts) console.log(error.toString()) } else { if (response.statusCode === 401) { throw new Error('Unauthorized - Are the USERNAME and PASSWORD env vars set correctly?') } if (Math.floor(response.statusCode/100) != 2) { throw new Error("Error http code: " + response.statusCode) } // Build the filename and store the translation file var filename = path.join(__dirname, 'translated-xliffs', languageCode.replace('_', '-') + '.xliff') console.log('[*] ' + filename) if (process.env.TEST) { console.log(body) } else { fs.writeFileSync(filename, body) } } }) })
JavaScript
0.000002
@@ -1095,16 +1095,17 @@ sword = +( '' + fs. @@ -1147,16 +1147,22 @@ HOME, '. +brave- transife @@ -1174,16 +1174,24 @@ sword')) +).trim() %0A if (!
9209081f4c5d612a801619937c72d0ea75c3c30a
refactor code
src/views/ArticlesView.js
src/views/ArticlesView.js
import React, { Component } from 'react'; import { Form, FormGroup, Input, Card, CardText, CardBlock, CardTitle, CardSubtitle, Row, Col } from 'reactstrap'; import PropTypes from 'prop-types'; import NewsStore from '../stores/NewsStore'; import NewsActions from '../actions/NewsActions'; class ArticlesView extends Component { constructor() { super(); this.state = { allItems: [], }; this.onChange = this.onChange.bind(this); } getInitialState() { return { allItems: null }; } componentDidMount() { const { params } = this.props; NewsStore.addChangeListener(this.onChange); NewsActions.getNews(params.id); } componentWillUnmount() { NewsStore.removeChangeListener(this.onChange); } onChange() { this.setState({ allItems: NewsStore.getAll() }); } getItemsState() { return { allItems: NewsStore.getAll(), }; } handleSort(event) { const { params } = this.props; event.preventDefault(); const val = event.target.value; NewsActions.getNews(`${params.id}&sortBy=${val}`); } /** * @return {object} */ render() { const { params } = this.props; const sort = params.sort.split(','); const option = sort.map((type, index) => <option value={type} key={index}> {type} </option>); return ( <div> <div> <div className="left"> <h1>{params.id}</h1> </div> <div className="right"> <Form className="order"> <FormGroup> <Input type="select" name="select" id="exampleSelect" onChange={this.handleSort.bind(this)}> <option>Sort News By</option> {option} </Input> </FormGroup> </Form> </div> </div> <div className="clear" /> <Row> {this.state.allItems.map(news => ( <Col xs="3" sm="3" className="news-frame"> <Card className="headline"> <CardBlock> <CardTitle className="title">{news.meta}</CardTitle> <CardSubtitle className="subtitle">{news.header}</CardSubtitle> </CardBlock> <img width="100%" src={news.image} /> <CardBlock> <CardText>{news.description}</CardText> <a href={news.href} rel="noopener noreferrer" target="_blank" >Read More</a> </CardBlock> </Card> </Col> ))} {this.state.allItems.map((news) => { const cssStyle = { height: '350px', background: `url(${news.image}) center center`, width: '100%', backgroundSize: 'cover', }; return ( <Col xs="3" sm="3" className="news-frame"> <Card className="headline"> <CardBlock> <CardTitle className="title">{news.meta}</CardTitle> <CardSubtitle className="subtitle">{news.header}</CardSubtitle> </CardBlock> <div style={cssStyle} /> <CardBlock> <CardText>{news.description}</CardText> <a href={news.href} rel="noopener noreferrer" target="_blank" >Read More</a> </CardBlock> </Card> </Col> ); })} </Row> </div> ); } } ArticlesView.propTypes = { params: PropTypes.object, }; export default ArticlesView;
JavaScript
0.023493
@@ -2012,33 +2012,110 @@ %3C -CardBlock +img width=%22100%25%22 src=%7Bnews.image%7D /%3E%0A %3CCardBlock className=%22news-title%22 %3E%0A @@ -2290,62 +2290,8 @@ ck%3E%0A - %3Cimg width=%22100%25%22 src=%7Bnews.image%7D /%3E%0A
5a501134d3684eb3711a9194f53b993e65ee8595
Improve page.js comments.
js/framework/page.js
js/framework/page.js
/** * @license Copyright (c) 2015 Cheng Fan * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ define(['RootBindings', 'PageDisposer', 'Knockout', 'Sugar'], function (RootBindings, PageDisposer, ko) { var initialRun = true; var Page = { init: function (name, data, controller) { Page.loading(false); name = name.toLowerCase(); if ((Page.page().name == name) && (Page.page().data == data)) { // if the requested page is the same page, immediately call controller without going further if (controller) { controller(data); } document.title = Page.title(); if (Page.initExtra) { Page.initExtra(name, data, controller); } return data; } var autoDispose = Page.page().data.dispose(Page); // if the requested page is not the same page, dispose current page first before swap to the new page if (autoDispose !== false) { // auto-dispose observables and simple values to initial values, return false to suppress PageDisposer.dispose(Page.page().data); } PageDisposer.init(data); //store initial observable and simple properties values of the page var initialized = data.init(Page); // init view model and call controller (optional) before template is swapped-in if (initialized === false) { return false; // stop initialization if page's init function return false (access control, etc.) } if (controller) { controller(data); } Page.bodyClass([name.dasherize(), ('ontouchstart' in document.documentElement) ? 'touch' : 'no-touch'].join(' ')); Page.page({ name: name, data: data }); // to test if template finished rendering, use afterRender binding document.title = Page.title(); if (Page.initExtra) { Page.initExtra(name, data, controller); } if (initialRun) { ko.applyBindings(Page, document.getElementsByTagName('html')[0]); // apply binding at root node to be able to bind to anywhere initialRun = false; } return data; }, page: ko.observable({ name: '', data: { init: function () {}, dispose: function () {} } }), bodyClass: ko.observable(''), loading: ko.observable(false), title: function () { return Page.page().name.titleize(); // override in RootBindings as needed } }; Object.merge(Page, RootBindings); // additional root bindings as needed by the app return Page; });
JavaScript
0
@@ -2063,16 +2063,32 @@ false) %7B +%0A // auto @@ -2096,16 +2096,31 @@ dispose +page's exposed observab @@ -2131,19 +2131,26 @@ and -simple valu +primitive properti es t @@ -2169,34 +2169,184 @@ lues -, return false to suppress +. if not desired, return false in dispose function to suppress%0A // auto-disposal for all public properties of the page, or make the particular properties private %0A @@ -2485,13 +2485,16 @@ and -simpl +primitiv e pr @@ -3183,16 +3183,40 @@ binding + in the template binding %0A%0A
ec4cb827db2eff3c10b6c62663a32bc278f91f9c
add lock for NumberBox #132
packages/web/src/components/basic/NumberBox.js
packages/web/src/components/basic/NumberBox.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { addComponent, removeComponent, watchComponent, updateQuery, } from '@appbaseio/reactivecore/lib/actions'; import { checkValueChange, checkPropChange, getClassName, } from '@appbaseio/reactivecore/lib/utils/helper'; import types from '@appbaseio/reactivecore/lib/utils/types'; import Title from '../../styles/Title'; import Button, { numberBoxContainer } from '../../styles/Button'; import Flex from '../../styles/Flex'; class NumberBox extends Component { constructor(props) { super(props); this.type = 'term'; this.state = { currentValue: this.props.data.start, }; } componentWillMount() { this.props.addComponent(this.props.componentId); this.setReact(this.props); if (this.props.selectedValue) { this.setValue(this.props.selectedValue); } else if (this.props.defaultSelected) { this.setValue(this.props.defaultSelected); } } componentWillReceiveProps(nextProps) { checkPropChange(this.props.react, nextProps.react, () => { this.setReact(nextProps); }); checkPropChange(this.props.defaultSelected, nextProps.defaultSelected, () => { this.setValue(nextProps.defaultSelected, nextProps); }); checkPropChange(this.props.queryFormat, nextProps.queryFormat, () => { this.updateQuery(this.state.currentValue, nextProps); }); checkPropChange(this.props.dataField, nextProps.dataField, () => { this.updateQuery(this.state.currentValue, nextProps); }); } componentWillUnmount() { this.props.removeComponent(this.props.componentId); } defaultQuery = (value, props) => { switch (props.queryFormat) { case 'exact': return { term: { [props.dataField]: value, }, }; case 'lte': return { range: { [props.dataField]: { lte: value, boost: 2.0, }, }, }; case 'gte': return { range: { [props.dataField]: { gte: value, boost: 2.0, }, }, }; default: return null; } }; setReact(props) { if (props.react) { props.watchComponent(props.componentId, props.react); } } incrementValue = () => { if (this.state.currentValue === this.props.data.end) { return; } const { currentValue } = this.state; this.setValue(currentValue + 1); }; decrementValue = () => { if (this.state.currentValue === this.props.data.start) { return; } const { currentValue } = this.state; this.setValue(currentValue - 1); }; setValue = (value, props = this.props) => { const performUpdate = () => { this.setState({ currentValue: value, }, () => { this.updateQuery(value, props); }); }; checkValueChange( props.componentId, value, props.beforeValueChange, props.onValueChange, performUpdate, ); }; updateQuery = (value, props) => { const query = props.customQuery || this.defaultQuery; let onQueryChange = null; if (props.onQueryChange) { onQueryChange = props.onQueryChange; } props.updateQuery({ componentId: props.componentId, query: query(value, props), value, onQueryChange, showFilter: false, // we don't need filters for NumberBox URLParams: props.URLParams, }); }; render() { return ( <div style={this.props.style} className={this.props.className}> {this.props.title && ( <Title className={getClassName(this.props.innerClass, 'title') || null}> {this.props.title} </Title> )} <Flex labelPosition={this.props.labelPosition} justifyContent="space-between" className={numberBoxContainer}> <span className={getClassName(this.props.innerClass, 'label') || null}> {this.props.data.label} </span> <div> <Button className={getClassName(this.props.innerClass, 'button') || null} onClick={this.decrementValue} disabled={this.state.currentValue === this.props.data.start} > <b>-</b> </Button> {this.state.currentValue} <Button className={getClassName(this.props.innerClass, 'button') || null} onClick={this.incrementValue} disabled={this.state.currentValue === this.props.data.end} > <b>+</b> </Button> </div> </Flex> </div> ); } } NumberBox.propTypes = { addComponent: types.funcRequired, componentId: types.stringRequired, defaultSelected: types.number, dataField: types.stringRequired, data: types.dataNumberBox, react: types.react, removeComponent: types.funcRequired, title: types.title, queryFormat: types.queryFormatNumberBox, labelPosition: types.labelPosition, URLParams: types.boolRequired, selectedValue: types.selectedValue, style: types.style, className: types.string, innerClass: types.style, }; NumberBox.defaultProps = { queryFormat: 'gte', labelPosition: 'left', URLParams: false, style: {}, className: null, }; const mapStateToProps = (state, props) => ({ selectedValue: state.selectedValues[props.componentId] ? state.selectedValues[props.componentId].value : null, }); const mapDispatchtoProps = dispatch => ({ addComponent: component => dispatch(addComponent(component)), removeComponent: component => dispatch(removeComponent(component)), watchComponent: (component, react) => dispatch(watchComponent(component, react)), updateQuery: updateQueryObject => dispatch(updateQuery(updateQueryObject)), }); export default connect(mapStateToProps, mapDispatchtoProps)(NumberBox);
JavaScript
0.000001
@@ -672,16 +672,39 @@ t,%0A%09%09%7D;%0A +%09%09this.locked = false;%0A %09%7D%0A%0A%09com @@ -2569,32 +2569,169 @@ his.props) =%3E %7B%0A +%09%09// ignore state updates when component is locked%0A%09%09if (props.beforeValueChange && this.locked) %7B%0A%09%09%09return;%0A%09%09%7D%0A%0A%09%09this.locked = true;%0A %09%09const performU @@ -2840,16 +2840,41 @@ props);%0A +%09%09%09%09this.locked = false;%0A %09%09%09%7D);%0A%09
26c5df47204403dd256c566e925cd6e979348dd1
fix warnings
src/screens/active-trip.js
src/screens/active-trip.js
import React, { Component } from 'react'; import { Button, Clipboard, Text, View } from 'react-native'; import { Header } from '../components'; class ActiveTrip extends Component { state = { id: '', results: {} }; constructor(props) { super(props); } componentWillMount() { this.fetchID(); } copyID = id => { Clipboard.setString(id); }; fetchID = () => { fetch('http://localhost:8000/v1/keygen') .then(response => response.json()) .then(responseJSON => { this.setState({ id: responseJSON.id }); }) .catch(error => { console.log('Failed to fetch response.', error); }); }; fetchResults = () => { fetch('http://localhost:8000/v1/results?id=' + this.state.id) .then(response => response.json()) .then(responseJSON => { this.setState({ results: responseJSON }); }) .catch(error => { console.log('Failed to fetch response.', error); }); }; render() { return ( <View> <Header>Active Trip</Header> <Text> {this.state.id} </Text> <View style={styles.buttonStyle}> <Button onPress={this.copyID(this.state.id)} title="Copy" color="#007aff" /> <Button onPress={this.fetchResults} title="Done" color="#007aff" /> <Text> {' '}{JSON.stringify(this.state.results)}{' '} </Text> <Text> Head on over to your mail app </Text> </View> </View> ); } } const styles = { buttonStyle: { borderWidth: 1, padding: 5, }, }; export default ActiveTrip;
JavaScript
0.000003
@@ -1180,24 +1180,30 @@ onPress=%7B +() =%3E this.copyID(
1325821f164730e13164b07da756c2f523bef6a6
Work for Issue #172
src/containers/HomePage.js
src/containers/HomePage.js
import React, { Component } from 'react'; import { Button, Container, Grid, Header, Icon, Image, List, Segment, Visibility, } from 'semantic-ui-react'; import { Link } from 'react-router-dom'; import { MainMenu } from '../MainMenu'; import FixedMenu from '../fixedMenu'; import logo_stacked from '../images/logo_stacked.svg'; class HomePage extends Component { state = {} hideFixedMenu = () => this.setState({ visible: false }) showFixedMenu = () => this.setState({ visible: true }) render() { const { visible } = this.state return ( <div> { visible ? <FixedMenu /> : null } <Visibility onBottomPassed={this.showFixedMenu} onBottomVisible={this.hideFixedMenu} once={false} > <Segment inverted textAlign='center' style={{ minHeight: 500, padding: '1em 0em' }} vertical color='teal' > <MainMenu/> <Container text> <br/> <Image src={logo_stacked} size='small' inline /> <Header as='h1' content='Cliff Effects Tool' inverted style={{ fontSize: '4em', fontWeight: 'normal', marginBottom: 0, marginTop: '1em' }} /> <Header as='h2' content='Intake a new client to begin.' inverted style={{ fontSize: '1.7em', fontWeight: 'normal' }} /> <Link to="/intake"><Button size='big' inverted>Intake New Client<Icon name='right arrow'/></Button></Link> </Container> </Segment> </Visibility> <Segment style={{ padding: '8em 0em' }} vertical textAlign='center' className={'spaceholder'}/> <Segment inverted vertical style={{ padding: '5em 0em' }} color='teal'> <Container> <Grid divided inverted stackable> <Grid.Row> <Grid.Column width={3}> <Header inverted as='h4' content='About' /> <List link inverted> <List.Item as='a'>Sitemap</List.Item> <List.Item as='a'>Contact Us</List.Item> </List> </Grid.Column> <Grid.Column width={3}> <Header inverted as='h4' content='Services' /> <List link inverted> <List.Item as='a'>Choice 1</List.Item> <List.Item as='a'>Choice 2</List.Item> <List.Item as='a'>Choice 3</List.Item> <List.Item as='a'>Choice 4</List.Item> </List> </Grid.Column> <Grid.Column width={7}> <Header as='h4' inverted>Cliff Effects Tool</Header> <p>Made with <Icon name='heart' size='small' /> by Code for Boston</p> </Grid.Column> </Grid.Row> </Grid> </Container> </Segment> </div> ) } } export default HomePage;
JavaScript
0
@@ -1886,17 +1886,17 @@ dding: ' -5 +2 em 0em' @@ -1980,16 +1980,16 @@ ckable%3E%0A + @@ -2009,762 +2009,8 @@ ow%3E%0A - %3CGrid.Column width=%7B3%7D%3E%0A %3CHeader inverted as='h4' content='About' /%3E%0A %3CList link inverted%3E%0A %3CList.Item as='a'%3ESitemap%3C/List.Item%3E%0A %3CList.Item as='a'%3EContact Us%3C/List.Item%3E%0A %3C/List%3E%0A %3C/Grid.Column%3E%0A %3CGrid.Column width=%7B3%7D%3E%0A %3CHeader inverted as='h4' content='Services' /%3E%0A %3CList link inverted%3E%0A %3CList.Item as='a'%3EChoice 1%3C/List.Item%3E%0A %3CList.Item as='a'%3EChoice 2%3C/List.Item%3E%0A %3CList.Item as='a'%3EChoice 3%3C/List.Item%3E%0A %3CList.Item as='a'%3EChoice 4%3C/List.Item%3E%0A %3C/List%3E%0A %3C/Grid.Column%3E%0A
edd81782b51f106eb84da10c3fadc95667e284bc
Fix bug with rogue `;`
src/components/dialog/dialog.js
src/components/dialog/dialog.js
import {KEYCODES, DEFAULT_CLASSNAMES, NATIVELY_FOCUSABLE_ELEMENTS} from '../../constants'; import createEl from '../../utils/createEl'; import defer from '../../utils/defer'; import qa from '../../utils/qa'; import trapFocus from '../../utils/trapFocus'; /** * @function VUIDialog * @version 0.0.2 * @desc Main VUIDialog function. Creates instances of the dialog based on * parameters passed in. * @param {object} settings */ const VUIDialog = ({ dialog = '.js-dialog', openBtn = '.js-dialog-btn-open', closeBtn = '.js-dialog-btn-close', isModal = false, isAlert = false, readyClass = DEFAULT_CLASSNAMES.isReady, activeClass = DEFAULT_CLASSNAMES.isActive, showBackdrop = true } = {}) => { // Stores all the constant dom nodes for the component regardless of instance. let DOM = { dialogs: qa(dialog) }; // Keeps track of current instance of dialog. let state = { currentOpenButton: null, currentDialog: null, focusableElements: null }; /** * @function setState * @desc Updates state for component * @param {object} updates Changes in state to be assigned. */ function setState(updates) { state = Object.assign(state, updates); } /** * @function bindBackdropEvents * @desc Adds event listener for clicking on backdrop */ function bindBackdropEvents() { DOM.backdrop.addEventListener('click', handleBackdropClick); } /** * @function unbindBackdropEvents * @desc Removes event listener for clicking on backdrop */ function unbindBackdropEvents() { DOM.backdrop.removeEventListener('click', handleBackdropClick); } /** * @function handleBackdropClick * @desc If backdrop has been clicked, dismiss dialog * @param {Event} e */ function handleBackdropClick(e) { if (e.target === DOM.backdrop) { closeDialog(state.currentDialog); } } /** * @function createBackdrop * @desc Creates the dialog backdrop */ function createBackdrop() { DOM.backdrop = createEl({className: DEFAULT_CLASSNAMES.backdrop}); } /** * @function bindOpenEvents * @desc Finds all open buttons and attaches click event listener * @param {node} dialog */ function bindOpenEvents(dialog) { const id = dialog.getAttribute('id'); // Grab all buttons which open this instance of the dialog const openButtons = qa(`${openBtn}[data-controls-dialog="${id}"]`); // Loop through all buttons that open modal and attach event listener openButtons.forEach(button => button.addEventListener('click', openDialog)); } /** * @function openDialog * @desc Sets up dialog and state ready to be shown. Is triggered by user clicking on open * button. Also sets up focusable elements, close and key events and displays dialog * @param {Event} e */ function openDialog(e) { // Get trigger button so focus can be returned to it later const button = e.target; // Get dialog that should be opened const dialog = document.getElementById(button.getAttribute('data-controls-dialog')); // Update State setState({ currentOpenButton: button, currentDialog: dialog; }); // Focus the dialog and remove aria attributes dialog.setAttribute('tabindex', 1); dialog.setAttribute('aria-hidden', false); // Bind events defer(bindKeyCodeEvents); defer(bindCloseEvents); if (!isModal && DOM.backdrop) { defer(bindBackdropEvents); } // Add backdrop if needed if (DOM.backdrop) { DOM.body.appendChild(DOM.backdrop); } // Grabs elements that are focusable inside this dialog instance. setState({ focusableElements: qa(NATIVELY_FOCUSABLE_ELEMENTS.join(), dialog) }); // Add class to make dialog visible. Needs to occur before focus. dialog.classList.add(activeClass); // Remove vertical viewport scroll DOM.root.classList.add(DEFAULT_CLASSNAMES.hasNoVerticalScroll); // Set focus to first element, fallback to Dialog. if (state.focusableElements.length) { state.focusableElements[0].focus(); } else { dialog.focus(); } } /** * @function bindCloseEvents * @desc Finds all close buttons and attaches click event listener * @param {node} dialog */ function bindCloseEvents(dialog = state.currentDialog) { // Grab all buttons which open this instance of the dialog const closeButtons = qa(closeBtn); closeButtons.forEach(button => button.addEventListener('click', closeDialog)); } /** * @function closeDialog * @desc Triggered by user interacting with a close button or in some cases clicking backdrop. * Adds aria attributes and hides dialog, removing backdrop if needed */ function closeDialog() { const dialog = state.currentDialog; // Hide dialog for screenreaders and make untabbable dialog.setAttribute('aria-hidden', true); dialog.removeAttribute('tabindex'); // Unbind events unbindKeyCodeEvents(); if (!isModal && DOM.backdrop) { unbindBackdropEvents(); } // Remove active state hook class dialog.classList.remove(activeClass); // Remove backdrop if needed if (DOM.backdrop) { DOM.body.removeChild(DOM.backdrop); } // Allow vertical viewport scroll DOM.root.classList.remove(DEFAULT_CLASSNAMES.hasNoVerticalScroll); // Return focus to button that opened the dialog state.currentOpenButton.focus(); // Reset State setState({ currentOpenButton: null, currentDialog: null }); } /** * @function bindKeyCodeEvents * @desc Adds event listener for keydown on the document */ function bindKeyCodeEvents() { document.addEventListener('keydown', handleKeyPress); } /** * @function unbindKeyCodeEvents * @desc Removes event listener for keydown on the document */ function unbindKeyCodeEvents() { document.removeEventListener('keydown', handleKeyPress); } /** * @function handleKeyPress * @desc Checks to if Esc or Tab key have been pressed * @param {Event} e */ function handleKeyPress(e) { if (e.keyCode === KEYCODES.escape && !isModal && !isAlert) { closeDialog(state.currentDialog); } if (e.keyCode === KEYCODES.tab && !isModal) { trapFocus(e, state.focusableElements); } } /** * @function init * @desc Initialises the dialog */ function init() { // Check if any dialogs exist, return if not if (DOM.dialogs === undefined) { return false; } // Add body and html element to the DOM object DOM.root = qa('html')[0]; DOM.body = qa('body')[0]; if (showBackdrop) { createBackdrop(); } DOM.dialogs.forEach(dialog => { // Add aria roles and attributes const role = isAlert ? 'alertdialog' : 'dialog'; dialog.setAttribute('aria-hidden', 'true'); dialog.setAttribute('role', role); // Set up event listeners for opening dialog bindOpenEvents(dialog); dialog.classList.add(readyClass); }); } // Initialise VUIDialog component init(); }; export default VUIDialog;
JavaScript
0
@@ -3420,17 +3420,16 @@ : dialog -; %0A
63c85b5ac55f5c99864ec91685acc1cea9ca4926
increase timeout for icdiff test
test/Reporting/Reporters/IcdiffReporterTests.js
test/Reporting/Reporters/IcdiffReporterTests.js
//icdiff test\Reporters\a.txt test\Reporters\b.txt var assert = require("assert"); var path = require("path"); var ReporterUnderTest = require("../../../lib/Reporting/Reporters/icdiffReporter.js"); describe('Reporter', function () { describe('icdiff', function () { it('reporter args are correct', function () { var reporter = new ReporterUnderTest(); var approved = path.join(__dirname, "a.txt"); var received = path.join(__dirname, "b.txt"); var expectedCommand = "'icdiff' '" + received + "' '" + approved + "'"; if (reporter.canReportOn(received)) { reporter.report(approved, received, function (command) { var startTrim = command.indexOf("icdiff"); command = "'" + command.substr(startTrim); assert.equal(command, expectedCommand); return {}; }); } }); }); });
JavaScript
0
@@ -310,24 +310,91 @@ ction () %7B%0A%0A + this.timeout(20000); // failed on appVeyor for some reason?%0A%0A var re
13daadf7549a0143ecfd2fd39728faf138f0075b
update examples to show escaping file paths
examples.js
examples.js
'use strict'; var Base = require('base'); var tasks = require('base-tasks'); var cli = require('base-cli'); var argv = require('./'); var app = new Base(); // register plugins app.use(cli()); app.use(tasks()); app.use(argv()); app.task('foo', function(cb) { console.log('task > default'); cb(); }); // parse argv var args = app.argv(['--a=b:c', '--a=d:e', '--f g']); console.log(args) var args = app.argv(['--a:b:c', '--a:d:e', '--f g']); console.log(args) var args = app.argv(['--a:b=c', '--a d:e', '--f g']); console.log(args) var args = app.argv(['foo', 'bar', '--set=a:b']); console.log(args)
JavaScript
0
@@ -66,17 +66,16 @@ ase-task -s ');%0Avar @@ -580,28 +580,167 @@ t=a:b'%5D);%0Aconsole.log(args)%0A +%0Avar args = app.argv(%5B'--file=index.js'%5D);%0Aconsole.log(args)%0A%0Avar args = app.argv(%5B'--file=index.js'%5D, %7Besc: %5B'file'%5D%7D);%0Aconsole.log(args)%0A
0c63a0fe5b11a5b7fc178d506846c494fc31147a
rename mapState and mapDispatch
source/views/sis/balances.js
source/views/sis/balances.js
/** * @flow * All About Olaf * Balances page */ import React from 'react' import {StyleSheet, ScrollView, View, Text, RefreshControl} from 'react-native' import {TabBarIcon} from '../components/tabbar-icon' import {connect} from 'react-redux' import {Cell, TableView, Section} from 'react-native-tableview-simple' import type {LoginStateType} from '../../flux/parts/settings' import {updateBalances} from '../../flux/parts/sis' import delay from 'delay' import isNil from 'lodash/isNil' import * as c from '../components/colors' import type {TopLevelViewPropsType} from '../types' class BalancesView extends React.Component { static navigationOptions = { tabBarLabel: 'Balances', tabBarIcon: TabBarIcon('card'), } props: TopLevelViewPropsType & { flex: ?number, ole: ?number, print: ?number, weeklyMeals: ?number, dailyMeals: ?number, loginState: LoginStateType, message: ?string, updateBalances: boolean => any, } state = { loading: false, } componentWillMount() { // calling "refresh" here, to make clear to the user // that the data is being updated this.refresh() } refresh = async () => { let start = Date.now() this.setState(() => ({loading: true})) await this.fetchData() // wait 0.5 seconds – if we let it go at normal speed, it feels broken. let elapsed = Date.now() - start await delay(500 - elapsed) this.setState(() => ({loading: false})) } fetchData = async () => { await this.props.updateBalances(true) } openSettings = () => { this.props.navigation.navigate('SettingsView') } render() { let {flex, ole, print, dailyMeals, weeklyMeals} = this.props let {loading} = this.state return ( <ScrollView contentContainerStyle={styles.stage} refreshControl={ <RefreshControl refreshing={this.state.loading} onRefresh={this.refresh} /> } > <TableView> <Section header="BALANCES"> <View style={styles.balancesRow}> <FormattedValueCell label="Flex" value={flex} indeterminate={loading} formatter={getFormattedCurrency} /> <FormattedValueCell label="Ole" value={ole} indeterminate={loading} formatter={getFormattedCurrency} /> <FormattedValueCell label="Copy/Print" value={print} indeterminate={loading} formatter={getFormattedCurrency} style={styles.finalCell} /> </View> </Section> <Section header="MEAL PLAN"> <View style={styles.balancesRow}> <FormattedValueCell label="Daily Meals Left" value={dailyMeals} indeterminate={loading} formatter={getFormattedMealsRemaining} /> <FormattedValueCell label="Weekly Meals Left" value={weeklyMeals} indeterminate={loading} formatter={getFormattedMealsRemaining} style={styles.finalCell} /> </View> </Section> {this.props.loginState !== 'logged-in' || this.props.message ? ( <Section footer="You'll need to log in again so we can update these numbers."> {this.props.loginState !== 'logged-in' ? ( <Cell cellStyle="Basic" title="Log in with St. Olaf" accessory="DisclosureIndicator" onPress={this.openSettings} /> ) : null} {this.props.message ? ( <Cell cellStyle="Basic" title={this.props.message} /> ) : null} </Section> ) : null} </TableView> </ScrollView> ) } } function mapStateToProps(state) { return { flex: state.sis.balances.flex, ole: state.sis.balances.ole, print: state.sis.balances.print, weeklyMeals: state.sis.balances.weekly, dailyMeals: state.sis.balances.daily, message: state.sis.balances.message, loginState: state.settings.credentials.state, } } function mapDispatchToProps(dispatch) { return { updateBalances: force => dispatch(updateBalances(force)), } } export default connect(mapStateToProps, mapDispatchToProps)(BalancesView) let cellMargin = 10 let cellSidePadding = 10 let cellEdgePadding = 10 let styles = StyleSheet.create({ stage: { backgroundColor: c.iosLightBackground, paddingTop: 20, paddingBottom: 20, }, common: { backgroundColor: c.white, }, balances: { borderRightWidth: StyleSheet.hairlineWidth, borderRightColor: c.iosSeparator, }, finalCell: { borderRightWidth: 0, }, balancesRow: { flexDirection: 'row', marginTop: 0, marginBottom: -10, }, rectangle: { height: 88, flex: 1, alignItems: 'center', paddingTop: cellSidePadding, paddingBottom: cellSidePadding, paddingRight: cellEdgePadding, paddingLeft: cellEdgePadding, marginBottom: cellMargin, }, // Text styling financialText: { paddingTop: 8, color: c.iosDisabledText, textAlign: 'center', fontWeight: '200', fontSize: 23, }, rectangleButtonText: { paddingTop: 15, color: c.black, textAlign: 'center', fontSize: 16, }, }) function getFormattedCurrency(value: ?number): string { if (isNil(value)) { return 'N/A' } return '$' + (((value: any): number) / 100).toFixed(2) } function getFormattedMealsRemaining(value: ?number): string { if (isNil(value)) { return 'N/A' } return (value: any).toString() } function FormattedValueCell({ indeterminate, label, value, style, formatter, }: { indeterminate: boolean, label: string, value: ?number, style?: any, formatter: (?number) => string, }) { return ( <View style={[styles.rectangle, styles.common, styles.balances, style]}> <Text selectable={true} style={styles.financialText} autoAdjustsFontSize={true} > {indeterminate ? '…' : formatter(value)} </Text> <Text style={styles.rectangleButtonText} autoAdjustsFontSize={true}> {label} </Text> </View> ) }
JavaScript
0.000001
@@ -4090,23 +4090,16 @@ mapState -ToProps (state) @@ -4421,23 +4421,16 @@ Dispatch -ToProps (dispatc @@ -4545,23 +4545,16 @@ mapState -ToProps , mapDis @@ -4562,15 +4562,8 @@ atch -ToProps )(Ba
900341d81af344262049458cd18c83a5bae7ba32
Use better method for calculating random int to return. This should provide a more even distrobution.
random.js
random.js
var Buffer = require('buffer').Buffer, crypto = require('crypto'); function _parseArgs(arg_array) { if (arg_array.length === 0) { throw new Error('Atleast a callback argument is required'); } var is_range = arg_array.length > 2; return { cb: arg_array[arg_array.length-1], min: is_range ? arg_array[0] : undefined, max: is_range ? arg_array[1] : undefined }; } /*** Returns a random unsigned Int *** Returns the random int returned by nodes crypto library */ exports.getRandomInt = function(min, max, callback) { var args = _parseArgs(arguments); crypto.randomBytes(8, function(err, bytes_slow_buf) { if (err) { return cb(err); } var unsigned_int = Buffer(bytes_slow_buf).readUInt32LE(0); if (args.min !== undefined) { unsigned_int = unsigned_int % Math.abs(args.max - args.min) + args.min; } args.cb(null, unsigned_int); }); };
JavaScript
0
@@ -4,16 +4,17 @@ Buffer + = requir @@ -44,16 +44,17 @@ crypto + = requir @@ -64,16 +64,75 @@ crypto') +,%0A assert = require('assert'),%0A MaxUInt = 4294967295 ;%0A%0A%0Afunc @@ -160,17 +160,16 @@ rray) %7B%0A - if (a @@ -254,25 +254,24 @@ red'); %7D%0A - var is_range @@ -299,17 +299,16 @@ 2;%0A%0A - return %7B @@ -308,18 +308,16 @@ eturn %7B%0A - cb @@ -356,18 +356,16 @@ ,%0A - min: is_ @@ -398,18 +398,16 @@ efined,%0A - ma @@ -452,11 +452,569 @@ %0A - %7D; +%0A%7D%0A%0A/** Map random int to the range so that an even distrobution of results is possible%0A *%0A * Using this method ensures an even distrobution of as opposed to the modulo%0A * technique is is biased.%0A *%0A * @see http://mathoverflow.net/questions/35556/skewing-the-distribution-of-random-values-over-a-range%0A * for an explaination of the modulo issue.%0A */%0Afunction _mapToRange(min, max, randUInt) %7B%0A var result_range = max - min,%0A factor = result_range / MaxUInt;%0A%0A return Math.round((randUInt * factor) + min); // Math.round may cause some slight issues. %0A%7D%0A%0A @@ -1052,16 +1052,20 @@ Int ***%0A + Returns @@ -1173,17 +1173,16 @@ k) %7B%0A - var args @@ -1205,20 +1205,43 @@ guments) +, unsigned_int, rand_int ;%0A%0A - crypt @@ -1291,26 +1291,24 @@ uf) %7B%0A - if (err) %7B r @@ -1331,22 +1331,16 @@ %0A%0A - -var unsigned @@ -1387,18 +1387,16 @@ LE(0);%0A%0A - if @@ -1436,89 +1436,191 @@ - unsigned_int = unsigned_int %25 Math.abs +assert(args.max !== undefined && args.min %3C args.max);%0A rand_int = _mapToRange (args.m -ax - +in, args.m -in) + args.m +ax, unsigned_int);%0A %7D%0A else %7B%0A rand_int = unsigned_ in +t ;%0A %7D%0A @@ -1619,15 +1619,11 @@ - %7D%0A%0A - @@ -1638,31 +1638,27 @@ b(null, -unsigne +ran d_int);%0A %7D);%0A @@ -1649,17 +1649,16 @@ d_int);%0A - %7D);%0A%7D
7c9bd1e1a5fd2e68e0b28381b2dfcc40c38cc70a
add button links
scripts/portfolio.js
scripts/portfolio.js
const glob = require('glob'); const fs = require('fs-extra'); const path = require('path'); const marked = require('marked'); const renderer = require('./utils/renderer'); const formatDate = require('date-fns/format'); const camelCase = require('camel-case'); const titleCase = require('title-case'); const shell = require('shelljs'); const getFileNameFromPath = require('@lukeboyle/get-filename-from-path'); function getMarkupFromMarkdown(markdownString) { return marked(markdownString, {renderer: renderer, gfm: true}); } renderer.heading = function(code, level) { if (level === 1) { return ` <header> <h1 className="single-portfolio-item__title">${code}</h1> </header> `; } else { return `<h${level}>${code}</h${level}>`; } }; function generateComponent(acc, curr, index) { const fileName = getFileNameFromPath(curr.path).replace('.md', ''); const camelCaseName = camelCase(fileName); let imports = ` import React from 'react'; import portfolioData from '../../data/portfolio-items'; import Helmet from 'react-helmet'; import {PORTFOLIO_ITEM_NAMES} from "../../constants";`; renderer.image = function(href, title, text) { const rawFilename = getFileNameFromPath(href); const imageName = `${camelCase(rawFilename.slice(0, rawFilename.indexOf('.')))}Src`; imports = `${imports}\nimport ${imageName} from '.${href}'`; return `<img src={${imageName}} alt="${text}"/>`; }; const bodyMarkup = getMarkupFromMarkdown(curr.contents); acc.push({ path: curr.path, fileName, componentName: camelCaseName[0].toUpperCase() + camelCaseName.slice(1), component: ` ${imports} export default class ${camelCaseName} extends React.Component { render() { const portfolioContent = portfolioData.find(data => data.name === PORTFOLIO_ITEM_NAMES.${fileName.toUpperCase().split('-').join('_')}); return ( <div className="max-width-container"> <Helmet> <title>{portfolioContent.name} | Project Case Study</title> <meta name="description" content={portfolioContent.snippet}/> </Helmet> <div className="single-portfolio-item"> <div className="single-portfolio-item__content"> ${bodyMarkup} </div> </div> </div> ); } } ` }); return acc; } (() => { glob('portfolio-items/**/*.md', {}, (err, files) => { const blogPosts = files.reduce((acc, curr) => { acc.push({ path: curr, contents: fs.readFileSync(curr, {encoding: 'utf-8'}) }); return acc; }, []); const reversedComponents = blogPosts.reduce(generateComponent, []); fs.copySync(`${__dirname}/../portfolio-items/images`, `${__dirname}/../src/pages/portfolio/images`); reversedComponents.forEach(component => { fs.writeFileSync(path.resolve(`${__dirname}/../src/pages/portfolio/${component.fileName}.jsx`), component.component); }); }); })();
JavaScript
0.000046
@@ -2198,16 +2198,385 @@ Markup%7D%0A +%09%09%09%09%09%09%09%09%09%3Cdiv className=%22single-portfolio-item__buttons%22%3E%0A%09%09%09%09%09%09%09%09%09%09%7BportfolioContent.links.map(link =%3E %7B%0A%09%09%09%09%09%09%09%09%09%09%09return (%0A%09%09%09%09%09%09%09%09%09%09%09%09%3Ca%0A%09%09%09%09%09%09%09%09%09%09%09%09%09target=%22_blank%22%0A%09%09%09%09%09%09%09%09%09%09%09%09%09className=%22single-portfolio-item__link button primary%22%0A%09%09%09%09%09%09%09%09%09%09%09%09%09href=%7Blink.href%7D%0A%09%09%09%09%09%09%09%09%09%09%09%09%3E%0A%09%09%09%09%09%09%09%09%09%09%09%09%09%7Blink.label%7D%0A%09%09%09%09%09%09%09%09%09%09%09%09%3C/a%3E%0A%09%09%09%09%09%09%09%09%09%09%09);%0A%09%09%09%09%09%09%09%09%09%09%7D)%7D%0A%09%09%09%09%09%09%09%09%09%3C/div%3E%0A %09%09%09%09%09%09%09%09 @@ -3063,17 +3063,16 @@ ages%60);%0A -%0A %09%09revers
747344cdc024ceccb27cb5c9a805c0dd0ff986aa
remove polyfills
html/s-w.js
html/s-w.js
importScripts('serviceworker-cache-polyfill.js'); this.addEventListener("install", function (event) { event.waitUntil( caches.open('v3').then(function (cache) { return cache.addAll(['/html/', '/html/js/911.js', '/html/img/trapped_lady.jpg', '/html/img/screaming.jpg', '/html/img/location4.jpg', '/html/img/embrace3.jpg' ]); }) ); }); this.addEventListener('activate', function(event) { var cacheWhitelist = ['v2']; event.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (cacheWhitelist.indexOf(key) === -1) { return caches.delete(key); } })); }) ); }); this.addEventListener('fetch', function (event) { event.respondWith( caches.match(event.request) ); });
JavaScript
0.000001
@@ -1,56 +1,4 @@ -importScripts('serviceworker-cache-polyfill.js');%0A%0A%0A this
b55ccabefebab25e4195793d0497aef434409b4c
improve cli
app/templates/bin/_index.js
app/templates/bin/_index.js
#!/usr/bin/env node 'use strict'; var pkg = require('../package.json') require('update-notifier')({pkg: pkg}).notify() var <%= appname %> = require('./') var cli = require('meow')({ pkg: pkg help: require('fs').readFileSync(__dirname + '/help.txt', 'utf8') }) if (cli.input.length === 0) cli.showHelp()
JavaScript
0.000015
@@ -28,16 +28,43 @@ rict';%0A%0A +var path = require('path')%0A var pkg @@ -92,16 +92,17 @@ .json')%0A +%0A require( @@ -177,16 +177,17 @@ e('./')%0A +%0A var cli @@ -216,16 +216,17 @@ pkg: pkg +, %0A help: @@ -253,16 +253,26 @@ ileSync( +path.join( __dirnam @@ -276,13 +276,11 @@ name - + +, ' -/ help @@ -284,16 +284,17 @@ elp.txt' +) , 'utf8'
e3f7f80b103dc0b172623200d5b045f997727a17
Create login functionality in Ally framework
plugins/gui-core/gui-resources/scripts/js/views/auth.js
plugins/gui-core/gui-resources/scripts/js/views/auth.js
define ([ 'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap', 'tmpl!auth', ], function($, superdesk, dust, jsSHA) { <<<<<<< HEAD var AuthLogin = function(username, password, logintoken){ ======= var AuthDetails = function(username){ var authDetails = new $.rest('Superdesk/User'); authDetails.resetData().xfilter('Name,Id,EMail').select({ name: username }).done(function(users){ var user = users.UserList[0]; localStorage.setItem('superdesk.login.id', user.Id); localStorage.setItem('superdesk.login.name', user.Name); localStorage.setItem('superdesk.login.email', user.EMail); }); return $(authDetails); }, AuthLogin = function(username, password, logintoken){ >>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81 var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"), authLogin = new $.rest('Authentication'); authLogin.resetData().insert({ UserName: username, LoginToken: logintoken, HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX") }).done(function(user){ localStorage.setItem('superdesk.login.session', user.Session); <<<<<<< HEAD localStorage.setItem('superdesk.login.id', user.Id); localStorage.setItem('superdesk.login.name', user.UserName); localStorage.setItem('superdesk.login.email', user.EMail); $(authLogin).trigger('success'); ======= //localStorage.setItem('superdesk.login.id', user.Id); localStorage.setItem('superdesk.login.name', user.UserName); localStorage.setItem('superdesk.login.email', user.EMail); $(authLogin).trigger('success'); /* authDetails = AuthDetails(username); $(authDetails).on('failed', function(){ $(authLogin).trigger('failed', 'authDetails'); }); */ >>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81 }); return $(authLogin); }, AuthToken = function(username, password) { var authToken = new $.rest('Authentication'); authToken.resetData().select({ userName: username }).done( function(data){ authLogin = AuthLogin(username, password, data.Token); authLogin.on('failed', function(){ $(authToken).trigger('failed', 'authToken'); }).on('success', function(){ $(authToken).trigger('success'); }); } ); return $(authToken); }, AuthApp = { success: $.noop, require: function() { if(this.showed) return; var self = this; // rest self.showed = true; $.tmpl('auth', null, function(e, o) { var dialog = $(o).eq(0).dialog ({ draggable: false, resizable: false, modal: true, width: "40.1709%", buttons: [ { text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"}, { text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"} ] }), form = dialog.find('form'); form.off('submit.superdesk')// .on('submit.superdesk', function(event) { var username = $(this).find('#username'), password=$(this).find('#password'); AuthToken(username.val(), password.val()).on('failed',function(evt, type){ username.val(''); password.val('') }).on('success', function(){ AuthApp.success && AuthApp.success.apply(); $(dialog).dialog('close'); self.showed = false; }); event.preventDefault(); }); }); } }; return AuthApp; });
JavaScript
0
@@ -1220,29 +1220,16 @@ ssion);%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0A %09%09%09local @@ -1445,437 +1445,8 @@ ');%0A -=======%0A%09%09%09//localStorage.setItem('superdesk.login.id', user.Id);%0A%09%09%09localStorage.setItem('superdesk.login.name', user.UserName);%0A%09%09%09localStorage.setItem('superdesk.login.email', user.EMail);%09%09%09%0A%09%09%09$(authLogin).trigger('success');%0A/*%09%09%09authDetails = AuthDetails(username);%0A%09%09%09$(authDetails).on('failed', function()%7B%0A%09%09%09%09$(authLogin).trigger('failed', 'authDetails');%0A%09%09%09%7D);%0A*/%09%09%09%0A%3E%3E%3E%3E%3E%3E%3E 718d8c014dc7f1c47606de731769286a6bcebb81%0A %09%09%7D)
31665e105685364f6ef8ea2638c39f86f9381dac
Use karma phantomjs in travis e2e-tests
protractor-travis.conf.js
protractor-travis.conf.js
var config = require('./protractor-shared.conf').config; config.allScriptsTimeout = 30000; config.seleniumArgs = [ '-browserTimeout=60' ]; config.capabilities = { browserName: 'phantomjs' }; exports.config = config;
JavaScript
0
@@ -186,16 +186,125 @@ antomjs' +,%0A 'phantomjs.binary.path': './node_modules/karma-phantomjs-launcher/node_modules/phantomjs/bin/phantomjs' %0A%7D;%0A%0Aexp
535e76877f605fc2ce5a31d77403f213c99ab6b1
Allow url uploads to respond with their own url.
src/providers/storage/url.js
src/providers/storage/url.js
import Promise from 'native-promise-only'; const url = function(formio) { return { title: 'Url', name: 'url', uploadFile: function(file, fileName, dir, progressCallback, url) { return new Promise(((resolve, reject) => { const data = { dir: dir, name: fileName, file: file }; // Send the file with data. const xhr = new XMLHttpRequest(); if (typeof progressCallback === 'function') { xhr.upload.onprogress = progressCallback; } const fd = new FormData(); for (const key in data) { fd.append(key, data[key]); } xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { // Need to test if xhr.response is decoded or not. let respData = {}; try { respData = (typeof xhr.response === 'string') ? JSON.parse(xhr.response) : {}; respData = (respData && respData.data) ? respData.data : respData; } catch (err) { respData = {}; } resolve({ storage: 'url', name: fileName, url: `${xhr.responseURL}/${fileName}`, size: file.size, type: file.type, data: respData }); } else { reject(xhr.response || 'Unable to upload file'); } }; // Fire on network error. xhr.onerror = function() { reject(xhr); }; xhr.onabort = function() { reject(xhr); }; xhr.open('POST', url); const token = formio.getToken(); if (token) { xhr.setRequestHeader('x-jwt-token', token); } xhr.send(fd); })); }, downloadFile: function(file) { // Return the original as there is nothing to do. return Promise.resolve(file); } }; }; url.title = 'Url'; export default url;
JavaScript
0
@@ -1100,32 +1100,139 @@ %0A %7D%0A%0A + const url = respData.hasOwnProperty('url') ? respData.url : %60$%7Bxhr.responseURL%7D/$%7BfileName%7D%60;%0A%0A reso @@ -1237,16 +1237,16 @@ solve(%7B%0A - @@ -1289,32 +1289,32 @@ name: fileName,%0A + ur @@ -1318,42 +1318,8 @@ url -: %60$%7Bxhr.responseURL%7D/$%7BfileName%7D%60 ,%0A
7d1f60417a85ca28369f74c4c697bf97f4f897de
Fix open rename/delete folder dialogs
test/e2e/specs/FoldersTree/FoldersTree.specs.js
test/e2e/specs/FoldersTree/FoldersTree.specs.js
const {adaPrivateKey, adminPrivateKey} = require('../../page/Authentication/ImportGpgKey/ImportGpgKey.data'); const SeleniumPage = require('../../page/Selenium/Selenium.page'); const RecoverAuthenticationPage = require('../../page/AuthenticationRecover/RecoverAUthentication/RecoverAuthentication.page'); const ShareDialogPage = require('../../page/Share/ShareDialog.page'); const DisplayMainMenuPage = require('../../page/Common/Menu/DisplayMainMenu.page'); const DisplayResourcesWorkspacePage = require('../../page/Resource/DisplayResourcesWorkspace/DisplayResourcesWorkspace.page'); const DisplayResourcesListPage = require('../../page/Resource/DisplayResourcesList/DisplayResourcesList.page'); const DisplayResourceDetailsPage = require('../../page/ResourceDetails/DisplayResourceDetails/DisplayResourceDetails.page'); const DisplayResourceFolderDetailsPage = require('../../page/ResourceFolderDetails/DisplayResourceFolderDetails/DisplayResourceFolderDetails.page'); const FilterResourcesByFoldersPage = require('../../page/Resource/FilterResourcesByFolders/FilterResourcesByFolders.page'); const FilterResourcesByTextPage = require('../../page/Resource/FilterResourcesByText/FilterResourcesByText.page'); const CreateResourcePage = require('../../page/Resource/CreateResource/CreateResource.page'); const CreateResourceFolderPage = require('../../page/ResourceFolder/CreateResourceFolder/CreateResourceFolder.page'); const RenameResourceFolderPage = require('../../page/ResourceFolder/RenameResourceFolder/RenameResourceFolder.page'); const DeleteResourceFolderPage = require('../../page/ResourceFolder/DeleteResourceFolder/DeleteResourceFolder.page'); const FilterResourcesByShortcutsPage = require('../../page/Resource/FilterResourcesByShortcuts/FilterResourcesByShortcuts.page'); describe('password workspace', () => { // WARNING : execution order is very important after(() => { // runs once after the last test in this block SeleniumPage.resetInstanceDefault() }); it('As LU I should recover ada account', () => { RecoverAuthenticationPage.recover('[email protected]', adaPrivateKey); DisplayMainMenuPage.switchAppIframe(); }); it('As LU I should create a new folder', () => { DisplayResourcesWorkspacePage.openCreateFolder(); CreateResourceFolderPage.createFolder('folderParent'); FilterResourcesByFoldersPage.selectedFolderNamed('folderParent'); }); it('As LU I should create a new password', () => { DisplayResourcesWorkspacePage.openCreatePassword(); CreateResourcePage.createPassword('nameA', 'uri', '[email protected]', 'secretA', 'description'); }); it('As LU I should create a subfolder folder', () => { FilterResourcesByFoldersPage.selectedFolderNamed('folderParent'); DisplayResourcesWorkspacePage.openCreateFolder(); CreateResourceFolderPage.createFolder('folderChild'); }); it('As LU I should create a new password', () => { FilterResourcesByFoldersPage.expandFolderSelected(); FilterResourcesByFoldersPage.selectedFolderNamed('folderChild'); DisplayResourcesWorkspacePage.openCreatePassword(); CreateResourcePage.createPassword('nameB', 'uri', '[email protected]', 'secretB', 'description'); }); it('As LU I should share a password', () => { DisplayResourceDetailsPage.openShareResource(); ShareDialogPage.shareResource('[email protected]', '[email protected]'); }); it('As LU I should share a folder', () => { FilterResourcesByFoldersPage.selectedFolderNamed('folderParent'); DisplayResourceFolderDetailsPage.openShareResource(); ShareDialogPage.shareResource('Accounting', '[email protected]'); }); it('As LU I should see my passwords share with admin user and accounting group', () => { DisplayResourcesListPage.selectedResourceNamed('nameA'); DisplayResourceDetailsPage.openShareSection(); DisplayResourceDetailsPage.getShareWithExist('Accounting'); FilterResourcesByFoldersPage.selectedFolderNamed('folderChild'); DisplayResourcesListPage.selectedResourceNamed('nameB'); DisplayResourceDetailsPage.openShareSection(); DisplayResourceDetailsPage.getShareWithExist('Admin User ([email protected])'); DisplayResourceDetailsPage.getShareWithExist('Accounting'); }); it('As LU I should recover admin account', () => { RecoverAuthenticationPage.recover('[email protected]', adminPrivateKey); DisplayMainMenuPage.switchAppIframe(); }); it('As LU I should filter my resource by shared with me', () => { FilterResourcesByShortcutsPage.filterBySharedWithMe(); DisplayResourcesListPage.selectedResourceNamed('nameB'); }); it('As LU I should copy the secret of my password', () => { DisplayResourcesListPage.copySecretResource('[email protected]'); FilterResourcesByTextPage.pasteClipBoardToVerify('secretB'); }); it('As LU I should rename a folder', () => { FilterResourcesByFoldersPage.openFolderRenameDialog(); RenameResourceFolderPage.renameFolder('rename'); }); it('As LU I should delete a folder', () => { FilterResourcesByFoldersPage.openFolderDeleteDialog(); DeleteResourceFolderPage.deleteFolder(); }); });
JavaScript
0
@@ -4915,26 +4915,28 @@ open -FolderRenameDialog +RenameResourceFolder ();%0A @@ -5083,26 +5083,28 @@ open -FolderDeleteDialog +DeleteResourceFolder ();%0A
93e02fbb52d14d5036c91417e86e8367d3e17ca4
Update UDPefef
udp.js
udp.js
var d = require ('dequeue'); var redis = require("redis"); var rClient = redis.createClient(); var dgram = require("dgram"); var FIFO = new d(); var port = 4444; init(); var udpServer = dgram.createSocket("udp4"); udpServer.on("message", function (msg, rinfo) { FIFO.push(msg.toString()); } ); udpServer.on('error', function (err) { console.log("Error server: ", err); }); udpServer.bind(port); console.log("Running server: ", port); function init() { while (FIFO.length > 0) { var msg = FIFO.shift(); rClient.hset("raw", "data", msg); //console.log("msg", msg); } setImmediate(init); }
JavaScript
0
@@ -572,16 +572,28 @@ , %22data%22 ++FIFO.length , msg);%0A
aace6be9aec700c5e3ca9a4a3713c39bc73f4cd6
allow to reorder slick grid preferences of module
util/ModulePrefsManager.js
util/ModulePrefsManager.js
import API from 'src/util/api'; import UI from 'src/util/ui'; import getViewInfo from './getViewInfo'; // ModulePrefsManager is created in the init script // Any module may have a gear in the settings allowing to change preferences // the system will either store in Roc or localStorge depending what is available export class ModulePrefsManager { constructor(options = {}) { let promises = []; if (options.hasRoc) { let waitingRoc = new Promise((resolveRoc) => { this.resolveRoc = resolveRoc; }).then(() => { console.log('Roc initialized'); }); promises.push(waitingRoc); } let waitingView = getViewInfo().then((result) => { this.viewID = result._id; }); promises.push(waitingView); let promiseAll = Promise.all(promises).then(() => { this.waiting = () => true; }); this.waiting = () => promiseAll; } setRoc(roc) { this.roc = roc; this.resolveRoc(); } async updateSlickGridPrefs(moduleID) { await this.waiting(); const objectStructure = API.getModule(moduleID).data.resurrect()[0]; const cols = JSON.parse( JSON.stringify(API.getModulePreferences(moduleID).cols) ); cols.forEach((item) => { if (!item.id) item.id = Math.random(); }); await UI.editTable(cols, { remove: true, dialog: { title: 'Configure the columns of the module' }, columns: [ { id: 'id', name: 'name', jpath: ['name'], editor: Slick.CustomEditors.TextValue }, { id: 'rendererOptions', name: 'rendererOptions', jpath: ['rendererOptions'], editor: Slick.CustomEditors.TextValue }, { id: 'width', name: 'width', jpath: ['width'], editor: Slick.CustomEditors.NumberValue }, { id: 'x', name: 'x', jpath: ['x'], editor: Slick.CustomEditors.Select, editorOptions: { choices: 'ab:cd;ef:gh' } }, { id: 'jpath', name: 'jpath', jpath: ['jpath'], editor: Slick.CustomEditors.JPathFactory(objectStructure), forceType: 'jpath', rendererOptions: { forceType: 'jpath' } } ] }); cols.forEach((item) => { item.formatter = 'typerenderer'; }); API.updateModulePreferences(moduleID, { cols: JSON.parse(JSON.stringify(cols)) }); this.saveModulePrefs(moduleID, { cols }); } async reloadModulePrefs(moduleID) { await this.waiting(); if (this.roc) { this.reloadModulePrefsFromRoc(moduleID); } else { this.reloadModulePrefsFromLocalStorage(moduleID); } } async reloadModulePrefsFromLocalStorage(moduleID) { let prefs = JSON.parse( localStorage.getItem('viewModulePreferences') || '{}' ); if (!prefs[this.viewID]) return; if (moduleID && !prefs[this.viewID][moduleID]) return; if (moduleID) { API.updateModulePreferences(moduleID, prefs[this.viewID][moduleID]); } else { for (moduleID in prefs[this.viewID]) { API.updateModulePreferences(moduleID, prefs[this.viewID][moduleID]); } } } async getRecord() { var user = await this.roc.getUser(); if (!user || !user.username) return undefined; return ( await this.roc.view('entryByOwnerAndId', { key: [user.username, ['userModulePrefs', this.viewID]] }) )[0]; } async reloadModulePrefsFromRoc(moduleID) { const record = await this.getRecord(); if (!record) return; if (moduleID) { API.updateModulePreferences(moduleID, record.$content[moduleID]); } else { for (moduleID in record.$content[moduleID]) { API.updateModulePreferences(moduleID, record.$content[moduleID]); } } } async saveModulePrefs(moduleID, modulePrefs) { await this.waiting(); if (this.roc) { this.saveModulePrefsToRoc(moduleID, modulePrefs); } else { this.saveModulePrefsToLocalStorage(moduleID, modulePrefs); } } async saveModulePrefsToLocalStorage(moduleID, modulePrefs) { let prefs = JSON.parse( localStorage.getItem('viewModulePreferences') || '{}' ); if (!prefs[this.viewID]) prefs[this.viewID] = {}; prefs[this.viewID][moduleID] = modulePrefs; localStorage.setItem('viewModulePreferences', JSON.stringify(prefs)); } async saveModulePrefsToRoc(moduleID, modulePrefs) { let record = await this.getRecord(); if (record) { record.$content[moduleID] = modulePrefs; return this.roc.update(record); } else { let content = {}; content[moduleID] = modulePrefs; return this.roc.create({ $id: ['userModulePrefs', this.viewID], $content: content, $kind: 'userModulePrefs' }); } } } module.exports = ModulePrefsManager;
JavaScript
0
@@ -458,17 +458,16 @@ Promise( -( resolveR @@ -468,17 +468,16 @@ solveRoc -) =%3E %7B%0A @@ -669,16 +669,14 @@ hen( -( result -) =%3E @@ -1201,38 +1201,36 @@ cols.forEach( -( item -) =%3E %7B%0A if ( @@ -1324,16 +1324,37 @@ : true,%0A + reorder: true,%0A di @@ -2390,14 +2390,12 @@ ach( -( item -) =%3E
f6c7a237953275b5a7043b1cf9782b4f1e315b63
Fix getting channel/group name. Code cleanup.
jira-bot.js
jira-bot.js
'use strict'; const RtmClient = require('@slack/client').RtmClient, CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS, RTM_EVENTS = require('@slack/client').RTM_EVENTS, MemoryDataStore = require('@slack/client').MemoryDataStore, EventEmitter = require('events').EventEmitter, util = require('util'), log = require('winston'), _ = require('lodash'); class JiraBot extends EventEmitter { constructor(config) { super(); log.info('Creating new JiraBot instance'); this.config = config; this.issueKeysRegex = new RegExp('(' + config.watchTicketPrefixes.join('|') + ')-\\d+', 'g'); this.slack = new RtmClient(config.apiToken, { dataStore: new MemoryDataStore() }); this.slack.on(CLIENT_EVENTS.RTM.AUTHENTICATED, this._onOpen.bind(this)); this.slack.on(RTM_EVENTS.MESSAGE, this._onMessage.bind(this)); } login() { this.slack.start(); } sendMessage(...args) { this.slack.sendMessage.apply(this.slack, args); } sendTyping(...args) { this.slack.sendTyping.apply(this.slack, args); } _onOpen(rtmStartData) { log.info(`Connected to Slack. You are @${rtmStartData.self.name} of "${rtmStartData.team.name}" team`); } _onMessage(message) { const text = message.text; const channel = this.slack.dataStore.getGroupById(message.channel); const user = this.slack.dataStore.getUserById(message.user); let issueKeys; if (message.type !== 'message' || message.user === this.slack.activeUserId || !text || this.config.allowChannels.indexOf(channel.name) === -1) { return; } if (text.match(/hello/i) && (text.search(`<@${this.slack.activeUserId}>`) !== -1)) { this.slack.sendMessage(`@${user.name} hello :)`, message.channel); } issueKeys = text.match(this.issueKeysRegex) || []; if (issueKeys.length) { _.uniq(issueKeys).forEach((issueKey) => { log.info(`Found Jira issue key ${issueKey} in channel #${channel.name} from user @${user.name}`); this.emit('ticketKeyFound', issueKey, channel); }); } } } module.exports = JiraBot;
JavaScript
0
@@ -1239,29 +1239,56 @@ nst -text = message.text;%0A +channel = this._getChannelById(message.channel); %0A @@ -1286,39 +1286,36 @@ nel);%0A const -channel +user = this.slack.da @@ -1329,13 +1329,12 @@ .get -Group +User ById @@ -1346,146 +1346,461 @@ age. -channel +user );%0A +%0A -const user = this.slack.dataStore.getUserById(message.user);%0A let issueKeys;%0A%0A if (message.type !== 'message'%0A %7C%7C +if (this._isSelfMessage(message) %7C%7C !this._isMessageFromAllowedChannel(message) %7C%7C message.text == null) %7B%0A return;%0A %7D%0A%0A this._respondToHello(message);%0A%0A this._getIssueKeysFromMessage(message).forEach((issueKey) =%3E %7B%0A log.info(%60Found Jira issue key $%7BissueKey%7D in channel #$%7Bchannel.name%7D from user @$%7Buser.name%7D%60);%0A%0A this.emit('ticketKeyFound', issueKey, channel);%0A %7D);%0A %7D%0A%0A _isSelfMessage(message) %7B%0A return mes @@ -1840,32 +1840,126 @@ erId +; %0A - %7C%7C !text%0A %7C%7C +%7D%0A%0A _isMessageFromAllowedChannel(message) %7B%0A const channel = this._getChannelById(message.channel);%0A return thi @@ -2007,20 +2007,59 @@ me) -= +! == -1 +;%0A %7D%0A%0A _getIssueKeysFromMessage(message ) %7B%0A - @@ -2068,25 +2068,114 @@ turn -;%0A %7D%0A%0A if ( + _.uniq(message.text.match(this.issueKeysRegex) %7C%7C %5B%5D);%0A %7D%0A%0A _respondToHello(message) %7B%0A if (message. text @@ -2195,16 +2195,24 @@ /i) && ( +message. text.sea @@ -2255,24 +2255,91 @@ !== -1)) %7B%0A + const user = this.slack.dataStore.getUserById(message.user);%0A this.s @@ -2356,16 +2356,22 @@ essage(%60 +Hello @$%7Buser. @@ -2379,17 +2379,9 @@ ame%7D - hello :) +! %60, m @@ -2407,319 +2407,172 @@ %7D%0A -%0A - issueKeys = text.match(this.issueKeysRegex) %7C%7C %5B%5D;%0A%0A if (issueKeys.length) %7B%0A _.uniq(issueKeys).forEach((issueKey) =%3E %7B%0A log.info(%60Found Jira issue key $%7BissueKey%7D in channel #$%7Bchannel.name%7D from user @$%7Buser.name%7D%60);%0A%0A this.emit('ticketKeyFound', issueKey, channel);%0A %7D);%0A %7D +%7D%0A%0A _getChannelById(channelId) %7B%0A const dataStore = this.slack.dataStore;%0A return dataStore.getGroupById(channelId) %7C%7C dataStore.getChannelById(channelId); %0A %7D
5a40f4109508ea2d011ce831d57979e7389c807b
fix project path variable
scripts/prod/fork.js
scripts/prod/fork.js
"use strict"; const path = require('path'); const express = require('express'); const proxy = require('http-proxy-middleware'); const compression = require('compression'); function run_fork() { const port = process.env.PORT || 5000; const app = express(); app.use(compression()); const projectPath = path.dirname(__dirname); const staticPath = path.join(projectPath, 'browser-bundle'); app.use(express.static(staticPath)); app.use('/api', proxy({target: 'http://localhost:3000'})); app.get('*', (req, res) => { res.sendFile(path.join(projectPath, '/browser-bundle', 'index.html')); }); app.listen(port, (err) => { if (err) { console.log(err); } console.info('==> 🌎 Listening on port %s. Open up http://0.0.0.0:%s/ in your browser.', port, port); }); } module.exports = run_fork;
JavaScript
0.000002
@@ -316,24 +316,37 @@ ojectPath = +path.dirname( path.dirname @@ -356,16 +356,17 @@ dirname) +) ;%0A co
852d151a1080089011b9176cab2d0fc326e27a91
修改fis 配置
fis-conf.js
fis-conf.js
/** * MIX fis conf file * * @author Yang,junlong at 2016-06-22 10:12:17 build. * @version $Id$ */ // 基础配置信息 命名空间 fis.config.merge({ //namespace: 'mix', project : { // 使用project.exclude排除某些后缀 svn、cvs默认已排除 exclude : [/\.(tar|rar|psd|jar|bat|sh|md|git|bak)$/i, /^\/mix\/lib\/est/i] } }); fis.config.merge({ // 插件安装 modules: { parser: { less: 'less', }, postprocessor: { js: 'jswrapper, require-async' //html: 'amd' }, postpackager: 'modjs' }, // 插件配置 settings : { postprocessor : { jswrapper: { type: 'amd' } }, postpackager: { modjs: { subpath: 'pkg/map.js', useType: false } } }, roadmap : { ext : { less : 'css' }, path : [ { reg: /LICENSE/i, release: false }, { reg: 'server.conf', release: '/WEB-INF/server.conf' }, { reg: /^\/app\/index\.html$/i, isMod: true, useMap: false, release: '/index.html' }, { // .html|css 后缀的文件不加入map.json reg: /^.*(.+\.(?:html|css))$/i, useMap: false }, { reg: /^(?!.*mod.js).*$/i, isMod: true }, { // default reg: /^.+$/, release: '/static/$&' } ] } }); // limit jello command if (fis.require.prefixes[0] != 'fis') { //fis.log.error('Please use the `fis` command!\nUsage: jello release -wL'); } // stdout.write some info... process.stdout.write('\n β start complie '.yellow +fis.config.get('namespace')+' project ...\n'.yellow);
JavaScript
0
@@ -1420,21 +1420,1189 @@ useMap: -false +true,%0A url: '/static$&',%0A release: '/static$&'%0A %7D,%0A %7B%0A reg: /%5E(?!.*mod.js)(.*$)/i,%0A isMod: true,%0A url: '/static$1',%0A release: '/static$1'%0A %7D,%0A %7B%0A // default%0A reg: /%5E.+$/,%0A url: '/static$&',%0A release: '/static$&'%0A %7D%0A %5D%0A %7D%0A%7D);%0A%0Afis.emitter.once('fis-conf:loaded', function() %7B%0A if (process.title.split(/%5Cs/)%5B3%5D == 'output') %7B%0A fis.config.set('roadmap.path', %5B%0A %7B%0A reg: /LICENSE/i,%0A release: false%0A %7D,%0A %7B%0A reg: 'server.conf',%0A release: '/WEB-INF/server.conf'%0A %7D,%0A %7B%0A reg: /%5E%5C/app%5C/index%5C.html$/i,%0A isMod: true,%0A useMap: false,%0A release: '/index.html'%0A %7D,%0A %7B%0A // .html%7Ccss %E5%90%8E%E7%BC%80%E7%9A%84%E6%96%87%E4%BB%B6%E4%B8%8D%E5%8A%A0%E5%85%A5map.json%0A reg: /%5E.*(.+%5C.(?:html%7Ccss))$/i,%0A useMap: true,%0A url: './static$&',%0A release: './static$&' %0A @@ -2658,19 +2658,21 @@ *mod.js) +( .*$ +) /i,%0A @@ -2694,16 +2694,102 @@ od: true +,%0A url: '/mix-dashboard/static$1',%0A release: '/static$1' %0A @@ -2858,32 +2858,80 @@ reg: /%5E.+$/,%0A + url: '/mix-dashboard/static$&',%0A @@ -2947,17 +2947,16 @@ '/static -/ $&'%0A @@ -2966,32 +2966,34 @@ %7D%0A %5D +); %0A %7D%0A%7D);%0A%0A// l
848956c7d24d8aa7d599d0bd57b46b034f322dc9
truncate result logic fix
routes/search/resolvers.js
routes/search/resolvers.js
const docsEn = require('../../lib/i18n').docs['en-US'] const npmPkgs = require('electron-npm-packages') const repos = require('repos-using-electron/lite') const searchScores = { docs: [ { field: 'title', weight: 10 }, { field: 'description', weight: 3 }, { field: 'markdown', weight: 1 } ], npm: [ { field: 'name', weight: 10 }, { field: 'keywords', weight: 2 }, { field: 'description', weight: 5 } ], repos: [ { field: 'fullName', weight: 10 }, { field: 'description', weight: 5 } ] } const trim = (arr) => { // TODO: use real pagination to eliminate use of an entirely arbituary // limit that's totally not the answer to life, the universe and everything const limit = 42 if (arr.length < limit) { return arr } return arr.splice(arr.length - limit, arr.length - limit) } const assignSearchScores = (type, input, keyword) => { if (!searchScores[type]) { return input } return input.map((entry) => { let score = 0 const re = new RegExp(keyword, 'gi') searchScores[type].forEach(rule => { const src = Array.isArray(entry[rule.field]) ? entry[rule.field].join(' ') : entry[rule.field] score += src ? (src.match(re) || []).length * rule.weight : 0 }) entry.score = score return entry }) } const filterByKeyword = (type, input, keyword) => { return assignSearchScores(type, input, keyword) .filter((pkg) => pkg.score > 0) .sort((a, b) => b.score - a.score) } const resolvers = { docs: ({ id, filter }) => { if (id) { return docsEn[id] } const docs = Object.keys(docsEn).map((key) => docsEn[key]) if (!filter) { return docs } return trim(filterByKeyword('docs', docs, filter)) }, npmPackages: ({ filter }) => { if (!filter) { return npmPkgs } else { return trim(filterByKeyword('npm', npmPkgs, filter)) } }, repos: ({ filter }) => { if (!filter) { return repos } else { return trim(filterByKeyword('repos', repos, filter)) } } } module.exports = resolvers
JavaScript
0.000015
@@ -529,34 +529,8 @@ %0A%7D%0A%0A -const trim = (arr) =%3E %7B%0A // T @@ -596,18 +596,16 @@ bituary%0A - // limit @@ -676,135 +676,47 @@ ing%0A - const -limit = 42%0A if (arr.length %3C limit) %7B%0A return arr%0A %7D%0A return arr.splice(arr.length - limit, arr.length - limit)%0A%7D +trim = (arr) =%3E arr.splice(0, 42) %0A%0Aco @@ -1552,20 +1552,26 @@ return +trim( docs +) %0A %7D%0A @@ -1694,23 +1694,29 @@ return +trim( npmPkgs +) %0A %7D e @@ -1850,21 +1850,27 @@ return +trim( repos +) %0A %7D e
847462719873d349dc223c031f0ba923f07a6e6c
Support jquery.form
corehq/apps/hqwebapp/static/hqwebapp/js/hq-bug-report.js
corehq/apps/hqwebapp/static/hqwebapp/js/hq-bug-report.js
hqDefine('hqwebapp/js/hq-bug-report', ["jquery"], function($) { $(function () { var $hqwebappBugReportModal = $('#modalReportIssue'), $hqwebappBugReportForm = $('#hqwebapp-bugReportForm'), $hqwebappBugReportCancel = $('#bug-report-cancel'), $ccFormGroup = $("#bug-report-cc-form-group"), $emailFormGroup = $("#bug-report-email-form-group"), $issueSubjectFormGroup = $("#bug-report-subject-form-group"), isBugReportSubmitting = false; var resetForm = function () { $hqwebappBugReportForm.find("button[type='submit']").button('reset'); $hqwebappBugReportForm.resetForm(); $hqwebappBugReportCancel.button('reset'); $ccFormGroup.removeClass('has-error has-feedback'); $ccFormGroup.find(".label-danger").addClass('hide'); $emailFormGroup.removeClass('has-error has-feedback'); $emailFormGroup.find(".label-danger").addClass('hide'); }; $hqwebappBugReportModal.on('shown.bs.modal', function() { $("input#bug-report-subject").focus(); }); $hqwebappBugReportForm.submit(function() { var isDescriptionEmpty = !$("#bug-report-subject").val() && !$("#bug-report-message").val(); if (isDescriptionEmpty) { highlightInvalidField($issueSubjectFormGroup); } var emailAddress = $(this).find("input[name='email']").val(); if (emailAddress && !IsValidEmail(emailAddress)){ highlightInvalidField($emailFormGroup); return false; } var emailAddresses = $(this).find("input[name='cc']").val(); emailAddresses = emailAddresses.replace(/ /g, "").split(","); for (var index in emailAddresses){ var email = emailAddresses[index]; if (email && !IsValidEmail(email)){ highlightInvalidField($ccFormGroup); return false; } } if (isDescriptionEmpty) { return false; } var $submitButton = $(this).find("button[type='submit']"); if(!isBugReportSubmitting && $submitButton.text() === $submitButton.data("success-text")) { $hqwebappBugReportModal.modal("hide"); } else if(!isBugReportSubmitting) { $submitButton.button('loading'); $hqwebappBugReportCancel.button('loading'); $(this).ajaxSubmit({ type: "POST", url: $(this).attr('action'), beforeSerialize: hqwebappBugReportBeforeSerialize, beforeSubmit: hqwebappBugReportBeforeSubmit, success: hqwebappBugReportSucccess, error: hqwebappBugReportError, }); } return false; }); function IsValidEmail(email) { var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; return regex.test(email); } function hqwebappBugReportBeforeSerialize($form) { $form.find("#bug-report-url").val(location.href); } function hqwebappBugReportBeforeSubmit(arr) { isBugReportSubmitting = true; } function hqwebappBugReportSucccess() { isBugReportSubmitting = false; $hqwebappBugReportForm.find("button[type='submit']").button('success').removeClass('btn-primary btn-danger').addClass('btn-success'); $hqwebappBugReportModal.one('hidden.bs.modal', function () { resetForm(); }); } function hqwebappBugReportError() { isBugReportSubmitting = false; $hqwebappBugReportForm.find("button[type='submit']").button('error').removeClass('btn-primary btn-success').addClass('btn-danger'); } function highlightInvalidField($element) { $element.addClass('has-error has-feedback'); $element.find(".label-danger").removeClass('hide'); $element.find("input").focus(function(){ $element.removeClass("has-error has-feedback"); $element.find(".label-danger").addClass('hide'); }); } }); });
JavaScript
0
@@ -40,16 +40,52 @@ %22jquery%22 +, %22jquery-form/dist/jquery.form.min%22 %5D, funct
f26a1ba30c637b15acb29cfd04ea0e69bdf7ae2e
Create login functionality in Ally framework
plugins/gui-core/gui-resources/scripts/js/views/auth.js
plugins/gui-core/gui-resources/scripts/js/views/auth.js
define ([ 'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap', 'tmpl!auth', ], function($, superdesk, dust, jsSHA) { var AuthLogin = function(username, password, logintoken){ var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"), authLogin = new $.rest('Authentication'); authLogin.resetData().insert({ UserName: username, LoginToken: logintoken, HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX") }).done(function(user){ localStorage.setItem('superdesk.login.session', user.Session); localStorage.setItem('superdesk.login.id', user.Id); localStorage.setItem('superdesk.login.name', user.UserName); localStorage.setItem('superdesk.login.email', user.EMail); $(authLogin).trigger('success'); }); return $(authLogin); }, AuthToken = function(username, password) { var authToken = new $.rest('Authentication'); authToken.resetData().select({ userName: username }).done( function(data){ authLogin = AuthLogin(username, password, data.Token); authLogin.on('failed', function(){ $(authToken).trigger('failed', 'authToken'); }).on('success', function(){ $(authToken).trigger('success'); }); } ); return $(authToken); }, AuthApp = }); return $(authToken); }, AuthApp = { success: $.noop, showed: false, require: function() { if(AuthApp.showed) return; var self = this; // rest AuthApp.showed = true; $.tmpl('auth', null, function(e, o) { var dialog = $(o).eq(0).dialog ({ draggable: false, resizable: false, modal: true, width: "40.1709%", buttons: [ { text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"}, { text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"} ] }), form = dialog.find('form'); form.off('submit.superdesk') .on('submit.superdesk', function(event) { var username = $(this).find('#username'), password=$(this).find('#password'); AuthToken(username.val(), password.val()).on('failed',function(evt, type){ username.val(''); password.val('') }).on('success', function(){ AuthApp.success && AuthApp.success.apply(); $(dialog).dialog('close'); self.showed = false; }); event.preventDefault(); }); }); } }; return AuthApp; });
JavaScript
0
@@ -838,19 +838,304 @@ .EMail); +%0A %09%09%09 +$.restAuth.prototype.requestOptions.headers.Authorization = localStorage.getItem('superdesk.login.session');%0A%09%09%09superdesk.login = %7BId: localStorage.getItem('superdesk.login.id'), Name: localStorage.getItem('superdesk.login.name'), EMail: localStorage.getItem('superdesk.login.email')%7D %0A%09%09%09$(au @@ -2821,16 +2821,18 @@ %09%0A%09%09%09%09%09%09 +// username
712835fdb075c44428f716482a6e041c816f5a98
fix possible null point in _getRotationAt(i)
src/renderer/geometry/symbolizers/PointSymbolizer.js
src/renderer/geometry/symbolizers/PointSymbolizer.js
import { computeDegree } from 'core/util'; import PointExtent from 'geo/PointExtent'; import CanvasSymbolizer from './CanvasSymbolizer'; /** * @classdesc * Base symbolizer class for all the point type symbol styles. * @abstract * @class * @private * @memberOf symbolizer * @name PointSymbolizer * @extends {symbolizer.CanvasSymbolizer} */ class PointSymbolizer extends CanvasSymbolizer { constructor(symbol, geometry, painter) { super(); this.symbol = symbol; this.geometry = geometry; this.painter = painter; } get2DExtent() { const map = this.getMap(); const maxZoom = map.getMaxNativeZoom(); const extent = new PointExtent(); const renderPoints = this._getRenderPoints()[0]; for (let i = renderPoints.length - 1; i >= 0; i--) { extent._combine(map._pointToPoint(renderPoints[i], maxZoom)); } return extent; } _getRenderPoints() { return this.getPainter().getRenderPoints(this.getPlacement()); } /** * Get container points to draw on Canvas * @return {Point[]} */ _getRenderContainerPoints(ignoreAltitude) { const painter = this.getPainter(), points = this._getRenderPoints()[0]; if (painter.isSpriting()) { return points; } const dxdy = this.getDxDy(); const cpoints = this.painter._pointContainerPoints(points, dxdy.x, dxdy.y, ignoreAltitude, true); if (!cpoints || !Array.isArray(cpoints[0])) { return cpoints; } const flat = []; for (let i = 0, l = cpoints.length; i < l; i++) { for (let ii = 0, ll = cpoints[i].length; ii < ll; ii++) { flat.push(cpoints[i][ii]); } } return flat; } _getRotationAt(i) { let r = this.getRotation(); const rotations = this._getRenderPoints()[1]; if (!rotations) { return r; } if (!r) { r = 0; } const map = this.getMap(); let p0 = rotations[i][0], p1 = rotations[i][1]; if (map.isTransforming()) { const maxZoom = map.getMaxNativeZoom(); p0 = map._pointToContainerPoint(rotations[i][0], maxZoom); p1 = map._pointToContainerPoint(rotations[i][1], maxZoom); } return r + computeDegree(p0, p1); } _rotate(ctx, origin, rotation) { if (rotation) { const dxdy = this.getDxDy(); const p = origin.sub(dxdy); ctx.save(); ctx.translate(p.x, p.y); ctx.rotate(rotation); return this.getDxDy(); } return null; } } export default PointSymbolizer;
JavaScript
0.99981
@@ -1876,24 +1876,71 @@ Rotation();%0A + if (!r) %7B%0A r = 0;%0A %7D%0A cons @@ -2003,16 +2003,33 @@ otations + %7C%7C !rotations%5Bi%5D ) %7B%0A @@ -2060,54 +2060,8 @@ %7D%0A - if (!r) %7B%0A r = 0;%0A %7D %0A
90e9363c229a0761347d00a2917e87eb18525f60
Fix the input to reset
app/widgets/charm-search.js
app/widgets/charm-search.js
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2012-2013 Canonical Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; /** * The widget used across Browser view to manage the search box and the * controls for selecting which view you're in. * * @module widgets * @submodule browser * */ YUI.add('browser-search-widget', function(Y) { var ns = Y.namespace('juju.widgets.browser'), templates = Y.namespace('juju.views').Templates; /** * Search widget present in the Charm browser across both fullscreen and * sidebar views. * * @class Search * @extends {Y.Widget} * @event EV_CLEAR_SEARCH the widget requests all search reset. * @event EV_SEARCH_CHANGED the widgets notifies that the search input has. * @event EV_SEARCH_GOHOME Signal that the user clicked the home button. * changed. * */ ns.Search = Y.Base.create('search-widget', Y.Widget, [ Y.Event.EventTracker ], { EVT_CLEAR_SEARCH: 'clear_search', EVT_SEARCH_CHANGED: 'search_changed', EVT_SEARCH_GOHOME: 'go_home', TEMPLATE: templates['browser-search'], /** * Halt page reload from form submit and let the app know we have a new * search. * * @method _handleSubmit * @param {Event} ev the submit event. */ _handleSubmit: function(ev) { ev.halt(); var form = this.get('boundingBox').one('form'), value = form.one('input').get('value'); this.fire(this.EVT_SEARCH_CHANGED, { newVal: value }); }, /** * When home is selected the event needs to be fired up to listeners. * * @method _onHome * @param {Event} ev The click event for the home button. * */ _onHome: function(ev) { ev.halt(); this.fire(this.EVT_SEARCH_GOHOME); }, /** * Set the form to active so that we can change the search appearance. * * @method _setActive * @private * */ _setActive: function() { var form = this.get('boundingBox').one('form').addClass('active'); }, /** * Toggle the active state depending on the content in the search box. * * @method _toggleActive * @private * */ _toggleActive: function() { var form = this.get('boundingBox').one('form'), value = form.one('input').get('value'); if (value === '') { form.removeClass('active'); } else { form.addClass('active'); } }, /** * bind the UI events to the DOM making up the widget control. * * @method bindUI * */ bindUI: function() { var container = this.get('boundingBox'); this.addEvent( container.one('form').on( 'submit', this._handleSubmit, this) ); this.addEvent( container.one('input').on( 'focus', this._setActive, this) ); this.addEvent( container.one('input').on( 'blur', this._toggleActive, this) ); this.addEvent( container.one('.browser-nav').delegate( 'click', this._onHome, '.home', this) ); this.addEvent( container.one('i').on( 'mouseenter', function(ev) { // Change the icon to hover on mounseenter. ev.target.removeClass('home-icon'); ev.target.addClass('home-icon-hover'); }, this) ); this.addEvent( container.one('i').on( 'mouseleave', function(ev) { // Change the icon to back on mouseleave. ev.target.removeClass('home-icon-hover'); ev.target.addClass('home-icon'); }, this) ); }, /** * Generic initializer for the widget. Publish events we expose for * outside use. * * @method initializer * @param {Object} cfg configuration override object. * */ initializer: function(cfg) { /* * Fires when the "Charm Browser" link is checked. Needs to communicate * with the parent view so that it can handle filters and the like. This * widget only needs to clear the search input box. * */ this.publish(this.EVT_SEARCH_CHANGED); this.publish(this.EVT_SEARCH_GOHOME); }, /** * Render all the things! * * @method renderUI * */ renderUI: function() { var data = this.getAttrs(); this.get('contentBox').setHTML( this.TEMPLATE(data) ); // If there's an existing search term, make sure we toggle active. if (data.filters.text) { this._toggleActive(); } }, /** * Update the search input to contain the string passed. This is meant to * be used by outside links that want to perform a pre-canned search and * display results. * * @method update_search * @param {String} newval the sting to update the input to. * */ updateSearch: function(newval) { var input = this.get('contentBox').one('input'); input.focus(); input.set('value', newval); } }, { ATTRS: { /** @attribute filters @default {Object} text: '' @type {Object} */ filters: { value: { text: '' } } } }); }, '0.1.0', { requires: [ 'base', 'browser-filter-widget', 'event', 'event-delegate', 'event-tracker', 'event-mouseenter', 'event-valuechange', 'juju-templates', 'juju-views', 'widget' ] });
JavaScript
0.000293
@@ -2405,32 +2405,128 @@ function(ev) %7B%0A + var form = this.get('boundingBox').one('form');%0A form.one('input').set('value', '');%0A ev.halt();
ff9fe370a7672fb99ebfa45d089b4108f23edce5
Fix error when store isn’t initially persisted.
src/components/navbar/Navbar.js
src/components/navbar/Navbar.js
import React from 'react' import classNames from 'classnames' import Mousetrap from 'mousetrap' import { replaceState } from 'redux-router' import { connect } from 'react-redux' import { SHORTCUT_KEYS } from '../../constants/gui_types' import NavbarLabel from './NavbarLabel' import NavbarOmniButton from './NavbarOmniButton' import NavbarLink from './NavbarLink' import NavbarMark from './NavbarMark' import NavbarMorePostsButton from './NavbarMorePostsButton' import NavbarProfile from './NavbarProfile' import { BoltIcon, CircleIcon, SearchIcon, SparklesIcon, StarIcon } from '../navbar/NavbarIcons' import HelpDialog from '../dialogs/HelpDialog' import { openModal, closeModal } from '../../actions/modals' import { addScrollObject, removeScrollObject } from '../interface/ScrollComponent' import { addResizeObject, removeResizeObject } from '../interface/ResizeComponent' import * as ACTION_TYPES from '../../constants/action_types' class Navbar extends React.Component { constructor(props, context) { super(props, context) this.scrollYAtDirectionChange = null this.state = { asLocked: false, asFixed: false, asHidden: false, skipTransition: false, offset: Math.round((window.innerWidth * 0.5625) - 120), } } componentDidMount() { const { dispatch } = this.props Mousetrap.bind(Object.keys(this.props.shortcuts), (event, shortcut) => { dispatch(replaceState(window.history.state, this.props.shortcuts[shortcut])) }) Mousetrap.bind(SHORTCUT_KEYS.HELP, () => { const { modal } = this.props if (modal.payload) { return dispatch(closeModal()) } return dispatch(openModal(<HelpDialog/>)) }) Mousetrap.bind(SHORTCUT_KEYS.TOGGLE_LAYOUT, () => { const { json, router } = this.props let result = null if (json.pages) { result = json.pages[router.location.pathname] } if (result && result.mode) { const newMode = result.mode === 'grid' ? 'list' : 'grid' dispatch({ type: ACTION_TYPES.SET_LAYOUT_MODE, payload: { mode: newMode }, }) } }) addResizeObject(this) addScrollObject(this) } componentWillReceiveProps(nextProps) { const { router } = nextProps const pathnames = router.location.pathname.split('/').slice(1) const whitelist = ['', 'discover', 'following', 'starred', 'notifications', 'search', 'invitations', 'onboarding', 'staff', 'find'] const isWhitelisted = (whitelist.indexOf(pathnames[0]) >= 0 || pathnames[1] === 'post') this.setState({ asLocked: !isWhitelisted }) } // componentDidUpdate() { // if (this.state.asLocked) { // window.scrollTo(0, this.state.offset - 120) // } // } componentWillUnmount() { Mousetrap.unbind(Object.keys(this.props.shortcuts)) Mousetrap.unbind(SHORTCUT_KEYS.HELP) Mousetrap.unbind(SHORTCUT_KEYS.TOGGLE_LAYOUT) removeResizeObject(this) removeScrollObject(this) } onResize(resizeProperties) { const { coverOffset } = resizeProperties this.setState({ offset: coverOffset - 120 }) } onScrollTop() { if (this.state.asFixed) { this.setState({ asFixed: false, asHidden: false, skipTransition: false }) } } onScrollDirectionChange(scrollProperties) { const { scrollY } = scrollProperties const { offset } = this.state if (scrollY >= offset) { this.scrollYAtDirectionChange = scrollY } } onScroll(scrollProperties) { const { scrollY, scrollDirection } = scrollProperties const { offset } = this.state // Going from absolute to fixed positioning if (scrollY >= offset && !this.state.asFixed) { this.setState({ asFixed: true, asHidden: true, skipTransition: true }) } // Scroll just changed directions so it's about to either be shown or hidden if (scrollY >= offset && this.scrollYAtDirectionChange) { const distance = Math.abs(scrollY - this.scrollYAtDirectionChange) const delay = scrollDirection === 'down' ? 20 : 80 if (distance >= delay ) { this.setState({ asHidden: scrollDirection === 'down', skipTransition: false }) this.scrollYAtDirectionChange = null } } } omniButtonWasClicked() { } searchWasClicked() { const { dispatch } = this.props dispatch({ type: ACTION_TYPES.SEARCH.CLEAR }) } loadMorePostsWasClicked() { const { dispatch } = this.props dispatch({ type: ACTION_TYPES.ADD_NEW_IDS_TO_RESULT, }) } render() { const { json, profile, router } = this.props const showLabel = true const klassNames = classNames( 'Navbar', { asLocked: this.state.asLocked }, { asFixed: this.state.asFixed }, { asHidden: this.state.asHidden }, { skipTransition: this.state.skipTransition }, ) const result = json.pages[router.location.pathname] || null const hasLoadMoreButton = result && result.newIds return ( <nav className={klassNames} role="navigation"> <NavbarMark /> { showLabel ? <NavbarLabel /> : <NavbarOmniButton callback={this.omniButtonWasClicked.bind(this)} />} { hasLoadMoreButton ? <NavbarMorePostsButton callback={this.loadMorePostsWasClicked.bind(this)} /> : null } <div className="NavbarLinks"> <NavbarLink to="/discover" label="Discover" icon={ <SparklesIcon/> } /> <NavbarLink to="/following" label="Following" icon={ <CircleIcon/> } /> <NavbarLink to="/starred" label="Starred" icon={ <StarIcon/> } /> <NavbarLink to="/notifications" label="Notifications" icon={ <BoltIcon/> } /> <NavbarLink to="/search" label="Search" onClick={this.searchWasClicked.bind(this)} icon={ <SearchIcon/> } /> </div> <NavbarProfile { ...profile.payload } /> </nav> ) } } // This should be a selector: @see: https://github.com/faassen/reselect function mapStateToProps(state) { return { json: state.json, modal: state.modal, profile: state.profile, router: state.router, } } Navbar.defaultProps = { shortcuts: { [SHORTCUT_KEYS.SEARCH]: '/search', [SHORTCUT_KEYS.DISCOVER]: '/discover', [SHORTCUT_KEYS.FOLLOWING]: '/following', [SHORTCUT_KEYS.ONBOARDING]: '/onboarding/communities', }, } Navbar.propTypes = { dispatch: React.PropTypes.func.isRequired, json: React.PropTypes.object.isRequired, modal: React.PropTypes.object, profile: React.PropTypes.object, router: React.PropTypes.object.isRequired, shortcuts: React.PropTypes.object.isRequired, } export default connect(mapStateToProps)(Navbar)
JavaScript
0
@@ -4845,32 +4845,55 @@ const result = + json.pages && router ? json.pages%5Brout @@ -4914,18 +4914,17 @@ thname%5D -%7C%7C +: null%0A
15e04692039672b0e497a8c1664c6ef605bf9771
Update UDPefef
udp.js
udp.js
var d = require ('dequeue'); var seatStateStore = require("./SeatStateStore"); var redis = require("redis"); var rClient = redis.createClient(); var dgram = require("dgram"); var FIFO = new d(); fetcher(); var udpserver = dgram.createSocket("udp4"); udpserver.on("message", function (msg, rinfo) { FIFO.push(msg.toString()); console.log("MSG", msg); } ); udpserver.bind(4444); function fetcher () { while (FIFO.length > 0) { var msg = FIFO.shift(); console.log("Goi tin: ", msg); //rClient.hset("raw", "data"+index, msg); seatStateStore.parseMessage(msg); process.nextTick(fetcher); } } ///
JavaScript
0
@@ -453,12 +453,15 @@ %3E 0) +%0A %7B%0A -%0A @@ -500,171 +500,145 @@ -console.log(%22Goi tin: %22, msg);%0A //rClient.hset(%22raw%22, %22data%22+index, msg);%0A seatStateStore.parseMessage(msg);%0A process.nextTick(fetcher);%0A %7D +seatStateStore.parseMessage(msg);%0A console.log(%22mg:%22, msg);%0A %7D%0A setImmediate(fetcher); //make this function continuously run %0A%7D%0A%0A
69c6b18011845e3dbf1791eebd0643a875278d63
Add tests
test/handlers/OpenIDConfigurationRequestSpec.js
test/handlers/OpenIDConfigurationRequestSpec.js
JavaScript
0
@@ -0,0 +1,984 @@ +'use strict'%0A%0A/**%0A * Test dependencies%0A */%0Aconst chai = require('chai')%0Aconst HttpMocks = require('node-mocks-http')%0A%0A/**%0A * Assertions%0A */%0Achai.use(require('dirty-chai'))%0Achai.should()%0Alet expect = chai.expect%0A%0A/**%0A * Code under test%0A */%0Aconst Provider = require('../../src/Provider')%0Aconst OpenIDConfigurationRequest = require('../../src/handlers/OpenIDConfigurationRequest')%0A%0A/**%0A * Tests%0A */%0Adescribe('OpenIDConfigurationRequest', () =%3E %7B%0A const providerUri = 'https://example.com'%0A let req, res, provider%0A%0A beforeEach(() =%3E %7B%0A req = HttpMocks.createRequest()%0A res = HttpMocks.createResponse()%0A%0A provider = new Provider(%7B issuer: providerUri %7D)%0A %7D)%0A%0A it('should respond with the provider configuration in JSON format', () =%3E %7B%0A OpenIDConfigurationRequest.handle(req, res, provider)%0A%0A expect(res._isJSON()).to.be.true()%0A%0A let config = JSON.parse(res._getData())%0A%0A expect(config%5B'authorization_endpoint'%5D).to.equal('https://example.com/authorize')%0A %7D)%0A%7D)%0A
e437c640d46b16cd8e33657e297810ba04310a0e
添加use strict声明
fis-conf.js
fis-conf.js
// 排除源码目录下的node_modules目录,不对其进行构建 fis.config.set('project.exclude', 'node_modules/**'); // 利用package.json文件定义项目名和版本 var meta = require('./package.json'); fis.config.set('name', meta.name); fis.config.set('version', meta.version); // 对md、tpl后缀的文件指定用fis-optimizer-html-minifier插件进行压缩 fis.config.set('modules.optimizer.md', 'html-minifier'); fis.config.set('modules.optimizer.tpl', 'html-minifier'); // scrat.js框架开启localstorage缓存 fis.config.set('framework.cache', true); // 静态资源加载路径模式 fis.config.set('framework.urlPattern', '/public/c/%s'); //设置url前缀 fis.config.set('urlPrefix', '/public'); // fis-lint-jshint插件配置 fis.config.set('settings.lint.jshint', { // 在jshint基础上加上了i18n配置,将报错信息翻译成中文 i18n: 'zh-CN', // 在jshint基础上加上了ignored配置,排除框架文件、第三方模块 ignored: [ 'views/lib/**', 'component_modules/**' ], // 其他配置项请直接参阅jshint官网说明 predef: [ 'define', 'Handlebars', '__FRAMEWORK_CONFIG__' ], bitwise: true, camelcase: true, eqeqeq: true, forin: true, immed: true, indent: 4, newcap: true, noarg: true, noempty: true, nonew: true, undef: true, strict: true, boss: true, trailing: true, eqnull: true, browser: true, devel: true, jquery: true, node: true, white: false }); // 使用pngquant把png图片压缩为png8,减少质量 fis.config.set('settings.optimizer.png-compressor.type', 'pngquant'); // fis-optimizer-html-minifier插件配置 fis.config.set('settings.optimizer.html-minifier', { // fis直接将此配置传递给html-minfier模块 // 因此相关配置项请直接参阅html-minifier文档 removeComments: true, collapseWhitespace: true, conservativeCollapse: true, removeAttributeQuotes: true });
JavaScript
0.000001
@@ -868,16 +868,24 @@ redef: %5B +%0A 'define @@ -886,16 +886,24 @@ define', +%0A 'Handle @@ -908,16 +908,24 @@ lebars', +%0A '__FRAM @@ -939,16 +939,34 @@ ONFIG__' +,%0A 'ga'%0A %5D,%0A
89c6430c31286f2a882e3a094a152acb127c7b7e
Update webpack build script to work when watching for changes
build/webpack.js
build/webpack.js
let webpack = require('webpack'); let path = require('path'); let _ = require('lodash'); let utils = require('./utils'); let config = require('../lib/config'); module.exports = function(files, minify, watch, cb) { let cbCalled = false; function finish(err, stats) { if(err) { console.log(err); return; } let jsonStats = stats.toJson(); if(stats.hasErrors()) { // console.log('errors start'); jsonStats.errors.forEach((err, index) => { let lines = err.trim().split('\n'); console.log(lines); let message = lines[1]; let file = lines[0]; let pieces = lines.pop().split(' '); let lineInfo = pieces[pieces.length-1]; let line = lineInfo.split(':')[0]; utils.error('Webpack', message, file, line); }); } if(stats.hasWarnings()) { jsonStats.warnings.forEach(console.log.bind(console)); } if(!jsonStats.errors.length && !jsonStats.warnings.length) { utils.log('Webpack', 'bundle updated', 'success'); } if((!cbCalled || watch) && cb && _.isFunction(cb)) { cb(err, stats); cbCalled = true; } } files = files.map(file => { if(file.charAt(0) !== path.sep) { return path.join(config.root, file); } return file; }); let webpackCompiler = webpack({ entry: files, output: { path: path.join(config.root, 'public', 'scripts'), filename: minify ? 'bundle.min.js' : 'bundle.js' }, module: { loaders: [ { test: /\.js/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ], plugins: minify ? [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ] : [] }, devtool: minify ? 'source-map' : 'inline-source-map', watchOptions: { poll: config.build.watching.poll ? config.build.watching.interval || 100 : undefined } }); if(watch) { webpackCompiler.watch({errorDetails: true}, finish); } else { webpackCompiler.run(finish); } };
JavaScript
0
@@ -1564,16 +1564,131 @@ ify ? %5B%0A +%09%09%09%09new webpack.DefinePlugin(%7B%0A%09%09%09%09%09'process.env': %7B%0A%09%09%09%09%09%09'NODE_ENV': JSON.stringify('production')%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D),%0A %09%09%09%09new
882ac5c849a5e8691a4cabce6d0e08d610d1339f
Simplify syntax
src/create-action-types.js
src/create-action-types.js
import assign from 'object-assign'; export default function(types) { return types .map(type => { return { [type]: type }; }) .reduce((prev, curr) => assign(prev, curr)); }
JavaScript
0.000164
@@ -100,17 +100,9 @@ =%3E -%7B return +( %7B %5Bt @@ -117,11 +117,9 @@ pe %7D -; %7D +) )%0A
f258dcdc3488c088f37821672aeda2ef7973410d
add options back to config
build.conf.js
build.conf.js
/* * Copyright 2015 Hippo B.V. (http://www.onehippo.com) * * 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 objectAssign = require('lodash.assign'); var appRootDir = require('app-root-dir'); function buildConfig(customConfig) { var cfg = {}; var customCfg = customConfig || {}; cfg.env = {}; // When set to true all files in the 'dist' folder are copied to the 'target' folder cfg.env.maven = false; cfg.srcDir = customCfg.srcDir || './src/'; cfg.distDir = customCfg.distDir || './dist/'; cfg.bowerDir = customCfg.bowerDir || './bower_components/'; cfg.npmDir = customCfg.npmDir || './node_modules/'; cfg.targetBowerDir = customCfg.targetBowerDir || cfg.distDir + cfg.projectName + cfg.bowerDir; cfg.targetNpmDir = customCfg.npmDir || cfg.npmDir + cfg.projectName + +cfg.npmDir; cfg.projectName = require(appRootDir.get() + '/package.json').name; cfg.src = {}; cfg.src.styles = cfg.srcDir + 'styles/**/*.scss'; cfg.src.indexStyles = cfg.srcDir + 'styles/' + cfg.projectName + '.scss'; cfg.src.images = cfg.srcDir + 'images/**/*.{png,jpg,gif,ico}'; cfg.src.fonts = cfg.srcDir + 'fonts/**/*'; cfg.src.indexScript = cfg.srcDir + 'angularjs/' + cfg.projectName + '.js'; cfg.src.unitTests = cfg.srcDir + 'angularjs/**/*.spec.js'; cfg.src.scripts = cfg.srcDir + 'angularjs/**/!(*.spec).js'; cfg.src.templates = cfg.srcDir + 'angularjs/**/*.html'; cfg.src.i18n = cfg.srcDir + 'i18n/**'; cfg.src.indexHtml = cfg.srcDir + 'index.html'; cfg.dist = {}; cfg.dist.indexHtml = cfg.distDir + 'index.html'; cfg.dist.styles = cfg.distDir + 'styles/'; cfg.dist.fonts = cfg.distDir + 'fonts/'; cfg.dist.scripts = cfg.distDir + 'scripts/'; cfg.dist.indexScript = cfg.distDir + 'scripts/' + cfg.projectName + '.js'; cfg.dist.images = cfg.distDir + 'images/'; cfg.dist.i18n = cfg.distDir + 'i18n/'; cfg.karmaConfig = appRootDir.get() + '/karma.conf.js'; cfg.bowerAssets = [cfg.bowerDir + 'hippo-theme/dist/**/*.{svg,woff,woff2,ttf,eot,png}']; cfg.bowerLinks = [cfg.bowerDir + 'hippo-theme/dist/**']; cfg.supportedBrowsers = ['last 1 Chrome versions', 'last 1 Firefox versions', 'Safari >= 7', 'Explorer >= 10']; cfg.serverMiddlewares = []; cfg.sassLintRules = { 'force-element-nesting': 0 }; cfg.esLintRules = { "ecmaFeatures": { "modules": true }, "env": { "browser": true, "node": true, "es6": true } }; cfg.systemjsConfig = appRootDir.get() + '/system.conf.js'; return objectAssign(cfg, customCfg); } module.exports = buildConfig;
JavaScript
0.000001
@@ -2940,53 +2940,78 @@ emjs -Config = appRootDir.get() + '/system.conf.js' +Options = %7B%0A transpiler: 'babel',%0A defaultJSExtensions: true%0A %7D ;%0A%0A
a4efbea888bd73c6d943dfa3696cd57b3de938cb
Allow custom content to be transcluded at bottom of sidebar
custom/gnap-angular/js/develop/gnap/sidebar.directive.js
custom/gnap-angular/js/develop/gnap/sidebar.directive.js
'use strict'; /** * @desc displays a sidebar * @file sidebar.directive.js * @example <div gnap-sidebar></div> */ (function () { angular .module('gnap') .directive('gnapSidebar', gnapSidebar) .animation('.submenu', gnapSidebarSlideUpSlideDown); angular .module('template/gnap/sidebar/sidebar.html', []) .run(gnapSidebarTemplate); gnapSidebar.$inject = ['$state', 'sidebarService']; gnapSidebarTemplate.$inject = ['$templateCache']; function gnapSidebar($state, sidebarService) { return { restrict: 'A', replace: true, templateUrl: 'template/gnap/sidebar/sidebar.html', link: link }; function link(scope) { scope.settings = sidebarService.settings; // handles sidebar item selection scope.select = function (item) { if (item.items) { sidebarService.toggleSubmenu(item); } if (item.click) { item.click(); } if (item.state) { $state.go(item.state); } }; // handles collapsed state of the sidebar scope.toggleCollapsed = function () { sidebarService.toggleCollapsed(); }; } } // custom animation for ng-hide (slide-up/slide-down) function gnapSidebarSlideUpSlideDown() { return { beforeAddClass: function (element, className, done) { if (className === 'ng-hide') { element.slideUp(done); return function (cancel) { if (cancel) { element.stop(); } }; } }, removeClass: function (element, className, done) { if (className === 'ng-hide') { element.hide(); element.slideDown(done); return function (cancel) { if (cancel) { return element.stop(); } }; } } }; } function gnapSidebarTemplate($templateCache) { /* jshint ignore:start */ $templateCache.put("template/gnap/sidebar/sidebar.html", "<div id=\"sidebar\" class=\"sidebar\" ng-class=\"{\'menu-min\': settings.collapsed, display: settings.visible}\">\n" + "\n" + " <div id=\"sidebar-shortcuts\" class=\"sidebar-shortcuts\">\n" + " <div class=\"sidebar-shortcuts-large\" id=\"sidebar-shortcuts-large\">\n" + " <button ng-repeat=\"shortcut in settings.shortcuts\"\n" + " ng-click=\"shortcut.click()\" \n" + " class=\"{{ shortcut.buttonClass }}\" \n" + " tooltip=\"{{ shortcut._title }}\" \n" + " tooltip-placement=\"bottom\">\n" + " <i class=\"{{ shortcut.icon }}\"><\/i>\n" + " <\/button>\n" + " <\/div>\n" + "\n" + " <div class=\"sidebar-shortcuts-mini\" id=\"sidebar-shortcuts-mini\">\n" + " <span ng-repeat=\"shortcut in settings.shortcuts\" class=\"{{ shortcut.buttonClass }}\"><\/span>\n" + " <\/div>\n" + " <\/div> <!-- #sidebar-shortcuts -->\n" + "\n" + " <ul class=\"nav nav-list\">\n" + " <li ng-repeat=\'levelOneItem in settings.items\'\n" + " ng-class=\"{open: levelOneItem.open, active: levelOneItem.active}\">\n" + " <a ng-click=\'select(levelOneItem)\'\n" + " ng-class=\"{\'dropdown-toggle\': levelOneItem.items}\">\n" + " <i class=\"{{ levelOneItem.icon }}\"><\/i>\n" + " <span class=\"menu-text\">{{ levelOneItem._title }}<\/span>\n" + " <b class=\"arrow icon-angle-down\" ng-show=\"levelOneItem.items\"><\/b>\n" + " <\/a>\n" + " <ul class=\"submenu\" ng-show=\"levelOneItem.open\">\n" + " <li ng-repeat=\'levelTwoItem in levelOneItem.items\'\n" + " ng-class=\'{open: levelTwoItem.open, active: levelTwoItem.active}\'>\n" + " <a ng-click=\'select(levelTwoItem)\'\n" + " ng-class=\"{\'dropdown-toggle\': levelTwoItem.items}\">\n" + " <i class=\"{{ levelTwoItem.icon }}\"><\/i>\n" + " <span class=\"menu-text\">{{ levelTwoItem._title }}<\/span>\n" + " <b class=\"arrow icon-angle-down\" ng-show=\"levelTwoItem.items\"><\/b>\n" + " <\/a>\n" + " <ul class=\"submenu\" ng-show=\"levelTwoItem.open\">\n" + " <li ng-repeat=\'levelThreeItem in levelTwoItem.items\'\n" + " ng-class=\"{active: levelThreeItem.active}\">\n" + " <a ng-click=\'select(levelThreeItem)\'>\n" + " <i class=\"{{ levelThreeItem.icon }}\"><\/i>\n" + " <span class=\"menu-text\">{{ levelThreeItem._title }}<\/span>\n" + " <\/a>\n" + " <\/li>\n" + " <\/ul>\n" + " <\/li>\n" + " <\/ul>\n" + " <\/li>\n" + " <\/ul> <!-- .nav .nav-list -->\n" + "\n" + " <div class=\"sidebar-collapse\" id=\"sidebar-collapse\" ng-click=\"toggleCollapsed()\">\n" + " <i ng-class=\"{\'icon-double-angle-left\': !settings.collapsed, \'icon-double-angle-right\': settings.collapsed}\"><\/i>\n" + " <\/div>\n" + "<\/div>\n" + ""); /* jshint ignore:end */ } })();
JavaScript
0
@@ -696,16 +696,46 @@ nk: link +,%0A transclude: true %0A @@ -6342,32 +6342,81 @@ %3C%5C/div%3E%5Cn%22 +%0A + %22 %3Cdiv ng-transclude%3E%3C%5C/div%3E%5Cn%22 +%0A %22%3C%5C/
96c1bb88b91a1451745ae9a9464d8d7143cf335e
Fix map resizing for SVGs without viewBox
js/slider.js
js/slider.js
var margin = {top: 10, right: 50, bottom: 10, left: 50}, sliderWidth = 200 - margin.left - margin.right, mapHeight = sliderHeight = 500 - margin.bottom - margin.top, minYear = 0; maxYear = 2012; var y = d3.scale.linear() .domain([maxYear, minYear]) .range([0, sliderHeight]) .clamp(true); var brush = d3.svg.brush() .y(y) .extent([0, 0]) .on("brush", brushed); var sliderSvg = d3.select("body").append("svg") .attr("width", sliderWidth + margin.left + margin.right) .attr("height", sliderHeight + margin.top + margin.bottom) .attr("id", "sliderContainer") .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); sliderSvg.append("g") .attr("class", "y axis") .attr("transform", "translate("+ sliderWidth / 2 + ", 0)") .call(d3.svg.axis() .scale(y) .orient("left") .tickFormat(function(d) { return d; }) .tickSize(0) .tickPadding(12)) .select(".domain") .select(function() { return this.parentNode.appendChild(this.cloneNode(true)); }) .attr("class", "halo"); var slider = sliderSvg.append("g") .attr("class", "slider") .call(brush); slider.selectAll(".extent,.resize") .remove(); slider.select(".background") .attr("width", sliderWidth) .attr("height", sliderHeight); var handle = slider.append("circle") .attr("class", "handle") .attr("transform", "translate("+ sliderWidth / 2 + ", 0)") .attr("r", 9); slider .call(brush.extent([maxYear, maxYear])); var optimalCoverage; var colorInterpolator = d3.scale.linear() .domain([0,1]) .interpolate(d3.interpolateRgb) .range(["#ff0000", "#008000"]); d3.json("gateway.php?getCoverage", function(error, coverageInfo) { optimalCoverage = coverageInfo.optimalCoverage; slider .datum({ignoredMaps: []}) .selectAll("rect.period") .data(coverageInfo.periodsAndCoverage) .enter() .append("rect") .classed("period", true) .attr("x", 46) .attr("y", function(d) { return sliderHeight*(1 - (d.end / (maxYear - minYear))); }) .attr("width", 8) .attr("height", function(d) { return sliderHeight*(d.end - d.start + 1) / (maxYear - minYear); }) .attr("fill", function(d) { return colorInterpolator(d.coverage / optimalCoverage); }); }); var svgMap = null; var isLoading; initSvgMap(); function initSvgMap() { $('#externalSvg, #resizeHandle').remove(); if (svgMap) { svgMap = null; } isLoading = false; d3.select("#mapHelper").classed("hidden", true); } function brushed() { var value = y.invert(d3.mouse(this)[1]); if (!isNaN(value)) { brush.extent([value, value]); handle.attr("cy", y(value)); var year = parseInt(value); if (!isLoading) { isLoading = true; d3.json("gateway.php?getSvg&year="+year+"&ignored="+slider.datum().ignoredMaps.join(",")+"", function(error, incompleteMapInfo) { var mapFileName = incompleteMapInfo.fileName; if (mapFileName) { if (!svgMap || svgMap.datum().fileName !== mapFileName) { initSvgMap(); d3.xml("cache/svg/"+mapFileName, "image/svg+xml", function(xml) { svgMap = d3.select(d3.select("#mapArea").node().appendChild(document.importNode(xml.documentElement, true))) .attr("name", mapFileName) .attr("id", "externalSvg") .classed("externalSvg", true) .call(svgmap_drag); svgMap .datum({ id: incompleteMapInfo.id, fileName: incompleteMapInfo.fileName, x: 0, y: 0, width: parseInt(svgMap.attr("width")), height: parseInt(svgMap.attr("height")) }); dragmove.call(svgMap.node(), svgMap.datum()); d3.select("#mapArea") .append("svg") .attr("id", "resizeHandle") .style("left", 200 + svgMap.datum().width - 16) .style("top", svgMap.datum().height - 16) .attr("width", 16) .attr("height", 16) .call(svgmap_resize) .append("rect") .attr("x", 0) .attr("y", 0) .attr("width", 16) .attr("height", 16); d3.select("#mapHelper") .datum(function(d) { d.activeStep = 0; return d; }) .classed("hidden", false); activateHelperNextStep(); isLoading = false; }); } } else { initSvgMap(); } }); } } return false; }
JavaScript
0.000001
@@ -3192,24 +3192,73 @@ ternalSvg%22)%0A +%09%09%09%09%09%09%09%09.attr(%22preserveAspectRatio%22, %22xMaxYMax%22)%0A %09%09%09%09%09%09%09%09.cla @@ -3308,24 +3308,133 @@ map_drag);%0A%0A +%09%09%09%09%09%09%09var width = parseFloat(svgMap.attr(%22width%22));%0A%09%09%09%09%09%09%09var height = parseFloat(svgMap.attr(%22height%22));%0A%0A %09%09%09%09%09%09%09svgMa @@ -3585,38 +3585,13 @@ h: -parseInt(svgMap.attr(%22 width -%22)) ,%0A%09%09 @@ -3609,49 +3609,79 @@ ht: -parseInt(svgMap.attr(%22height%22))%0A%09%09%09%09%09%09%09%09%7D +height%0A%09%09%09%09%09%09%09%09%7D)%0A%09%09%09%09%09%09%09%09.attr(%22viewBox%22, %220 0 %22 + width +%22 %22 + height );%0A%0A
2129607fde92b0c59a94b7b3424acca6dfa0c51f
Add missing comma to CSV export for AdvisorReports
client/src/components/AdvisorReports/FilterableAdvisorReportsTable.js
client/src/components/AdvisorReports/FilterableAdvisorReportsTable.js
import React, { Component } from 'react' import OrganizationAdvisorsTable from 'components/AdvisorReports/OrganizationAdvisorsTable' import Toolbar from 'components/AdvisorReports/Toolbar' import _debounce from 'lodash/debounce' import moment from 'moment' import API from 'api' import { connect } from 'react-redux' import LoaderHOC, {mapDispatchToProps} from 'HOC/LoaderHOC' const DEFAULT_WEEKS_AGO = 3 const advisorReportsQueryUrl = `/api/reports/insights/advisors` // ?weeksAgo=3 default set at 3 weeks ago const OrganizationAdvisorsTableWithLoader = connect(null, mapDispatchToProps)(LoaderHOC('isLoading')('data')(OrganizationAdvisorsTable)) class FilterableAdvisorReportsTable extends Component { constructor() { super() this.state = { filterText: '', export: false, data: [], isLoading: false, selectedData: [] } this.handleFilterTextInput = this.handleFilterTextInput.bind(this) this.handleExportButtonClick = this.handleExportButtonClick.bind(this) this.handleRowSelection = this.handleRowSelection.bind(this) } componentDidMount() { this.setState( {isLoading: true} ) let advisorReportsQuery = API.fetch(advisorReportsQueryUrl) Promise.resolve(advisorReportsQuery).then(value => { this.setState({ isLoading: false, data: value }) }) } handleFilterTextInput(filterText) { this.setState({ filterText: filterText }) } handleExportButtonClick() { let selectedData = this.state.selectedData let allData = this.state.data let exportData = (selectedData.length > 0) ? selectedData : allData this.downloadCSV( { data: exportData } ) } handleRowSelection(data) { this.setState({ selectedData: data }) } getWeekColumns() { const dateEnd = moment().startOf('week') const dateStart = moment().startOf('week').subtract(DEFAULT_WEEKS_AGO, 'weeks') let currentDate = dateStart let weekColumns = [] while(currentDate.isBefore(dateEnd)) { weekColumns.push(currentDate.week()) currentDate = currentDate.add(1, 'weeks') } return weekColumns } convertArrayOfObjectsToCSV(args) { let result, ctr, csvGroupCols, csvCols, columnDelimiter, lineDelimiter, data data = args.data || null if (data == null || !data.length) { return null } columnDelimiter = args.columnDelimiter || ',' lineDelimiter = args.lineDelimiter || '\n' let weekColumns = this.getWeekColumns() csvGroupCols = [''] weekColumns.forEach( (column) => { csvGroupCols.push(column) csvGroupCols.push('') }) result = '' result += csvGroupCols.join(columnDelimiter) result += lineDelimiter csvCols = ['Organization name'] weekColumns.forEach( (column) => { csvCols.push('Reports submitted') csvCols.push('Engagements attended') }) result += csvCols.join(columnDelimiter) result += lineDelimiter data.forEach( (item) => { let stats = item.stats ctr = 0 result += item.organizationshortname weekColumns.forEach( (column, index) => { if (ctr > 0) result += columnDelimiter if (stats[index]) { result += stats[index].nrreportssubmitted result += columnDelimiter result += stats[index].nrengagementsattended } else { result += '0,0' } ctr++ }) result += lineDelimiter }) return result } downloadCSV(args) { let filename let csv = this.convertArrayOfObjectsToCSV({ data: args.data }) if (csv == null) return filename = args.filename || 'export-advisor-report.csv' var blob = new Blob([csv], {type: "text/csv;charset=utf-8;"}) if (navigator.msSaveBlob) { // IE 10+ navigator.msSaveBlob(blob, filename) } else { var link = document.createElement("a") if (link.download !== undefined) { // feature detection, Browsers that support HTML5 download attribute var url = URL.createObjectURL(blob) link.setAttribute("href", url) link.setAttribute("download", filename) link.style = "visibility:hidden" document.body.appendChild(link) link.click() document.body.removeChild(link) } } } render() { const handleFilterTextInput = _debounce( (filterText) => {this.handleFilterTextInput(filterText) }, 300) const columnGroups = this.getWeekColumns() return ( <div> <Toolbar onFilterTextInput={ handleFilterTextInput } onExportButtonClick={ this.handleExportButtonClick } /> <OrganizationAdvisorsTableWithLoader data={ this.state.data } columnGroups={ columnGroups } filterText={ this.state.filterText } onRowSelection={ this.handleRowSelection } isLoading={ this.state.isLoading } /> </div> ) } } export default FilterableAdvisorReportsTable
JavaScript
0.000001
@@ -2372,13 +2372,8 @@ ult, - ctr, csv @@ -3301,28 +3301,8 @@ ats%0A - ctr = 0%0A @@ -3419,21 +3419,8 @@ - if (ctr %3E 0) res @@ -3735,30 +3735,8 @@ %7D%0A - ctr++%0A
52f311dfa9a24761e8c796a1d87c8245a476d41e
Update AzureTranslatorGui.js
src/resource/WebGui/service/js/AzureTranslatorGui.js
src/resource/WebGui/service/js/AzureTranslatorGui.js
angular.module('mrlapp.service.AcapelaSpeechGui', []) .controller('AcapelaSpeechGuiCtrl', ['$scope', '$log', 'mrl', function($scope, $log, mrl) { $log.info('AcapelaSpeechGuiCtrl'); var _self = this; var msg = this.msg; $scope.text = ''; $scope.speakingState = ''; // GOOD TEMPLATE TO FOLLOW this.updateState = function(service) { $scope.service = service; $scope.voice = service.voice; } ; _self.updateState($scope.service); // init scope variables $scope.text = ''; this.onMsg = function(inMsg) { var data = inMsg.data[0]; switch (inMsg.method) { case 'onState': _self.updateState(data); $scope.$apply(); break; case 'onStartSpeaking': $scope.speakingState = 'speaking'; $scope.$apply(); break; case 'onEndSpeaking': $scope.speakingState = 'finished speaking'; $scope.$apply(); break; default: $log.error("ERROR - unhandled method " + $scope.name + " " + inMsg.method); break; } } ; //mrl.subscribe($scope.service.name, 'pulse'); msg.subscribe('publishStartSpeaking'); msg.subscribe('publishEndSpeaking'); msg.subscribe(this); } ]);
JavaScript
0
@@ -25,28 +25,30 @@ ervice.A -capelaSpeech +zureTranslator Gui', %5B%5D @@ -63,28 +63,30 @@ oller('A -capelaSpeech +zureTranslator GuiCtrl' @@ -163,20 +163,22 @@ o('A -capelaSpeech +zureTranslator GuiC @@ -251,42 +251,21 @@ pe.t -ext = '';%0A $scope.speakingState +ranslatedText = ' @@ -395,21 +395,62 @@ $scope. -voice +from = service.fromLanguage;%0A $scope.to = servi @@ -456,12 +456,17 @@ ice. -voic +toLanguag e;%0A @@ -560,16 +560,26 @@ $scope.t +ranslatedT ext = '' @@ -632,718 +632,73 @@ -var data = inMsg.data%5B0%5D;%0A switch (inMsg.method) %7B%0A case 'onState':%0A _self.updateState(data);%0A $scope.$apply();%0A break;%0A case 'onStartSpeaking':%0A $scope.speakingState = 'speaking';%0A $scope.$apply();%0A break;%0A case 'onEndSpeaking':%0A $scope.speakingState = 'finished speaking';%0A $scope.$apply();%0A break;%0A default:%0A $log.error(%22ERROR - unhandled method %22 + $scope.name + %22 %22 + inMsg.method);%0A break;%0A %7D%0A %7D%0A ;%0A %0A //mrl.subscribe($scope.service.name, 'pulse');%0A msg.subscribe('publishStartSpeaking');%0A msg.subscribe('publishEndSpeaking +%0A %7D%0A ;%0A %0A //mrl.subscribe($scope.service.name, 'pulse ');%0A
6b9fdcc798e7907d5606f0bd99ff36266c93e16e
Use public sentry DSN for front-end error reporting (#1113)
src/server/helpers/html.js
src/server/helpers/html.js
import React, { Component, PropTypes } from 'react'; import ReactDOM from 'react-dom/server'; import Helmet from 'react-helmet'; import { Provider } from 'react-redux'; import { conf } from '../helpers/config'; import style from '../../common/style/vanilla/css/footer.css'; const GAID = conf.get('GOOGLE_ANALYTICS_ID'); const OPTID = conf.get('GOOGLE_OPTIMIZE_ID'); const GTMID = conf.get('GOOGLE_TAG_MANAGER_ID'); const SENTRY_DSN = conf.get('SENTRY_DSN'); const googleOptimizePageHideCss = GAID && OPTID ? <style dangerouslySetInnerHTML={{ __html: '.async-hide { opacity: 0 !important}' }} /> : null; const googleOptimizePageHide = GAID && OPTID ? <script dangerouslySetInnerHTML={{ __html: ` (function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date; h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')}; (a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c; })(window,document.documentElement,'async-hide','dataLayer',4000, {'${OPTID}':true});` }} /> : null; const googleAnalytics = GAID && OPTID ? <script dangerouslySetInnerHTML={{ __html: ` (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', '${GAID}', 'auto', {'allowLinker': true}); ga('require', 'linker'); ga('linker:autoLink', ['snapcraft.io', 'build.snapcraft.io', 'dashboard.snapcraft.io', 'conjure-up.io', 'login.ubuntu.com', 'www.ubuntu.com', 'ubuntu.com', 'insights.ubuntu.com', 'developer.ubuntu.com', 'cn.ubuntu.com', 'design.ubuntu.com', 'maas.io', 'canonical.com', 'landscape.canonical.com', 'pages.ubuntu.com', 'tutorials.ubuntu.com', 'docs.ubuntu.com']); ga('require', '${OPTID}');` }} /> : null; const googleTagManager = GTMID ? <script dangerouslySetInnerHTML={{ __html: `(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','dataLayer', '${GTMID}')` }} /> : null; const googleTagManagerNoScript = GTMID ? <noscript> <iframe src="https://www.googletagmanager.com/ns.html?id=${GTMID}" height="0" width="0" style={{ display: 'none', visibility: 'hidden' }} /> </noscript> : null; export default class Html extends Component { render() { const { assets, store, component, config, csrfToken } = this.props; const preloadedState = store.getState(); const content = component ? this.renderComponent(component, store) : ''; // read Helmet props after component is rendered const head = Helmet.rewind(); const attrs = head.htmlAttributes.toComponent(); return ( <html {...attrs}> <head> { googleOptimizePageHideCss } { googleOptimizePageHide } { googleAnalytics } { googleTagManager } {head.title.toComponent()} {head.meta.toComponent()} {head.link.toComponent()} {head.script.toComponent()} <link rel="icon" type="image/png" href="https://assets.ubuntu.com/v1/fdc99abe-ico_16px.png" sizes="16x16" /> <link rel="icon" type="image/png" href="https://assets.ubuntu.com/v1/0f3c662c-ico_32px.png" sizes="32x32" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu:300,400" /> <link rel="stylesheet" href={ assets.main.css } /> { /* Insert third party scripts (e.g. Stripe) here. Trying to load them with Helmet will make them load twice. */ } </head> <body> { googleTagManagerNoScript } <div id="content" className={ style.content } dangerouslySetInnerHTML={{ __html: content }}/> { SENTRY_DSN && <script src="https://cdn.ravenjs.com/3.25.1/raven.min.js" crossOrigin="anonymous"></script> } { SENTRY_DSN && <script dangerouslySetInnerHTML={{ __html: `Raven.config('${ SENTRY_DSN }').install();` }} /> } <script dangerouslySetInnerHTML={{ __html: `window.__CONFIG__ = ${JSON.stringify(config)}` }} /> <script dangerouslySetInnerHTML={{ __html: `window.__CSRF_TOKEN__ = ${JSON.stringify(csrfToken)}` }} /> <script dangerouslySetInnerHTML={{ __html: `window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState)}` }} /> <script src={ assets.main.js } /> </body> </html> ); } renderComponent(component, store) { return ReactDOM.renderToString( <Provider store={store} key="provider"> { component } </Provider> ); } } Html.propTypes = { config: PropTypes.object, component: PropTypes.node, store: PropTypes.object, csrfToken: PropTypes.string, assets: PropTypes.shape({ main: PropTypes.shape({ js: PropTypes.string, css: PropTypes.string }) }) };
JavaScript
0
@@ -427,16 +427,23 @@ NTRY_DSN +_PUBLIC = conf. @@ -457,16 +457,23 @@ NTRY_DSN +_PUBLIC ');%0A%0Acon @@ -4244,32 +4244,39 @@ SENTRY_DSN +_PUBLIC &&%0A @@ -4413,16 +4413,23 @@ NTRY_DSN +_PUBLIC &&%0A @@ -4521,16 +4521,23 @@ NTRY_DSN +_PUBLIC %7D').ins
7750b8f4ff51a739cd9442257254147e98266bd6
Update home.js
build/home.js
build/home.js
'use strict'; var Home = React.createClass({ displayName: 'Home', render: function render() { var socials = [{ link: 'https://github.com/aligos', icon: 'github' }, { link: 'http://linkedin.com/in/aligos', icon: 'linkedin' }, { link: 'https://speakerdeck.com/aligos', icon: 'slideshare' }, { link: 'http://twitter.com/rahmataligos', icon: 'twitter' }, { link: 'http://facebook.com/matt.aligos', icon: 'facebook' }]; return React.createElement( 'div', { className: 'about' }, React.createElement( 'img', { src: 'img/header.png', className: 'aligos' } ), React.createElement( 'h1', { className: 'jumbo-title' }, 'just a stupid child, who was told to learn JavaScript.' ), React.createElement( 'p', { className: 'jumbo-desc' }, 'Aligos - I Love JavaScript' ), React.createElement( 'button', { className: 'btn btn-default' }, 'Font Line' ), React.createElement( 'div', { className: 'social' }, socials.map(function (item) { return React.createElement( 'a', { href: item.link }, React.createElement('i', { className: 'fa fa-' + item.icon }) ); }) ) ); } });
JavaScript
0.000001
@@ -1104,16 +1104,34 @@ default' + href: '/fontline' %7D,%0A
6b6044eca61b88f62b531ea0d41d19049741ed06
fix URL handling
js/common.js
js/common.js
'use strict'; const defaultHost = 'localhost'; const defaultPort = 9229; const launchDefaults = false; function storeOptions (options, callback) { const settings = Object.assign({ host: defaultHost, port: defaultPort, defaults: launchDefaults }, options); chrome.storage.sync.set(settings, callback); } function loadOptions (callback) { chrome.storage.sync.get({ host: defaultHost, port: defaultPort, defaults: launchDefaults }, callback); } function setBrowserClickAction () { loadOptions(function loadCb (options) { if (options.defaults === true) { chrome.browserAction.setPopup({ popup: '' }); } else { chrome.browserAction.setPopup({ popup: 'index.html' }); } }); } function launchDevTools (options) { const jsonUrl = `http://${options.host}:${options.port}/json/list`; return fetch(jsonUrl) .then(function parseJson (response) { if (response.status !== 200) { throw new Error(`Invalid configuration data at ${jsonUrl}`); } return response.json(); }) .then(function openInspector (data) { chrome.tabs.create({ url: data[0].devtoolsFrontendUrl }); }); }
JavaScript
0
@@ -1112,61 +1112,839 @@ -chrome.tabs.create(%7B url: data%5B0%5D.dev +// The replace is for older versions. For newer versions, it is a no-op.%0A const devtoolsFrontendUrl = data%5B0%5D.devtoolsFrontendUrl.replace(%0A /%5Ehttps:%5C/%5C/chrome-devtools-frontend%5C.appspot%5C.com/i,%0A 'chrome-devtools://devtools/remote'%0A );%0A%0A const url = new URL(devtoolsFrontendUrl);%0A const wsUrl = new URL(data%5B0%5D.webSocketDebuggerUrl);%0A%0A // Update the WebSocket URL with the host and port options. Then, update%0A // the DevTools URL with the new WebSocket URL. Also strip the pro to +c ol -sFrontendUrl +.%0A wsUrl.hostname = options.host;%0A wsUrl.port = options.port;%0A url.searchParams.set('ws', wsUrl.toString().replace('ws://', ''));%0A%0A chrome.tabs.create(%7B%0A // Without decoding 'ws', DevTools won't load the source files properly.%0A url: decodeURIComponent(url.toString())%0A %7D);
b699f79980014b7abfcbac6d3a0e95cc38868ded
Fix starting date for cs3217
claims/module-claims/claim-cs3217.js
claims/module-claims/claim-cs3217.js
// *********************************************************** // READ THE FOLLOWING BEFORE STARTING // *********************************************************** // 1. **IMPORTANT STEP** Change the properties in the config object in the next section. // 2. Login to the portal at: https://mysoc.nus.edu.sg/~tssclaim/. Fill in your bank account information if you haven't. // 3. Access the page titled 'Student Claim Submission' (https://mysoc.nus.edu.sg/~tssclaim/tutor/teach_claim.php?page=1) and click on // the 'Claim' button under your module. You should see the interface for you to enter details of the teaching claim activity. // 4. Open the JS console (Ctrl/Cmd + Shift/Option + J), paste all the code in this file in the JS console and press enter. You should // see the message 'Claim object successfully created. Run c.makeAllClaims() to start.'. // 5. Run the function c.makeAllClaims() . Wait until the alert 'All claims made!' is shown, then press 'OK'. // 6. You will be brought back to the previous page. Click on the button 'Claim' again and verify that you have 80 hours in total. // To delete all claims on the page, run the function c.deleteAllClaims() // *********************************************************** // CONFIGURE THE RELEVANT PROPERTIES IN THE CONFIG OBJECT // *********************************************************** var config = { // Your NUSSTU ID, such as a0012345 student_id: prompt('Your NUSSTU ID, such as a0012345'), // Module you are claiming hours for, such as CS1101S module: 'CS3217', // Format: YYYY/MM/DD // Note: Month is from 0-11, Date is from 1-31 // This should be the semester's week 1. For AY115/16 Sem 2, it's Monday, Jan 11 first_day_of_sem: new Date(2015, 0, 11), // in case you want to customize the duties field for each activity // Do not modify the keys duties: { 'Assignment Marking': 'Graded students\' assignments', 'Course Material Preparation': 'Prepared problem sets' }, // the following function should return a list of claim objects that you want to make activities_list_fn: function () { var activities_list = []; for (var week = 1; week <= 2; week++) { activities_list.push({ activity_type: Claim.COURSE_MATERIAL_PREPARATION, week: week, day: 'SUNDAY', start_time: '1300', end_time: '1800' }); } for (var week = 3; week <= 8; week++) { if (week == 7) continue; activities_list.push({ activity_type: Claim.ASSIGNMENT_MARKING, week: week, day: 'SATURDAY', start_time: '0900', end_time: '1200' }); activities_list.push({ activity_type: Claim.ASSIGNMENT_MARKING, week: week, day: 'SUNDAY', start_time: '1400', end_time: '1600' }); }; return activities_list; } }; // *********************************************************** // DO NOT CHANGE THE BOTTOM UNLESS YOU KNOW WHAT YOU ARE DOING // *********************************************************** var core_script = 'https://rawgit.com/nusmodifications/nus-soc-scripts/master/claims/claim.js'; var c = undefined; $.getScript(core_script) .done(function () { c = new Claim(config); }) .fail(function (jqxhr, settings, exception) { console.log('Error loading script'); console.log(jqxhr); console.log(exception); }); // c.makeAllClaims();
JavaScript
0.999999
@@ -1677,17 +1677,16 @@ For AY1 -1 5/16 Sem @@ -1741,17 +1741,17 @@ Date(201 -5 +6 , 0, 11)
79f6a0caaf718b3d29fed44b1bd7749d3bd4cb8e
Make date string format slightly friendlier
src/web/js/hbs-helpers.js
src/web/js/hbs-helpers.js
/** * Handlebars Helpers */ 'use strict'; var Handlebars = require('hbsfy/runtime'); var moment = require('moment'); Handlebars.registerHelper('parseDate', function(options) { var date = moment.unix(options.fn(this)/1000); return date.format('YYYY/MM/DD HH:mm'); });
JavaScript
0.999002
@@ -260,17 +260,43 @@ YY/MM/DD - +') + ' at ' + date.format(' HH:mm');
4a057a75f44bffed88d6316d09e9b907948b8e2a
fix service worker
src/serviceWorker/index.js
src/serviceWorker/index.js
/* global caches self URL fetch */ const assets = ['root.html', 'index.html', 'app.js', 'style.css'] const assetCacheKey = assets.join('-') const imageCacheKey = 'image' const dataCacheKey = 'data' self.addEventListener('install', event => { event.waitUntil( caches.open(assetCacheKey).then(cache => cache.addAll(assets)) ) }) self.addEventListener('activate', event => { const whiteList = [assetCacheKey, imageCacheKey] event.waitUntil( // get the currently cached files, remove the one that are out of date caches.keys().then(cacheKeys => { Promise.all( cacheKeys.map( key => !whiteList.includes(key) && caches.delete(key) ) ) }) ) }) const cacheFirstStrategy = cacheName => async request => { const resFromCache = await caches.match(request) if (resFromCache) return resFromCache const resFromFetch = await fetch(request.clone()) const cache = await caches.open(cacheName) cache.put(request, resFromFetch.clone()) return resFromFetch } const networkFirstStrategy = cacheName => request => fetch(request.clone()) .then(async resFromFetch => { const cache = await caches.open(cacheName) cache.put(request, resFromFetch.clone()) }) .catch(async err => { const resFromCache = await caches.match(request) return resFromCache || Promise.reject(err) }) self.addEventListener('fetch', event => { const requestURL = new URL(event.request.url) if (assets.includes(requestURL.pathname)) // cached as asset event.respondWith(caches.match(event.request)) else if (requestURL.pathname.match(/\.(png|jpg|gif)$/)) // image, serve from cache if exists event.respondWith(cacheFirstStrategy(imageCacheKey)(event.request)) else if (requestURL.pathname.match(/\/data\/(\w+)\/top\.json$/)) // short term caching data ( change at every new post ) event.respondWith(networkFirstStrategy(dataCacheKey)(event.request)) else if (requestURL.pathname.match(/\/data\/(\w+)\/(\w+)\.json$/)) // long term caching data event.respondWith(networkFirstStrategy(dataCacheKey)(event.request)) })
JavaScript
0.000001
@@ -1314,32 +1314,65 @@ omFetch.clone()) +%0A%0A return resFromFetch %0A %7D)%0A @@ -2320,11 +2320,203 @@ quest))%0A + else if (requestURL.pathname.match(/%5C.html$/))%0A // short term caching data ( change at every new post )%0A event.respondWith(networkFirstStrategy(dataCacheKey)(event.request))%0A %7D)%0A
c10c7925d6357cd4311cbf931215a1ad3981b429
return of the redirect url
vendor/spark/spark-auth.js
vendor/spark/spark-auth.js
/** * Our spark auth object * See API reference - http://docs.spark.authentication.apiary.io/ */ spark.auth = function () { 'use strict'; /** * Get from local storage the token obj, and return it parsed * @returns {*|any} */ var getTokenObj = function () { var rawToken = localStorage.getItem('spark-token'); return rawToken ? JSON.parse(rawToken) : {}; } /** * Get guest token from your local server * @param code * @param callback */ var getGuestTokenFromServer = function (callback) { spark.util.xhr(GUEST_TOKEN_URL, 'GET', {}, {}, function (response) { var date = new Date(); var now = date.getTime(); response.expires_at = now + parseInt(response.expires_in) * 1000; localStorage.setItem('spark-guest-token', JSON.stringify(response)); callback(response); }); }; /** * Fetch current logged in member * @param callback * See API reference - http://docs.sparkdriveapi.apiary.io/#reference/members/members-without-id/retrieve-the-current-member */ var getMemberFromServer = function (callback) { var headers = { "Authorization": "Bearer " + spark.auth.accessToken(), "Content-type": "application/x-www-form-urlencoded" } var url = spark.const.API_PROTOCOL + '://' + spark.const.API_SERVER + '/members/' + spark.auth.accessToken(true).spark_member_id; spark.util.xhr(url, 'GET', '', headers, function (response) { var date = new Date(); var now = date.getTime(); //expire in 2 hours response.expires_at = now + 7200 * 1000; localStorage.setItem('spark-member', JSON.stringify(response)); callback(response); }); }; /** * Return the Auth2.0 provider login screen URL * @returns {string} * See API reference - http://docs.spark.authentication.apiary.io/#reference/oauth-2.0/access-token */ var getAuthLoginUrl = function(){ return spark.const.API_PROTOCOL + "://" + spark.const.API_SERVER + '/oauth/authorize' + "?response_type=code" + "&client_id=" + CLIENT_ID //"&redirect_uri=" + REDIRECT_URL ; }; /** * Return the factory object */ return { /** * Check if access token validaty */ isAccessTokenValid: function () { var token = getTokenObj(); var date = new Date(); var now = date.getTime(); return (token && token.expires_at && new Date(token.expires_at).getTime() > now); }, /** * Logout the user - clear the token and the member in local storage */ logout: function () { localStorage.removeItem('spark-token'); localStorage.removeItem('spark-member'); location.reload(); }, getAuthLoginUrl: getAuthLoginUrl, /** * Redirect user to Auth login page */ redirectToAuthLoginURL: function () { window.location = getAuthLoginUrl(); }, /** * Get the access token * @param code - The code from the previous step * @param callback - Callback to run after getting the access token */ getAccessToken: function (code, callback) { var params = "code=" + code; spark.util.xhr(ACCESS_TOKEN_URL + '?' + params, 'GET', {}, {}, function (response) { //If request was for access token, set it in localStorage if (response.access_token) { var date = new Date(); var now = date.getTime(); response.expires_at = now + parseInt(response.expires_in) * 1000; localStorage.setItem('spark-token', JSON.stringify(response)); } callback(response); }); }, /** * Gets logged in user profile * @param callback */ getMyProfile: function (callback) { //Make sure token is still valid if (spark.auth.isAccessTokenValid()) { var member = JSON.parse(localStorage.getItem('spark-member')); var date = new Date(); var now = date.getTime(); if (member && member.expires_at && member.expires_at > now) { callback(member); } else { getMemberFromServer(function (member) { callback(member); }); } } else { callback(false); } }, /** * Get access token * @returns {*|any} */ accessToken: function (returnFullObject) { var token = getTokenObj(); if (token) { return (returnFullObject ? token : token.access_token); } else { return false; } }, /** * Get the guest token from localStorage. If missing - make a server * call to acquire a new guest token * @param callback */ getGuestToken: function (callback) { var guestToken = JSON.parse(localStorage.getItem('spark-guest-token')); var date = new Date(); var now = date.getTime(); if (guestToken && guestToken.expires_at && guestToken.expires_at > now) { callback(guestToken.access_token); } else { getGuestTokenFromServer(function (response) { callback(response.access_token); }); } }, /** * method checking validity of access token and return it if it is valid ,false otherwise. * @returns {*} */ getValidAccessToken: function () { var token = getTokenObj(); var date = new Date(); var now = date.getTime(); if (token && token.expires_at && token.expires_at > now) { return token.access_token; } else { return false; } } }; }();
JavaScript
0.000006
@@ -1976,18 +1976,16 @@ T_ID%0A%09%09%09 -// %22&redire
ac1ffa67e2f044cb74f92147f48978ba76240044
Update config.js
js/config.js
js/config.js
const Config = { primary: 'https://api.ethplorer.io/getAddressInfo', secondary: '', apiKey: 'apiKey=igei3425wgGmM73', cmcTicker: 'https://api.coinmarketcap.com/v1/ticker/?limit=0', cmcIcons: 'https://coincodex.com//en/resources/images/admin/coins/' };
JavaScript
0.000002
@@ -131,24 +131,28 @@ r: 'https:// +pro- api.coinmark @@ -168,23 +168,91 @@ /v1/ -ticker/?limit=0 +cryptocurrency/listings/latest?CMC_PRO_API_KEY=a7e67b45-3482-49fb-92dc-1080d5b30ac7 ',%0A%09 @@ -323,6 +323,7 @@ s/'%0A - %7D; +%0A