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
33d26ac11ef2c0096912fd546d79ad302715b5d3
Fix deprecated Buffer constructor in readNiftiHeader
utils/files/readNiftiHeader.js
utils/files/readNiftiHeader.js
const nifti = require('nifti-js') const pako = require('pako') const fs = require('fs') const zlib = require('zlib') const testFile = require('./testFile') const Issue = require('../../utils/issues').Issue const isNode = typeof window == 'undefined' /** * Read Nifti Header * * Takes a files and returns a json parsed nifti * header without reading any extra bytes. */ function readNiftiHeader(file, callback) { if (isNode) { nodeNiftiTest(file, callback) } else { browserNiftiTest(file, callback) } } function nodeNiftiTest(file, callback) { testFile(file, function(issue, stats) { file.stats = stats if (issue) { callback({ error: issue }) return } if (stats.size < 348) { callback({ error: new Issue({ code: 36, file: file }) }) return } return extractNiftiFile(file, callback) }) } function extractNiftiFile(file, callback) { var bytesRead = 500 var buffer = new Buffer(bytesRead) var decompressStream = zlib .createGunzip() .on('data', function(chunk) { callback(parseNIfTIHeader(chunk, file)) decompressStream.pause() }) .on('error', function() { callback(handleGunzipError(buffer, file)) }) fs.open(file.path, 'r', function(err, fd) { if (err) { callback({ error: new Issue({ code: 44, file: file }) }) return } else { fs.read(fd, buffer, 0, bytesRead, 0, function() { if (file.name.endsWith('.nii')) { callback(parseNIfTIHeader(buffer, file)) } else { decompressStream.write(buffer) } }) } }) } function browserNiftiTest(file, callback) { const bytesRead = 500 if (file.size == 0) { callback({ error: new Issue({ code: 44, file: file }) }) return } // file size is smaller than nifti header size if (file.size < 348) { callback({ error: new Issue({ code: 36, file: file }) }) return } var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice let fileReader = constructBrowserFileReader(file, callback) fileReader.readAsArrayBuffer(blobSlice.call(file, 0, bytesRead)) } function constructBrowserFileReader(file, callback) { let fileReader = new FileReader() fileReader.onloadend = function() { var buffer = new Uint8Array(fileReader.result) var unzipped try { unzipped = file.name.endsWith('.nii') ? buffer : pako.inflate(buffer) } catch (err) { callback(handleGunzipError(buffer, file)) return } callback(parseNIfTIHeader(unzipped, file)) } return fileReader } /** * Parse NIfTI Header (private) * * Attempts to parse a header buffer with * nifti-js and handles errors. */ function parseNIfTIHeader(buffer, file) { var header try { header = nifti.parseNIfTIHeader(buffer) } catch (err) { // file is unreadable return { error: new Issue({ code: 26, file: file }) } } // file was not originally gzipped return header } /** * Handle Gunzip Error (private) * * Used when unzipping fails. Tests if file was * actually gzipped to begin with by trying to parse * the original header. */ function handleGunzipError(buffer, file) { try { nifti.parseNIfTIHeader(buffer) } catch (err) { // file is unreadable return { error: new Issue({ code: 26, file: file }) } } // file was not originally gzipped return { error: new Issue({ code: 28, file: file }) } } module.exports = readNiftiHeader
JavaScript
0.000001
@@ -901,19 +901,21 @@ ck) %7B%0A -var +const bytesRe @@ -925,19 +925,21 @@ = 500%0A -var +const buffer @@ -943,19 +943,21 @@ er = - new Buffer +.alloc (byt
9e1e6814283a8cb01f9bf0a3bdf51071e5904102
Move DOM knowledge into Tab instead of TabManager
ide/static/js/tabs.js
ide/static/js/tabs.js
ide.tabs = (function() { var Tab = function (li, name) { this.li = li; this.name = name; this.label = this.li.find('a').first(); this.li.data('tab', this); this.dirty = false; }; Tab.prototype.markDirty = function() { if (!this.dirty) { this.dirty = true; this.label.prepend('*'); } }; Tab.prototype.clearDirty = function() { if (this.dirty) { this.dirty = false; this.label.html(this.label.html().substring(1)); } }; Tab.prototype.getNext = function() { var tab = this.li.prev('li'); if (tab.length === 0) { tab = this.li.next('li'); } if (tab.length !== 0) { return tab.data('tab') || null; } return null; }; Tab.prototype.selected = function() { return this.li.hasClass('active'); }; Tab.prototype.close = function() { this.li.remove(); }; Tab.prototype.select = function() { this.li.addClass('active'); _.chain(this.li.siblings()).map($).invoke('removeClass', 'active'); }; Tab.prototype.rename = function(newName) { this.label.html(this.label.html().replace(this.name, newName)); this.name = newName; }; Tab.prototype.remove = function() { this.li.remove(); }; var TabManager = function(ul) { this.ul = ul; this.tabs = {}; this.callbacks = { all_tabs_closed: null, tab_select: null, }; var self = this; this.ul .on('click', 'li:not(.editor-add-file)', function() { self.select($(this).data('tab').name); }) .on('click', 'span.glyphicon-remove', function() { self.close($(this).parents('li').first().data('tab').name); return false; }); }; TabManager.prototype.on = function(event, callback) { this.callbacks[event] = callback; return this; }; TabManager.prototype.trigger = function(event) { var callback = this.callbacks[event]; if (callback) { callback.apply(null, _(arguments).toArray().slice(1)); } }; TabManager.prototype.numDirtyTabs = function(name) { return _.chain(this.tabs).values().where({dirty: true}).value().length; } TabManager.prototype.isDirty = function(name) { return this.tabs[name].dirty; } TabManager.prototype.has = function(name) { return _(this.tabs).has(name); }; TabManager.prototype.close = function(name) { var tab = this.tabs[name]; if (!tab.dirty) { this.forceClose(name); return; } ide.utils.confirm('This file has unsaved changes. Really close?', (function (confirmed) { if (confirmed) { this.forceClose(name); } }).bind(this)); }; TabManager.prototype.forceClose = function(name) { var tab = this.tabs[name]; if (tab.selected()) { var next = tab.getNext(); if (next !== null) { this.select(next.name); } } tab.close(); delete this.tabs[name]; if (_(this.tabs).isEmpty()) { this.trigger('all_tabs_closed'); } }; TabManager.prototype.rename = function(name, newName) { var tab = this.tabs[name]; tab.rename(newName); this.tabs[newName] = tab; delete this.tabs[name]; }; TabManager.prototype.select = function(name) { this.tabs[name].select(); this.trigger('tab_select', name); }; TabManager.prototype.getSelected = function() { return this.ul.find('li.active').data('tab').name; }; TabManager.prototype.markDirty = function(name) { this.tabs[name].markDirty(); } TabManager.prototype.clearDirty = function(name) { this.tabs[name].clearDirty(); } TabManager.prototype.create = function(name) { var li = $('<li>').append($('<a>').attr('href', '#').append( name, '&nbsp;', ide.utils.makeIcon('remove'))); li.appendTo(this.ul); this.tabs[name] = new Tab(li, name); return name; }; return { TabManager: TabManager }; })();
JavaScript
0
@@ -189,32 +189,275 @@ = false;%0A %7D;%0A%0A + Tab.create = function(name, parent) %7B%0A var li = $('%3Cli%3E').append(%0A $('%3Ca%3E')%0A .attr('href', '#')%0A .append(name, '&nbsp;', ide.utils.makeIcon('remove'))%0A ).appendTo(parent);%0A return new Tab(li, name);%0A %7D;%0A%0A Tab.prototype. @@ -2361,22 +2361,22 @@ e%7D). +size(). value() -.length ;%0A @@ -3598,44 +3598,77 @@ urn +_( this. -ul +tabs) .find( -'li.active').data('tab' +function (tab) %7B%0A return tab.selected();%0A %7D ).na @@ -3916,205 +3916,51 @@ -var li = $('%3Cli%3E').append($('%3Ca%3E').attr('href', '#').append(%0A name, '&nbsp;', ide.utils.makeIcon('remove')));%0A li.appendTo(this.ul);%0A this.tabs%5Bname%5D = new Tab(li, name);%0A return name +this.tabs%5Bname%5D = Tab.create(name, this.ul) ;%0A
1913e8c30d6e3edd195adc54c7f4fc6a16a72648
Update sumArray.js
src/sumArray.js
src/sumArray.js
/* Sums up and returns all the values in the array passed into the function usage: sumArray([1,2]) returns 3 sumArray([1, 2, 3]) returns 6 sumArray([1, 2, 3, 4]) returns 10 */ var sumArray = function (array) { var response = 0; for (i in array) { response += array[i]; } return response; } anything.prototype.sumArray = sumArray;
JavaScript
0
@@ -227,94 +227,99 @@ %7B%0A -var response = 0;%0A for (i in array) %7B%0A response += array%5Bi%5D;%0A %7D%0A return response +return array.reduce(function (previous, current) %7B%0A return previous + current;%0A %7D, 0) ;%0A%7D%0A
df9030a2c64a1534490932caafe76dcb003de585
Switch off a browsersync label
tasks/browser-sync-server.js
tasks/browser-sync-server.js
/** * Start browserSync server */ 'use strict'; const gulp = require('gulp'), fs = require('fs'); module.exports = function(options) { return () => { // If index.html exist - open it, else show folder let listDirectory = fs.existsSync(options.mainHtml) ? false : true; options.browserSync.init({ server: { baseDir: "./", directory: listDirectory }, snippetOptions: { // Provide a custom Regex for inserting the snippet rule: { match: /$/i, fn: (snippet, match) => snippet + match } }, port: 8080 }); }; };
JavaScript
0.000001
@@ -319,16 +319,37 @@ .init(%7B%0A + notify: false,%0A se
a5789198ba4f139e153f5ae7f971de1687d11d4c
Fix Teledactyl option initialization typo.
teledactyl/content/config.js
teledactyl/content/config.js
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org> // // This work is licensed for reuse under an MIT license. Details are // given in the LICENSE.txt file included with this file. "use strict"; const Config = Module("config", ConfigBase, { init: function init() { init.supercall(this); // don't wait too long when selecting new messages // GetThreadTree()._selectDelay = 300; // TODO: make configurable }, autocommands: { DOMLoad: "Triggered when a page's DOM content has fully loaded", FolderLoad: "Triggered after switching folders in Thunderbird", PageLoadPre: "Triggered after a page load is initiated", PageLoad: "Triggered when a page gets (re)loaded/opened", Enter: "Triggered after Thunderbird starts", Leave: "Triggered before exiting Thunderbird", LeavePre: "Triggered before exiting Thunderbird", }, get browser() getBrowser(), dialogs: { about: ["About Thunderbird", function () { window.openAboutDialog(); }], addons: ["Manage Add-ons", function () { window.openAddonsMgr(); }], addressbook: ["Address book", function () { window.toAddressBook(); }], checkupdates: ["Check for updates", function () { window.checkForUpdates(); }], console: ["JavaScript console", function () { window.toJavaScriptConsole(); }], dominspector: ["DOM Inspector", function () { window.inspectDOMDocument(content.document); }], downloads: ["Manage Downloads", function () { window.toOpenWindowByType('Download:Manager', 'chrome://mozapps/content/downloads/downloads.xul', 'chrome,dialog=no,resizable'); }], preferences: ["Show Thunderbird preferences dialog", function () { openOptionsDialog(); }], printsetup: ["Setup the page size and orientation before printing", function () { PrintUtils.showPageSetup(); }], print: ["Show print dialog", function () { PrintUtils.print(); }], saveframe: ["Save frame to disk", function () { window.saveFrameDocument(); }], savepage: ["Save page to disk", function () { window.saveDocument(window.content.document); }], }, defaults: { guioptions: "frb", showtabline: 1, titlestring: "Teledactyl" }, /*** optional options, there are checked for existence and a fallback provided ***/ features: ["hints", "mail", "marks", "addressbook", "tabs"], focusChange: function (win) { // we switch to -- MESSAGE -- mode for Teledactyl when the main HTML widget gets focus if (win && win.document instanceof HTMLDocument || dactyl.focus instanceof HTMLAnchorElement) { if (config.isComposeWindow) modes.set(modes.INSERT, modes.TEXT_EDIT); else if (dactyl.mode != modes.MESSAGE) dactyl.mode = modes.MESSAGE; } }, guioptions: { m: ["MenuBar", ["mail-toolbar-menubar2"]], T: ["Toolbar" , ["mail-bar2"]], f: ["Folder list", ["folderPaneBox", "folderpane_splitter"]], F: ["Folder list header", ["folderPaneHeader"]] }, // they are sorted by relevance, not alphabetically helpFiles: ["intro.html", "version.html"], get isComposeWindow() window.wintype == "msgcompose", get mainWidget() this.isComposeWindow ? document.getElementById("content-frame") : GetThreadTree(), get mainWindowId() this.isComposeWindow ? "msgcomposeWindow" : "messengerWindow", modes: [ ["MESSAGE", { char: "m" }], ["COMPOSE"] ], get browserModes() [modes.MESSAGE], get mailModes() [modes.NORMAL], // NOTE: as I don't use TB I have no idea how robust this is. --djk get outputHeight() { if (!this.isComposeWindow) { let container = document.getElementById("tabpanelcontainer").boxObject; let deck = document.getElementById("displayDeck"); let box = document.getElementById("messagepanebox"); let splitter = document.getElementById("threadpane-splitter").boxObject; if (splitter.width > splitter.height) return container.height - deck.minHeight - box.minHeight- splitter.height; else return container.height - Math.max(deck.minHeight, box.minHeight); } else return document.getElementById("appcontent").boxObject.height; }, removeTab: function (tab) { if (config.tabbrowser.mTabs.length > 1) config.tabbrowser.removeTab(tab); else dactyl.beep(); }, get scripts() this.isComposeWindow ? ["compose/compose.js"] : [ "addressbook", "mail", "tabs", ], styleableChrome: ["chrome://messenger/content/messenger.xul", "chrome://messenger/content/messengercompose/messengercompose.xul"], tabbrowser: { __proto__: document.getElementById("tabmail"), get mTabContainer() this.tabContainer, get mTabs() this.tabContainer.childNodes, get mCurrentTab() this.tabContainer.selectedItem, get mStrip() this.tabStrip, get browsers() [browser for (browser in Iterator(this.mTabs))] }, // to allow Vim to :set ft=mail automatically tempFile: "mutt-ator-mail", get visualbellWindow() document.getElementById(this.mainWindowId), }, { }, { commands: function () { commands.add(["pref[erences]", "prefs"], "Show " + config.host + " preferences", function () { window.openOptionsDialog(); }, { argCount: "0" }); }, modes: function () { this.ignoreKeys = { "<Return>": modes.NORMAL | modes.INSERT, "<Space>": modes.NORMAL | modes.INSERT, "<Up>": modes.NORMAL | modes.INSERT, "<Down>": modes.NORMAL | modes.INSERT }; }, optons: function () { // FIXME: comment obviously incorrect // 0: never automatically edit externally // 1: automatically edit externally when message window is shown the first time // 2: automatically edit externally, once the message text gets focus (not working currently) options.add(["autoexternal", "ae"], "Edit message with external editor by default", "boolean", false); options.add(["online"], "Set the 'work offline' option", "boolean", true, { setter: function (value) { if (MailOfflineMgr.isOnline() != value) MailOfflineMgr.toggleOfflineStatus(); return value; }, getter: function () MailOfflineMgr.isOnline() }); } }); // vim: set fdm=marker sw=4 ts=4 et:
JavaScript
0.000375
@@ -6084,16 +6084,17 @@ %0A opt +i ons: fun
2d7202f8b83c22daf30c2e4ecab762f47f8226c0
connect error!
syncUserData.js
syncUserData.js
/** * Created by gggin on 16-3-13. */ var mysql = require('mysql'); var debug = require('debug'); var output = debug('app:log'); var config = require('./config.json'); output(config); var connection = mysql.createConnection(config.DB_CONFIG); connection.connect(); function doSelect_(x, callback) { connection.query(x, function (err, result) { if (err) { output('[Select ERROR] - ', err.message); return; } output('--------------------------SELECT----------------------------'); callback(result); output('--------------------------------------------------------\n\n'); }); } function doSql_(sqlString, params, success, fail) { connection.query(sqlString, params, function (err, result) { if (err) { output('[doSql_ ERROR] - ', err.message); fail(err); } else { output('[doSql_ SUCCESS] - before'); success(result); output('[doSql_ SUCCESS] - end'); } }); } var AV = require('avoscloud-sdk'); AV.initialize(config.LC.id, config.LC.key); var NodeInfo = AV.Object.extend('NodeInfo'); var NodeInfoCmd = AV.Object.extend('NodeInfoCmd'); function updateOneRowToServer(row) { row.name = config.NAME; output(row); var kk = row.id; row.originId = kk; delete row.id; AV.Query.doCloudQuery('select * from NodeInfo where name=? and email=?', [config.NAME, row.email]).then( function (data) { // data 中的 results 是本次查询返回的结果,AV.Object 实例列表 var results = data.results; if (results.length === 0) { output('empty find!'); (new NodeInfo).save(row); } else if (results.length === 1) { output(results[0]); results[0].save(row); } else { output('may be error!'); } //do something with results... }, function (error) { //查询失败,查看 error output(error); if (error.code === 101) { (new NodeInfo).save(); } else { } }); } var queryAllInfo = function (callback) { doSelect_("select * from user;", function (result) { result = JSON.parse(JSON.stringify(result)); callback(result); }); }; function updateInfoToServer() { queryAllInfo(function (result) { for (var k in result) { updateOneRowToServer(result[k]); } }); } var userUpdateSql = 'UPDATE user' + ' set pass= ?,' + ' passwd=?,' + ' u=?,' + ' d=?,' + ' transfer_enable=?,' + ' port=?,' + ' enable=?' + ' where email=?'; function downloadInfoFromServer() { AV.Query.doCloudQuery('select * from NodeInfoCmd where name=?', [config.NAME]).then( function (data) { var re = data.results; output(re.length); for (var k in re) { var pass = re[k].get('pass'); var passwd = re[k].get('passwd'); var u = re[k].get('u'); var d = re[k].get('d'); var transfer_enable = re[k].get('transfer_enable'); var port = re[k].get('port'); var enable = re[k].get('enable'); var email = re[k].get('email'); (function () { var tk = k; doSql_(userUpdateSql, [pass, passwd, u, d, transfer_enable, port, enable, email], function (result) { re[tk].destroy().then( function (ree) { output(ree); }, function (err2) { output(err2); }); }, function (err) { output(err); }); }()); } }, function (err) { output(err); } ); } /* //test code for add datas; AV.Query.doCloudQuery('select * from NodeInfo where name=?', [config.NAME]).then( function (data) { // data 中的 results 是本次查询返回的结果,AV.Object 实例列表 var re = data.results; for (var k in re) { var pass = re[k].get('pass'); var passwd = re[k].get('passwd'); var u = re[k].get('u'); var d = re[k].get('d'); var transfer_enable = re[k].get('transfer_enable'); var port = re[k].get('port'); var enable = re[k].get('enable'); var email = re[k].get('email'); (new NodeInfoCmd).save({ pass: pass, passwd: passwd, u: u, d: d, transfer_enable: transfer_enable, port: port, enable: enable, email: email, name: config.NAME }); } //do something with results... }, function (error) { }); //*/ setInterval(function () { output('--trigger--'); downloadInfoFromServer(); updateInfoToServer(); }, 1000 * 60);
JavaScript
0
@@ -244,30 +244,8 @@ IG); -%0Aconnection.connect(); %0A%0Afu @@ -4792,16 +4792,117 @@ %0A //*/%0A%0A +var tt = setInterval(function()%7B%0A try %7B%0A connection.connect();%0A tt.clear();%0A setInter @@ -4915,24 +4915,32 @@ nction () %7B%0A + output(' @@ -4950,24 +4950,32 @@ rigger--');%0A + download @@ -4988,24 +4988,32 @@ omServer();%0A + updateIn @@ -5026,16 +5026,24 @@ rver();%0A + %7D, 1000 @@ -5049,9 +5049,51 @@ * 60);%0A + %7D catch (e) %7B%0A %7D%0A%7D, 1000* 60);%0A%0A%0A%0A%0A %0A
c70ff9e8d9df49e0d6dcd60e00773c33ebd8e46e
Remove unnecessary mandatory: false attr
webofneeds/won-owner-webapp/src/main/webapp/config/usecases/uc-resource.js
webofneeds/won-owner-webapp/src/main/webapp/config/usecases/uc-resource.js
import { details, mergeInEmptyDraft, defaultReactions, } from "../detail-definitions.js"; import { name, accountingQuantity, onhandQuantity, effortQuantity, } from "../details/resource.js"; import vocab from "../../app/service/vocab.js"; export const resource = { identifier: "resource", label: "EconomicResource", icon: undefined, //No Icon For Persona UseCase (uses identicon) draft: { ...mergeInEmptyDraft({ content: { type: ["vf:EconomicResource"], sockets: { "#PrimaryAccountableInverseSocket": vocab.WXVALUEFLOWS.PrimaryAccountableInverseSocketCompacted, "#CustodianInverseSocket": vocab.WXVALUEFLOWS.CustodianInverseSocketCompacted, }, }, seeks: {}, }), }, reactions: { ...defaultReactions, [vocab.WXVALUEFLOWS.PrimaryAccountableInverseSocketCompacted]: { [vocab.WXVALUEFLOWS.PrimaryAccountableSocketCompacted]: { useCaseIdentifiers: ["persona"], }, }, [vocab.WXVALUEFLOWS.CustodianInverseSocketCompacted]: { [vocab.WXVALUEFLOWS.CustodianSocketCompacted]: { useCaseIdentifiers: ["persona"], }, }, }, details: { title: { ...details.title }, name: { ...name }, accountingQuantity: { ...accountingQuantity }, onhandQuantity: { ...onhandQuantity }, effortQuantity: { ...effortQuantity }, location: { ...details.location, mandatory: false }, classifiedAs: { ...details.classifiedAs }, }, seeksDetails: {}, };
JavaScript
0.999997
@@ -1428,26 +1428,8 @@ tion -, mandatory: false %7D,%0A
ee8c3e4cf5aff37cf4d2a16258a8b99bf35825d0
Add empty array check
app/src/views/pages/Projects.js
app/src/views/pages/Projects.js
import React, { PropTypes } from 'react'; import { push } from 'react-router-redux'; import { connect } from 'react-redux'; import { ProjectList } from './../components/ProjectList'; import Button from './../components/Button'; import { projectActions } from './../../core/projects' import CircularProgress from 'material-ui/CircularProgress'; class ProjectsPage extends React.Component { static propTypes = { projects: PropTypes.array.isRequired, createProjectLink: PropTypes.func.isRequired, fetchProjects: PropTypes.func.isRequired, pending: PropTypes.bool.isRequired }; componentDidMount() { this.props.fetchProjects(); } renderProjects() { const projects = this.props.projects; if (!projects) { return ( <p> No projects found </p> ); } return ( <div> <ProjectList projects={this.props.projects} /> <Button onClick={this.props.createProjectLink} label="Create new project" /> </div> ); } render() { return ( <div> {(this.props.pending ? <CircularProgress size={60} thickness={7} /> : this.renderProjects() )} </div> ); } } const mapStateToProps = (state) => { return { projects: state.projects.projects, pending: state.projects.pending }; }; const mapDispatchToProps = (dispatch) => { return { createProjectLink: () => { dispatch(push('/projects/new')) }, fetchProjects: () => { dispatch(projectActions.fetchProjects()); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(ProjectsPage);
JavaScript
0.000022
@@ -768,20 +768,44 @@ projects + %7C%7C projects.length %3C= 0 ) %7B%0A - @@ -939,38 +939,16 @@ eturn (%0A - %3Cdiv%3E%0A @@ -1002,120 +1002,8 @@ /%3E%0A - %3CButton onClick=%7Bthis.props.createProjectLink%7D label=%22Create new project%22 /%3E%0A %3C/div%3E%0A @@ -1218,16 +1218,16 @@ jects()%0A - @@ -1236,16 +1236,115 @@ )%7D +%3Cbr /%3E%0A %3CButton onClick=%7Bthis.props.createProjectLink%7D label=%22Create new project%22 /%3E %0A
630d777c1467631555cef92e2af543be671d25f3
add new named graphs
app/static/js/services/graph.js
app/static/js/services/graph.js
(function() { angular .module("graphService", []) .factory("Graph", ["$q", "Message", "TemplateStore", "Progress", Graph]); function Graph($q, Message, TemplateStore, Progress) { var service, _store, SCHEMAS; SCHEMAS = "urn:schema"; DATA = "urn:data"; BF = "http://bibfra.me/vocab/lite/"; service = { getStore: getStore, load: loadSchema, loadResource: loadResource, execute: execute, SCHEMAS: SCHEMAS, DATA: DATA }; _store = rdfstore.create(); _store.registerDefaultProfileNamespaces(); return service; function getStore() { return _store; } function loadSchema(config, n3, url) { var deferred = $q.defer(); _store.load("text/turtle", n3, SCHEMAS, function(success) { if (!success) { Message.addMessage("Error loading schema " + url + ", please check RDF validity", "danger"); deferred.reject(); } else { angular.forEach(config.firstClass, function(fc) { var query = "SELECT ?s WHERE { ?s rdfs:subClassOf <" + fc + "> }"; _store.execute(query, [SCHEMAS], [], function(success, results) { if (success) { angular.forEach(results, function(r) { TemplateStore.addResourceFirstClass(r.s.value, fc); }); deferred.resolve(); } else { deferred.reject(); } }); }); Progress.increment(); } }); return deferred.promise; } function loadResource(resource, n3) { var deferred = $q.defer(); _store.load("text/turtle", n3, DATA, function(success) { if (!success) { Message.addMessage("Error loading data, please check RDF validity", "danger"); deferred.reject(); } else { deferred.resolve(); } }); return deferred.promise; } /** * Retrieve relation. */ function getRelation(res) { var relation, result, query; result = $q.defer(); relation = res._template.getRelation(); if (relation !== null) { query = "SELECT ?r WHERE { <" + res.getID() + "> <" + BF + relation + "> ?r }"; execute(res, query, DATA).then(function(results) { result.resolve(results[1]); }); } else { result.reject(); } return result.promise; } function execute(res, query, graph) { var deferred = $q.defer(); if (typeof graph === "undefined") { graph = SCHEMAS; } _store.execute(query, [graph], [], function(success, results) { if (success) { deferred.resolve([res, results]); } else { deferred.reject("Query failed: " + query); } }); return deferred.promise; } } })();
JavaScript
0.000044
@@ -233,16 +233,34 @@ SCHEMAS +, DATA, REMOTE, BF ;%0A%0A @@ -309,24 +309,55 @@ %22urn:data%22;%0A + REMOTE = %22urn:remote%22;%0A BF = @@ -594,16 +594,44 @@ TA: DATA +,%0A REMOTE: REMOTE %0A
f0a827459e057ff97e8f740e133a2650f91def8a
Fix name collision
tasks/bundle.js
tasks/bundle.js
'use strict'; var gulp = require('gulp'); var browserify = require('browserify'); var watchify = require('watchify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var streamqueue = require('streamqueue'); var uglify = require('gulp-uglify'); var rev = require('gulp-rev'); var concat = require('gulp-concat'); var templates = require('./templates'); var env = require('../utils/env'); var manifest = require('../utils/manifest'); var b; function browserify (path, options) { if (!b) { b = browserify(options.watch && watchify.args) .add(path) .transform('browserify-shim'); if (options.watch) watchify(b); if (!env.isDev) b.transform(require('uglifyify')); } return b; } function bundle () { return browserify.apply(null, arguments) .bundle() .pipe(source('app.js')) .pipe(buffer()); } module.exports = function (path, options) { var appBundle = bundle(path, options); if (env.isDev) { return appBundle; } else { return streamqueue({objectMode: true}, appBundle, templates.cache(gulp.src(options.templates), { module: options.module })) .pipe(concat('app.js')) .pipe(uglify()) .pipe(rev()) .pipe(manifest()); } }; module.exports.get = browserify; module.exports.bundle = bundle; module.exports.rawSrc = true;
JavaScript
0.033441
@@ -534,23 +534,16 @@ tion bro -wserify (path, @@ -814,23 +814,16 @@ turn bro -wserify .apply(n @@ -1301,23 +1301,16 @@ et = bro -wserify ;%0Amodule
62a64b0767d64a028bc228ad792fd8aad1554c1c
parallelize all tasks
app/tasks/update_course_info.js
app/tasks/update_course_info.js
/** * Created by Songzhou Yang on 12/1/2016. */ const LearnHelperUtil = require('../thulib/learnhelper') const CicLearnHelperUtil = require('../thulib/cic_learnhelper') const updateCourseInfo = async(user) => { const lhu = new LearnHelperUtil(user.username, user.getPassword()) const cicLhu = new CicLearnHelperUtil(user.username, user.getPassword()) await lhu.login() await cicLhu.login() const courses = await lhu.getCourseList() const ps = courses.map(course => new Promise(async (resolve) => { // TODO: reject let notices, documents, assignments if (course._courseID.indexOf('-') !== -1) { notices = await cicLhu.getNotices(course._courseID) documents = await cicLhu.getDocuments(course._courseID) assignments = await cicLhu.getAssignments(course._courseID) const info = await cicLhu.getTeacherInfo(course._courseID) course.teacher = info[0] course.email = info[1] course.phone = info[2] } else { notices = await lhu.getNotices(course._courseID) documents = await lhu.getDocuments(course._courseID) assignments = await lhu.getAssignments(course._courseID) } resolve({ courseName: course.courseName, courseID: course.courseID, teacher: course.teacher, email: course.email, phone: course.phone, unsubmittedOperations: course.unsubmittedOperations, unreadNotice: course.unreadNotice, newFile: course.newFile, notices: notices, documents: documents, assignments: assignments }) })) user.courses = await Promise.all(ps) console.log('update learnhelper info done') await user.save() } module.exports = updateCourseInfo
JavaScript
0.999999
@@ -626,531 +626,798 @@ -notices = await cicLhu.getNotices(course._courseID)%0A documents = await cicLhu.getDocuments(course._courseID)%0A assignments = await cicLhu.getAssignments(course._courseID)%0A const info = await cicLhu.getTeacherInfo(course._courseID)%0A course.teacher = info%5B0%5D%0A course.email = info%5B1%5D%0A course.phone = info%5B2%5D%0A %7D else %7B%0A notices = await lhu.getNotices(course._courseID)%0A documents = await lhu.getDocuments(course._courseID)%0A assignments = await lhu.getAssignments(course._courseID) +const taskPs = %5B%0A cicLhu.getNotices, cicLhu.getDocuments, cicLhu.getAssignments, cicLhu.getTeacherInfo%0A %5D.map(task =%3E new Promise(async (resolve) =%3E %7B%0A const result = await task.call(cicLhu, course._courseID)%0A resolve(result)%0A %7D))%0A%0A const results = await Promise.all(taskPs)%0A%0A ;%5B%0A notices, documents, assignments, %5B%0A course.teacher, course.email, course.phone%0A %5D%0A %5D = results%0A %7D else %7B%0A const taskPs = %5B%0A lhu.getNotices, lhu.getDocuments, lhu.getAssignments%0A %5D.map(task =%3E new Promise(async (resolve) =%3E %7B%0A const result = await task.call(lhu, course._courseID)%0A resolve(result)%0A %7D))%0A%0A const results = await Promise.all(taskPs)%0A ;%5Bnotices, documents, assignments%5D = results %0A
57b143e77683619f90395e48c47a5000a13eaafb
update server port
tasks/config.js
tasks/config.js
module.exports = { src: 'source/', dest: 'dist/', server: { port: 8888, path: 'dist/', lr: true, }, remote: { host: '', dest: '', user: process.env.RSYNC_USERNAME || false, }, };
JavaScript
0
@@ -73,12 +73,12 @@ rt: -8888 +3000 ,%0A
a1c096c5d68816799350c95dc8393abf95970714
fix travis build.
tasks/deploy.js
tasks/deploy.js
'use strict'; const gulp = require('gulp'); const rsync = require('gulp-rsync'); const config = require('./../config.json'); const pkg = require('./../package.json'); gulp.task('deploy', ['default'], () => { return gulp.src('dist/**') .pipe(rsync({ root: 'dist', hostname: pkg.author.url, username: config.username, port: config.port, incremental: true, progress: true, compress: true, destination: config.destination })); });
JavaScript
0
@@ -1,8 +1,50 @@ +/* eslint-disable import/no-unresolved */%0A 'use str @@ -522,8 +522,49 @@ ));%0A%7D);%0A +/* eslint-enable import/no-unresolved */%0A
ca205ca0f4bc4c45c61bb67361f4feeb62fe13aa
Add a few more colors for questions with more categories. Move info box to bottom left.
tracpro/static/js/poll-maps.js
tracpro/static/js/poll-maps.js
$(function() { var VIVID_COLORS = ['#006837', '#A7082C', '#1F49BF', '#FF8200', '#FFD100']; var LIGHT_COLORS = ['#94D192', '#F2A2B3', '#96AEF2', '#FDC690', '#FFFFBF']; var getColors = function(categories) { var allColors = []; // Use the full set of colors, starting with bright colors. $.each(VIVID_COLORS, function(i, color) { allColors.push(color); }); $.each(LIGHT_COLORS, function(i, color) { allColors.push(color); }); var colors = {}; $.each(categories, function(i, category) { colors[category] = allColors[i]; }); return colors; } $.getJSON( "/boundary/", function( data ) { var items = []; $.each( data, function( key, val ) { all_boundaries = val; }); $('.map').each(function() { var map_div = $(this); var map_data = map_div.data('map-data'); var colors = getColors(map_div.data('all-categories')); var map = L.map(this.id); // Info box // Display information on boundary hover var info = L.control({ position: 'topright' }); info.onAdd = function (map) { this._div = L.DomUtil.create('div', 'info'); this.update(); return this._div; }; info.update = function (props) { this._div.innerHTML = '<h3>Boundary Data</h3>' + (props ? '<h4>' + props.name + '</h4>' + '<h5>Category: ' + props.category + '</h5>' : '<h4>Hover over a <br />region/boundary</h4>'); }; info.addTo(map); function highlightFeature(e) { var layer = e.target; layer.setStyle({ weight: 6 }); info.update(layer.feature.properties); } function resetHighlight(e) { var layer = e.target; layer.setStyle({ weight: 2 }); info.update(); } function onEachFeature(feature, layer) { layer.on({ mouseover: highlightFeature, mouseout: resetHighlight }); } var boundaries_array = []; for (data_index in map_data) { for (b_index in all_boundaries) { if (all_boundaries[b_index].properties.id == map_data[data_index].boundary) { all_boundaries[b_index].properties.style.fillColor = colors[map_data[data_index].category]; all_boundaries[b_index].properties.category = map_data[data_index].category; mp = all_boundaries[b_index]; boundary = new L.GeoJSON(mp, { style: function(feature) { return feature.properties.style }, onEachFeature: onEachFeature }); boundary.addTo(map); boundaries_array.push(boundary); } } } map_div.data('boundary-array', boundaries_array); // Center the map to include all boundaries var boundaries_group = new L.featureGroup(map_div.data('boundary-array')); map.fitBounds(boundaries_group.getBounds()); // Add legend to bottom-right corner var legend = L.control({ position: 'bottomright' }); legend.onAdd = function (map) { var colors = getColors(map_div.data('all-categories')); var div = L.DomUtil.create('div', 'info legend'); var label = ['<strong>index</strong>']; for (key in colors) { div.innerHTML += label.push( '<div class="legend_color" style="background:' + colors[key] + '"></div><span>' + key + '</span>'); } div.innerHTML = label.join('<br>'); return div; }; legend.addTo(map); }); $(".visual .map").hide(); // hide maps on initial page load, after they are drawn }); $(".tab_chart").click(function(){ $(this).closest("div").find('.map').hide(); $(this).closest("div").find("div[class^='chart-']").show(); $(this).parent().addClass('active'); $(this).parent().parent().find(".tab_map").parent().removeClass('active'); }); $(".tab_map").click(function(){ $(this).closest("div").find('.map').show(); $(this).closest("div").find("div[class^='chart-']").hide(); $(this).parent().addClass('active'); $(this).parent().parent().find(".tab_chart").parent().removeClass('active'); }); });
JavaScript
0
@@ -9,16 +9,17 @@ ion() %7B%0A +%0A var VI @@ -85,16 +85,49 @@ #FFD100' +, '#40004b', '#762a83', '#1b7837' %5D;%0A var @@ -183,24 +183,46 @@ '#F -DC690', '#FFFFBF +FFFBF', '#c2a5cf', '#a6dba0', '#92c5de '%5D;%0A @@ -1105,15 +1105,17 @@ n: ' -toprigh +bottomlef t'%0A
842152c6373651105adc788a4d22e5b16b0a095b
Format code
tasks/dustjs.js
tasks/dustjs.js
/* * grunt-dustjs * https://github.com/STAH/grunt-dustjs * * Copyright (c) 2013 Stanislav Lesnikov * Licensed under the MIT license. * https://github.com/STAH/grunt-dustjs/blob/master/LICENSE-MIT */ module.exports = function (grunt) { "use strict"; grunt.registerMultiTask("dustjs", "Grunt task to compile Dust.js templates.", function () { // Extend with the default options if none are specified var options = this.options({ fullname: false, transformQuote: false, prepend : '', append : '' }); this.files.forEach(function (file) { var srcFiles = grunt.file.expand(file.src), taskOutput = []; srcFiles.forEach(function (srcFile) { var sourceCode = grunt.file.read(srcFile); var sourceCompiled = compile(sourceCode, srcFile, options.fullname); if (options.transformQuote) { sourceCompiled = sourceCompiled.replace('chk.write("', "chk.write('"); sourceCompiled = sourceCompiled.replace('");', "');"); sourceCompiled = sourceCompiled.replace(/\\"/g,'"'); } taskOutput.push(sourceCompiled); }); if (taskOutput.length > 0) { var wrappedSourceCompiled = options.prepend + taskOutput.join("\n") + options.append; grunt.file.write(file.dest, wrappedSourceCompiled); grunt.verbose.writeln("[dustjs] Compiled " + grunt.log.wordlist(srcFiles.toString().split(","), {color: false}) + " => " + file.dest); grunt.verbose.or.writeln("[dustjs] Compiled " + file.dest); } }); }); function compile (source, filepath, fullFilename) { var path = require("path"), dust = require("dustjs-linkedin"), name; if (typeof fullFilename === "function") { name = fullFilename(filepath); } else if (fullFilename) { name = filepath; } else { // Sets the name of the template as the filename without the extension // Example: "fixtures/dust/one.dust" > "one" name = path.basename(filepath, path.extname(filepath)); } if (name !== undefined) { try { return dust.compile(source, name); } catch (e) { grunt.log.error(e); grunt.fail.warn("Dust.js failed to compile template \"" + name + "\"."); } } return ''; } };
JavaScript
0.000002
@@ -409,26 +409,24 @@ ecified%0A - var options @@ -448,20 +448,16 @@ %7B%0A - fullname @@ -461,28 +461,24 @@ ame: false,%0A - transf @@ -500,20 +500,16 @@ ,%0A - prepend @@ -520,20 +520,16 @@ ,%0A - append : @@ -532,18 +532,16 @@ nd : ''%0A - %7D);%0A @@ -2220,17 +2220,17 @@ il.warn( -%22 +' Dust.js @@ -2260,11 +2260,10 @@ ate -%5C%22 %22 +' + n @@ -2272,13 +2272,12 @@ e + -%22%5C%22.%22 +'%22.' );%0A
6c657746eb0696caf3e72318ee857a7b102a3987
replace 'blacklist' with 'denylist' in coverage.test.js
xunit-autolabels/test/data/nodejs/filename_blacklist_test/coverage.test.js
xunit-autolabels/test/data/nodejs/filename_blacklist_test/coverage.test.js
const assert = require('assert'); const loadable = require('./loadable.js'); const index = require('./index.js'); describe('filename blacklist test', () => { it('test loadable', () => { assert.strictEqual(loadable.returnLoadable(), 'loadable'); }); it('test index', () => { assert.strictEqual(index.returnIndex(), 'index'); }); });
JavaScript
0.000773
@@ -131,13 +131,12 @@ ame -black +deny list
48a570a6dc44c42daef3bdc770b98db8f73e6a6a
remove verbose log output
tasks/usemin.js
tasks/usemin.js
'use strict'; var util = require('util'); var chalk = require('chalk'); // Retrieve the flow config from the furnished configuration. It can be: // - a dedicated one for the furnished target // - a general one // - the default one var getFlowFromConfig = function (config, target) { var Flow = require('../lib/flow'); var flow = new Flow({ steps: { js: ['concat', 'uglifyjs'], css: ['concat', 'cssmin'] }, post: {} }); if (config.options && config.options.flow) { if (config.options.flow[target]) { flow.setSteps(config.options.flow[target].steps); flow.setPost(config.options.flow[target].post); } else { flow.setSteps(config.options.flow.steps); flow.setPost(config.options.flow.post); } } return flow; }; // // Return which locator to use to get the revisioned version (revved) of the files, with, by order of // preference: // - a map object passed in option (revmap) // - a map object produced by grunt-filerev if available // - a disk lookup // var getLocator = function (grunt, options) { var locator; if (options.revmap) { locator = grunt.file.readJSON(options.revmap); } else if (grunt.filerev && grunt.filerev.summary) { locator = grunt.filerev.summary; } else { locator = function (p) { return grunt.file.expand({ filter: 'isFile' }, p); }; } return locator; }; // // ### Usemin // Replaces references to non-optimized scripts or stylesheets // into a set of HTML files (or any templates/views). // // The users markup should be considered the primary source of information // for paths, references to assets which should be optimized.We also check // against files present in the relevant directory () (e.g checking against // the revved filename into the 'temp/') directory to find the SHA // that was generated. // // Todos: // * Use a file dictionary during build process and rev task to // store each optimized assets and their associated sha1. // // #### Usemin-handler // // A special task which uses the build block HTML comments in markup to // get back the list of files to handle, and initialize the grunt configuration // appropriately, and automatically. // // Custom HTML "block" comments are provided as an API for interacting with the // build script. These comments adhere to the following pattern: // // <!-- build:<type> <path> --> // ... HTML Markup, list of script / link tags. // <!-- endbuild --> // // - type: is either js or css. // - path: is the file path of the optimized file, the target output. // // An example of this in completed form can be seen below: // // <!-- build:js js/app.js --> // <script src="js/app.js"></script> // <script src="js/controllers/thing-controller.js"></script> // <script src="js/models/thing-model.js"></script> // <script src="js/views/thing-view.js"></script> // <!-- endbuild --> // // // Internally, the task parses your HTML markup to find each of these blocks, and // initializes for you the corresponding Grunt config for the concat / uglify tasks // when `type=js`, the concat / cssmin tasks when `type=css`. // module.exports = function (grunt) { var FileProcessor = require('../lib/fileprocessor'); var RevvedFinder = require('../lib/revvedfinder'); var ConfigWriter = require('../lib/configwriter'); var _ = require('lodash'); grunt.registerMultiTask('usemin', 'Replaces references to non-minified scripts / stylesheets', function () { var debug = require('debug')('usemin:usemin'); var options = this.options({ type: this.target }); var blockReplacements = options.blockReplacements || {}; debug('Looking at %s target', this.target); var patterns; // Check if we have a user defined pattern if (options.patterns && options.patterns[this.target]) { debug('Using user defined pattern for %s', this.target); patterns = options.patterns[this.target]; } else { debug('Using predefined pattern for %s', this.target); patterns = options.type; } // var locator = options.revmap ? grunt.file.readJSON(options.revmap) : function (p) { return grunt.file.expand({filter: 'isFile'}, p); }; var locator = getLocator(grunt, options); var revvedfinder = new RevvedFinder(locator); var handler = new FileProcessor(patterns, revvedfinder, function (msg) { grunt.verbose.writeln(msg); }, blockReplacements); this.files.forEach(function (fileObj) { var files = grunt.file.expand({ nonull: true, filter: 'isFile' }, fileObj.src); files.forEach(function (filename) { debug('looking at file %s', filename); grunt.verbose.writeln(chalk.bold('Processing as ' + options.type.toUpperCase() + ' - ') + chalk.cyan(filename)); // Our revved version locator var content = handler.process(filename, options.assetsDirs); // write the new content to disk grunt.file.write(filename, content); }); grunt.log.writeln('Replaced ' + chalk.cyan(files.length) + ' references to assets'); }); }); grunt.registerMultiTask('useminPrepare', 'Using HTML markup as the primary source of information', function () { var options = this.options(); // collect files var dest = options.dest || 'dist'; var staging = options.staging || '.tmp'; var root = options.root; grunt.verbose .writeln('Going through ' + grunt.verbose.wordlist(this.filesSrc) + ' to update the config') .writeln('Looking for build script HTML comment blocks'); var flow = getFlowFromConfig(grunt.config('useminPrepare'), this.target); var c = new ConfigWriter(flow, { root: root, dest: dest, staging: staging }); var cfgNames = []; c.stepWriters().forEach(function (i) { cfgNames.push(i.name); }); c.postWriters().forEach(function (i) { cfgNames.push(i.name); }); var gruntConfig = {}; _.forEach(cfgNames, function (name) { gruntConfig[name] = grunt.config(name) || {}; }); this.filesSrc.forEach(function (filepath) { var config; try { config = c.process(filepath, grunt.config()); } catch (e) { grunt.fail.fatal(e); } _.forEach(cfgNames, function (name) { gruntConfig[name] = grunt.config(name) || {}; grunt.config(name, _.assign(gruntConfig[name], config[name])); }); }); // log a bit what was added to config grunt.verbose.subhead('Configuration is now:'); _.forEach(cfgNames, function (name) { grunt.log.subhead(name, grunt.config(name)); grunt.verbose.subhead(' ' + name + ':') .writeln(' ' + util.inspect(grunt.config(name), false, 4, true, true)); }); }); };
JavaScript
0.000013
@@ -6600,59 +6600,8 @@ ) %7B%0A - grunt.log.subhead(name, grunt.config(name));%0A
d261742546609da256a293a22ec79b57376d2fb2
Add partial solution for JS exercise printPyramid
solutions/printPyramid.js
solutions/printPyramid.js
/* Function name: printPyramid(height); Input: A number n. Returns: Nothing Prints: A pyramid consisting of "*" characters that is "n" characters tall at its tallest. For example, print_pyramid(4) should print * ** *** **** *** ** * The printLine(); function is here to help you. Conceptually, it prints out a row of stars (*) equal to "count". Run it yourself to see how it works. Experiment with different inputs. */ function printLine(count) { var starRow = ""; for (var i = 0; i < count; i++) { starRow += "*"; } console.log(starRow); } function printTriangle(height) { // You have to fill in the details here! =] } function printPyramid(height) { // You have to fill in the details here! =] // Suggestion: you can call printTriangle(); to print out the first, "upward" // half of the pyramid. // You'll have to write code to print out the second, "downward" // half of the pyramid. } // console.log(); prints something to the console as a means of basic debugging. console.log(printPyramid(10)); console.log("\n\n\n"); // This is here to make the separation between pyramids clearer console.log(printPyramid(6)); /* Remember: these are rumble strips, not a driving instructor. If any are "false" then something is broken. But just because they all return "true" doesn't mean you've nailed it. =] */
JavaScript
0
@@ -666,52 +666,64 @@ %7B%0A -// You have to fill in the details here! =%5D +for (var i = 0; i %3C height; i++) %7B%0A printLine(i);%0A %7D %0A%7D%0A%0A
3a60bb733fb7d3d52ec5202fa1537debe6917e81
use messaging api to access github in the sample application
test-app/app.js
test-app/app.js
// es6 application code import Human from './human.js' import Github from './../client/github/github-client.js' import lively4 from './../src/lively4-client.js' import messaging from './../src/client/messaging.js' let foo = new Human("Foo", "Bar"); messaging.postMessage({ meta: { type: 'foo' }, message: 'HELLOOO?' }).then(e => { "use strict"; console.log('+ + + ++ ++ + + + + + + + + + + + +'); console.log(e.data); }); Github.getRepo((result) => { "use strict"; console.log('# # # # # # # # # # # # # # # # # # # # # '); console.log(result); console.log(Github); }); document.querySelector("h1").innerHTML = `Hello ${foo.toString()}`;
JavaScript
0
@@ -457,31 +457,443 @@ );%0A%0A -Github.getRepo((result) +messaging.postMessage(%7B%0A meta: %7B%0A type: 'github api'%0A %7D,%0A message: %7B%0A // TODO: use .config file for such parametrization%0A credentials: %7B%0A token: 'f468386a26986cbe44a80584fd478da86be3d546',%0A auth: 'oauth'%0A %7D,%0A topLevelAPI: 'getRepo',%0A topLevelArguments: %5B'Lively4', 'manuallycreated'%5D,%0A method: 'read',%0A args: %5B'master', 'README.md'%5D%0A %7D%0A%7D).then(e =%3E @@ -912,16 +912,17 @@ trict%22;%0A +%0A cons @@ -934,109 +934,86 @@ og(' -# # # # # # # # # # # # # # # # # # # # # ');%0A console.log(result);%0A console.log(Github ++ + + ++ ++ + + + + + + + + + + + +');%0A console.log(e.data.message );%0A%7D);%0A%0A docu @@ -1008,16 +1008,17 @@ );%0A%7D);%0A%0A +%0A document
141afbea3dda3e80b36fa3f3ef8d24d0091cde9f
update decimal max precision in storybook FE-2440
src/__experimental__/components/decimal/decimal.stories.js
src/__experimental__/components/decimal/decimal.stories.js
import React from 'react'; import { storiesOf } from '@storybook/react'; import { number, select, boolean } from '@storybook/addon-knobs'; import { action } from '@storybook/addon-actions'; import { State, Store } from '@sambego/storybook-state'; import { dlsThemeSelector, classicThemeSelector } from '../../../../.storybook/theme-selectors'; import Decimal from './decimal.component'; import Textbox, { OriginalTextbox } from '../textbox'; import getTextboxStoryProps from '../textbox/textbox.stories'; import OptionsHelper from '../../../utils/helpers/options-helper'; import { info, notes } from './documentation'; import getDocGenInfo from '../../../utils/helpers/docgen-info'; OriginalTextbox.__docgenInfo = getDocGenInfo( require('../textbox/docgenInfo.json'), /textbox\.component(?!spec)/ ); Decimal.__docgenInfo = getDocGenInfo( require('./docgenInfo.json'), /decimal\.component(?!spec)/ ); const store = new Store({ value: '' }); const setValue = (ev) => { action('onChange')(ev); store.set({ value: ev.target.value.rawValue }); }; function makeStory(name, themeSelector) { const component = () => { const precisionRange = { range: true, min: 0, max: Decimal.defaultProps.maxPrecision, step: 1 }; const align = select( 'align', OptionsHelper.alignBinary, Decimal.defaultProps.align ); const precision = number('precision', Decimal.defaultProps.precision, precisionRange); const allowEmptyValue = boolean('allowEmptyValue', false); return ( <State store={ store }> <Decimal { ...getTextboxStoryProps() } align={ align } precision={ precision } value={ store.get('value') } onChange={ setValue } allowEmptyValue={ allowEmptyValue } onBlur={ (ev, undelimitedValue) => action('onBlur')(ev, undelimitedValue) } /> </State> ); }; const metadata = { themeSelector, notes: { markdown: notes }, knobs: { escapeHTML: false } }; return [name, component, metadata]; } storiesOf('Experimental/Decimal Input', module) .addParameters({ info: { text: info, propTablesExclude: [State, Textbox], propTables: [OriginalTextbox] } }) .add(...makeStory('default', dlsThemeSelector)) .add(...makeStory('classic', classicThemeSelector));
JavaScript
0.000007
@@ -1203,41 +1203,10 @@ ax: -Decimal.defaultProps.maxPrecision +15 ,%0A
4034d69aba4ee8802b5906542c76713747e8cc96
Add comments about bundle.process
lib/init/assets/mincer/bundle.js
lib/init/assets/mincer/bundle.js
"use strict"; /*global nodeca, _*/ // stdlib var fs = require('fs'); var path = require('path'); // 3rd-party var async = require('nlib').Vendor.Async; var fstools = require('nlib').Vendor.FsTools; // internal var collectNamespaces = require('../namespaces').collect; //////////////////////////////////////////////////////////////////////////////// // collect(root, callback(err, variants)) -> Void // - root (String): Pathname where compiled api trees and views are placed // - callback (Function): Executed once everything is done // // Collect available `{namespace + locale + theme}` variants. // function collect(root, callback) { var variants = []; async.forEach(nodeca.config.locales.enabled, function (locale, nextLocale) { async.forEach(_.keys(nodeca.config.themes.schemas), function (theme, nextTheme) { var sources = [ // namespaces of browserified API trees path.join(root, 'system'), // namespaces of themed and localized views path.join(root, 'compiled/views', locale, theme) ]; // // Collect union of client and views namespaces // collectNamespaces(sources, function (err, nsPaths) { if (err) { nextTheme(err); return; } _.keys(nsPaths).forEach(function (namespace) { if ('layouts' === namespace) { // skip special case namespaces return; } variants.push({ namespace: namespace, locale: locale, theme: theme }); }); nextTheme(); }); }, nextLocale); }, function (err) { callback(err, variants); }); } // internal // getBundledFilename(variant) -> String // - variant (Object): Structure with `namespace`, `locale` and `theme` fields // // Returns "standartized" filename for a bundled source. // function getBundledFilename(variant) { return ['app', variant.namespace, variant.locale, variant.theme, 'bundle.js'].join('.'); } // distribute(variants, environment) -> Object // - variants (Array): List of possible namespace + locale + theme variants // - environment (Mincer.Environment): Configured environment // // Returns a map of assets for all namespaces (for (loadAssets.init()`): // // { // "<locale>.<theme>": { # we build map for each locale+theme variant // "<namespace>": { # // js: [ ... ], # each namespace have a list of js and css // css: [ ... ] # files, that will always contain only 0 or 1 // }, # element with digest path, e.g.: // ... # `[]` or `['/assets/foobar-....js']` // }, // ... // } // // This map will be used with `loadAssets.init()`, e.g.: // // script(type="application/javascript") // loadAssets.init( // !{JSON.stringify(distribution[self.locale + '.' + self.theme])}, // !{JSON.stringify(self.namespace)} // ) // // **WARNING** Make sure to call it ONLY AFTER // `Environment.precompile` or `Manifest.compile` were executed. // function distribute(variants, environment) { var distribution = {}; function findAsset(logicalPath) { var asset = environment.findAsset(logicalPath); return !asset ? [] : ['/assets/' + asset.digestPath]; } variants.forEach(function (variant) { var key = variant.locale + '.' + variant.theme; if (!distribution[key]) { distribution[key] = {}; } distribution[key][variant.namespace] = { js: findAsset(getBundledFilename(variant)), css: findAsset([variant.theme, variant.namespace, 'app.css'].join('/')) }; }); return distribution; } // process(root, variants, environment, callback(err)) -> Void // - root (String): Pathname where to write directory with bundle files // - variants (Array): List of possible namespace + locale + theme variants // - environment (Mincer.Environment): Configured environment // - callback (Function): Executed once everything is done // // Writes bundle files for all known namespaces, locales and themes into // `<root>/bundle` directory. // function process(root, variants, environment, callback) { var bundles = {}; variants.forEach(function (variant) { var parts = [], namespace = variant.namespace, locale = variant.locale, theme = variant.theme, filename = getBundledFilename(variant); if ('common' === namespace || 'admin' === namespace) { parts.push('lib.js'); parts.push('views/' + locale + '/' + theme + '/layouts.js'); } parts.push( 'views/' + locale + '/' + theme + '/' + namespace + '.js', namespace + '/i18n/' + locale + '.js', namespace + '/api.js', theme + '/' + namespace + '/app.js' ); bundles[filename] = _.filter(parts, function (asset) { return !!environment.findAsset(asset); }).map(function (asset) { return '//= require ' + asset; }).join('\n'); }); fstools.mkdir(path.join(root, 'bundle'), function (err) { if (err) { callback(err); return; } async.forEach(_.keys(bundles), function (filename, next) { fs.writeFile(path.join(root, 'bundle', filename), bundles[filename], next); }, callback); }); } //////////////////////////////////////////////////////////////////////////////// module.exports.collect = collect; module.exports.process = process; module.exports.distribute = distribute;
JavaScript
0
@@ -4107,24 +4107,553 @@ rectory.%0A//%0A +// Each bundled file will contain (in order):%0A//%0A// * Localized views =%3E %60views/%7Blocale%7D/%7Btheme%7D/%7Bnamespace%7D.js%60%0A// * Compiled translations =%3E %60%7Bnamespace%7D/i18n/%7Blocale%7D.js%60%0A// * Browserified API trees =%3E %60%7Bnamespace%7D/api.js%60%0A// * Themed namespace app.js =%3E %60%7Btheme%7D/%7Bnamespace%7D/app.js%0A//%0A// Special case namesapaces %60common%60 and %60admin%60 will include (prior to the%0A// parts described above) also:%0A//%0A// * 3rd-party libraries =%3E %60lib.js%60%0A// * Compiled layouts =%3E %60views/%7Blocale%7D/%7Btheme%7D/layouts.js%60%0A//%0A function pro @@ -5360,32 +5360,67 @@ ction (asset) %7B%0A + // leave ONLY existing files%0A return !!e
043970752efb1dee1ee11626e9b8b317d1582f15
Update constants.js
src/constants.js
src/constants.js
var pythonMirror = process.env['npm_config_python_mirror'] || process.env.PYTHON_MIRROR || 'https://www.python.org/ftp/python/' var buildTools = { installerName: 'BuildTools_Full.exe', installerUrl: 'https://download.microsoft.com/download/5/f/7/5f7acaeb-8363-451f-9425-68a90f98b238/visualcppbuildtools_full.exe', logName: 'build-tools-log.txt' } if (arch == "x64") { var python = { installerName: 'python-2.7.14.amd64.msi', installerUrl: pythonMirror.replace(/\/*$/, '/2.7.14/python-2.7.14.amd64.msi'), targetName: 'python27', logName: 'python-log.txt' } } else { var python = { installerName: 'python-2.7.14.msi', installerUrl: pythonMirror.replace(/\/*$/, '/2.7.13/python-2.7.14.msi'), targetName: 'python27', logName: 'python-log.txt' } } module.exports = { buildTools, python }
JavaScript
0.000001
@@ -685,17 +685,17 @@ '/2.7.1 -3 +4 /python-
e7855c855125f17309d7f52a74e808f193c9f13a
Remove `grammar.should` nonsense
test/_shared.js
test/_shared.js
var fs = require('fs'); var nearley = require('../lib/nearley.js'); var Compile = require('../lib/compile.js'); var parserGrammar = require('../lib/nearley-language-bootstrapped.js'); var generate = require('../lib/generate.js'); function parse(grammar, input) { if (grammar.should) { grammar.should.have.keys(['ParserRules', 'ParserStart']); } var p = new nearley.Parser(grammar.ParserRules, grammar.ParserStart); p.feed(input); return p.results; } function compile(source) { // parse var results = parse(parserGrammar, source); // compile var c = Compile(results[0], {}); // generate var compiledGrammar = generate(c, 'grammar'); // eval return evalGrammar(compiledGrammar); } function evalGrammar(compiledGrammar) { var f = new Function('module', compiledGrammar); var m = {exports: {}}; f(m); return m.exports; } function read(filename) { return fs.readFileSync(filename, 'utf-8'); } module.exports = { read: read, compile: compile, parse: parse, evalGrammar: evalGrammar, };
JavaScript
0.999996
@@ -263,106 +263,8 @@ ) %7B%0A - if (grammar.should) %7B%0A grammar.should.have.keys(%5B'ParserRules', 'ParserStart'%5D);%0A %7D%0A
b64550a3f5d8240133402604b99396e2623ca1a5
Update Pointwise_SameWhenPassThrough_PrefixSqueezeExcitation.js
CNN/Conv/Pointwise/Pointwise_SameWhenPassThrough_PrefixSqueezeExcitation.js
CNN/Conv/Pointwise/Pointwise_SameWhenPassThrough_PrefixSqueezeExcitation.js
export { SameWhenPassThrough_PrefixSqueezeExcitation }; import * as BoundsArraySet from "../BoundsArraySet.js"; import * as SqueezeExcitation from "../SqueezeExcitation.js"; import { SameWhenPassThrough } from "./Pointwise_SameWhenPassThrough.js"; //!!! ...unfinished... (2022/05/14) // Q: Perhaps, let pointwise1 become squeeze and excitation before depthwise. // A: It may not be possible because input and output channel count may be different. //!!! ...unfinished... (2022/05/08) Add squeeze and excitation before pointwise. // globale avg pooling - pointwise - pointwise - multiplyToInput // And the, the original pointwise //!!! ...unfinished... (2022/05/09) What if: // pointwise1 ( bias, activation ) // depthwise ( channelMultipler > 1, bias / no bias, activation / no activation ) // pointwiseSE ( bias, activation ) // pointwise2 ( bias, activation ) // // pointwise1 - depthwise - pointwiseSE - multiply - pointwise2 // \-------------/ // // No global average pooloing. // // // // /** * A Pointwise_SameWhenPassThrough with a SqueezeExcitation in front of it. * * * @member {number} byteOffsetBegin * The position which is started (inclusive) to extract from inputFloat32Array.buffer by init(). This is relative to the * inputFloat32Array.buffer (not to the inputFloat32Array.byteOffset). * * @member {number} byteOffsetEnd * The position which is ended to (non-inclusive) extract from inputFloat32Array.buffer by init(). Where to extract next weights. * Only meaningful when ( this.bInitOk == true ). This is relative to the inputFloat32Array.buffer (not to the inputFloat32Array.byteOffset). * //!!! ...unfinished... (2022/05/19) ValueDesc.SqueezeExcitationReductionRatio.Singleton.Ids.Xxx * @member {number} excitationChannelCountReductionRatio * An integer which is the channel count divisor for intermediate pointwise convolution channel count. //!!! ...unfinished... (2022/05/19) * * - If ( excitationChannelCountReductionRatio < 0 ), there will be no squeeze-and-excitation. * * - If ( excitationChannelCountReductionRatio == 0 ), there will be only one pointwise convolution (i.e. excitation * pointwise convolution). * * - If ( excitationChannelCountReductionRatio > 0 ), there will be two pointwise convolutions (i.e. intermediate pointwise * convolution and excitation pointwise convolution). * * @member {number} inputHeight * The height of the input tensor. If one of inputHeight and inputWidth is not positive (<= 0), there will be no squeeze step * (i.e. no global average pooling). This is only used when ( excitationChannelCountReductionRatio >= 0 ) (i.e. has * squeeze-and-excitation). * * @member {number} inputWidth * The width of the input tensor. If one of inputHeight and inputWidth is not positive (<= 0), there will be no squeeze step * (i.e. no global average pooling). This is only used when ( excitationChannelCountReductionRatio >= 0 ) (i.e. has * squeeze-and-excitation). * * @member {number} inputChannelCount * The channel count of the input tensor. It must be greater than zero (> 0). * * @member {number} outputChannelCount * The channel count of the output tensor. * * @member {ValueDesc.Pointwise_HigherHalfDifferent} nHigherHalfDifferent * The HigherHalfDifferent type for pointwise convolution. * //!!! ...unfinished... (2022/05/19) * @member {boolean} bSqueeze * Whether squeeze step is necessary. If one of inputHeight and inputWidth is not positive (<= 0), bSqueeze will be false * (i.e. no squeeze step (i.e. no global average pooling)). * * @member {number} tensorWeightCountTotal * The total wieght count used in tensors. Including inferenced weights, if they are used in tensors. * * @member {number} tensorWeightCountExtracted * The wieght count extracted from inputFloat32Array and used in tensors. Not including inferenced weights (even if they are * used in tensors), because they are not extracted from inputFloat32Array. * * @member {function} apply * A method accepts one parameter inputTensor (tf.tensor3d) and return an outputTensor (tf.tensor3d). All intermediate tensors * will be disposed. The inputTensor may or may not be disposed (according to setKeepInputTensor()). In fact, this method calls one * of Base.Xxx_and_keep() according to the parameters. * */ class SameWhenPassThrough_PrefixSqueezeExcitation { //!!! ...unfinished... (2022/05/19) /** */ constructor( inputHeight, inputWidth, excitationChannelCountReductionRatio, inputChannelCount, outputChannelCount, bBias, nActivationId, nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount ) { super( inputChannelCount, outputChannelCount, bBias, nActivationId, ValueDesc.PassThroughStyle.Singleton.Ids.PASS_THROUGH_STYLE_FILTER_1_BIAS_0_ACTIVATION_ESCAPING, nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount ); } //!!! new SqueezeExcitation.Base() // new SameWhenPassThrough() }
JavaScript
0
@@ -2128,16 +2128,44 @@ will be +squeeze-and-excitation with only one @@ -2186,16 +2186,27 @@ volution +%0A * (i.e. e @@ -2214,27 +2214,16 @@ citation -%0A * pointwi @@ -2315,16 +2315,44 @@ will be +squeeze-and-excitation with two poin @@ -2369,16 +2369,27 @@ olutions +%0A * (i.e. i @@ -2409,27 +2409,16 @@ ointwise -%0A * convolu @@ -2421,16 +2421,17 @@ volution +, and exc @@ -3490,16 +3490,26 @@ bSqueeze +Excitation %0A * Wh @@ -3525,169 +3525,351 @@ eeze - step is necessary. If one of inputHeight and inputWidth is not positive (%3C= 0), bSqueeze will be false%0A * (i.e. no squeeze step (i.e. no global average pooling) +-and-excitation exists. It will be true if ( excitationChannelCountReductionRatio %3E= 0 ).%0A *%0A * @member %7Bboolean%7D bSqueeze%0A * Whether squeeze-and-excitation has squeeze. It will be true if ( excitationChannelCountReductionRatio %3E= 0 ) and ( inputHeight %3E 0 )%0A * and ( inputWidth %3E 0). It is only meaningful when ( bSqueezeExcitation == true ).%0A
057aaa1a64e9f90a56e04531ae793e777e421405
Update test app.
test/app/app.js
test/app/app.js
var _ = require('underscore'); var debug = require('debug')('test-app'); var express = require('express'); var FormidableGrid = require('../../lib/formidable-grid'); var gm = require('gm'); var logger = require('morgan'); var mongo = require('mongodb'); var GridFs = require('gridfs'); var util = require('util'); var port = process.env.PORT || 3000; function create_thumb(db, file) { return new Promise(function(resolve, reject) { var gfs = new GridFs(mongo, db); var id = new mongo.ObjectID(); var istream = gfs.createReadStream(file); var ostream = gfs.createWriteStream(id, { content_type: 'image/png' }); ostream .once('end', resolve.bind(null, { original: file, thumbnail: id.toString() })) .once('error', reject); gm(istream) .resize(256) .stream('png') .pipe(ostream); }); } function create_thumbs(db, files) { return Promise.all(_.map(files, create_thumb.bind(null, db))); } mongo.MongoClient.connect( 'mongodb://test:test@127.0.0.1:27017/test', {native_parser: true}, function (err, db) { debug('Connected to db'); var app = express(); app.use(logger('dev')); app.get('/', function(req, res) { res.send( '<!DOCTYPE html>' + '<html>' + '<head>' + '<title>FormidableGrid app test</title>' + '</head>' + '<body>' + '<form action="/upload" enctype="multipart/form-data" method="post">' + '<input type="file" name="file">' + '<input type="submit" value="upload">' + '</form>' + '</body>' + '</html>' ); }); app.post('/upload', function(req, res, next) { var form = new FormidableGrid(db, mongo, { accepted_field_names: [ /^file$/ ], accepted_mime_types: [ /^image\/.*/ ] }); form.parse(req) .then(function(form_data) { return _.pluck(form_data, 'file'); }) .then(function(files) { return create_thumbs(db, files); }) .then(function(result) { debug(util.format('-- %s', util.inspect(result))); res.send(result); }) .catch(next); }); app.get('/files/:id', function(req, res, next) { var gfs = new GridFs(mongo, db); var file_id = req.params.id; gfs.existsAsync(file_id) .then(function(exist) { if (! exist) { throw Object.create( new Error('File not found'), {status: {value: 404}} ); } return gfs.statAsync(file_id); }) .then(function(stats) { debug(util.format('-- %s', util.inspect(stats))); res.type(stats.contentType); gfs.createReadStream(file_id).pipe(res); }) .catch(next); }); // 404 not found app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers app.use(function(err, req, res, next) { debug(err); res.status(err.status || 500); res.send(err); }); app.listen(port, function() { debug('Express server listening on port ' + port); }); } );
JavaScript
0
@@ -511,16 +511,259 @@ ctID();%0A + gfs.existsAsync(file)%0A .then(function(exist) %7B%0A if (! exist) %7B%0A reject(new Error(util.format('Cannot create thumbnail because file %22%25s%22 does exist.')));%0A %7D else %7B%0A @@ -800,24 +800,36 @@ ream(file);%0A + var @@ -862,24 +862,36 @@ tream(id, %7B%0A + @@ -916,16 +916,28 @@ ge/png'%0A + @@ -948,16 +948,28 @@ + + ostream%0A @@ -972,32 +972,44 @@ eam%0A + + .once('end', res @@ -1042,16 +1042,28 @@ + original @@ -1086,16 +1086,28 @@ + + thumbnai @@ -1123,16 +1123,28 @@ tring()%0A + @@ -1151,16 +1151,28 @@ %7D))%0A + @@ -1195,24 +1195,36 @@ ', reject);%0A + gm(i @@ -1243,16 +1243,28 @@ + + .resize( @@ -1280,16 +1280,28 @@ + + .stream( @@ -1319,16 +1319,28 @@ + + .pipe(os @@ -1347,16 +1347,50 @@ tream);%0A + %7D%0A %7D);%0A %7D);%0A @@ -2451,16 +2451,28 @@ : %5B -/%5E +' file -$/ +', 'foo', 'gee' %5D,%0A @@ -2637,40 +2637,439 @@ -return _.pluck(form_data, 'file' +debug(util.inspect(form_data));%0A return _.chain(form_data)%0A .reject(_.partial(_.has, _, 'file'))%0A .map(function(data) %7B%0A return %5Bdata.field, data.value%5D;%0A %7D)%0A .object()%0A .extend(%7Bfiles: _.chain(form_data).pluck('file').compact().value()%7D)%0A .value( );%0A @@ -3117,21 +3117,20 @@ unction( -files +data ) %7B%0A @@ -3174,15 +3174,297 @@ db, +data. files) -; +%0A .then(function(pictures) %7B%0A return _.chain(data)%0A .omit('files')%0A .extend(%7Bpictures: pictures%7D)%0A .value();%0A %7D) %0A
3ec1fb756ed0ca395e800136e678f1e0c454800d
throw async errors in function-tree (#440)
packages/cerebral/src/Controller.js
packages/cerebral/src/Controller.js
import DependencyStore from './DependencyStore' import FunctionTree from 'function-tree' import Module from './Module' import Model from './Model' import {ensurePath, isDeveloping, throwError, isSerializable, verifyStrictRender} from './utils' import VerifyInputProvider from './providers/VerifyInput' import StateProvider from './providers/State' import DebuggerProvider from './providers/Debugger' import ControllerProvider from './providers/Controller' import EventEmitter from 'eventemitter3' import {dependencyStore as computedDependencyStore} from './Computed' /* The controller is where everything is attached. The devtools and router is attached directly. Also a top level module is created. The controller creates the function tree that will run all signals, based on top level providers and providers defined in modules */ class Controller extends EventEmitter { constructor ({state = {}, signals = {}, providers = [], modules = {}, router, devtools = null, options = {}}) { super() this.computedDependencyStore = computedDependencyStore this.componentDependencyStore = new DependencyStore() this.options = options this.flush = this.flush.bind(this) this.devtools = devtools this.model = new Model({}, this.devtools) this.module = new Module([], { state, signals, modules }, this) this.router = router ? router(this) : null const allProviders = [ ControllerProvider(this) ].concat( this.router ? [ this.router.provider ] : [] ).concat(( this.devtools ? [ DebuggerProvider() ] : [] )).concat(( isDeveloping() ? [ VerifyInputProvider ] : [] )).concat( StateProvider() ).concat( providers.concat(this.module.getProviders()) ) this.runTree = new FunctionTree(allProviders) this.runTree.on('asyncFunction', () => this.flush()) this.runTree.on('pathEnd', () => this.flush()) this.runTree.on('end', () => this.flush()) if (this.devtools) { this.devtools.init(this) } else if ( process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && /Chrome/.test(navigator.userAgent) ) { console.warn('You are not using the Cerebral devtools. It is highly recommended to use it in combination with the debugger: https://cerebral.github.io/cerebral-website/getting-real/03_devtools.html') } if (this.router) this.router.init() this.emit('initialized') } /* Whenever computeds and components needs to be updated, this method can be called */ flush (force) { const changes = this.model.flush() this.updateComputeds(changes, force) this.updateComponents(changes, force) this.emit('flush', changes, Boolean(force)) } updateComputeds (changes, force) { let computedsAboutToBecomeDirty if (force) { computedsAboutToBecomeDirty = this.computedDependencyStore.getAllUniqueEntities() } else if (this.options.strictRender) { computedsAboutToBecomeDirty = this.computedDependencyStore.getStrictUniqueEntities(changes) } else { computedsAboutToBecomeDirty = this.computedDependencyStore.getUniqueEntities(changes) } computedsAboutToBecomeDirty.forEach((computed) => { computed.flag() }) } /* On "flush" use changes to extract affected components from dependency store and render them */ updateComponents (changes, force) { let componentsToRender = [] if (force) { componentsToRender = this.componentDependencyStore.getAllUniqueEntities() } else if (this.options.strictRender) { componentsToRender = this.componentDependencyStore.getStrictUniqueEntities(changes) if (this.devtools && this.devtools.verifyStrictRender) { verifyStrictRender(changes, this.componentDependencyStore.map) } } else { componentsToRender = this.componentDependencyStore.getUniqueEntities(changes) } const start = Date.now() componentsToRender.forEach((component) => { if (this.devtools) { this.devtools.updateComponentsMap(component) } component._update(force) }) const end = Date.now() if (this.devtools && componentsToRender.length) { this.devtools.sendComponentsMap(componentsToRender, changes, start, end) } } /* Conveniance method for grabbing the model */ getModel () { return this.model } /* Method called by view to grab state */ getState (path) { return this.model.get(ensurePath(path)) } /* Checks if payload is serializable */ isSerializablePayload (payload) { if (!isSerializable(payload)) { return false } return Object.keys(payload).reduce((isSerializablePayload, key) => { if (!isSerializable(payload[key])) { return false } return isSerializablePayload }, true) } /* Uses function tree to run the array and optional payload passed in. The payload will be checkd */ runSignal (name, signal, payload = {}) { if (this.devtools && this.devtools.enforceSerializable && !this.isSerializablePayload(payload)) { throwError(`You passed an invalid payload to signal "${name}". Only serializable payloads can be passed to a signal`) } this.runTree(name, signal, payload || {}) } /* Returns a function which binds the name/path of signal, and the array. This allows view layer to just call it with an optional payload and it will run */ getSignal (path) { const pathArray = ensurePath(path) const signalKey = pathArray.pop() const module = pathArray.reduce((currentModule, key) => { return currentModule ? currentModule.modules[key] : undefined }, this.module) const signal = module && module.signals[signalKey] if (!signal) { throwError(`There is no signal at path "${path}"`) } return function (payload) { this.runSignal(path, signal, payload) }.bind(this) } } export default function (...args) { return new Controller(...args) }
JavaScript
0
@@ -5344,16 +5344,83 @@ oad %7C%7C %7B +%7D, (error) =%3E %7B%0A if (error) %7B%0A throw error%0A %7D%0A %7D)%0A %7D%0A
84e0073b38d37e89cc843b0089e5491e7a268f38
Address some vet issues in the Wizard
src/client/app/components/wizard/wizard-service.factory.js
src/client/app/components/wizard/wizard-service.factory.js
(function() { 'use strict'; angular.module('app.components') .factory('WizardService', WizardServiceFactory); /** @ngInject */ function WizardServiceFactory($modal, WizardQuestion) { var service = { showModal: showModal }; return service; function showModal() { var modalOptions = { templateUrl: 'app/components/wizard/wizard-modal.html', controller: WizardModalController, controllerAs: 'vm', resolve: { questions: resolveQuestions }, windowTemplateUrl: 'app/components/common/modal-window.html' }; var modal = $modal.open(modalOptions); return modal.result; function resolveQuestions() { return WizardQuestion.query().$promise; } } } /** @ngInject */ function WizardModalController(questions, lodash) { var vm = this; vm.state = 'intro'; vm.questions = questions; vm.question = null; vm.questionPointer = 0; vm.answeredQuestions = []; vm.startWizard = startWizard; vm.answerWith = answerWith; vm.questionNavigation = questionNavigation; activate(); function activate() { } function startWizard() { vm.question = vm.questions[vm.questionPointer]; vm.state = 'wizard'; } function answerWith(index) { if (0 <= index) { vm.answeredQuestions[vm.questionPointer] = vm.question.wizard_answers[index]; } else { vm.answeredQuestions[vm.questionPointer] = -1; } if (vm.questionPointer < vm.questions.length - 1) { vm.questionNavigation(1); } else { lodash.forEach(vm.answeredQuestions, parseQuestionAnswers); vm.state = 'complete'; } } function parseQuestionAnswers(item) { var filter; if (item !== -1) { filter = item.tags_to_remove; filter.unshift(lodash.union(vm.tags, item.tags_to_add)); vm.tags = lodash.without.apply(this, filter); } } function questionNavigation(direction) { vm.questionPointer = vm.questionPointer + direction; vm.question = vm.questions[vm.questionPointer]; } } })();
JavaScript
0
@@ -1328,34 +1328,8 @@ ) %7B%0A - if (0 %3C= index) %7B%0A @@ -1372,16 +1372,33 @@ inter%5D = + 0 %3E index ? -1 : vm.ques @@ -1428,86 +1428,8 @@ ex%5D; -%0A %7D else %7B%0A vm.answeredQuestions%5Bvm.questionPointer%5D = -1;%0A %7D %0A%0A @@ -1707,16 +1707,17 @@ filter;%0A +%0A if @@ -1875,20 +1875,18 @@ t.apply( -this +vm , filter
0c9aa0c670a91d6b5d1f5c6b892161cf8fb2ce70
添加view_parse返回结果判断
src/core/view.js
src/core/view.js
'use strict'; import path from 'path'; /** * view class * @return {} [] */ export default class extends think.http.base { /** * init method * @param {Object} http [] * @return {} [] */ init(http){ super.init(http); this.tVar = {}; } /** * assign * @param {String} name [] * @param {mixed} value [] * @return {} [] */ assign(name, value){ if (name === undefined) { return this.tVar; }else if (value === undefined) { if (think.isString(name)) { return this.tVar[name]; }else{ for(let key in name){ this.tVar[key] = name[key]; } } }else{ this.tVar[name] = value; } } /** * output template file * @param {String} templateFile [template filepath] * @param {String} charset [content encoding] * @param {String} contentType [content type] * @return {Promise} [] */ async display(templateFile, charset, contentType, config){ if(think.isObject(charset)){ config = charset; charset = ''; }else if(think.isObject(contentType)){ config = contentType; contentType = ''; } try{ await this.hook('view_before'); let content = await this.fetch(templateFile, undefined, config); await this.render(content, charset, contentType); await this.hook('view_after', content); }catch(err){ this.http.error = err; await think.statusAction(500, this.http, true); } return think.prevent(); } /** * render template content * @param {String} content [template content] * @param {String} charset [charset] * @param {String} contentType [contentType] * @return {} [] */ render(content = '', charset = this.http.config('encoding'), contentType = this.http.config('view.content_type')){ this.http.type(contentType, charset); return this.http.end(content, charset); } /** * check template filepath exist * @param {String} templateFile [template filepath] * @param {Boolean} inView [] * @return {Promise} [] */ checkTemplateExist(templateFile){ let cacheData = thinkData.template; if (templateFile in cacheData) { return true; } if (think.isFile(templateFile)) { //add template file to cache cacheData[templateFile] = true; return true; } return false; } /** * fetch template file content * @param {String} templateFile [template file] * @return {Promise} [] */ async fetch(templateFile, data, config){ let tVar = data && think.isObject(data) ? data : this.tVar; config = think.extend({ templateFile: templateFile }, this.config('view'), config); if (!templateFile || !path.isAbsolute(templateFile)) { templateFile = await this.hook('view_template', config); } if(!this.checkTemplateExist(templateFile)){ let err = new Error(think.locale('TEMPLATE_NOT_EXIST', templateFile)); return think.reject(err); } let promises = Object.keys(tVar).map((key) => { if (!think.isPromise(tVar[key])) { return; } return tVar[key].then((data) => { tVar[key] = data; }); }); await Promise.all(promises); let content = await this.hook('view_parse', { 'var': tVar, 'file': templateFile, 'config': config }); return this.hook('view_filter', content); } }
JavaScript
0
@@ -3312,55 +3312,35 @@ s);%0A - +%0A -let con -tent = await this.hook('view_p +st data4ViewP arse -', + = %7B%0A @@ -3409,26 +3409,155 @@ config%0A %7D -) ; +%0A let content = await this.hook('view_parse', data4ViewParse);%0A if (data4ViewParse === content) %7B%0A content = '';%0A %7D%0A %0A return
d81a2d1ac15443d617cd462d8c3f8bb7a7b7e8c9
Update tests.
lib/serialize-log-result.spec.js
lib/serialize-log-result.spec.js
var serializeLogResult = require('./serialize-log-result').serializeLogResult, _countObjectProperties = require('./serialize-log-result')._countObjectProperties; describe('Serialization of non-string primitives', function(){ it('Just calls toString on numbers and booleans', function(){ expect(serializeLogResult(88.22)).toBe("88.22"); expect(serializeLogResult(false)).toBe("false"); }) it('Should return the normal names for undefined and null', function(){ expect(serializeLogResult(undefined)).toBe("undefined"); expect(serializeLogResult(null)).toBe("null"); }); it('Should just return strings the way they are', function(){ expect(serializeLogResult('string')).toBe('"string"'); }); it('Should be able to count object properties', function(){ expect(_countObjectProperties({a: 1, b:2})).toBe(2); }) });
JavaScript
0
@@ -614,16 +614,214 @@ %7D);%0A + it('Should handle arrays decently', function()%7B%0A expect(serializeLogResult(%5B1,2,3%5D)).toBe('%5B1, 2, 3%5D');%0A expect(serializeLogResult(%5B'1','2','3'%5D)).toBe('%5B%221%22, %222%22, %223%22%5D');%0A %7D);%0A it('
c28393a0410c67a887e81155e21e189068bf5492
Add PreviewGraph prop types.
assets/js/modules/search-console/components/dashboard/SearchFunnelWidget/PreviewGraph.js
assets/js/modules/search-console/components/dashboard/SearchFunnelWidget/PreviewGraph.js
/** * PreviewGraph component. * * Site Kit by Google, Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import UpArrow from '../../../../../../svg/icons/cta-graph-arrow-up.svg'; export default function PreviewGraph( { title, GraphSVG } ) { return ( <div className="googlesitekit-cta--graph"> <div className="googlesitekit-cta--graph--title">{ title }</div> <div> <GraphSVG /> </div> <div className="googlesitekit-cta--graph--icons"> <UpArrow className="googlesitekit-cta--graph--up-arrow" /> <div className="googlesitekit-cta--graph--bar" /> </div> </div> ); }
JavaScript
0
@@ -640,16 +640,86 @@ e.%0A */%0A%0A +/**%0A * External dependencies%0A */%0Aimport PropTypes from 'prop-types';%0A%0A /**%0A * I @@ -1234,8 +1234,121 @@ %3E%0A%09);%0A%7D%0A +%0APreviewGraph.propTypes = %7B%0A%09title: PropTypes.string.isRequired,%0A%09GraphSVG: PropTypes.elementType.isRequired,%0A%7D;%0A
74334444711ed60d0b9a2dbcd61a5f697d10f957
Use the static class references rather than dynamic ones
source/classes/Westley.js
source/classes/Westley.js
(function(module) { "use strict"; var Inigo = require("__buttercup/classes/InigoGenerator.js"), commandTools = require("__buttercup/tools/command.js"), searching = require("__buttercup/tools/searching.js"), entry = require("__buttercup/tools/entry.js"); var VALID_COMMAND_EXP = /^[a-z]{3}[ ].+$/; var commandClasses = { cen: require("__buttercup/classes/commands/command.cen.js"), cgr: require("__buttercup/classes/commands/command.cgr.js"), cmm: require("__buttercup/classes/commands/command.cmm.js"), dea: require("__buttercup/classes/commands/command.dea.js"), dem: require("__buttercup/classes/commands/command.dem.js"), den: require("__buttercup/classes/commands/command.den.js"), dga: require("__buttercup/classes/commands/command.dga.js"), dgr: require("__buttercup/classes/commands/command.dgr.js"), fmt: require("__buttercup/classes/commands/command.fmt.js"), men: require("__buttercup/classes/commands/command.men.js"), mgr: require("__buttercup/classes/commands/command.mgr.js"), pad: require("__buttercup/classes/commands/command.pad.js"), sea: require("__buttercup/classes/commands/command.sea.js"), sem: require("__buttercup/classes/commands/command.sem.js"), sep: require("__buttercup/classes/commands/command.sep.js"), sga: require("__buttercup/classes/commands/command.sga.js"), tgr: require("__buttercup/classes/commands/command.tgr.js") }; /** * Westley. Archive object dataset and history manager. Handles parsing and * revenge for the princess. * @class Westley */ var Westley = function() { this.clear(); }; /** * Clear the dataset and history * @returns {Westley} Returns self * @memberof Westley */ Westley.prototype.clear = function() { this._dataset = {}; this._history = []; this._cachedCommands = {}; return this; }; /** * Execute a command - stored in history and modifies the dataset * @param {String} command The command to execute * @returns {Westley} Returns self * @memberof Westley */ Westley.prototype.execute = function(command) { if (!VALID_COMMAND_EXP.test(command)) { throw new Error("Invalid command"); } var commandComponents = commandTools.extractCommandComponents(command), commandKey = commandComponents.shift(); var commandObject = this._getCommandForKey(commandKey); this._history.push(command); commandObject.execute.apply(commandObject, [this._dataset].concat(commandComponents)); return this; }; /** * Gets a command by its key from the cache with its dependencies injected * @param {String} commandKey The key of the command * @returns {Command} Returns the command * @memberof Westley */ Westley.prototype._getCommandForKey = function(commandKey) { // If the command doesn't exist in the cache if (this._cachedCommands[commandKey] === undefined) { // Get the command object and inject its dependencies var requirement = new (require("__buttercup/classes/commands/command." + commandKey + ".js"))(); if (requirement.injectSearching !== undefined) { requirement.injectSearching(searching); } if (requirement.injectEntry !== undefined) { requirement.injectEntry(entry); } // Store it in the cache this._cachedCommands[commandKey] = requirement; } return this._cachedCommands[commandKey]; }; /** * Insert a padding in the archive (used for delta tracking) * @returns {Westley} Returns self * @memberof Westley */ Westley.prototype.pad = function() { this.execute(Inigo.generatePaddingCommand()); return this; }; /** * Get the core dataset * @returns {Object} * @memberof Westley */ Westley.prototype.getDataset = function() { return this._dataset; }; /** * Get the history (deltas) * @returns {String[]} * @memberof Westley */ Westley.prototype.getHistory = function() { return this._history; }; module.exports = Westley; })(module);
JavaScript
0
@@ -2918,58 +2918,23 @@ ew ( -require(%22__buttercup/classes/commands/command.%22 + +commandClasses%5B comm @@ -2943,17 +2943,9 @@ dKey - + %22.js%22) +%5D )();
f21fa3b6f80f8088c9ea9211e6a79a21f44753ac
Correct the order to make sense after the optimization/caching fix.
source/moon-resolution.js
source/moon-resolution.js
(function(enyo, scope) { /** * Instantiates and loads [iLib]{@link ilib} and its resources. * * @private */ scope.moon = scope.moon || {}; var baseScreenType = 'fhd', riRatio, screenType, screenTypeObject; /** * A hash-store of all of our detectable screen types in incrementing sizes. * * @public */ scope.moon.screenTypes = [ {name: 'hd', pxPerRem: 8, height: 720, width: 1280}, {name: 'fhd', pxPerRem: 12, height: 1080, width: 1920}, {name: 'uhd', pxPerRem: 24, height: 2160, width: 3840} ]; var getScreenTypeObject = function (name) { if (name == screenType && screenTypeObject) { return screenTypeObject; } var types = scope.moon.screenTypes; return types.filter(function (elem) { return (name == elem.name); })[0]; }; /** * Fetches the best-matching screen type name for the current screen size. The "best" screen type * is determined by the screen type name that is the closest to the screen resolution without * going over. ("The Price is Right" style.) * * @param {Object} [rez] - Optional measurement scheme. Must have "height" and "width" properties. * @returns {String} Screen type, like "fhd", "uhd", etc. * @name moon.$L * @public */ scope.moon.getScreenType = function (rez) { rez = rez || { height: scope.innerHeight, width: scope.innerWidth }; var i, types = this.screenTypes, bestMatch = types[types.length - 1].name; // loop thorugh resolutions for (i = types.length - 1; i >= 0; i--) { // find the one that matches our current size or is smaller. default to the first. if (rez.width <= types[i].width) { bestMatch = types[i].name; } } // return the name of the resolution if we find one. return bestMatch; }; scope.moon.updateScreenTypeOnBody = function (type) { type = type || screenType; if (type) { enyo.dom.addBodyClass('moon-res-' + type.toLowerCase()); return type; } }; scope.moon.getRiRatio = function (type) { type = type || screenType; if (type) { return this.getUnitToPixelFactors(type) / this.getUnitToPixelFactors(baseScreenType); } return 1; }; scope.moon.getUnitToPixelFactors = function (type) { type = type || screenType; if (type) { return getScreenTypeObject(type).pxPerRem; } return 1; }; scope.moon.riScale = function (px) { return (riRatio || this.getRiRatio()) * px; // return (riRatio || this.getRiRatio()) * px; }; scope.moon.initResolution = function () { this.updateScreenTypeOnBody(); screenType = this.getScreenType(); enyo.dom.unitToPixelFactors.rem = scope.moon.getUnitToPixelFactors(); screenTypeObject = getScreenTypeObject(); riRatio = this.getRiRatio(); }; // This will need to be re-run any time the screen size changes, so all the values can be re-cached. scope.moon.initResolution(); })(enyo, this);
JavaScript
0.999949
@@ -2464,62 +2464,56 @@ %7B%0A%09%09 -this.updateScreenTypeOnBody();%0A%09%09screenType = this.get +screenType = this.getScreenType();%0A%09%09this.update Scre @@ -2514,24 +2514,30 @@ teScreenType +OnBody ();%0A%09%09enyo.d
183594feb0e922bcd882d407ad9dca558480b5f1
Add `buffer as options.body` test
test/headers.js
test/headers.js
import fs from 'fs'; import util from 'util'; import path from 'path'; import test from 'ava'; import FormData from 'form-data'; import got from '../source'; import pkg from '../package'; import {createServer} from './helpers/server'; let s; test.before('setup', async () => { s = await createServer(); s.on('/', (request, response) => { request.resume(); response.end(JSON.stringify(request.headers)); }); await s.listen(s.port); }); test.after('cleanup', async () => { await s.close(); }); test('user-agent', async t => { const headers = (await got(s.url, {json: true})).body; t.is(headers['user-agent'], `${pkg.name}/${pkg.version} (https://github.com/sindresorhus/got)`); }); test('accept-encoding', async t => { const headers = (await got(s.url, {json: true})).body; t.is(headers['accept-encoding'], 'gzip, deflate'); }); test('do not override accept-encoding', async t => { const headers = (await got(s.url, { json: true, headers: { 'accept-encoding': 'gzip' } })).body; t.is(headers['accept-encoding'], 'gzip'); }); test('do not set accept-encoding header when decompress options is false', async t => { const {body: headers} = await got(s.url, { json: true, decompress: false }); t.false(Reflect.has(headers, 'accept-encoding')); }); test('accept header with json option', async t => { let headers = (await got(s.url, {json: true})).body; t.is(headers.accept, 'application/json'); headers = (await got(s.url, { headers: { accept: '' }, json: true })).body; t.is(headers.accept, ''); }); test('host', async t => { const headers = (await got(s.url, {json: true})).body; t.is(headers.host, `localhost:${s.port}`); }); test('transform names to lowercase', async t => { const headers = (await got(s.url, { headers: { 'USER-AGENT': 'test' }, json: true })).body; t.is(headers['user-agent'], 'test'); }); test('zero content-length', async t => { const {body} = await got(s.url, { headers: { 'content-length': 0 }, body: 'sup' }); const headers = JSON.parse(body); t.is(headers['content-length'], '0'); }); test('form-data manual content-type', async t => { const form = new FormData(); form.append('a', 'b'); const {body} = await got(s.url, { headers: { 'content-type': 'custom' }, body: form }); const headers = JSON.parse(body); t.is(headers['content-type'], 'custom'); }); test('form-data automatic content-type', async t => { const form = new FormData(); form.append('a', 'b'); const {body} = await got(s.url, { body: form }); const headers = JSON.parse(body); t.is(headers['content-type'], `multipart/form-data; boundary=${form.getBoundary()}`); }); test('form-data sets content-length', async t => { const form = new FormData(); form.append('a', 'b'); const {body} = await got(s.url, {body: form}); const headers = JSON.parse(body); t.is(headers['content-length'], '157'); }); test('stream as options.body sets content-length', async t => { const fixture = path.join(__dirname, 'fixtures/stream-content-length'); const {size} = await util.promisify(fs.stat)(fixture); const {body} = await got(s.url, { body: fs.createReadStream(fixture) }); const headers = JSON.parse(body); t.is(Number(headers['content-length']), size); }); test('remove null value headers', async t => { const {body} = await got(s.url, { headers: { 'user-agent': null } }); const headers = JSON.parse(body); t.false(Reflect.has(headers, 'user-agent')); }); test('setting a header to undefined keeps the old value', async t => { const {body} = await got(s.url, { headers: { 'user-agent': undefined } }); const headers = JSON.parse(body); t.not(headers['user-agent'], undefined); }); test('non-existent headers set to undefined are omitted', async t => { const {body} = await got(s.url, { headers: { blah: undefined } }); const headers = JSON.parse(body); t.false(Reflect.has(headers, 'blah')); });
JavaScript
0.00001
@@ -3250,24 +3250,280 @@ size);%0A%7D);%0A%0A +test('buffer as options.body sets content-length', async t =%3E %7B%0A%09const buffer = Buffer.from('unicorn');%0A%09const %7Bbody%7D = await got(s.url, %7B%0A%09%09body: buffer%0A%09%7D);%0A%09const headers = JSON.parse(body);%0A%09t.is(Number(headers%5B'content-length'%5D), buffer.length);%0A%7D);%0A%0A test('remove
61305c06e6d5b67ad2aa04f919bb8bee804e61c5
Include proper file for DataServer dependency
src/dashboard.js
src/dashboard.js
(function($) { "use strict"; if (Echo.AppServer.Dashboard.isDefined("Echo.Apps.RecentParticipants.Dashboard")) return; var dashboard = Echo.AppServer.Dashboard.manifest("Echo.Apps.RecentParticipants.Dashboard"); dashboard.inherits = Echo.Utils.getComponent("Echo.AppServer.Dashboards.AppSettings"); dashboard.mappings = { "dependencies.appkey": { "key": "dependencies.StreamServer.appkey" } }; dashboard.dependencies = [{ "url": "{config:cdnBaseURL.apps.appserver}/controls/configurator.js", "control": "Echo.AppServer.Controls.Configurator" }, { "url": "{config:cdnBaseURL.apps.dataserver}/full.pack.js", "control": "Echo.DataServer.Controls.Pack" }, { "url": "//cdn.echoenabled.com/apps/echo/social-map/v1/slider.js" }]; dashboard.config.ecl = [{ "component": "Group", "name": "presentation", "type": "object", "config": { "title": "Presentation" }, "items": [{ "component": "Slider", "name": "avatarSize", "type": "number", "default": 48, "config": { "title": "Avatar size", "desc": "Specifies user avatar size (in px)", "min": 10, "max": 100, "step": 1, "unit": "px" } }, { "component": "Slider", "name": "maxParticipants", "type": "number", "default": 15, "config": { "title": "Maximum participants", "desc": "Specifies maximum amount of participants to be displayed at app load time. Note: new participants will be attached to the list.", "min": 5, "max": 50, "step": 1 } }, { "component": "Input", "name": "maxWidth", "type": "number", "config": { "title": "Maximum width", "desc": "Specify a maximum width (in pixels) of an App container", "data": {"sample": 500} } }, { "component": "Input", "name": "maxHeight", "type": "number", "config": { "title": "Maximum height", "desc": "Specify a maximum height (in pixels) of an App container", "data": {"sample": 300} } }] }, { "component": "Group", "name": "dependencies", "type": "object", "config": { "title": "Dependencies", "expanded": false }, "items": [{ "component": "Select", "name": "appkey", "type": "string", "config": { "title": "StreamServer application key", "desc": "Specifies the application key for this instance", "options": [] } }] }, { "name": "targetURL", "component": "Echo.DataServer.Controls.Dashboard.DataSourceGroup", "type": "string", "required": true, "config": { "title": "", "expanded": false, "labels": { "dataserverBundleName": "Echo Recent Participants Auto-Generated Bundle for {instanceName}" }, "apiBaseURLs": { "DataServer": "{%= apiBaseURLs.DataServer %}/" } } }]; dashboard.modifiers = { "dependencies.appkey": { "endpoint": "customer/{self:user.getCustomerId}/appkeys", "processor": function() { return this.getAppkey.apply(this, arguments); } }, "targetURL": { "endpoint": "customer/{self:user.getCustomerId}/subscriptions", "processor": function() { return this.getBundleTargetURL.apply(this, arguments); } } }; dashboard.init = function() { this.parent(); }; Echo.AppServer.Dashboard.create(dashboard); })(Echo.jQuery);
JavaScript
0
@@ -600,12 +600,18 @@ er%7D/ -full +dashboards .pac
60d62efefb50d973f81de1dcb247d0bb205add5f
Fix another typo
src/directive.js
src/directive.js
/* global angular */ (function() { 'use strict'; function Radio($rootScope) { var Radio = { CheckedEvent: 'radio.checked', setCheckedView: function($element) { $element.attr('checked', 'checked'); $element.find('.radio-toggle').addClass('checked'); }, setUncheckedView: function($element) { $element.removeAttr('checked'); $element.find('.radio-toggle').removeClass('checked'); }, isChecked: function($element) { return $element.attr('checked') === 'checked'; }, isEnabled: function($element) { return $element.attr('disabled') !== 'disabled'; }, shouldCheck: function($element) { return (this.isEnabled($element) && !(this.isChecked($element))); }, setEnabledView: function($element) { $element.removeAttr('disabled'); $element.find('.radio-toggle').removeClass('disabled'); }, setDisabledView: function($element) { $element.attr('disabled', 'disabled'); $element.find('.radio-toggle').addClass('disabled'); } }; function link($scope, $element, $attr, ctrls) { function ngModelLink($scope, $element, $attr, $ctrl) { $element.click(function() { if (Radio.shouldCheck($element)) { Radio.setCheckedView($element); $scope.$apply(function() { $ctrl.$setViewValue($attr.value); }); } }); $scope.$watch($attr.ngModel, function() { if (!angular.isDefined($ctrl.$viewValue) || $ctrl.$viewValue !== $attr.value) { Radio.setUncheckedView($element); } else if ($ctrl.$viewValue === $attr.value) { Radio.setCheckedView($element); } }); } function simulateNativeRadio($scope, $element, $attr) { $element.click(function() { if (Radio.shouldCheck($element)) { $attr.$set('checked', 'checked'); } }); $scope.$on(Radio.CheckedEvent, function(event, value) { if ($element.attr('value') !== value) { Radio.setUncheckedView($element); } }); $attr.$observe('checked', function() { if (Radio.isChecked($element)) { Radio.setCheckedView($element); $rootScope.$broadcast(Radio.CheckedEvent, $element.attr('value')); } else { Radio.uncheck($element); } }); $attr.$observe('disabled', function() { if (Radio.isEnabled($element)) { Radio.setEnabledView($element); } else { Radio.setDisabledView($element); } }); } if (Radio.isChecked($element)) { Radio.setCheckedView($element); } if (!Radio.isEnabled($element)) { Radio.setDisabledView($element); } if (ctrls[0]) { ngModelLink($scope, $element, $attr, ctrls[0]); } else { simulateNativeRadio($scope, $element, $attr); } } return { replace: true, restrict: 'AE', transclude: true, priority: 0, require: ['?ngModel'], link: link, template: [ '<div class="radio-input">', ' <div class="radio-toggle" ng-class="{\'checked\': checked, \'disabled\': disabled}"/>', ' <span class="label-text" ng-transclude/>', '</div>' ].join('') } } angular.module('corespring.input.radio', []).directive('radio', ['$rootScope', Radio]); })();
JavaScript
1
@@ -2458,15 +2458,24 @@ dio. -u +setU ncheck +edView ($el
6c8d530abaa6d1c66132e1cf30d71ef7bd109ce2
Remove alerts by logs
src/directive.js
src/directive.js
angular.module('angular-cordova-file') .directive('cordovaFile', function ($injector, $q, $timeout, $parse, CordovaFile) { var sourcesMapping = typeof Camera != "undefined" ? { camera: Camera.PictureSourceType.CAMERA, photoLibrary: Camera.PictureSourceType.PHOTOLIBRARY } : {}; /** * Request picture from specified source. * * @param sourceType * @returns promise */ function requestPictureFromSource (sourceType, options) { var deferred = $q.defer(); navigator.camera.getPicture(function (fileUri) { if (fileUri.indexOf("://") == -1) { fileUri = 'file://'+fileUri; } else if (fileUri.substr(0, 10) == 'content://') { // Currently not supported by Android because of a bug // @see https://issues.apache.org/jira/browse/CB-5398 return deferred.reject('Image provider not supported'); } var file = CordovaFile.fromUri(fileUri); file.set('contentType', 'image/png'); deferred.resolve([file]); }, function (reason) { deferred.reject(reason); }, angular.extend({ quality: 100, sourceType: sourceType, destinationType: Camera.DestinationType.FILE_URI, encodingType: Camera.EncodingType.PNG, correctOrientation: true }, options)); return deferred.promise; } /** * Modal controller of input. * */ function fileInputController ($scope, $modalInstance, options) { function getPictureFromSource (sourceType) { requestPictureFromSource(sourceType, options).then(function(files) { $modalInstance.close(files); }, function (reason) { $modalInstance.dismiss(reason); }); } $scope.close = function() { $modalInstance.dismiss('canceled'); }; $scope.takePicture = function () { getPictureFromSource(Camera.PictureSourceType.CAMERA); }; $scope.fromLibrary = function () { getPictureFromSource(Camera.PictureSourceType.PHOTOLIBRARY); }; } return { link: function (scope, element, attributes) { var fn = $parse(attributes.cordovaFile), options = {}, source; if (attributes.options) { scope.$watch(attributes.options, function (value) { options = value || options; }); } if (attributes.source) { scope.$watch(attributes.source, function (value) { source = value; }); } element.on('change', function (e) { if (typeof Camera == "undefined") { var files = [], fileList, i; fileList = e.target.files; if (fileList != null) { for (i = 0; i < fileList.length; i++) { files.push(CordovaFile.fromFile(fileList.item(i))); } } $timeout(function() { fn(scope, { $files : files, $event : e }); }); } }); element.on('click', function (event) { if (typeof Camera != "undefined") { event.preventDefault(); if (source !== undefined) { if (!(source in sourcesMapping)) { throw new Error(source+' data source not found'); } requestPictureFromSource(sourcesMapping[source], options).then(function (files) { $timeout(function() { fn(scope, { $files : files, $event : {} }); }); }, function (reason) { alert(reason); }); } else if ($injector.has('$modal')) { var modalInstance = $injector.get('$modal').open({ templateUrl: 'template/cordova-file/choice.html', controller: fileInputController, resolve: { options: function () { return options; } } }); modalInstance.result.then(function (files) { $timeout(function() { fn(scope, { $files : files, $event : {} }); }); }, function (reason) { alert(reason); }); scope.$on('$destroy', function () { modalInstance.dismiss('Scope destroyed'); }); } else { throw new Error('If no `data-source` attribute is specified, `$modal` must be available' + ' (see `angular-ui-bootstrap` or another implementation)'); } } }); } }; });
JavaScript
0
@@ -4677,37 +4677,117 @@ -alert +console.log('Unable to request picture');%0A console.log (reason);%0A @@ -5809,13 +5809,19 @@ -alert +console.log (rea
5d4e76d2dbc0627557f1503f07447193be012048
Create a better fluent example in the tests
test/replace.js
test/replace.js
var replace = require( "../src/str-replace" ); module.exports = { replace_all: function( assert ) { var actual = replace .all( "/" ) .from( "/home/dir" ) .to( "\\" ); var expected = "\\home\\dir"; assert.strictEqual( actual, expected ); assert.done(); }, replace_all_ignoring_case: function( assert ) { var actual = replace .all( "G" ) .ignoreCase() .from( "Eggs" ) .to( "f" ); var expected = "Effs"; assert.strictEqual( actual, expected ); assert.done(); } };
JavaScript
0.999779
@@ -379,9 +379,13 @@ l( %22 -G +house %22 )%0A @@ -424,11 +424,18 @@ m( %22 -Egg +Many House s%22 ) @@ -447,17 +447,21 @@ .to( %22 -f +Horse %22 );%0A @@ -481,11 +481,18 @@ = %22 -Eff +Many Horse s%22;%0A
56f42abb6de41f26da204e312ea6d36f4ec74d66
Fix date
Project/sun.js
Project/sun.js
var APIEndPoint = "http://api.sunrise-sunset.org/json?" var date; $(document).ready(function() { // Put your code in here! updateTime(); getLocation(); }); function updateTime() { date = new Date(); time = date.getTime(); time = Math.round(time / 1000); var dayArray = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; $("#date_section #day_of_week").text(dayArray[moment.unix(time).format("E")-1]); $("#date_section #date").text(moment.unix(time).format("MMMM DD, YYYY")); } function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(getSunPosFromAPI); } else { displayError({ "errorTitle": "Sorry", "errorText": "Geolocation is not supported by this browser."}); } } function showPosition(position) { var innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; $("#content").html("<h4>"+innerHTML+"<h4>"); } function getSunPosFromAPI(position) { $.getJSON(APIEndPoint + "lat=" + position.coords.latitude + "&lng=" + position.coords.longitude + "&date=today" + "&callback=?") .done(parseData) .fail(getAPIError); } function getAPIError() { displayError({ "errorTitle": "Sorry", "errorText": "Refresh Me! - Service Temporarily Unavailable"}); } function parseData(data) { $("#sun-rise .time").text(getLocalDateFromUTCDate(data["results"]["sunrise"])); $("#noon .time").text(getLocalDateFromUTCDate(data["results"]["solar_noon"])); $("#sun-set .time").text(getLocalDateFromUTCDate(data["results"]["sunset"])); } //helper functions function displayError(errorInfo) { var item_html = $("#error-prototype").html(); var innerHTML = Mustache.render(item_html, errorInfo); $("#content").html(innerHTML); } function getLocalDateFromUTCDate(utcDateString) { var offsetHours = date.getTimezoneOffset() / 60; var localDate = new Date(utcDateString).addHours(offsetHours); return moment.unix(localDate.toString()).format("HH:MM:SS A"); } Date.prototype.addHours= function(h){ this.setHours(this.getHours()+h); return this; }
JavaScript
0.999998
@@ -1934,20 +1934,22 @@ e = new -Date +moment (utcDate @@ -1959,21 +1959,16 @@ ing).add -Hours (offsetH @@ -1971,16 +1971,25 @@ setHours +, 'hours' );%0A%0A @@ -1999,157 +1999,38 @@ urn -moment.unix(localDate.toString()).format(%22HH:MM:SS A%22);%0A%7D%0A%0ADate.prototype.addHours= function(h)%7B%0A this.setHours(this.getHours()+h);%0A return this;%0A%7D +localDate.format(%22HH:MM:SS A%22);%0A%7D%0A
a6fff98360e324be3f1262423a36099982c3e583
Change ProjectView from a tabstack to an HBox.
ProjectView.js
ProjectView.js
"use strict"; var ProjectView = JakeKit.w2tabstack.extend({ initialize: function() { JakeKit.w2tabstack.prototype.initialize.call(this); this.views = {}; this.schemas = {}; this.history = []; this.history_position = 0; _.bindAll(this, "openTab", "schemaNameChanged"); this.listenTo(this, "viewSelected", this.viewSelected); }, setProject: function(project) { var that = this; // Get rid of any existing views _.each(this.views, function(view, id) { this.removeChild(view); }); this.views = {}; this.data = project; this.schemas = new SchemaList(); this.schemas.fetch({ conditions: { project_id: this.data.id }, success: function() { var open_tabs = that.data.get("open_tabs"); if (_.size(open_tabs) == 0) { that.newTab(); //need to select the tab as well } else { _.each(open_tabs, function(schema_id) { var schema = that.schemas.get(schema_id); that.openTab(schema); }); var selected_tab = that.data.get("selected_tab"); if (!selected_tab) { selected_tab = open_tabs[0].schema_id; this.data.set("selected_tab", selected_tab); } that.selectTab(that.views[selected_tab]); } that.schemas.on("change:name", that.schemaNameChanged); }, error: function() { console.log("error"); console.log(arguments); } }); }, newTab: function() { var new_schema = new Schema({ project_id: this.data.id, contains: [], contains_recursive: [], name: "New Schema" }); new_schema.save({}, { success: this.openTab }); }, openTab: function(schema) { var new_view = new SchemaView(schema, this); this.views[schema.id] = new_view; this.addChild(new_view, schema.get("name")); var open_tabs = this.data.get("open_tabs"); if (! _.contains(open_tabs, schema.id)) { this.data.set("open_tabs", open_tabs.concat(new_view.id)); } }, selectTab: function(view) { this.data.set("selected_tab", view.schema_data.id); this.data.save(); this.makeActive(view); }, viewSelected: function(view) { this.data.set("selected_tab", view.schema_data.id); this.data.save(); }, activeSchema: function() { return this.activeView().schema; }, schemaNameChanged: function(schema) { this.setCaption(this.views[schema.id], schema.get("name")); }, record: function(action) { if (this.history_position != this.history.length) { // We need to get rid of redo history this.history = _.first(this.history, this.history_position); } this.history.push(action); this.history_position++; }, undo: function() { if (this.history_position > 0) { var last_action = this.history[this.history_position - 1]; var undo_action = last_action.inverse(); undo_action.doTo(this.views[undo_action.schemaID()].model); this.history_position--; this.views[undo_action.schemaID()].saveSchema(); } }, redo: function() { if (this.history_position < this.history.length) { var action = this.history[this.history_position]; action.doTo(this.views[action.schemaID()].model); this.history_position++; this.views[action.schemaID()].saveSchema(); } }, deleteSelection: function() { this.activeView().deleteSelection(); } }); var ComponentView = Backbone.View.extend({ render: function() { var html = "Hi you bam pots"; this.$el.html(html); return this; } }); var ComponentList = Backbone.View.extend({ render: function() { this.collection.each(function(component) { var component_view = new ComponentView({ model: component }); this.$el.append(component_view.render().el); }, this); } });
JavaScript
0
@@ -34,26 +34,20 @@ JakeKit. -w2tabstack +HBox .extend( @@ -126,24 +126,100 @@ call(this);%0A +%09%09this.tabstack = new JakeKit.w2tabstack();%0A%09%09this.addChild(this.tabstack);%0A %09%09this.views @@ -367,16 +367,25 @@ nTo(this +.tabstack , %22viewS @@ -1773,32 +1773,41 @@ ew_view;%0A%09%09this. +tabstack. addChild(new_vie @@ -2105,16 +2105,25 @@ %0A%09%09this. +tabstack. makeActi @@ -2365,16 +2365,25 @@ %0A%09%09this. +tabstack. setCapti @@ -3298,24 +3298,24 @@ unction() %7B%0A - %09%09this.activ @@ -3341,16 +3341,85 @@ tion();%0A +%09%7D,%0A%09%0A%09activeView: function() %7B%0A%09%09return this.tabstack.activeView();%0A %09%7D%0A%09%09%0A%7D)
816848974e3675626dab63c62dbe730a16abfd8c
Desactiva botón asíncronamente
webapp/static/js/main.js
webapp/static/js/main.js
var data = { username: '', password: '' } /* eslint-disable no-new */ /* eslint-disable no-undef */ new Vue({ el: '#app', data: data, methods: { setLoading: function (message) { var el = message.target el.disabled = true el.setAttribute('value', el.getAttribute('data-loading-text')) } }, delimiters: ['${', '}'] })
JavaScript
0.000001
@@ -216,16 +216,49 @@ .target%0A + setTimeout(function () %7B%0A el @@ -274,16 +274,28 @@ = true%0A + %7D, 0)%0A el
b5de2d8498d4268f7c26e170059527499744b49e
remove unnecessary require
webpack/common.config.js
webpack/common.config.js
const path = require('path'); // webpack plugins const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin'); module.exports = { entry: { 'app': [ './src/bootstrap.js' ], 'vendor': './src/vendor.js' }, resolve: { extensions: ['.js', '.scss'], modules: ['node_modules'] }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: ['babel-loader', 'eslint-loader'] }, { test: /\.json$/, loader: 'json' }, { test: /\.(jpg|png|gif|eot|svg|ttf|woff|woff2)$/, loader: 'file', }, { test: /\.(mp4|webm)$/, loader: 'url?limit=10000' } ] }, plugins: [ new CommonsChunkPlugin({ name: ['app', 'vendor'], minChunks: Infinity }) ] };
JavaScript
0.000002
@@ -1,35 +1,4 @@ -const path = require('path');%0A%0A // w
39081f8ab76c57c47a84c2fc80bfe4f1df8734e1
Exclude admin directory for plugin dictionary
packages/strapi/lib/configuration/hooks/dictionary/_config/index.js
packages/strapi/lib/configuration/hooks/dictionary/_config/index.js
'use strict'; /** * Module dependencies */ // Node.js core. const path = require('path'); // Public node modules. const _ = require('lodash'); const async = require('async'); // Strapi utilities. const dictionary = require('strapi-utils').dictionary; /** * Async module loader to create a * dictionary of the user config */ module.exports = strapi => { return { /** * Initialize the hook */ initialize: cb => { async.auto( { // Load common settings from `./config/*.js|json`. 'config/*': cb => { dictionary.aggregate( { dirname: path.resolve( strapi.config.appPath, strapi.config.paths.config ), excludeDirs: /(locales|environments|policies)$/, filter: /(.+)\.(js|json)$/, depth: 2 }, cb ); }, // Load locales from `./config/locales/*.json`. 'config/locales/*': cb => { dictionary.optional( { dirname: path.resolve( strapi.config.appPath, strapi.config.paths.config, 'locales' ), filter: /(.+)\.(json)$/, identity: false, depth: 1 }, cb ); }, // Load functions config from `./config/functions/*.js`. 'config/functions/*': cb => { dictionary.optional( { dirname: path.resolve( strapi.config.appPath, strapi.config.paths.config, 'functions' ), filter: /^(?!bookshelf)((.+)\.(js))$/, depth: 1, replaceExpr: '.js', replaceVal: '' }, cb ); }, // Load functions config from `./config/functions/*.js`. 'config/functions/responses/*': cb => { dictionary.optional( { dirname: path.resolve( strapi.config.appPath, strapi.config.paths.config, 'functions', 'responses' ), filter: /(.+)\.(js|json)$/, depth: 1 }, cb ); }, // Load all environments config from `./config/environments/*/*.js|json`. // Not really used inside the framework but useful for the Studio. 'config/environments/**': cb => { dictionary.optional( { dirname: path.resolve( strapi.config.appPath, strapi.config.paths.config, 'environments' ), filter: /(.+)\.(js|json)$/, identity: false, depth: 3 }, cb ); }, // Load environment-specific config from `./config/environments/**/*.js|json`. 'config/environments/*': cb => { dictionary.aggregate( { dirname: path.resolve( strapi.config.appPath, strapi.config.paths.config, 'environments', strapi.config.environment ), filter: /(.+)\.(js|json)$/, depth: 1 }, cb ); }, // Load global policies from `./config/policies/*.js`.. 'config/policies/*': cb => { dictionary.optional( { dirname: path.resolve( strapi.config.appPath, strapi.config.paths.config, 'policies' ), filter: /(.+)\.(js)$/, depth: 1 }, cb ); }, // Load APIs from `./api/**/*.js|json`. 'api/**': cb => { dictionary.optional( { dirname: path.resolve( strapi.config.appPath, strapi.config.paths.api ), excludeDirs: /(public)$/, filter: /(.+)\.(js|json)$/, depth: 3 }, cb ); }, // // Load admin from `./admin/**/*.js|json`. // 'admin/**': cb => { // dictionary.optional({ // dirname: path.resolve(strapi.config.appPath, strapi.config.paths.admin), // excludeDirs: /(public)$/, // filter: /(.+)\.(js|json)$/, // depth: 3 // }, cb); // }, // Load plugins from `./plugins/**/*.js|json`. 'plugins/**': cb => { dictionary.optional( { dirname: path.resolve( strapi.config.appPath, strapi.config.paths.plugins ), excludeDirs: /(public)$/, filter: /(.+)\.(js|json)$/, depth: 4 }, cb ); } }, // Callback. (err, config) => { // Just in case there is an error. if (err) { // return cb(err); } // Merge every user config together. const mergedConfig = _.merge( config['config/*'], config['config/environments/*'], config['config/functions/**/*'] ); // Remove cache. delete require.cache[ path.resolve(strapi.config.appPath, 'package.json') ]; // Local `package.json`. const packageJSON = require(path.resolve( strapi.config.appPath, 'package.json' )); // Merge default config and user loaded config together inside `strapi.config`. strapi.config = _.merge(strapi.config, mergedConfig, packageJSON); // Set responses. strapi.config.responses = config['config/functions/responses/*']; // Set policies value. strapi.config.policies = config['config/policies/*']; // Expose user APIs. strapi.api = config['api/**']; // Expose user plugins. strapi.plugins = config['plugins/**']; // Initialize plugin's routes. _.set(strapi.config, 'plugins.routes', {}); // Add user locales for the settings of the `i18n` hook // aiming to load locales automatically. if ( _.isPlainObject(strapi.config.i18n) && !_.isEmpty(strapi.config.i18n) ) { strapi.config.i18n.locales = _.keys(config['config/locales/*']); } // Save different environments because we need it in the Strapi Studio. strapi.config.environments = config['config/environments/**'] || {}; // Make the application name in config match the server one. strapi.app.name = strapi.config.name; // Template literal string strapi.config = templateConfigurations(strapi.config); // Initialize empty API objects. strapi.controllers = {}; strapi.models = {}; cb(); } ); } }; /** * Allow dynamic config values through * the native ES6 template string function. */ function templateConfigurations(object) { // Allow values which looks like such as // an ES6 literal string without parenthesis inside (aka function call). const regex = /\$\{[^()]*\}/g; return _.mapValues(object, value => { if (_.isPlainObject(value)) { return templateConfigurations(value); } else if (_.isString(value) && regex.test(value)) { return eval('`' + value + '`'); } return value; }); } };
JavaScript
0
@@ -5185,32 +5185,38 @@ deDirs: /(public +%7Cadmin )$/,%0A
70632615f35edb9a778bbd4dd8ac4c7ab5de2454
return findNodeHandle to public api
Libraries/react-native/react-native-implementation.js
Libraries/react-native/react-native-implementation.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule react-native-implementation * @flow */ 'use strict'; const invariant = require('fbjs/lib/invariant'); // Export React, plus some native additions. const ReactNative = { // Components get AccessibilityInfo() { return require('AccessibilityInfo'); }, get ActivityIndicator() { return require('ActivityIndicator'); }, get ART() { return require('ReactNativeART'); }, get Button() { return require('Button'); }, get DatePickerIOS() { return require('DatePickerIOS'); }, get DrawerLayoutAndroid() { return require('DrawerLayoutAndroid'); }, get FlatList() { return require('FlatList'); }, get Image() { return require('Image'); }, get ImageEditor() { return require('ImageEditor'); }, get ImageStore() { return require('ImageStore'); }, get KeyboardAvoidingView() { return require('KeyboardAvoidingView'); }, get ListView() { return require('ListView'); }, get Modal() { return require('Modal'); }, get NavigatorIOS() { return require('NavigatorIOS'); }, get Picker() { return require('Picker'); }, get PickerIOS() { return require('PickerIOS'); }, get ProgressBarAndroid() { return require('ProgressBarAndroid'); }, get ProgressViewIOS() { return require('ProgressViewIOS'); }, get ScrollView() { return require('ScrollView'); }, get SectionList() { return require('SectionList'); }, get SegmentedControlIOS() { return require('SegmentedControlIOS'); }, get Slider() { return require('Slider'); }, get SnapshotViewIOS() { return require('SnapshotViewIOS'); }, get Switch() { return require('Switch'); }, get RefreshControl() { return require('RefreshControl'); }, get StatusBar() { return require('StatusBar'); }, get SwipeableListView() { return require('SwipeableListView'); }, get TabBarIOS() { return require('TabBarIOS'); }, get Text() { return require('Text'); }, get TextInput() { return require('TextInput'); }, get ToastAndroid() { return require('ToastAndroid'); }, get ToolbarAndroid() { return require('ToolbarAndroid'); }, get Touchable() { return require('Touchable'); }, get TouchableHighlight() { return require('TouchableHighlight'); }, get TouchableNativeFeedback() { return require('TouchableNativeFeedback'); }, get TouchableOpacity() { return require('TouchableOpacity'); }, get TouchableWithoutFeedback() { return require('TouchableWithoutFeedback'); }, get View() { return require('View'); }, get ViewPagerAndroid() { return require('ViewPagerAndroid'); }, get VirtualizedList() { return require('VirtualizedList'); }, get WebView() { return require('WebView'); }, // APIs get ActionSheetIOS() { return require('ActionSheetIOS'); }, get AdSupportIOS() { return require('AdSupportIOS'); }, get Alert() { return require('Alert'); }, get AlertIOS() { return require('AlertIOS'); }, get Animated() { return require('Animated'); }, get AppRegistry() { return require('AppRegistry'); }, get AppState() { return require('AppState'); }, get AsyncStorage() { return require('AsyncStorage'); }, get BackAndroid() { return require('BackAndroid'); }, // deprecated: use BackHandler instead get BackHandler() { return require('BackHandler'); }, get CameraRoll() { return require('CameraRoll'); }, get Clipboard() { return require('Clipboard'); }, get DatePickerAndroid() { return require('DatePickerAndroid'); }, get DeviceInfo() { return require('DeviceInfo'); }, get Dimensions() { return require('Dimensions'); }, get Easing() { return require('Easing'); }, get I18nManager() { return require('I18nManager'); }, get ImagePickerIOS() { return require('ImagePickerIOS'); }, get InteractionManager() { return require('InteractionManager'); }, get Keyboard() { return require('Keyboard'); }, get LayoutAnimation() { return require('LayoutAnimation'); }, get Linking() { return require('Linking'); }, get NativeEventEmitter() { return require('NativeEventEmitter'); }, get NetInfo() { return require('NetInfo'); }, get PanResponder() { return require('PanResponder'); }, get PermissionsAndroid() { return require('PermissionsAndroid'); }, get PixelRatio() { return require('PixelRatio'); }, get PushNotificationIOS() { return require('PushNotificationIOS'); }, get Settings() { return require('Settings'); }, get Share() { return require('Share'); }, get StatusBarIOS() { return require('StatusBarIOS'); }, get StyleSheet() { return require('StyleSheet'); }, get Systrace() { return require('Systrace'); }, get TimePickerAndroid() { return require('TimePickerAndroid'); }, get TVEventHandler() { return require('TVEventHandler'); }, get UIManager() { return require('UIManager'); }, get Vibration() { return require('Vibration'); }, get VibrationIOS() { return require('VibrationIOS'); }, // Plugins get DeviceEventEmitter() { return require('RCTDeviceEventEmitter'); }, get NativeAppEventEmitter() { return require('RCTNativeAppEventEmitter'); }, get NativeModules() { return require('NativeModules'); }, get Platform() { return require('Platform'); }, get processColor() { return require('processColor'); }, get requireNativeComponent() { return require('requireNativeComponent'); }, get takeSnapshot() { return require('takeSnapshot'); }, // Prop Types get ColorPropType() { return require('ColorPropType'); }, get EdgeInsetsPropType() { return require('EdgeInsetsPropType'); }, get PointPropType() { return require('PointPropType'); }, get ViewPropTypes() { return require('ViewPropTypes'); }, // Deprecated get Navigator() { invariant( false, 'Navigator is deprecated and has been removed from this package. It can now be installed ' + 'and imported from `react-native-deprecated-custom-components` instead of `react-native`. ' + 'Learn about alternative navigation solutions at http://facebook.github.io/react-native/docs/navigation.html' ); }, }; module.exports = ReactNative;
JavaScript
0.000378
@@ -3806,24 +3806,98 @@ asing'); %7D,%0A + get findNodeHandle() %7B return require('ReactNative').findNodeHandle; %7D,%0A get I18nMa
fe043f952ee5147a000ea14a838d1beb30c80b0b
include total size of files in deployment
api/deployments/controllers/deployments.js
api/deployments/controllers/deployments.js
'use strict'; var fs = require('fs'); var path = require('path'); var Q = require('q'); var Url = require('../../../util/url'); var File = require('../../../util/file'); var settings = require('../../../settings'); var deploymentParentDir = 'deployments' ; var deploymentParentDirPath = settings.dataDir + '/' + deploymentParentDir; /** * * @param dirName * @param contents * * returns object with properties describing contents of a deployment directory */ var digestDeploymentDir = function(req, dirName, contents){ var deferred = Q.defer(); // If no manifest file, message this deployment directory as invalid if (contents.indexOf('manifest.json') === -1) { return {name: dirName, valid: false, message: "Unable to find manifest file."}; } // Create object that describes deployment var deploymentObj = { name: dirName, valid: true, files: {"osm": [], "mbtiles": []}, url: Url.apiUrl(req, '/omk/' + deploymentParentDir + '/' + dirName), listingUrl: Url.dataDirFileUrl(req, deploymentParentDir, dirName) }; File.readFileDeferred(deploymentParentDirPath + '/' + dirName + '/manifest.json') .then(function(manifest){ deploymentObj.manifest = JSON.parse(manifest); return Q.all(contents.map(function(dirItem){ return File.statDeferred(deploymentParentDirPath + '/' + dirName + '/' + dirItem); })); }) .then(function(results){ results.forEach(function(stat, index){ // Get the file extentions var fileExt = path.extname(contents[index]) // Check the file extension, and if its a match, add to deploy object if ([".osm", ".mbtiles"].indexOf(fileExt) > -1) { deploymentObj.files[fileExt.substring(1)].push({ name: contents[index], url: Url.dataDirFileUrl(req, 'deployments/' + dirName, contents[index]), size: stat.size, lastModified: stat.mtime }); } }); deferred.resolve(deploymentObj); }) .catch(function(err){ deferred.reject(err); }) .done(); return deferred.promise; }; /** * Override the default parent directory of the deployments data directory. This allows us to test these endpoints * with fixtures. * * @param parentDir * @private */ module.exports._setParentDirectory = function(parentDir){ deploymentParentDirPath = parentDir + '/' + deploymentParentDir; }; module.exports.getAll = function(req, res, next) { var deployments = []; var deploymentDirContents; var deploymentDirs; fs.readdir(deploymentParentDirPath, function(err, deploymentDirContents){ if(err) { if (err.errno === -2) { res.status(200).json([]); return; } next(err); return; } // Return empty array if deployments directory is empty if (deploymentDirContents.length === 0) { res.status(200).json([]); return; } // Get stats on contents of the deployment directory Q.all(deploymentDirContents.map(function (dirItem) { return File.statDeferred(deploymentParentDirPath + '/' + dirItem); })) .then(function (results) { // remove items that are not directories deploymentDirs = deploymentDirContents.filter(function (dirItem, index) { return results[index].isDirectory(); }); // Read directory contents return Q.all(deploymentDirs.map(function (dirName) { return File.readDirRecursiveDeferred(deploymentParentDirPath + '/' + dirName) })) }) .then(function (results) { // Digest the contents of the deployment directories return Q.all(results.map(function (directoryContents, index) { return digestDeploymentDir(req, deploymentDirs[index], directoryContents); })); }) .then(function(deployments){ res.status(200).json(deploymentsSorted(deployments)); }) .catch(function (err) { next(err); }) .done(); }); }; module.exports.get = function(req, res, next) { var deploymentDir = req.params.deployment; // Make sure it exists File.statDeferred(deploymentParentDirPath + '/' + deploymentDir) .then(function(stat){ // read the directory contents return File.readDirRecursiveDeferred(deploymentParentDirPath + '/' + deploymentDir); }) .then(function(contents){ // Digest the contents of the deployment directories return digestDeploymentDir(req,deploymentDir, contents ); }) .then(function(deployment){ res.status(200).json(deployment); }) .catch(function(err){ next(err); }) .done(); }; function deploymentsSorted(deployments) { return deployments.sort(function (a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }); }
JavaScript
0.000001
@@ -868,16 +868,38 @@ irName,%0A + totalSize: 0,%0A @@ -1666,16 +1666,17 @@ %5Bindex%5D) +; %0A%0A @@ -1817,24 +1817,81 @@ xt) %3E -1) %7B%0A + deploymentObj.totalSize += stat.size; %0A @@ -5189,25 +5189,24 @@ eployment)%7B%0A -%0A
a90aac75f80e6556d2ebb2913c7c8be15919d195
use const
api/services/user/recoverquantities/get.js
api/services/user/recoverquantities/get.js
'use strict'; exports = module.exports = function(services, app) { var gt = require('./../../../../modules/gettext'); var service = new services.get(app); /** * Call the recover quantity get service * * @param {Object} params * @return {Promise} */ service.getResultPromise = function(params) { service.app.db.models.RecoverQuantity .findOne({ '_id' : params.id}, 'name quantity quantity_unit') .exec(function(err, document) { if (service.handleMongoError(err)) { if (document) { service.outcome.success = true; service.deferred.resolve(document); } else { service.notFound(gt.gettext('This recover quantity does not exists')); } } }); return service.deferred.promise; }; return service; };
JavaScript
0.000007
@@ -67,19 +67,21 @@ %7B%0A%0A -var +const gt = re
2048f556a11a78195d638928ee5eb73321169813
Update preview on index page selection
src/main/web/florence/js/functions/_visualisationEditor.js
src/main/web/florence/js/functions/_visualisationEditor.js
/** * Editor screen for uploading visualisations * @param collectionId * @param data */ function visualisationEditor(collectionId, data, collectionData) { var path = Florence.globalVars.pagePath, setActiveTab, getActiveTab; // Active tab $(".edit-accordion").on('accordionactivate', function() { setActiveTab = $(".edit-accordion").accordion("option", "active"); if (setActiveTab !== false) { Florence.globalVars.activeTab = setActiveTab; } }); getActiveTab = Florence.globalVars.activeTab; accordion(getActiveTab); getLastPosition(); // Submit new ZIP file bindZipSubmit(); // Edit existing ZIP file $('#edit-vis').on('submit', function(e) { e.preventDefault(); e.stopImmediatePropagation(); // Refresh visualisations tab but show 'submit ZIP' option var tempData = data; tempData.zipTitle = ""; var html = templates.workEditVisualisation(tempData); $('.workspace-menu').html(html); bindZipSubmit(); // Set visualisation tab to active accordion(1); }); // Bind save buttons var editNav = $('.edit-nav'); editNav.off(); // remove any existing event handlers. editNav.on('click', '.btn-edit-save', function () { //updateContent(collectionId, data.uri, JSON.stringify(data), true); var indexPage = $('#filenames').val(); data['indexPage'] = indexPage; save(); }); editNav.on('click', '.btn-edit-save-and-submit-for-review', function () { saveAndCompleteContent(collectionId, data.uri, JSON.stringify(data), true); }); editNav.on('click', '.btn-edit-save-and-submit-for-approval', function () { saveAndReviewContent(collectionId, data.uri, JSON.stringify(data), true); }); function bindZipSubmit() { // Upload ZIP file $('#upload-vis').on('submit', function(e) { e.preventDefault(); e.stopImmediatePropagation(); var formdata = new FormData($(this)[0]), file = this[0].files[0]; if (!$('#input-vis')) { sweetAlert("Please choose a file before submitting"); return false; } if (!file.name.match(/\.zip$/)) { sweetAlert("Incorrect file format", "You are only allowed to upload ZIP files", "warning") } else { var fileNameNoSpace = file.name.replace(/[^a-zA-Z0-9\.]/g, "").toLowerCase(); var uniqueIdNoSpace = data.uid.replace(/[^a-zA-Z0-9\.]/g, "").toLowerCase(); var contentUri = "/visualisations/" + uniqueIdNoSpace + "/content"; var uriUpload = contentUri + "/" + fileNameNoSpace; var safeUriUpload = checkPathSlashes(uriUpload); deleteAndUploadFile( safeUriUpload, contentUri, formdata, success = function() { unpackZip(safeUriUpload, success = function() { // On unpack of Zip refresh the reload editor and preview refreshPreview(path); loadPageDataIntoEditor(path, collectionId); } ); } ) } }); } function deleteAndUploadFile(path, contentUri, formData, success) { $.ajax({ url: "/zebedee/DataVisualisationZip/" + Florence.collection.id + "?zipPath=" + contentUri, type: 'DELETE', async: false, cache: false, contentType: false, processData: false, success: function (response) { uploadFile(path, formData, success); }, error: function(response) { handleApiError(response); } }); } function uploadFile(path, formData, success) { // Send zip file to zebedee $.ajax({ url: "/zebedee/content/" + Florence.collection.id + "?uri=" + path, type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (response) { success(response); }, error: function(response) { handleApiError(response); } }); } function unpackZip(zipPath, success, error) { // Unpack contents of ZIP console.log("Unpack: " + zipPath); var url = "/zebedee/DataVisualisationZip/" + Florence.collection.id + "?zipPath=" + zipPath; $.ajax({ url: url, contentType: 'application/json', type: 'POST', success: function (response) { success(response); }, error: function (response) { if (error) { error(response); } else { handleApiError(response); } } }); } function save() { putContent(collectionId, data.uri, JSON.stringify(data), success = function () { Florence.Editor.isDirty = false; refreshPreview(path); loadPageDataIntoEditor(data.uri, collectionId); }, error = function (response) { if (response.status === 409) { sweetAlert("Cannot edit this page", "It is already part of another collection."); } else { handleApiError(response); } }, true ); } }
JavaScript
0
@@ -194,24 +194,64 @@ s.pagePath,%0A + $indexSelect = $('#filenames'),%0A setA @@ -274,16 +274,16 @@ iveTab;%0A - %0A // @@ -643,24 +643,182 @@ osition();%0A%0A + // Refresh preview with new URL if index page previously selected%0A if ($indexSelect.val()) %7B%0A refreshPreview(path + $indexSelect.val());%0A %7D%0A%0A // Submi @@ -1324,24 +1324,203 @@ );%0A %7D);%0A%0A + // Listen to change of index page input and refresh preview to new index page%0A $indexSelect.change(function() %7B%0A refreshPreview(path + $indexSelect.val());%0A %7D);%0A%0A // Bind @@ -1685,85 +1685,8 @@ ) %7B%0A - //updateContent(collectionId, data.uri, JSON.stringify(data), true);%0A @@ -2139,24 +2139,45 @@ );%0A %7D);%0A%0A +%0A /* FUNCTIONS */%0A function @@ -5739,32 +5739,53 @@ reshPreview(path + + $indexSelect.val() );%0A
4c59edde4b9317db3cbc2987b83f6f8eb9b04eac
Reset the select2 entry field once a user has been added.
src/main/webapp/resources/js/pages/users/groups-members.js
src/main/webapp/resources/js/pages/users/groups-members.js
var groupMembersTable = (function(page, notifications) { function userNameLinkRow(data, type, full) { return "<a class='item-link' title='" + data + "' href='" + page.urls.usersLink + full.subject.identifier + "'><span>" + data + "</span></a>"; }; function renderGroupRole(data, type, full) { return page.i18n[data]; }; function removeUserButton(data, type, full) { return "<div class='btn-group pull-right' data-toggle='tooltip' data-placement='left' title='" + page.i18n.remove + "'><button type='button' data-toggle='modal' data-target='#removeUserModal' class='btn btn-default btn-xs remove-user-btn'><span class='fa fa-remove'></span></div>"; }; function deleteLinkCallback(row, data) { var row = $(row); row.find(".remove-user-btn").click(function () { $("#removeUserModal").load(page.urls.deleteModal+"#removeUserModalGen", { 'userId' : data.subject.identifier}, function() { var modal = $(this); modal.on("show.bs.modal", function () { $(this).find("#remove-user-button").off("click").click(function () { $.ajax({ url : page.urls.removeMember + data.subject.identifier, type : 'DELETE', success : function (result) { oTable_groupMembersTable.ajax.reload(); notifications.show({ 'msg': result.result }); modal.modal('hide'); }, error: function () { notifications.show({ 'msg' : page.i18n.unexpectedRemoveError, 'type': 'error' }); modal.modal('hide'); } }); }); }); modal.modal('show'); }); }); row.find('[data-toggle="tooltip"]').tooltip(); }; $("#add-user-username").select2({ minimumInputLength: 2, ajax: { url: page.urls.usersSelection, dataType: 'json', data: function(term) { return { term: term, page_limit: 10 }; }, results: function(data, params) { return {results: data.map(function(el) { return {"id": el["identifier"], "text": el["label"]}; })}; } } }); $("#submitAddMember").click(function() { $.ajax({ url: page.urls.addMember, method: 'POST', data: { "userId" : $("#add-user-username").val(), "groupRole" : $("#add-user-role").val() }, success: function(result) { $("#addUserModal").modal('hide'); oTable_groupMembersTable.ajax.reload(); notifications.show({ 'msg': result.result }); }, error: function() { $("#addUserModal").modal('hide'); notifications.show({ 'msg': page.i18n.unexpectedAddError, 'type': 'error' }) } }) }); return { userNameLinkRow : userNameLinkRow, renderGroupRole : renderGroupRole, removeUserButton : removeUserButton, deleteLinkCallback : deleteLinkCallback }; })(window.PAGE, window.notifications);
JavaScript
0
@@ -2520,16 +2520,64 @@ %09%09%09%09%7D);%0A +%09%09%09%09$(%22#add-user-username%22).select2(%22val%22, %22%22);%0A %09%09%09%7D,%0A%09%09
2708a31f0f3215719cf4856819921db4c9068c5a
Fix space/tab thing.
lib/EditablePermissions/EditablePermissions.js
lib/EditablePermissions/EditablePermissions.js
import _ from 'lodash'; import React from 'react'; import PropTypes from 'prop-types'; import { FieldArray } from 'redux-form'; import { Dropdown } from '@folio/stripes-components/lib/Dropdown'; import DropdownMenu from '@folio/stripes-components/lib/DropdownMenu'; import Button from '@folio/stripes-components/lib/Button'; import Icon from '@folio/stripes-components/lib/Icon'; import List from '@folio/stripes-components/lib/List'; import IfPermission from '@folio/stripes-components/lib/IfPermission'; import { Accordion } from '@folio/stripes-components/lib/Accordion'; import { Row, Col } from '@folio/stripes-components/lib/LayoutGrid'; import Badge from '@folio/stripes-components/lib/Badge'; import PermissionList from '../PermissionList'; import css from './EditablePermissions.css'; class EditablePermissions extends React.Component { static propTypes = { heading: PropTypes.string.isRequired, permToRead: PropTypes.string.isRequired, permToDelete: PropTypes.string.isRequired, permToModify: PropTypes.string.isRequired, availablePermissions: PropTypes.arrayOf(PropTypes.object), initialValues: PropTypes.object, stripes: PropTypes.shape({ hasPerm: PropTypes.func.isRequired, config: PropTypes.shape({ showPerms: PropTypes.bool, listInvisiblePerms: PropTypes.bool, }).isRequired, }).isRequired, accordionId: PropTypes.string, expanded: PropTypes.bool, onToggle: PropTypes.func, name: PropTypes.string, }; static defaultProps = { name: 'permissions', }; constructor(props) { super(props); this.state = { addPermissionOpen: false, searchTerm: '', }; this.onChangeSearch = this.onChangeSearch.bind(this); this.onToggleAddPermDD = this.onToggleAddPermDD.bind(this); this.isPermAvailable = this.isPermAvailable.bind(this); this.addPermissionHandler = this.addPermissionHandler.bind(this); this.renderList = this.renderList.bind(this); } onChangeSearch(e) { const searchTerm = e.target.value; this.setState({ searchTerm }); } onToggleAddPermDD() { const isOpen = this.state.addPermissionOpen; this.setState({ addPermissionOpen: !isOpen, }); } addPermissionHandler(perm) { this.fields.unshift(perm); this.onToggleAddPermDD(); } removePermission(index) { this.fields.remove(index); } isPermAvailable(perm) { const listedPermissions = (this.fields) ? this.fields.getAll() : this.props.initialValues.permissions; if ((listedPermissions || []).some(x => x.permissionName === perm.permissionName)) { return false; } if (!perm.visible && !this.props.stripes.config.listInvisiblePerms) return false; return _.includes(perm.displayName || perm.permissionName, this.state.searchTerm.toLowerCase()); } renderList({ fields }) { this.fields = fields; const showPerms = _.get(this.props.stripes, ['config', 'showPerms']); const listFormatter = (fieldName, index) => (this.renderItem(fields.get(index), index, showPerms)); return ( <List items={fields} itemFormatter={listFormatter} isEmptyMessage="This user has no permissions applied." /> ); } renderItem(item, index, showPerms) { return ( <li key={item.permissionName}> { (showPerms ? `${item.permissionName} (${item.displayName})` : (item.displayName || item.permissionName)) } <IfPermission perm={this.props.permToDelete}> <Button buttonStyle="fieldControl" align="end" type="button" id="clickable-remove-permission" onClick={() => this.removePermission(index)} aria-label={`Remove Permission: ${item.permissionName}`} title="Remove Permission" > <Icon icon="hollowX" iconClassName={css.removePermissionIcon} iconRootClass={css.removePermissionButton} /> </Button> </IfPermission> </li> ); } render() { const { accordionId, expanded, onToggle, initialValues } = this.props; const permissions = (initialValues || {}).permissions || []; if (!this.props.stripes.hasPerm(this.props.permToRead)) return null; const permissionsDD = ( <PermissionList items={_.filter(this.props.availablePermissions, this.isPermAvailable)} onClickItem={this.addPermissionHandler} onChangeSearch={this.onChangeSearch} stripes={this.props.stripes} /> ); const permsDropdownButton = ( <IfPermission perm={this.props.permToModify}> <Dropdown id="section-add-permission" style={{ float: 'right' }} pullRight open={this.state ? this.state.addPermissionOpen : false} onToggle={this.onToggleAddPermDD} > <Button align="end" bottomMargin0 data-role="toggle" aria-haspopup="true" id="clickable-add-permission">&#43; Add Permission</Button> <DropdownMenu data-role="menu" width="40em" aria-label="available permissions" onToggle={this.onToggleAddPermDD} >{permissionsDD}</DropdownMenu> </Dropdown> </IfPermission> ); return ( <Accordion open={expanded} id={accordionId} onToggle={onToggle} label={ <h2 className="marginTop0">{this.props.heading}</h2> } displayWhenClosed={ <Badge>{permissions.length}</Badge> } > <Row> <Col xs={8}> <Row> <Col xs={12}> {permsDropdownButton} </Col> </Row> <br /> <Row> <Col xs={12}> <FieldArray name={this.props.name} component={this.renderList} /> </Col> </Row> </Col> </Row> </Accordion> ); } } export default EditablePermissions;
JavaScript
0
@@ -3680,9 +3680,16 @@ on%22%0A -%09 +
2b4ec02c2ad646007827b5a41386ce85ba8093e3
Correct path to exception token
src/dslEngine.js
src/dslEngine.js
var mongoose = require("mongoose"); var DslConcreteStrategy = require("./model/DslConcreteStrategy"); var MaapError = require("./utils/MaapError"); var Token = require("./token"); var TransmissionNode = require("./transmissionNode"); var LoadModelsProtocol = require("./protocol/loadModelsProtocol") var NoConnectionEstabilished = require("./utils/noConnectionEstabilished"); var NoTokenConnectedException = require("./utils/noTokenConnectedException"); var CellEngine = require("./engine/CellEngine"); var CollectionEngine = require("./engine/CollectionEngine"); var DashboardEngine = require("./engine/DashboardEngine"); var DocumentEngine = require("./engine/DocumentEngine"); /** * Core class, it keep manage the connesion with MongoDB and run the DSL passed * in text format. * * @history * | Name | Action performed | Date | * | --- | --- | --- | * | Andrea Mantovani | The token keep the connectio to db | 2016-06-03 | * | Andrea Mantovani | Uso Token and remove method get | 2016-06-01 | * | Andrea Mantovani | Update document and correct import | 2016-05-12 | * | Andrea Mantovani | Create class | 2016-05-11 | * * @author Andrea Mantovani * @license MIT */ var DSLEngine = function () { this.strategy = new DslConcreteStrategy(); this.node = new TransmissionNode(); this.cellEngine = new CellEngine(this.node); this.collectionEngine = new CollectionEngine(this.node); this.dashboardEngine = new DashboardEngine(this.node); this.documentEngine = new DocumentEngine(this.node); this.token = undefined; }; DSLEngine.prototype.cell = function () { if (this.token == undefined) { throw new NoTokenConnectedException(); } return this.cellEngine; }; DSLEngine.prototype.collection = function () { if (this.token == undefined) { throw new NoTokenConnectedException(); } return this.collectionEngine; }; DSLEngine.prototype.dashboardEngine = function () { if (this.token == undefined) { throw new NoTokenConnectedException(); } return this.dashboardEngine; }; DSLEngine.prototype.documentEngine = function () { if (this.token == undefined) { throw new NoTokenConnectedException(); } return this.documentEngine; }; /** * @description * Remove the token from engine emit an event to save the engines' environment, * so when the token is repush, the engines can take the data stored into it. * @return {Token} * The token push into the engine. */ DSLEngine.prototype.ejectSafelyToken = function () { var token = this.token; this.token = undefined; this.node.emitEjectToken(token); return token; }; /** * @description * Create a token to comunicate with the engine. The token is not directly * connect to the engine, and is needed call `pushToken` method to make. * @return {Token} * A token connected with this database passed by argument. */ DSLEngine.prototype.generateToken = function (db) { return new Token(db); }; /** * @description * Load the dsl into the token passed by argument. Use this method if you want * load new dsl model in a previous token. * @param dsl {string} * The code of the dsl * @param token {Token} * The token where to be store the dsl. * @return {Promise<void>} * @throws {NoTokenConnectedException} */ DSLEngine.prototype.loadDSL = function (dsl) { if (this.token == undefined) { throw new NoTokenConnectedException(); } return new Promise((resolve, reject) => { try { var models = this.strategy.load(dsl, this.token.getConnection()); } catch (err) { // Catch the loading error reject(err); } protocolLoad = new LoadModelsProtocol(this.node); protocolLoad .waitAck(models.length) .onComplete((err) => { if (err) { reject(err); } else { resolve(); } }); this.node.emitLoad(models); }); }; /** * @description * Connect the token with the engine to perform action of save, load model and * environment. * @param token {Token} * Token to store the envirnoment. */ DSLEngine.prototype.pushToken = function (token) { if (this.token != undefined) { throw new TokenAlreadyInsertException(); } this.token = token; this.node.emitPushToken(token); }; module.exports = DSLEngine;
JavaScript
0.000002
@@ -443,24 +443,112 @@ xception%22);%0A +var TokenAlreadyInsertException = require(%0A %22./utils/tokenAlreadyInsertException%22%0A);%0A var CellEngi
10f9d01dd46b6e99fbf4a75b5781fc7dff4b65d3
use proper index type
app/addons/documents/mango/mango.helper.js
app/addons/documents/mango/mango.helper.js
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. define([ 'api' ], function (FauxtonAPI) { function getIndexName (doc) { var nameArray = [], indexes; nameArray = doc.get('def').fields.reduce(function (acc, el, i) { if (i === 0) { acc.push('json: ' + Object.keys(el)[0]); } else { acc.push(Object.keys(el)[0]); } return acc; }, []); if (!nameArray.length) { indexes = FauxtonAPI.getExtensions('mango:additionalIndexes')[0]; nameArray = indexes.createHeader(doc); } return nameArray.join(', '); } return { getIndexName: getIndexName }; });
JavaScript
0
@@ -777,13 +777,27 @@ ush( -'json +doc.get('type') + ' : '
d7cf0bb4d6c70dc3ba5797b051b7e8cf6b9f7cbd
Use the new noconflict build to show an example of how to embed rollbar.js into a library which will not cause any conflicts with another install of Rollbar @rokob
examples/no-conflict/tool.js
examples/no-conflict/tool.js
import Rollbar from 'rollbar'; const rollbar = new Rollbar({ accessToken: 'POST_CLIENT_ITEM_TOKEN', captureUncaught: false, captureUnhandledRejections: false }) module.exports = function tool(x) { rollbar.log('foobar got data', {x}) }
JavaScript
0
@@ -1,33 +1,125 @@ -import Rollbar from 'rollbar' +// Use noconflict so we can embed rollbar.js in this library%0Avar Rollbar = require('rollbar/dist/rollbar.noconflict.umd') ;%0A%0Ac @@ -207,20 +207,19 @@ caught: -fals +tru e,%0A cap @@ -247,12 +247,11 @@ ns: -fals +tru e%0A%7D)
51a631a717e2953e6e97d1d7402e896bedfad6e4
优化 Uncaught TypeError: vc.component._getOrgsByOrgLevelStaff is not a function
WebService/src/main/resources/components/staffPackage/staff-manage/staff.js
WebService/src/main/resources/components/staffPackage/staff-manage/staff.js
(function(vc){ var DEFAULT_PAGE = 1; var DEFAULT_ROWS = 10; vc.extends({ data:{ staffInfo:{ moreCondition:false, branchOrgs:[], departmentOrgs:[], conditions:{ branchOrgId:'', departmentOrgId:'', orgId:'', orgName:'', orgLevel:'', parentOrgId:'', name:'', tel:'', staffId:'' } }, staffData:[], }, watch:{ "staffInfo.conditions.branchOrgId":{//深度监听,可监听到对象、数组的变化 handler(val, oldVal){ vc.component._getOrgsByOrgLevelStaff(DEFAULT_PAGE, DEFAULT_ROWS,3,val); vc.component.staffInfo.conditions.branchOrgId = val; vc.component.staffInfo.conditions.departmentOrgId = ''; vc.component.loadData(DEFAULT_PAGE, DEFAULT_ROWS); }, deep:true }, "staffInfo.conditions.departmentOrgId":{//深度监听,可监听到对象、数组的变化 handler(val, oldVal){ if(val == ''){ vc.component.staffInfo.conditions.parentOrgId = vc.component.staffInfo.conditions.branchOrgId; }else{ vc.component.staffInfo.conditions.parentOrgId = val; } vc.component.loadData(DEFAULT_PAGE, DEFAULT_ROWS); }, deep:true } }, _initMethod:function(){ vc.component.loadData(1,10); vc.component._getOrgsByOrgLevelStaff(DEFAULT_PAGE, DEFAULT_ROWS,2,''); }, _initEvent:function(){ vc.component.$on('pagination_page_event',function(_currentPage){ vc.component.currentPage(_currentPage); }); vc.component.$on('addStaff_reload_event',function(){ vc.component.loadData(1,10); }); vc.component.$on('editStaff_reload_event',function(){ vc.component.loadData(1,10); }); vc.component.$on('deleteStaff_reload_event',function(){ vc.component.loadData(1,10); }); }, methods:{ loadData:function(_page,_rows){ vc.component.staffInfo.conditions.page = _page; vc.component.staffInfo.conditions.row = _rows; var param = { params:vc.component.staffInfo.conditions }; //发送get请求 vc.http.get('staff', 'loadData', param, function(json){ var _staffInfo = JSON.parse(json); vc.component.staffData = _staffInfo.datas; vc.component.$emit('pagination_info_event',{ total:_staffInfo.records, currentPage:_staffInfo.page }); },function(){ console.log('请求失败处理'); } ); }, currentPage:function(_currentPage){ vc.component.loadData(_currentPage,10); }, openEditStaff:function(_staffInfo){ vc.component.$emit('edit_staff_event',_staffInfo); }, openDeleteStaff:function(_staffInfo){ vc.component.$emit('delete_staff_event',_staffInfo); } }, _getOrgsByOrgLevelStaff:function(_page, _rows,_orgLevel,_parentOrgId){ var param = { params:{ page: _page, row: _rows, orgLevel:_orgLevel, parentOrgId: _parentOrgId } }; //发送get请求 vc.http.get('staff', 'list', param, function(json,res){ var _orgInfo=JSON.parse(json); if(_orgLevel == 2){ vc.component.staffInfo.branchOrgs = _orgInfo.orgs; }else{ vc.component.staffInfo.departmentOrgs = _orgInfo.orgs; } },function(errInfo,error){ console.log('请求失败处理'); } ); } }); })(window.vc);
JavaScript
0.00005
@@ -4204,33 +4204,23 @@ %7D -%0A%0A %7D,%0A +,%0A @@ -4295,16 +4295,20 @@ rgId)%7B%0A%0A + @@ -4345,24 +4345,28 @@ + params:%7B%0A @@ -4358,24 +4358,28 @@ params:%7B%0A + @@ -4427,16 +4427,20 @@ + row: _ro @@ -4443,16 +4443,20 @@ _rows,%0A + @@ -4507,32 +4507,36 @@ + parentOrgId: _pa @@ -4557,34 +4557,42 @@ -%7D%0A + %7D%0A @@ -4588,32 +4588,36 @@ %7D;%0A%0A + / @@ -4632,32 +4632,36 @@ %0A + vc.http.get('sta @@ -4657,32 +4657,36 @@ tp.get('staff',%0A + @@ -4726,32 +4726,36 @@ + param,%0A @@ -4766,32 +4766,36 @@ + + function(json,re @@ -4794,24 +4794,28 @@ (json,res)%7B%0A + @@ -4897,16 +4897,20 @@ + + if(_orgL @@ -4921,16 +4921,20 @@ == 2)%7B%0A + @@ -5037,39 +5037,47 @@ + + %7Delse%7B%0A + @@ -5176,34 +5176,42 @@ -%7D%0A + %7D%0A @@ -5274,32 +5274,36 @@ + + console.log('%E8%AF%B7%E6%B1%82%E5%A4%B1 @@ -5301,32 +5301,36 @@ .log('%E8%AF%B7%E6%B1%82%E5%A4%B1%E8%B4%A5%E5%A4%84%E7%90%86');%0A + @@ -5371,16 +5371,20 @@ + );%0A @@ -5390,17 +5390,38 @@ -%7D + %7D%0A%0A %7D,%0A %0A%0A%0A
4ae3a6efa802836b6560401d9178b3ce6445b585
Update req_with_payload.js
examples/req_with_payload.js
examples/req_with_payload.js
const coap = require('../') // or coap coap.createServer(function(req, res) { res.end('Hello ' + req.url.split('/')[1] + '\n. Message payload:\n'+req.payload+'\n') }).listen(function() { var req = coap.request('coap://localhost/Matteo') var payload = { title: 'this is a test payload', body: 'containing nothing useful' } req.write(JSON.stringify(payload)); req.on('response', function(res) { res.pipe(process.stdout) res.on('end', function() { process.exit(0) }) }) req.end() })
JavaScript
0.000002
@@ -131,10 +131,8 @@ '%5Cn -. Mess
7ad53d461e44f047d2bd2ee7860fa08d3e83686e
update file/copy.js
src/file/copy.js
src/file/copy.js
var path = require('path') var readFile = require('./readFile') var writeFile = require('./writeFile') // make async version function copy (files, dest) { files = Array.isArray(files) ? files : [files] files.forEach(function (file) { var destFile = path.resolve(dest, file) var content = readFile(file) writeFile(destFile, content) }) } module.exports = copy
JavaScript
0
@@ -25,16 +25,50 @@ 'path')%0A +var assert = require('assert')%0A var read @@ -140,30 +140,528 @@ e')%0A -%0A// make async version +var eachAsync = require('../async/iterate').each%0A%0A// THIS NEEDS WORK, but not today.%0Afunction copy (files, dest, cb) %7B%0A files = Array.isArray(files) ? files : %5Bfiles%5D%0A%0A eachAsync(files, function (file, key, done) %7B%0A readFile(file, function (err, data) %7B%0A assert.ifError(err)%0A writeFile(path.resolve(dest, file), data, function (err) %7B%0A assert.ifError(err)%0A done(null, 'File ' + file + 'copied to ' + dest)%0A %7D)%0A %7D)%0A %7D, function (err, res) %7B%0A assert.ifError(err)%0A cb(res)%0A %7D)%0A%7D %0A%0Afu @@ -663,32 +663,36 @@ %7D%0A%0Afunction copy +Sync (files, dest) %7B @@ -916,8 +916,39 @@ = copy%0A +module.exports.sync = copySync%0A
4abade0c78196d5a396b22518ea1ae8957713c49
Fix error when removing an expense (#789)
app/services/data/remove-claim-document.js
app/services/data/remove-claim-document.js
const { getDatabaseConnector } = require('../../databaseConnector') const { AWSHelper } = require('../aws-helper') const aws = new AWSHelper() module.exports = function (claimDocumentId) { const db = getDatabaseConnector() return db('ClaimDocument') .returning('Filepath') .where('ClaimDocumentId', claimDocumentId) .update({ IsEnabled: false }) .then(async function (filepath) { if (filepath[0].Filepath) { await aws.delete(filepath[0].Filepath) } }) }
JavaScript
0.000001
@@ -418,32 +418,33 @@ if (filepath%5B0%5D +? .Filepath) %7B%0A
c9e144ed0719a74a1a335b2ef457233c45b803c6
Refactor service resource definition schema to use JSON Schema primitive data type descriptor functions
lib/metering/schemas/src/service-definition.js
lib/metering/schemas/src/service-definition.js
'use strict'; module.exports = () => ({ 'title': 'Service Resource Definition', 'description': 'Defines the resources, units, metering, aggregation and rating formulas used to meter a particular service', 'type': 'object', 'required': ['id', 'resources', 'aggregations'], 'properties': { 'id': { 'type': 'string' }, 'resources': { 'type': 'array', 'minItems': 1, 'items': { 'type': 'object', 'required': ['units'], 'properties': { 'name': { 'type': 'string' }, 'units' : { 'type': 'array', 'minItems': 1, 'items': { 'type': 'object', 'required': ['name', 'quantityType'], 'properties': { 'name': { 'type': 'string' }, 'quantityType': { 'enum' : [ 'DELTA', 'CURRENT'] } }, 'additionalProperties': false }, 'additionalItems': false } }, 'additionalProperties': false }, 'additionalItems': false }, 'aggregations': { 'type': 'array', 'items': { 'type': 'object', 'required': ['id', 'unit', 'formula'], 'properties': { 'id': { 'type': 'string' }, 'unit': { 'type': 'string' }, 'aggregationGroup': { 'type': 'object', 'required': ['name'], 'properties': { 'name': { 'enum': ['daily', 'monthly'] }, 'additionalProperties': false } }, 'formula': { }, 'accumulate': { }, 'aggregate': { }, 'rate': { } }, 'additionalProperties': false }, 'additionalItems': false } }, 'additionalProperties': false });
JavaScript
0
@@ -12,2743 +12,1247 @@ ';%0A%0A -module.exports = () =%3E (%7B%0A 'title': 'Service Resource Definition',%0A 'description': 'Defines the resources, units, metering, aggregation and rating formulas used to meter a particular service',%0A 'type': 'object',%0A 'required': %5B'id', 'resources', 'aggregations'%5D,%0A 'properties': %7B%0A 'id': %7B%0A 'type': 'string'%0A %7D,%0A 'resources': %7B%0A 'type': 'array',%0A 'minItems': 1,%0A 'items': %7B%0A 'type': 'object',%0A 'required': %5B'units'%5D,%0A 'properties': %7B%0A 'name': %7B%0A 'type': 'string'%0A %7D,%0A 'units' : %7B%0A 'type': 'array',%0A 'minItems': 1,%0A 'items': %7B%0A 'type': 'object',%0A 'required': %5B'name', 'quantityType'%5D,%0A 'properties': %7B%0A 'name': %7B%0A 'type': 'string'%0A %7D,%0A 'quantityType': %7B%0A 'enum' : %5B 'DELTA', 'CURRENT'%5D%0A %7D%0A %7D,%0A 'additionalProperties': false%0A %7D,%0A 'additionalItems': false%0A %7D%0A %7D,%0A 'additionalProperties': false%0A %7D,%0A 'additionalItems': false%0A %7D,%0A 'aggregations': %7B%0A 'type': 'array',%0A 'items': %7B%0A 'type': 'object',%0A 'required': %5B'id', 'unit', 'formula'%5D,%0A 'properties': %7B%0A 'id': %7B%0A 'type': 'string'%0A %7D,%0A 'unit': %7B%0A 'type': 'string'%0A %7D,%0A 'aggregationGroup': %7B%0A 'type': 'object',%0A 'required': %5B'name'%5D,%0A 'properties': %7B%0A 'name': %7B%0A 'enum': %5B'daily', 'monthly'%5D%0A %7D,%0A 'additionalProperties': false%0A %7D%0A %7D,%0A 'formula': %7B%0A %7D,%0A 'accumulate': %7B%0A %7D,%0A 'aggregate': %7B%0A %7D,%0A 'rate': %7B%0A %7D%0A %7D,%0A 'additionalProperties': false%0A %7D,%0A 'additionalItems': false%0A %7D%0A %7D,%0A 'additionalProperties': false%0A%7D);%0A +// Service resource definition schema%0A%0Aconst _ = require('underscore');%0A%0Aconst schema = require('cf-abacus-schema');%0A%0Aconst clone = _.clone;%0Aconst extend = _.extend;%0A%0Aconst string = schema.types.string;%0Aconst enumType = schema.types.enumType;%0Aconst object = schema.types.object;%0Aconst arrayOf = schema.types.arrayOf;%0A%0A// Unit schema%0Aconst unit = object(%7B name: string(), quantityType: enumType(%5B'DELTA', 'CURRENT'%5D) %7D, %5B'name', 'quantityType'%5D);%0A%0A// Resource schema%0Aconst resource = object(%7B name: string(), units: arrayOf(unit) %7D, %5B'units'%5D);%0A%0A// AggregationGroup schema%0Aconst aggregationGroup = object(%7B name: enumType(%5B'daily', 'monthly'%5D) %7D, %5B'name'%5D);%0A%0A// Aggregation schema%0Aconst aggregation = object(%7B id: string(), unit: string(), aggregationGroup: aggregationGroup, formula: %7B%7D, accumulate: %7B%7D, aggregate: %7B%7D, rate: %7B%7D %7D, %5B'id', 'unit', 'formula'%5D);%0A%0A// Export our public functions%0Amodule.exports = () =%3E extend(clone(object(%7B id: string(), resources: arrayOf(resource), aggregations: arrayOf(aggregation) %7D), %5B'id', 'resources', 'aggregations'%5D),%0A %7B title: 'Service Resource Definition', description : 'Defines the resources, units, metering, accumulation, aggregation and rating formulas used to meter a particular service' %7D%0A); %0A
30da544aae47b164ac948174fb33dafee54c7ca9
Use createInterpolateElement to create link.
assets/js/modules/pagespeed-insights/components/common/ReportDetailsLink.js
assets/js/modules/pagespeed-insights/components/common/ReportDetailsLink.js
/** * Report Details Link component. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { sprintf, __, _x } from '@wordpress/i18n'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { STORE_NAME } from '../../datastore/constants'; import { STORE_NAME as CORE_SITE } from '../../../../googlesitekit/datastore/site/constants'; import { sanitizeHTML } from '../../../../util'; const { useSelect } = Data; export default function ReportDetailsLink() { const referenceURL = useSelect( ( select ) => select( CORE_SITE ).getCurrentReferenceURL() ); const pagespeedInsightsURL = useSelect( ( select ) => select( STORE_NAME ).getServiceURL( { query: { url: referenceURL } } ) ); const footerLinkHTML = sprintf( /* translators: %s: link with translated service name */ __( 'View details at %s', 'google-site-kit' ), `<a href="${ pagespeedInsightsURL }" class="googlesitekit-cta-link googlesitekit-cta-link--external" target="_blank" rel="noopener noreferrer">${ _x( 'PageSpeed Insights', 'Service name', 'google-site-kit' ) }</a>` ); return ( <p dangerouslySetInnerHTML={ sanitizeHTML( footerLinkHTML, { ALLOWED_TAGS: [ 'a' ], ALLOWED_ATTR: [ 'href', 'class', 'target', 'rel' ], } ) } /> ); }
JavaScript
0
@@ -731,16 +731,79 @@ s/i18n'; +%0Aimport %7B createInterpolateElement %7D from '@wordpress/element'; %0A%0A/**%0A * @@ -1029,24 +1029,12 @@ ort -%7B sanitizeHTML %7D +Link fro @@ -1052,12 +1052,23 @@ /../ -util +components/Link ';%0Ac @@ -1371,31 +1371,63 @@ ;%0A%0A%09 -const footerLinkHTML = +return (%0A%09%09%3Cp%3E%0A%09%09%09%7B%0A%09%09%09%09createInterpolateElement(%0A%09%09%09%09%09 spri @@ -1431,16 +1431,20 @@ printf(%0A +%09%09%09%09 %09%09/* tra @@ -1494,16 +1494,20 @@ name */%0A +%09%09%09%09 %09%09__( 'V @@ -1553,397 +1553,200 @@ ,%0A%09%09 -%60%3Ca href=%22$%7B pagespeedInsightsURL %7D%22 class=%22googlesitekit-cta-link googlesitekit-cta-link--external%22 target=%22_blank%22 rel=%22noopener noreferrer%22%3E$%7B _x( 'PageSpeed Insights', 'Service name', 'google-site-kit' ) %7D%3C/a%3E%60%0A%09);%0A%0A%09return (%0A%09%09%3Cp%0A%09%09%09dangerouslySetInnerHTML=%7B sanitizeHTML(%0A%09%09%09%09footerLinkHTML, +%09%09%09%09%60%3Ca%3E$%7B _x( 'PageSpeed Insights', 'Service name', 'google-site-kit' ) %7D%3C/a%3E%60%0A%09%09%09%09%09),%0A%09%09%09%09%09%7B%0A%09%09%09%09%09%09a: %3CLink %0A%09%09%09%09 -%7B%0A %09%09%09 -%09%09ALLOWED_TAGS: %5B 'a' %5D,%0A%09%09%09%09%09ALLOWED_ATTR: %5B 'href', 'class', 'target', 'rel' %5D +key=%22link%22%0A%09%09%09%09%09%09%09href=%7B pagespeedInsightsURL %7D%0A%09%09%09%09%09%09%09external%0A%09%09%09%09%09%09/%3E ,%0A +%09 %09%09%09%09 @@ -1754,16 +1754,23 @@ %0A%09%09%09 -) %7D%0A%09%09/%3E +%09)%0A%09%09%09%7D%0A%09%09%3C/p%3E%0A %0A%09);
c3447793694816fd9d1863c94d01fc94a5658615
use new api
data/findTables.js
data/findTables.js
(function() { //var ocServer = "opencompare.org"; var ocServer = "localhost:9000"; var tables; self.port.on("addButtons", function () { tables = document.getElementsByTagName("table"); for(var index = 0; index < tables.length; index++) { var table = tables[index]; /* Replace table button */ var button = document.createElement("button"); button.class = "waves-effect waves-light btn"; button.style = "margin-top: 10px"; button.id = index.toString(); button.setAttribute("data-type", 'OpenCompareButton'); button.addEventListener('click', function(event) { id = event.target.getAttribute("id"); document.getElementById(id).style.display = 'none'; sendTable(event.target.getAttribute("id")); }); var buttonContent = document.createTextNode("Replace this table"); button.appendChild(buttonContent); var parentDiv = tables[index].parentNode; parentDiv.insertBefore(button, tables[index]); /* Open in OpenCompare button */ var button2 = document.createElement("button"); button2.class = "waves-effect waves-light btn"; button2.style = "margin-top: 10px"; button2.id = index.toString(); button2.setAttribute("data-type", 'OpenCompareButton'); button2.addEventListener('click', function(event) { id = event.target.getAttribute("id"); openTable(event.target.getAttribute("id")); }); var buttonOpen = document.createTextNode("Open in OpenCompare.org"); button2.appendChild(buttonOpen); var parentDiv = tables[index].parentNode; parentDiv.insertBefore(button2, tables[index]); } }); function createForm(table, appendToPage) { var form = document.createElement("form"); form.method = "post"; // Set values in form var inputTitle = document.createElement("input"); inputTitle.type = "hidden"; inputTitle.name = "title"; inputTitle.value = "test"; var inputProductAsLines = document.createElement("input"); inputProductAsLines.type = "hidden"; inputProductAsLines.name = "productAsLines"; inputProductAsLines.value = "true"; var inputContent = document.createElement("input"); inputContent.type = "hidden"; inputContent.name = "content"; inputContent.value = table.outerHTML; // Add form to page table.parentNode.appendChild(form); form.appendChild(inputTitle); form.appendChild(inputProductAsLines); form.appendChild(inputContent); return form; } function sendTable(id) { var table = tables[id]; // Create form var form = createForm(table); form.target = "ocIframe"; form.action = "http://" + ocServer + "/embed/html"; // Create iframe var ocIframe = document.createElement("iframe"); ocIframe.name = "ocIframe"; ocIframe.setAttribute("type", "content"); ocIframe.scrolling = "auto"; ocIframe.width = "100%"; var originalheight = tables[id].offsetHeight; if(originalheight < 300) { ocIframe.height = "300px"; } else { ocIframe.height = originalheight; } ocIframe.style = "border:none;"; // Replace table by iframe table.parentNode.replaceChild(ocIframe, table); form.submit(); table.parentNode.removeChild(form); } function openTable(id) { var table = tables[id]; var form = createForm(table); form.target = "_blank"; form.action = "http://" + ocServer + "/embed/html"; form.submit(); table.parentNode.removeChild(form); } self.port.on("removeButtons", function() { var buttons = document.querySelectorAll("button[data-type='OpenCompareButton'"); var index; var button; for (index = 0; index < buttons.length; index++) { button = buttons[index]; button.parentNode.removeChild(button); } }); })();
JavaScript
0
@@ -3055,26 +3055,46 @@ ver + %22/ -embed/html +api/import/html?format='embed' %22;%0A%0A @@ -3921,18 +3921,37 @@ + %22/ -embed/html +api/import/html?format='page' %22;%0A
7a6fef5ced0a0f64f54d310008dfe2eef749f09c
add media display name
assets/src/edit-story/components/library/panes/media/media3p/media3pPane.js
assets/src/edit-story/components/library/panes/media/media3p/media3pPane.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; import styled from 'styled-components'; import { useCallback, useEffect } from 'react'; import { useFeature } from 'flagged'; /** * WordPress dependencies */ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ import PaginatedMediaGallery from '../common/paginatedMediaGallery'; import useMedia from '../../../../../app/media/useMedia'; import { PaneHeader, PaneInner, SearchInputContainer, StyledPane, } from '../common/styles'; import { SearchInput } from '../../../common'; import useLibrary from '../../../useLibrary'; import { ProviderType } from '../common/providerType'; import Flags from '../../../../../flags'; import Media3pCategories from './media3pCategories'; import paneId from './paneId'; import ProviderTab from './providerTab'; const ProviderTabSection = styled.div` margin-top: 30px; padding: 0 24px; `; /** * Pane that contains the media 3P integrations. * * @param {Object} props Component props * @return {*} The media pane element for 3P integrations. */ function Media3pPane(props) { const { isActive } = props; const { insertElement } = useLibrary((state) => ({ insertElement: state.actions.insertElement, })); /** * Insert element such image, video and audio into the editor. * * @param {Object} resource Resource object * @return {null|*} Return onInsert or null. */ const insertMediaElement = useCallback( (resource) => insertElement(resource.type, { resource }), [insertElement] ); const { searchTerm, setSelectedProvider, setSearchTerm, unsplash, selectedProviderState, } = useMedia( ({ media3p: { state: { selectedProvider, searchTerm }, actions: { setSelectedProvider, setSearchTerm }, unsplash, }, media3p, }) => ({ searchTerm, setSelectedProvider, setSearchTerm, unsplash, selectedProviderState: media3p[selectedProvider ?? ProviderType.UNSPLASH], }) ); const { state: { categories }, actions: { selectCategory, deselectCategory }, } = selectedProviderState; useEffect(() => { if (isActive) { setSelectedProvider({ provider: 'unsplash' }); } }, [isActive, setSelectedProvider]); const onSearch = (v) => setSearchTerm({ searchTerm: v }); const incrementalSearchDebounceMedia = useFeature( Flags.INCREMENTAL_SEARCH_DEBOUNCE_MEDIA ); const onProviderTabClick = useCallback(() => { // TODO(#2393): set state. }, []); // TODO(#2368): handle pagination / infinite scrolling return ( <StyledPane id={paneId} {...props}> <PaneInner> <PaneHeader> <SearchInputContainer> <SearchInput initialValue={searchTerm} placeholder={__('Search', 'web-stories')} onSearch={onSearch} incremental={incrementalSearchDebounceMedia} disabled={Boolean(categories.selectedCategoryId)} /> </SearchInputContainer> <ProviderTabSection> <ProviderTab name={'Unsplash'} active={true} onClick={onProviderTabClick} /> </ProviderTabSection> <Media3pCategories categories={categories.categories} selectedCategoryId={categories.selectedCategoryId} selectCategory={selectCategory} deselectCategory={deselectCategory} /> </PaneHeader> <PaginatedMediaGallery providerType={ProviderType.UNSPLASH} resources={unsplash.state.media} isMediaLoading={unsplash.state.isMediaLoading} isMediaLoaded={unsplash.state.isMediaLoaded} hasMore={unsplash.state.hasMore} setNextPage={unsplash.actions.setNextPage} onInsert={insertMediaElement} /> </PaneInner> </StyledPane> ); } Media3pPane.propTypes = { isActive: PropTypes.bool, }; export default Media3pPane;
JavaScript
0.000003
@@ -1517,16 +1517,170 @@ px;%0A%60;%0A%0A +const MediaDisplayName = styled.div%60%0A margin-top: 24px;%0A padding: 0 24px;%0A visibility: $%7B(props) =%3E (props.shouldDisplay ? 'visible' : 'hidden')%7D;%0A%60;%0A%0A /**%0A * P @@ -3306,16 +3306,474 @@ , %5B%5D);%0A%0A + const displayName = categories.selectedCategoryId%0A ? categories.categories.find((e) =%3E e.id === categories.selectedCategoryId)%0A .displayName%0A : __('Trending', 'web-stories');%0A%0A // We display the media name if there's media to display or a category has%0A // been selected.%0A // TODO: Update for Coverr.%0A const displayMediaName = Boolean(%0A (unsplash.state.isMediaLoaded && unsplash.state.media) %7C%7C%0A categories.selectedCategoryId%0A );%0A%0A // TOD @@ -4700,32 +4700,32 @@ selectCategory%7D%0A - /%3E%0A @@ -4713,32 +4713,150 @@ y%7D%0A /%3E%0A + %3CMediaDisplayName shouldDisplay=%7BdisplayMediaName%7D%3E%0A %7BdisplayName%7D%0A %3C/MediaDisplayName%3E%0A %3C/PaneHe
d73947eb497fa2707cbb25578bd3494baa3ba634
Update xls.js
test/inventory/finishing-printing/shipment-document/xls.js
test/inventory/finishing-printing/shipment-document/xls.js
require("should"); var DataUtil = require('../../../data-util/inventory/finishing-printing/fp-shipment-document-data-util'); var helper = require("../../../helper"); var validate = require("dl-models").validator.inventory.finishingPrinting.fpShipmentDocument; var moment = require('moment'); var Manager = require("../../../../src/managers/inventory/finishing-printing/fp-shipment-document-manager"); var instanceManager = null; before('#00. connect db', function (done) { helper.getDb() .then(db => { instanceManager = new Manager(db, { username: 'dev' }); done(); }) .catch(e => { done(e); }); }); var createdId; it("#01. should success when create new data", function (done) { DataUtil.getNewTestData() .then((data) => instanceManager.create(data)) .then((id) => { id.should.be.Object(); createdId = id; done(); }) .catch((e) => { done(e); }); }); var createdData; it(`#02. should success when get created data with id`, function (done) { instanceManager.getSingleById(createdId) .then((data) => { data.should.instanceof(Object); validate(data); createdData = data; done(); }) .catch((e) => { done(e); }); }); var resultForExcelTest = {}; it('#03. should success when create report', function (done) { var info = {}; info.shipmentNumber = createdData.shipmentNumber; info.deliveryCode = createdData.deliveryCode; info.productIdentity = createdData.productIdentity; info.buyerId = createdData.buyerId; info.dateFrom = createdData._createdDate; info.dateTo = createdData._createdDate.toISOString().split("T", "1").toString(); instanceManager.getShipmentReport(info) .then(result => { resultForExcelTest = result; var shipment = result.data; shipment.should.instanceof(Array); shipment.length.should.not.equal(0); done(); }).catch(e => { done(e); }); }); it('#04. should success when get data for Excel Report', function (done) { var query = {}; instanceManager.getXls(resultForExcelTest, query) .then(xlsData => { xlsData.should.have.property('data'); xlsData.should.have.property('options'); xlsData.should.have.property('name'); done(); }).catch(e => { done(e); }); }); it("#05. should success when destroy all unit test data", function (done) { instanceManager.destroy(createdData._id) .then((result) => { result.should.be.Boolean(); result.should.equal(true); done(); }) .catch((e) => { done(e); }); });
JavaScript
0.000001
@@ -796,20 +796,16 @@ l.getNew -Test Data()%0A
f9f80cb69b67be78de12e190756f84ab0de4e133
make sure a base object exists on the scope even if the parent scope isn't base
client/scripts/features/food-recall-search/food-recall-search-controller.js
client/scripts/features/food-recall-search/food-recall-search-controller.js
define([ 'angular', 'app', 'components/services/open-fda-service', 'components/services/food-data-service' ], function(angular, app) { app.controller('FoodRecallSearchController', function($scope, $mdDialog, $stateParams, OpenFDAService, FoodDataService) { $scope.recallData = FoodDataService.getFoodSearchData(); $scope.initialized = FoodDataService.isInitialized(); //TODO Move arrays to config file. $scope.healthHazardLevels = ['Class I', 'Class II', 'Class III']; $scope.dateRange = [ {'id':0, 'name':'Last 7 Days', 'dateOffset':6}, {'id':1, 'name':'Last 30 Days','dateOffset':29}, {'id':2, 'name':'Last 1 Year', 'dateOffset':364}, {'id':3, 'name':'All Records', 'dateOffset':null} ]; $scope.statusList = ['Ongoing', 'Pending', 'Completed', 'Terminated']; $scope.search = function(params) { OpenFDAService.getData(params) .then(function(resp) { $scope.recallData = resp; if(!$scope.initialized) { $scope.initialized = true; $scope.base.searchParams = { page: $stateParams.page }; } }, function(resp) { console.log(resp.error); if(resp.error && resp.error.code === 'NOT_FOUND') { $scope.recallData = null; } }); }; $scope.viewDetails = (function() { var config = { templateUrl: 'scripts/features/\ food-recall-search/food-recall-details.html' }; return function(item) { var dialog = null, scope = $scope.$new(); scope.details = item; config.scope = scope; item.active = true; scope.hideDialog = function() { $mdDialog.cancel(dialog); }; dialog = $mdDialog.show(config) .finally(function(){ item.active = false; }); }; })(); $scope.base.search = function(params) { if (params && params.recallStartDate && params.recallStartDate.getFullYear() < 2012) { var confirm = $mdDialog.alert() .title('Disclaimer') .content('Please note, \ search results prior to 2012 may be incomplete.') .ariaLabel('Disclaimer') .ok('Ok'); $mdDialog.show(confirm).then(function() { $scope.search(params); }); } else { $scope.search(params); } }; $scope.showDisclaimer = (function() { var disclaimerDialog = $mdDialog.alert() .title('Disclaimer') .ariaLabel('Disclaimer') .ok('Ok'), metaDataPromise = OpenFDAService.getMeta(), displaying = false; return function() { return metaDataPromise.then(function(meta) { if(!displaying) { displaying = true; disclaimerDialog.content(meta.disclaimer); $mdDialog.show(disclaimerDialog) .finally(function() { displaying = false; }); } }); }; })(); $scope.showDisclaimer(); // $scope.search({ page: parseInt($stateParams.page) }); }); });
JavaScript
0.000001
@@ -862,16 +862,57 @@ nated'%5D; +%0A $scope.base = $scope.base %7C%7C %7B%7D; %0A%0A%09%09%09%09$s
84e66aa7011d7b3ebcc8e4d204f9115a2151bafd
Change templates action to follow our naming convention
backend/servers/mcapid/actions/templates-actions.js
backend/servers/mcapid/actions/templates-actions.js
const {Action, api} = require('actionhero'); const templates = require('../lib/dal/templates'); module.exports.allTemplatesPublic = class TopViewedPublishedDatasetsAction extends Action { constructor() { super(); this.name = 'allTemplatesPublic'; this.description = 'Returns all public templages'; this.do_not_authenticate = true; } async run({response}) { api.log("Call to get all templates",'info'); response.data = await templates.getAllTemplates(); api.log("Results of get all templates",'info',response.data.length); } };
JavaScript
0
@@ -10,13 +10,8 @@ tion -, api %7D = @@ -85,17 +85,16 @@ tes');%0A%0A -%0A module.e @@ -100,19 +100,28 @@ exports. -all +GetAllPublic Template @@ -121,22 +121,22 @@ emplates -Public +Action = class @@ -140,33 +140,28 @@ ass -TopViewedPublishedDataset +GetAllPublicTemplate sAct @@ -239,19 +239,28 @@ name = ' -all +getAllPublic Template @@ -260,22 +260,16 @@ emplates -Public ';%0A @@ -316,17 +316,17 @@ c templa -g +t es';%0A @@ -410,186 +410,56 @@ -api.log(%22Call to get all templates%22,'info');%0A response.data = await templates.getAllTemplates();%0A api.log(%22Results of get all templates%22,'info',response.data.length +response.data = await templates.getAllTemplates( );%0A
148073bcabd51f4473d78a83ffc606565c32ff15
Add packageType to the list of flags android builds understand and can parse
lib/targets/cordova/utils/parse-build-flags.js
lib/targets/cordova/utils/parse-build-flags.js
const _pick = require('lodash').pick; const CORDOVA_OPTS = [ 'release', 'debug', 'emulator', 'device', 'buildConfig' ]; const IOS_OPTS = [ 'codeSignIdentity', 'provisioningProfile', 'codesignResourceRules', 'developmentTeam', 'packageType' ]; const ANDROID_OPTS = [ 'keystore', 'storePassword', 'alias', 'password', 'keystoreType', 'gradleArg', 'cdvBuildMultipleApks', 'cdvVersionCode', 'cdvReleaseSigningPropertiesFile', 'cdvDebugSigningPropertiesFile', 'cdvMinSdkVersion', 'cdvBuildToolsVersion', 'cdvCompileSdkVersion' ]; module.exports = function(platform, options) { let platformKeys = []; if (platform === 'ios') { platformKeys = IOS_OPTS; } else if (platform === 'android') { platformKeys = ANDROID_OPTS; } let ret = _pick(options, CORDOVA_OPTS.concat(platformKeys)); ret.argv = [].concat(...platformKeys .filter((key) => options.hasOwnProperty(key)) .map((key) => [`--${key}`, options[key]])); return ret; };
JavaScript
0
@@ -573,16 +573,33 @@ Version' +,%0A 'packageType' %0A%5D;%0A%0Amod
a6e4c02b46b7881ec76f2a32d45a1c9348749702
add function for creating the mapping link in teh mappign page
ui/js/doc-review/DocMapping.js
ui/js/doc-review/DocMapping.js
var React = require('react/addons'); var _ = require('lodash'); var API = require('../data/api'); var { Datascope, LocalDatascope, SimpleDataTable, SimpleDataTableColumn, Paginator, SearchBar, FilterPanel, FilterDateRange } = require('react-datascope'); var ReviewPage = require('./ReviewPage'); const fields = { map_link: { title: 'Edit', key: 'id', renderer: (id) => { return <a href={`/datapoints/campaigns/update/${id}`}>Edit Campaign</a>; } }, }; const fieldNamesOnTable = ['id','db_model','source_string','master_display_name','document_id']//,'source_dp_count','master_dp_count']; // const fieldNamesOnTable = ['id']; var DocMapping = React.createClass({ render() { var doc_id = this.props.params.docId var datascopeFilters = <div> <SearchBar placeholder="search campaigns"/> <FilterPanel> <FilterDateRange name="start_date" time={false} /> <FilterDateRange name="end_date" time={false} /> </FilterPanel> </div>; var data_fn = function(){ return API.admin.docReview({id:doc_id},null,{'cache-control':'no-cache'}) }; return <ReviewPage title="ToMap" getMetadata={API.admin.docReviewMeta} getData={data_fn} datascopeFilters={datascopeFilters} fields={fields} > <Paginator /> <SimpleDataTable> {fieldNamesOnTable.map(fieldName => { return <SimpleDataTableColumn name={fieldName} /> })} </SimpleDataTable> </ReviewPage> } }); module.exports = DocMapping;
JavaScript
0
@@ -298,16 +298,155 @@ age');%0A%0A +var MapButtonFunction = function(data)%7B%0A%09console.log(data)%0A%09return %3Ca href=%7B%60/datapoints/campaigns/update/$%7Bdata%7D%60%7D%3E THIS IS JOHN %3C/a%3E;%0A%7D%0A%0A const fi @@ -477,20 +477,34 @@ title: ' -Edit +Master Object Name ',%0A%09%09key @@ -540,83 +540,41 @@ %0A%09%09%09 +%09 return -%3Ca href=%7B%60/datapoints/campaigns/update/$%7Bid%7D%60%7D%3EEdit Campaign%3C/a%3E; +MapButtonFunction(id) %0A%09%09 +%09 %7D%0A%09%7D @@ -644,30 +644,8 @@ g',' -master_display_name',' docu @@ -651,16 +651,27 @@ ument_id +','map_link '%5D//,'so @@ -710,49 +710,8 @@ %5D;%0A%0A -// const fieldNamesOnTable = %5B'id'%5D;%0A%0A%0A%0A%0A var
a7d60e4590d3f8e5b8d220437dec9402c98df166
update jsdoc.js (#278)
packages/google-cloud-iot/.jsdoc.js
packages/google-cloud-iot/.jsdoc.js
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // 'use strict'; module.exports = { opts: { readme: './README.md', package: './package.json', template: './node_modules/jsdoc-fresh', recurse: true, verbose: true, destination: './docs/' }, plugins: [ 'plugins/markdown', 'jsdoc-region-tag' ], source: { excludePattern: '(^|\\/|\\\\)[._]', include: [ 'build/src' ], includePattern: '\\.js$' }, templates: { copyright: 'Copyright 2018 Google, LLC.', includeDate: false, sourceFiles: false, systemName: '@google-cloud/iot', theme: 'lumen' }, markdown: { idInHeadings: true } };
JavaScript
0
@@ -1040,9 +1040,9 @@ 201 -8 +9 Goo @@ -1156,16 +1156,71 @@ 'lumen' +,%0A default: %7B%0A %22outputSourceFiles%22: false%0A %7D %0A %7D,%0A
935692cb41a1b2014e6d1b6c7837188cb9803589
update .jsdoc.js by add protos and remove double quotes (#279)
packages/google-cloud-iot/.jsdoc.js
packages/google-cloud-iot/.jsdoc.js
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // 'use strict'; module.exports = { opts: { readme: './README.md', package: './package.json', template: './node_modules/jsdoc-fresh', recurse: true, verbose: true, destination: './docs/' }, plugins: [ 'plugins/markdown', 'jsdoc-region-tag' ], source: { excludePattern: '(^|\\/|\\\\)[._]', include: [ 'build/src' ], includePattern: '\\.js$' }, templates: { copyright: 'Copyright 2019 Google, LLC.', includeDate: false, sourceFiles: false, systemName: '@google-cloud/iot', theme: 'lumen', default: { "outputSourceFiles": false } }, markdown: { idInHeadings: true } };
JavaScript
0
@@ -950,16 +950,32 @@ ild/src' +,%0A 'protos' %0A %5D,%0A @@ -1195,17 +1195,16 @@ %7B%0A -%22 outputSo @@ -1212,17 +1212,16 @@ rceFiles -%22 : false%0A
1397793a4d38c52ae790d0df6f22fe15a054437b
fix difficulty
test/common/genesishashes.js
test/common/genesishashes.js
var genesisData = require('../../../tests/genesishashestest.json'), assert = require('assert'), Blockchain = require('../../lib/blockchain.js'), levelup = require('levelup'), // async = require('async'), utils = require('../../lib/utils'), rlp = require('rlp'), SHA3 = require('sha3'); var blockDB = levelup('', { db: require('memdown') }), detailsDB = levelup('/does/not/matter', { db: require('memdown') }), internals = {}; describe('[Common]', function () { it('should create a new block chain', function (done) { internals.blockchain = new Blockchain(blockDB, detailsDB); internals.blockchain.init(done); }); it('should have added the genesis correctly', function () { var expected = ["0000000000000000000000000000000000000000000000000000000000000000", "1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "0000000000000000000000000000000000000000", "08bf6a98374f333b84e7d063d607696ac7cbbd409bd20fbe6a741c2dfc0eb285", "00", "020000", "00", "00", "0f4240", "00", "00", "00", "04994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829"]; var zero = '00', parentHash = '0000000000000000000000000000000000000000000000000000000000000000', unclesHash = utils.emptyRlpHash().toString('hex'), coinbase = utils.zero160().toString('hex'), stateRoot = genesisData.genesis_state_root, transactionTrie = zero, difficulty = '020000', // todo: fix number = zero, minGasPrice = zero, gasLimit = '0f4240', // todo: fix gasUsed = zero, timestamp = zero, extraData = zero, nonce, uncles = [], transactions = [], hash; hash = new SHA3.SHA3Hash(256); hash.update(rlp.encode(42)); nonce = hash.digest('hex'); // nonce = '04994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829'; // todo: remove var genesis = [ [ parentHash, unclesHash, coinbase, stateRoot, transactionTrie, difficulty, number, minGasPrice, gasLimit, gasUsed, timestamp, extraData, nonce ], uncles, transactions ]; console.log('genesis: ', genesis) console.log('expected: ', expected) assert(genesis[0].length === expected.length) assert.deepEqual(genesis[0], expected) internals.blockchain.addBlock(genesis, function() { assert(internals.blockchain.meta.genesis === genesisData.genesis_hash); }); }); });
JavaScript
0.000012
@@ -1420,31 +1420,40 @@ y = -'020000', // todo: fix +utils.intToHex(Math.pow(2, 17)), %0A
7bf056f3e7fb794aa3704db92cb031cd9ba32ede
initialize test object with the appropriate apikey
test/echonest_api_v4_test.js
test/echonest_api_v4_test.js
var vows = require('vows'), assert = require('assert'), EchoNestAPI = require('../index.js'); vows.describe('Basics!').addBatch({ 'we can create an EchoNestAPI object': { topic: function () { return new EchoNestAPI('apikey', { version:'4'}); }, 'it is not totally borked': function (topic) { assert.isNotNull(topic); }, 'the howdy function works': function (topic) { assert.equal(topic.howdy(), 'Howdy!'); } } }).export(module);
JavaScript
0.000012
@@ -92,16 +92,63 @@ .js');%0A%0A +var theAPIKey = process.env.ECHONEST_API_KEY;%0A%0A vows.des @@ -270,16 +270,17 @@ API( -'apik +theAPIK ey -' , %7B
b443bb5ee8d46a3028422848c6cfeaba70aa13c6
Clarify comment
dev_mode/webpack.prod.config.js
dev_mode/webpack.prod.config.js
const merge = require('webpack-merge').default; const config = require('./webpack.config'); const LicenseWebpackPlugin = require('license-webpack-plugin') .LicenseWebpackPlugin; config[0] = merge(config[0], { mode: 'production', devtool: 'source-map', output: { // Add version argument when in production so the Jupyter server // does not cache the files the static file handler. filename: '[name].[contenthash].js?v=[contenthash]' }, optimization: { minimize: false }, plugins: [ new LicenseWebpackPlugin({ perChunkOutput: false, outputFilename: 'third-party-licenses.txt', excludedPackageTest: packageName => packageName === '@jupyterlab/application-top' }) ] }); module.exports = config;
JavaScript
0.000034
@@ -344,36 +344,106 @@ // -does not cache the files the +allows caching of files (i.e., does not set the CacheControl header to no-cache to prevent caching sta @@ -454,17 +454,10 @@ file - handler. +s) %0A
9264e8d6823127da131c16e4d76e46a8b59ec08c
Use userid when getting a users group (#130)
spacialgaze-plugins/SG.js
spacialgaze-plugins/SG.js
'use strict'; let fs = require('fs'); let http = require('http'); const Autolinker = require('autolinker'); let regdateCache = {}; SG.nameColor = function (name, bold, userGroup) { let userGroupSymbol = Users.usergroups[toId(name)] ? '<b><font color=#948A88>' + Users.usergroups[name].substr(0, 1) + '</font></b>' : ""; return (userGroup ? userGroupSymbol : "") + (bold ? "<b>" : "") + "<font color=" + SG.hashColor(name) + ">" + (Users(name) && Users(name).connected && Users.getExact(name) ? Chat.escapeHTML(Users.getExact(name).name) : Chat.escapeHTML(name)) + "</font>" + (bold ? "</b>" : ""); }; // usage: SG.nameColor(user.name, true) for bold OR SG.nameColor(user.name, false) for non-bolded. SG.messageSeniorStaff = function (message, pmName, from) { pmName = (pmName ? pmName : '~SG Server'); from = (from ? ' (PM from ' + from + ')' : ''); Users.users.forEach(curUser => { if (curUser.group === '~' || curUser.group === '&') { curUser.send('|pm|' + pmName + '|' + curUser.getIdentity() + '|' + message + from); } }); }; // format: SG.messageSeniorStaff('message', 'person') // // usage: SG.messageSeniorStaff('Mystifi is a confirmed user and they were banned from a public room. Assess the situation immediately.', '~Server') // // this makes a PM from ~Server stating the message SG.regdate = function (target, callback) { target = toId(target); if (regdateCache[target]) return callback(regdateCache[target]); let options = { host: 'pokemonshowdown.com', port: 80, path: '/users/' + target + '.json', method: 'GET', }; http.get(options, function (res) { let data = ''; res.on('data', function (chunk) { data += chunk; }).on('end', function () { data = JSON.parse(data); let date = data['registertime']; if (date !== 0 && date.toString().length < 13) { while (date.toString().length < 13) { date = Number(date.toString() + '0'); } } if (date !== 0) { regdateCache[target] = date; saveRegdateCache(); } callback((date === 0 ? false : date)); }); }); }; SG.parseMessage = function (message) { if (message.substr(0, 5) === "/html") { message = message.substr(5); message = message.replace(/\_\_([^< ](?:[^<]*?[^< ])?)\_\_(?![^<]*?<\/a)/g, '<i>$1</i>'); // italics message = message.replace(/\*\*([^< ](?:[^<]*?[^< ])?)\*\*/g, '<b>$1</b>'); // bold message = message.replace(/\~\~([^< ](?:[^<]*?[^< ])?)\~\~/g, '<strike>$1</strike>'); // strikethrough message = message.replace(/&lt;&lt;([a-z0-9-]+)&gt;&gt;/g, '&laquo;<a href="/$1" target="_blank">$1</a>&raquo;'); // <<roomid>> message = Autolinker.link(message.replace(/&#x2f;/g, '/'), {stripPrefix: false, phone: false, twitter: false}); return message; } message = Chat.escapeHTML(message).replace(/&#x2f;/g, '/'); message = message.replace(/\_\_([^< ](?:[^<]*?[^< ])?)\_\_(?![^<]*?<\/a)/g, '<i>$1</i>'); // italics message = message.replace(/\*\*([^< ](?:[^<]*?[^< ])?)\*\*/g, '<b>$1</b>'); // bold message = message.replace(/\~\~([^< ](?:[^<]*?[^< ])?)\~\~/g, '<strike>$1</strike>'); // strikethrough message = message.replace(/&lt;&lt;([a-z0-9-]+)&gt;&gt;/g, '&laquo;<a href="/$1" target="_blank">$1</a>&raquo;'); // <<roomid>> message = Autolinker.link(message, {stripPrefix: false, phone: false, twitter: false}); return message; }; SG.randomString = function (length) { return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1); }; SG.reloadCSS = function () { const cssPath = 'spacialgaze'; // This should be the server id if Config.serverid doesn't exist. Ex: 'serverid' let options = { host: 'play.pokemonshowdown.com', port: 80, path: '/customcss.php?server=' + (Config.serverid || cssPath), method: 'GET', }; http.get(options); }; //Daily Rewards System for SpacialGaze by Lord Haji SG.giveDailyReward = function (userid, user) { if (!user || !userid) return false; userid = toId(userid); if (!Db.DailyBonus.has(userid)) { Db.DailyBonus.set(userid, [1, Date.now()]); return false; } let lastTime = Db.DailyBonus.get(userid)[1]; if ((Date.now() - lastTime) < 86400000) return false; if ((Date.now() - lastTime) >= 127800000) Db.DailyBonus.set(userid, [1, Date.now()]); if (Db.DailyBonus.get(userid)[0] === 8) Db.DailyBonus.set(userid, [7, Date.now()]); Economy.writeMoney(userid, Db.DailyBonus.get(userid)[0]); user.send('|popup||wide||html| <center><u><b><font size="3">SpacialGaze Daily Bonus</font></b></u><br>You have been awarded ' + Db.DailyBonus.get(userid)[0] + ' Stardust.<br>' + showDailyRewardAni(userid) + '<br>Because you have connected to the server for the past ' + Db.DailyBonus.get(userid)[0] + ' Days.</center>'); Db.DailyBonus.set(userid, [(Db.DailyBonus.get(userid)[0] + 1), Date.now()]); }; // last two functions needed to make sure SG.regdate() fully works function loadRegdateCache() { try { regdateCache = JSON.parse(fs.readFileSync('config/regdate.json', 'utf8')); } catch (e) {} } loadRegdateCache(); function saveRegdateCache() { fs.writeFileSync('config/regdate.json', JSON.stringify(regdateCache)); } function showDailyRewardAni(userid) { userid = toId(userid); let streak = Db.DailyBonus.get(userid)[0]; let output = ''; for (let i = 1; i <= streak; i++) { output += "<img src='http://i.imgur.com/ZItWCLB.png' width='16' height='16'> "; } return output; }
JavaScript
0
@@ -276,20 +276,26 @@ rgroups%5B +toId( name +) %5D.substr
6b484f481b8ba77aaa38869fb7ca93ac3940d53f
remove unnecessary toString
test/integration/multisig.js
test/integration/multisig.js
/* global describe, it */ var assert = require('assert') var bitcoin = require('../../') var blockchain = require('./_blockchain') describe('bitcoinjs-lib (multisig)', function () { it('can create a 2-of-3 multisig P2SH address', function () { var pubKeys = [ '026477115981fe981a6918a6297d9803c4dc04f328f22041bedff886bbc2962e01', '02c96db2302d19b43d4c69368babace7854cc84eb9e061cde51cfa77ca4a22b8b9', '03c6103b3b83e4a24a0e33a4df246ef11772f9992663db0c35759a5e2ebf68d8e9' ].map(function (hex) { return new Buffer(hex, 'hex') }) var redeemScript = bitcoin.scripts.multisigOutput(2, pubKeys) // 2 of 3 var scriptPubKey = bitcoin.scripts.scriptHashOutput(redeemScript.getHash()) var address = bitcoin.Address.fromOutputScript(scriptPubKey).toString() assert.strictEqual(address, '36NUkt6FWUi3LAWBqWRdDmdTWbt91Yvfu7') }) it('can spend from a 2-of-4 multsig P2SH address', function (done) { this.timeout(20000) var keyPairs = [ '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgwmaKkrx', '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgww7vXtT', '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgx3cTMqe', '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgx9rcrL7' ].map(function (wif) { return bitcoin.ECPair.fromWIF(wif, bitcoin.networks.testnet) }) var pubKeys = keyPairs.map(function (x) { return x.getPublicKeyBuffer() }) var redeemScript = bitcoin.scripts.multisigOutput(2, pubKeys) // 2 of 4 var scriptPubKey = bitcoin.scripts.scriptHashOutput(redeemScript.getHash()) var address = bitcoin.Address.fromOutputScript(scriptPubKey, bitcoin.networks.testnet).toString() // attempt to send funds to the source address blockchain.t.faucet(address, 2e4, function (err) { if (err) return done(err) // get latest unspents from the address blockchain.t.addresses.unspents(address, function (err, unspents) { if (err) return done(err) // filter small unspents unspents = unspents.filter(function (unspent) { return unspent.value > 1e4 }) // use the oldest unspent var unspent = unspents.pop() // make a random destination address var targetAddress = bitcoin.ECPair.makeRandom({ network: bitcoin.networks.testnet }).getAddress() var txb = new bitcoin.TransactionBuilder(bitcoin.networks.testnet) txb.addInput(unspent.txId, unspent.vout) txb.addOutput(targetAddress, 1e4) // sign with 1st and 3rd key txb.sign(0, keyPairs[0], redeemScript) txb.sign(0, keyPairs[2], redeemScript) // broadcast our transaction blockchain.t.transactions.propagate(txb.build().toHex(), function (err) { if (err) return done(err) // check that the funds (1e4 Satoshis) indeed arrived at the intended address blockchain.t.addresses.summary(targetAddress, function (err, result) { if (err) return done(err) assert.strictEqual(result.balance, 1e4) done() }) }) }) }) }) })
JavaScript
0.000023
@@ -779,27 +779,16 @@ tPubKey) -.toString() %0A%0A as @@ -1638,19 +1638,8 @@ net) -.toString() %0A%0A
1cde5704849e3353e3719294947c157cce5df39b
Update format.spec.js
test/pipeline/format.spec.js
test/pipeline/format.spec.js
import { expect } from 'chai' import { formatEvent, buildEvent } from '../../src/pipeline' describe('pipeline.formatEvent', () => { it('writes default values when no attributes passed', () => { const event = buildEvent() const formattedEvent = formatEvent(event) expect(formattedEvent).to.contain('BEGIN:VCALENDAR') expect(formattedEvent).to.contain('VERSION:2.0') expect(formattedEvent).to.contain('PRODID:adamgibbons/ics') expect(formattedEvent).to.contain('BEGIN:VEVENT') expect(formattedEvent).to.contain('SUMMARY:Untitled event') expect(formattedEvent).to.contain('UID:') expect(formattedEvent).to.contain('DTSTART:') expect(formattedEvent).to.contain('DTSTAMP:20') expect(formattedEvent).to.contain('END:VEVENT') expect(formattedEvent).to.contain('END:VCALENDAR') }) it('writes a title', () => { const event = buildEvent({ title: 'foo bar' }) const formattedEvent = formatEvent(event) expect(formattedEvent).to.contain('SUMMARY:foo bar') }) it('writes a start date-time', () => { const event = buildEvent({ start: [2017, 5, 15, 10, 0] }) const formattedEvent = formatEvent(event) expect(formattedEvent).to.contain('DTSTART:2017051') }) it('writes an end date-time', () => { const event = buildEvent({ end: [2017, 5, 15, 11, 0] }) const formattedEvent = formatEvent(event) expect(formattedEvent).to.contain('DTEND:2017051') }) it('writes a description', () => { const event = buildEvent({ description: 'bar baz' }) const formattedEvent = formatEvent(event) expect(formattedEvent).to.contain('DESCRIPTION:bar baz') }) it('writes a url', () => { const event = buildEvent({ url: 'http://www.example.com/' }) const formattedEvent = formatEvent(event) expect(formattedEvent).to.contain('URL:http://www.example.com/') }) it('writes a geo', () => { const event = buildEvent({ geo: { lat: 1.234, lon: -9.876 } }) const formattedEvent = formatEvent(event) expect(formattedEvent).to.contain('GEO:1.234;-9.876') }) it('writes a location', () => { const event = buildEvent({ location: 'Folsom Field, University of Colorado at Boulder' }) const formattedEvent = formatEvent(event) expect(formattedEvent).to.contain('LOCATION:Folsom Field, University of Colorado at Boulder') }) it('writes a status', () => { const event = buildEvent({ status: 'tentative' }) const formattedEvent = formatEvent(event) expect(formattedEvent).to.contain('STATUS:tentative') }) it('writes categories', () => { const event = buildEvent({ categories: ['boulder', 'running'] }) const formattedEvent = formatEvent(event) expect(formattedEvent).to.contain('CATEGORIES:boulder,running') }) it('writes attendees', () => { const event = buildEvent({ attendees: [ {name: 'Adam Gibbons', email: 'adam@example.com'}, {name: 'Brittany Seaton', email: 'brittany@example.com', rsvp: true } ]}) const formattedEvent = formatEvent(event) expect(formattedEvent).to.contain('ATTENDEE;RSVP=FALSE;CN=Adam Gibbons:mailto:adam@example.com') expect(formattedEvent).to.contain('ATTENDEE;RSVP=TRUE;CN=Brittany Seaton:mailto:brittany@example.com') }) it('writes an organizer', () => { const event = formatEvent({ organizer: { name: 'Adam Gibbons', email: 'adam@example.com' }}) const formattedEvent = formatEvent(event) expect(event).to.contain('ORGANIZER;CN=Adam Gibbons:mailto:adam@example.com') }) it('writes an alarm', () => { const formattedEvent = formatEvent({ alarms: [{ action: 'audio', trigger: [1997, 2, 17, 1, 30], repeat: 4, duration: { minutes: 15 }, attach: 'ftp://example.com/pub/sounds/bell-01.aud' }]}) expect(formattedEvent).to.contain('BEGIN:VALARM') expect(formattedEvent).to.contain('TRIGGER;VALUE=DATE-TIME:19970217T') expect(formattedEvent).to.contain('REPEAT:4') expect(formattedEvent).to.contain('DURATION:PT15M') expect(formattedEvent).to.contain('ACTION:audio') expect(formattedEvent).to.contain('ATTACH;FMTTYPE=audio/basic:ftp://example.com/pub/sounds/bell-01.aud') expect(formattedEvent).to.contain('END:VALARM') }) })
JavaScript
0.000003
@@ -4050,21 +4050,21 @@ 'ACTION: -audio +AUDIO ')%0A e
b560cc4a06d60dab74611af47455751395e9723f
Remove extraneous curly braces
test/precommit-entry-test.js
test/precommit-entry-test.js
import * as pce from '../src/precommit-entry'; import sinon from 'sinon'; import sPromise from 'sinon-as-promised'; import * as issueHandler from '../src/issue-handler'; import fsp from 'fs-promise'; import os from 'os'; let eol = os.EOL; describe('precommit-entry tests', () => { describe('Hook Message', () => { beforeEach(() => { sinon.stub(issueHandler, 'issueStrategizer', issues => { let jsonObjects = [ { 'issueType': { 'name': 'Story' } }, { 'issueType': { 'name': 'Story' } }, { 'issueType': { 'name': 'Story' } } ]; return jsonObjects; }); let readFileStub = sinon.stub(fsp, 'readFile'); readFileStub.resolves('TW-5032' + eol + 'TW-2380' + eol + 'TW-2018'); }); afterEach(() => { issueHandler.issueStrategizer.restore(); fsp.readFile.restore(); }); it('read from issue list and return JSON array', () => { return pce.getCommitMsg('issuesTestFile.txt') .then(results => { results.length.should.equal(3); }); }); }); describe('Issue number test', () => { it('Parse issue number, no issue numbers found', () => { pce.getIssueReference('no issue numbers here', 'TW').should.eql([]); }); it('Parse issue number', () => { pce.getIssueReference('TW-5734', 'TW').should.eql(['TW-5734']); }); it('Parse multiple issue numbers', () => { pce.getIssueReference('TW-763 blah TW-856', 'TW').should.eql(['TW-763', 'TW-856']); }); it('Parse multiple issue numbers, ignore duplicates', () => { pce.getIssueReference('TW-123 blah blah TW-123', 'TW').should.eql(['TW-123']); }); it('Parse issue number, ignore issue numbers in comments', () => { let content = 'TW-2345' + eol + '#TW-6346'; pce.getIssueReference(content, 'TW').should.eql(['TW-2345']); }); }); });
JavaScript
0.000081
@@ -1146,28 +1146,16 @@ sults =%3E - %7B%0A results @@ -1181,19 +1181,8 @@ l(3) -;%0A %7D );%0A
0bfd3a94f70b81573a5a1bfcf9709bee5e5cfeb9
test if focus is triggered by original select on select
test/spec/multiSelectSpec.js
test/spec/multiSelectSpec.js
describe("multiSelect", function() { var select; var msContainer; beforeEach(function() { $('<select id="multi-select" multiple="multiple" name="test[]"></select>').appendTo('body'); for (var i=1; i <= 10; i++) { $('<option value="value'+i+'">text'+i+'</option>').appendTo($("#multi-select")); }; select = $("#multi-select"); }); it ('should be chainable', function(){ select.multiSelect().addClass('chainable'); expect(select.hasClass('chainable')).toBeTruthy(); }); describe('init without options', function(){ beforeEach(function() { select.multiSelect(); msContainer = select.next(); }); it('should hide the standard select', function(){ expect(select.css('position')).toBe('absolute'); expect(select.css('left')).toBe('-9999px'); }); it('should create a container', function(){ expect(msContainer).toBe('div.ms-container'); }); it ('should create a selectable and a selection container', function(){ expect(msContainer).toContain('div.ms-selectable, div.ms-selection'); }); it ('should create a list for both selectable and selection container', function(){ expect(msContainer).toContain('div.ms-selectable ul.ms-list, div.ms-selection ul.ms-list'); }); it ('should populate the selectable list', function(){ expect($('.ms-selectable ul.ms-list li').length).toEqual(10); }); it ('should not populate the selection list if none of the option is selected', function(){ expect($('.ms-selection ul.ms-list li').length).toEqual(0); }); }); describe('init with pre-selected options', function(){ var selectedValues = []; beforeEach(function() { var firstOption = select.children('option').first(); var lastOption = select.children('option').last(); firstOption.prop('selected', true); lastOption.prop('selected', true); selectedValues.push(firstOption.val(), lastOption.val()); select.multiSelect(); msContainer = select.next(); }); it ('should select the pre-selected options', function(){ $.each(selectedValues, function(index, value){ expect($('.ms-selectable ul.ms-list li[ms-value="'+value+'"]')).toBe('.ms-selected'); }); expect($('.ms-selectable ul.ms-list li.ms-selected').length).toEqual(2); }); }); describe('init with keepOrder option activated', function(){ beforeEach(function() { $('#multi-select').multiSelect({ keepOrder: true }); msContainer = select.next(); firstItem = $('.ms-selectable ul.ms-list li').first() lastItem = $('.ms-selectable ul.ms-list li').last(); lastItem.trigger('click'); firstItem.trigger('click'); }); it('should keep order on selection list', function(){ expect($('.ms-selection li', msContainer).first().attr('ms-value')).toBe('value1'); expect($('.ms-selection li', msContainer).last().attr('ms-value')).toBe('value10'); }); }); describe("When selectable item is clicked", function(){ var clickedItem; beforeEach(function() { $('#multi-select').multiSelect(); clickedItem = $('.ms-selectable ul.ms-list li').first(); spyOnEvent(select, 'change'); clickedItem.trigger('click'); }); it('should hide selected item', function(){ expect(clickedItem).toBeHidden(); }); it('should add the .ms-selected to the selected item', function(){ expect(clickedItem).toBe('.ms-selected'); }); it('should select corresponding option', function(){ expect(select.children().first()).toBeSelected(); }); it('should populate the selection ul with the rigth item', function(){ expect($('.ms-selection ul.ms-list li').first()).toBe('li.ms-elem-selected[ms-value="value1"]'); }); it('should trigger the standard select change event', function(){ expect('change').toHaveBeenTriggeredOn("#multi-select"); }); afterEach(function(){ select.multiSelect('deselect_all'); }); }); afterEach(function () { $("#multi-select, .ms-container").remove(); }); });
JavaScript
0
@@ -3245,24 +3245,59 @@ 'change');%0A + spyOnEvent(select, 'focus');%0A clicke @@ -4001,24 +4001,150 @@ );%0A %7D);%0A%0A + it('should focus the original select', function()%7B%0A expect('focus').toHaveBeenTriggeredOn(%22#multi-select%22);%0A %7D);%0A%0A afterEac
07970f3875a3911be5d6d2ddc62179dbaa363bda
reinstate some semicolons
doc/_static/javascript/index.js
doc/_static/javascript/index.js
'use strict' window.addEventListener ('load', function () { const $links = $('ul > .toctree-l1') const $sublinks = $('.toctree-l2') const $allLinks = $('ul > .toctree-l1,.toctree-l2') const $sections = $('.section') const $menu = $('.wy-menu') const $searchArea = $('.wy-side-nav-search') const searchHeight = $searchArea.outerHeight () // change the DOM structure so that captions can slide over sidebar links let lastP = null for (const child of $menu.children ()) { if (child.nodeName === 'P') { lastP = child } else if (lastP !== null) { const $li = $('<li class="toctree-l1"></li>') $li.append (lastP) child.prepend ($li[0]) lastP = null } } // link the sidebar links and the sections const $topLinks = $links.find ('a.reference.internal[href="#"]') $topLinks.each (function () { const text = this.innerText.toLowerCase () $(this).attr ('href', '#' + text) }) // limit faq to just one question per link const $faq = $('a.reference.internal[href="#frequently asked questions"]') $faq.empty () let $faqlinks = $faq.siblings ().children ().children () if ($faqlinks.length === 0) { $faqlinks = $('a.reference.internal[href^="FAQ.html#"]') } $faqlinks.each (function () { this.parentNode.parentNode.remove () }) // set the height values for the sticky css property const $linkGroups = $links.parents ('ul') const heights = {} const size = $links.find (':not(".current")').innerHeight () $linkGroups.each (function () { const $sublinks = $(this).find ('li.toctree-l1') let height = -searchHeight + 2 for (const link of $sublinks) { const $link = $(link) heights[$link.children ().first ().attr ('href')] = -Math.ceil (height) height += size } }) const linksBySectionId = {} $sections.each (function () { linksBySectionId[this.id] = $allLinks.find ('a.reference.internal[href="#' + this.id + '"]').parent ().filter ('li') }) let lock = null let prevLock = null let last = null let lastLock = null let $current = null function open () { if (lock === null) { $current = $(this) if (prevLock !== this && $current.hasClass ('toctree-l1')) { lock = this prevLock = lock $links.removeClass ('current') $current.removeClass ('hidden') $current.addClass ('current', 400, 'linear', () => { lock = null if (last !== null && lastLock === null) { lastLock = last setTimeout (() => { open.call (last) lastLock = null }, 400) } }) // console.log ('setting height to ', heights[$current.children ().first ().attr ('href')]) $current.parent ().css ('top', heights[$current.children ().first ().attr ('href')]) } else { $sublinks.removeClass ('current') $links.not ($current.parent ().parent ()).removeClass ('current') $current.addClass ('current') } } else { last = this } } // $links.on ('mouseover', open) window.addEventListener ('scroll', () => { const fromTop = window.scrollY + window.innerHeight * 0.5 $sections.each (function () { if (this.offsetTop <= fromTop && this.offsetTop + this.offsetHeight > fromTop) { const sidelink = linksBySectionId[this.id] if (sidelink.length) { const element = sidelink[0] open.call (element) } } }) }) // change the width here... const width = 200 const height = width * 0.5625 const footerHeight = Math.max ((width / 400) * 32, 16) const iconSize = Math.max ((width / 400) * 24, 16) const footerPadding = Math.max ((width / 400) * 20, 10) const style = `.CLS-slider.swiper-wrapper{height: ${height}px}.CLS-footer{height: ${footerHeight}pxpadding: 0 ${footerPadding}px}.CLS-prev > svg, .CLS-next > svg{width: ${iconSize}px height: ${iconSize}px}` // hack into the binance sdk /0-0\ /0v0\ /0-0\ function onReadyStateChangeReplacement () { let result if (this._onreadystatechange) { result = this._onreadystatechange.apply (this, arguments) } // after binance's setTimeout setTimeout (() => { $('.swiper-slide').css ('width', width + 'px') $('.swiper-container').css ('max-width', width + 'px') $('#widget').css ('display', 'initial').trigger ('resize') $('#widget-wrapper').css ('border-style', 'solid') const brokerRef = $('.bnc-broker-widget-link') for (let i = 0 i < brokerRef.length i++) { const element = brokerRef[i] const url = new URL (element.href) element.href = url.origin + url.pathname } }, 0) return result } const openRequest = window.XMLHttpRequest.prototype.open function openReplacement (method, url, async, user, password) { if (this.onreadystatechange) { this._onreadystatechange = this.onreadystatechange } this.onreadystatechange = onReadyStateChangeReplacement return openRequest.call (this, method, url, async, user, password) } window.XMLHttpRequest.prototype.open = openReplacement window.binanceBrokerPortalSdk.initBrokerSDK ('#widget', { 'apiHost': 'https://www.binance.com', 'brokerId': 'R4BD3S82', 'slideTime': 40.0e3, 'overrideStyle': style, }) const createThemeSwitcher = () => { const $btn = $('<div id="btn-wrapper"><btn id="themeSwitcher" class="theme-switcher"><i id="themeMoon" class="fa fa-moon-o"></i><i id="themeSun" class="fa fa-sun-o"></i></btn></div>') const $previous = $('.btn.float-left') if ($previous.length) { $previous.after ($btn) } else { const $next = $('.btn.float-right') $next.after ($btn) } if (localStorage.getItem ('theme') === 'dark') { $('#themeMoon').hide (0) } else { $('#themeSun').hide (0) } } const switchTheme = function () { const $this = $(this) if ($this.attr ('disabled')) { return } $this.attr ('disabled', true) if (localStorage.getItem ('theme') === 'dark') { localStorage.setItem ('theme', 'light') document.documentElement.setAttribute ('data-theme', 'light') $('#themeSun').fadeOut (150, () => { $('#themeMoon').fadeIn (150, () => { $this.attr ('disabled', false) }) }) } else { localStorage.setItem ('theme', 'dark') document.documentElement.setAttribute ('data-theme', 'dark') $('#themeMoon').fadeOut (150, () => { $('#themeSun').fadeIn (150, () => { $this.attr ('disabled', false) }) }) } } createThemeSwitcher () $('#themeSwitcher').click (switchTheme) $('colgroup').remove () })
JavaScript
0.999991
@@ -5088,16 +5088,17 @@ et i = 0 +; i %3C bro @@ -5110,16 +5110,17 @@ f.length +; i++) %7B%0A
89f7265711ca2e5551bdaeeb2e7566fec9e1926e
use prev safari version while latest doesnt work on sauce (#5011)
karma-demo.conf.js
karma-demo.conf.js
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html const customLaunchers = require('./scripts/sauce-browsers').customLaunchers; module.exports = function (config) { const configuration = { basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-firefox-launcher'), require('karma-ie-launcher'), require('karma-edge-launcher'), require('karma-safari-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], // files: [ // {pattern: './scripts/test.ts', watched: false} // ], // preprocessors: { // './scripts/test.ts': ['@angular-devkit/build-angular'] // }, coverageIstanbulReporter: { dir: require('path').join(__dirname, 'coverage'), reports: ['html', 'lcovonly'], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: config.angularCli && config.angularCli.codeCoverage ? ['dots', 'coverage-istanbul'] : ['dots', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], browserNoActivityTimeout: 20000, browserDisconnectTolerance: 2, browserDisconnectTimeout: 5000, singleRun: true, customLaunchers: { Chrome_travis_ci: { base: 'ChromeHeadless', flags: [ '--headless', '--disable-gpu', '--no-sandbox', '--remote-debugging-port=9222' ] } }, mime: {'text/x-typescript': ['ts', 'tsx']}, client: {captureConsole: true, clearContext: false} }; if (process.env.TRAVIS) { configuration.browsers = ['Chrome_travis_ci']; } if (process.env.SAUCE) { if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) { console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.'); process.exit(1); } configuration.plugins.push(require('karma-sauce-launcher')); Object.assign(configuration, { logLevel: config.LOG_INFO, reporters: ['dots', 'saucelabs'], singleRun: true, concurrency: 2, captureTimeout: 60000, sauceLabs: { testName: 'ngx-bootstrap', build: process.env.TRAVIS_JOB_NUMBER, tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER, // retryLimit: 5, startConnect: false, recordVideo: false, recordScreenshots: false, options: { 'command-timeout': 600, 'idle-timeout': 600, 'max-duration': 5400 } }, customLaunchers: { //LATEST /*'SL_CHROME': { base: 'SauceLabs', browserName: 'chrome', version: 'latest' },*/ 'SL_FIREFOX': { base: 'SauceLabs', browserName: 'firefox', version: 'latest' }, 'SL_IE11': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 8.1', version: '11.0' }, 'SL_EDGE': { base: 'SauceLabs', browserName: 'MicrosoftEdge', version: 'latest' }, 'SL_SAFARI': { base: 'SauceLabs', browserName: 'safari', version: 'latest' } //LATEST-1 /*'SL_CHROME_1': { base: 'SauceLabs', browserName: 'chrome', version: 'latest-1' }, 'SL_FIREFOX_1': { base: 'SauceLabs', browserName: 'firefox', version: 'latest-1' }, 'SL_IE_1': { base: 'SauceLabs', browserName: 'internet explorer', version: 'latest-1' }, 'SL_EDGE_1': { base: 'SauceLabs', browserName: 'MicrosoftEdge', version: 'latest-1' }, 'SL_SAFARI_1': { base: 'SauceLabs', browserName: 'safari', version: 'latest-1' }*/ } }); configuration.browsers = Object.keys(configuration.customLaunchers); } config.set(configuration); };
JavaScript
0
@@ -3566,32 +3566,34 @@ version: 'latest +-1 '%0A %7D%0A
d8e1ee477f1600d51c4c9ee9d9b2c1d7074ff5eb
Update itemslide.js
src/itemslide.js
src/itemslide.js
(function ($) { var accel = 0; var overallslide = 0; var sensitivity = 20; var slides; var currentIndex = 0; //Waypoints check position relative to waypoint and decide if to scroll to or not... $.fn.initslide = function () { //var target = $(this).attr('id'); //alert(target); //$(this) // (WIDTH of (this) - WIDTH of slide)/2 slides = $(this); //Saves the object given to the plugin in a variable console.log(slides.css("width")); slides.css("left", ($("body").css("width").replace("px","")-slides.css("left").replace("px","")-slides.children('li').css("width").replace("px",""))/2);//Centerize sliding area console.log(slides.css("left")); $('li:nth-child(' + (currentIndex + 1) + ')').attr('id', 'active'); var mc = new Hammer(slides.get(0)); //Retrieve DOM Elements to create hammer.js object mc.on("panleft panright", function (ev) {//Hammerjs pan(drag) event happens very fast slides.css("left", "+="+ev.velocityX);//Change x of slides to velocity of drag }); mc.on("swipe", function (ev) {//Hammerjs Swipe (called when mouse realsed after mouse down) console.log(ev.velocityX); slides.animate({ left: "-="+(ev.velocityX*250) }, { /*duration: 225,*/ easing: 'easeOutQuart'//Choose easing from easing plugin http://gsgd.co.uk/sandbox/jquery/easing/ }); },{ velocity: 0.05,//minimum velocity threshold: 0//Minimum distance }); } $.fn.next = function () { //Next slide changeActiveSlideTo(currentIndex + 1); } function changeActiveSlideTo(i) { $('li:nth-child(' + (currentIndex + 1) + ')').attr('id', ''); currentIndex = i; console.log("new index: " + currentIndex); $('li:nth-child(' + (currentIndex + 1) + ')').attr('id', 'active'); } })(jQuery);
JavaScript
0.000001
@@ -1114,17 +1114,17 @@ left%22, %22 -+ +- =%22+ev.ve
7a8970f988527f88c2df47f8d1012bc301f3e5b7
copy paste fail
app-engine-proxy.js
app-engine-proxy.js
var https = require('https'); var http = require('http'); var util = require('util'); var path = require('path'); var fs = require('fs'); var url = require('url'); var httpProxy = require('http-proxy'); var respond = function(status, msg, res){ res.writeHead(status, {'content-type': 'text/plain'}); res.write(msg); res.end(); } var getHTTPSOptions = function() { return JSON.parse(fs.readFileSync('config.json', 'utf8')).keyCert; } var getHTTPSOptions = function() { return JSON.parse(fs.readFileSync('config.json', 'utf8')).keyCert; } var proxy = httpProxy.createProxyServer({}); proxy.on('proxyReq', function (proxyReq, req, res) { }); proxy.on('proxyRes', function (proxyRes, req, res) { }); // var server = http.createServer(function(req, res) { var server = https.createServer(httpsOptions, function(req, res) { console.log(req.url); if(req.url == '/health-check') { return respond(200, '', res); } if(!req.headers['x-target']) { return respond(400, 'required header "X-Target" not found', res); } var target = req.headers['x-target']; var proxyURL = url.parse(target); var host = proxyURL.host; var protocol = proxyURL.protocol; var agent = (protocol == 'https:' ? https.globalAgent:http.globalAgent); req.url = ''; proxy.web(req, res, { target: target, agent: agent, headers: { host: host } }); }); // server.listen(8585); server.listen(443);
JavaScript
0.000001
@@ -437,32 +437,29 @@ ert;%0A%7D%0A%0Avar -getHTTPS +https Options = fu @@ -460,93 +460,107 @@ s = -func +%7B%0A key: fs.readFileSync(getHTTPSOp tion +s () - %7B%0A return JSON.parse(fs.readFileSync('config.json', 'utf8')).keyCert; +.key),%0A cert: fs.readFileSync(getHTTPSOptions().cert) %0A%7D%0A -%0A var
70911dbb2a143051916e5736960dd05b456811ef
Fix relative path handling.
app-require-path.js
app-require-path.js
'use strict'; module.exports = appRequirePath; var fs = require('fs'), path = require('path'); function appRequirePath(dirname) { var rootPath = detectRoot(dirname || path.dirname(__dirname)); var iface = { /** * Resolves a path. Expands ~ to the project root, and {% ENV %} to the * value of the specified environment variable or the default value. * * @param modulePath String path to the module **/ resolve: function resolve(modulePath) { if (modulePath[0] === '~') { modulePath = path.join(rootPath, modulePath.substr(1)); } modulePath = resolveEnvVars(modulePath); return modulePath; }, /** * requires a file relative to the applicaiton rootPath * * @param modulePath String path to the module **/ require: function requireModule(modulePath) { return require(iface.resolve(modulePath)); }, // TODO: add the good parts from [requireFrom](https://github.com/dskrepps/requireFrom) // add in createLinks method to add symlinks to node_modules for defined paths /** * returns the rootPath of the application/module **/ toString: function toString() { return rootPath; }, }; /** * creates the `path` getter/setter which allows overriding of the auto detected path. **/ Object.defineProperty(iface, 'path', { get: function() { return rootPath; }, set: function(explicitPath) { rootPath = explicitPath; }, enumerable: true, }); return iface; } /** * Detects the root path of the application. * * @param dirname String a directory within the application **/ function detectRoot(dirname) { // check for environment variables if (process.env.NODE_PATH || process.env.APP_ROOT_PATH) { return path.resolve(process.env.NODE_PATH || process.env.APP_ROOT_PATH); } var resolved = path.resolve(dirname), rootPath = null, parts = resolved.split(path.sep), i = parts.length, filename; // Attempt to locate root path based on the existence of `package.json` while (rootPath === null && i > 0) { try { filename = path.join(parts.slice(0, i).join(path.sep), 'package.json'); i--; if (fs.statSync(filename).isFile()) { rootPath = path.dirname(filename); } } catch(err) { // the ENOENT error just indicates we need to look up the path continue; } } // If the above didn't work, or this module is loaded globally, then // resort to require.main.filename (See http://nodejs.org/api/modules.html) if (null === rootPath) { console.log('using alternate method'); rootPath = path.dirname(require.main.filename); } return path.resolve(rootPath); } /** * resolve environment variables in `modulePath`. Valid syntax is {%VAR} or {%VAR%} with * an optional default value specified as {% VAR|default %}. If no default value is supplied * then an empty string will be used. * * @param modulePath String path to module **/ function resolveEnvVars(modulePath) { var nPos1 = modulePath.indexOf("{%"), nPos2, name, value, defaultVal, parts; while (nPos1 !== -1) { nPos2 = modulePath.indexOf("}", nPos1); name = modulePath.substring(nPos1 + 2, nPos2); if (name.slice(-1) === "%") { name = name.slice(0, -1); } parts = name.split('|'); name = parts[0].trim(); defaultVal = (parts[1] || '').trim(); value = process.env[name] || defaultVal; modulePath = modulePath.slice(0, nPos1) + value + modulePath.slice(nPos2 + 1); nPos1 = modulePath.indexOf("{%"); } return modulePath; }
JavaScript
0.000001
@@ -620,24 +620,147 @@ substr(1));%0A + %7D else if (modulePath%5B0%5D === '.') %7B%0A modulePath = path.join((dirname %7C%7C rootPath), modulePath);%0A
2238f533123a6fc07165139c6016178556c58fda
Add width to API
kendo.flippable.js
kendo.flippable.js
(function(f, define){ define([ "./kendo.core", "./kendo.fx" ], f); })(function(){ var __meta__ = { id: "flippable", name: "Flippable", category: "web", description: "The flippable widget displays a card that flips from front to back.", depends: [ "core", "fx" ] }; (function ($, undefined) { var kendo = window.kendo, ui = kendo.ui, Widget = ui.Widget, CLICK = "click", FLIPSTART = "flipStart", FLIPEND = "flipEnd", NS = ".kendoFlip", proxy = $.proxy; var Flippable = Widget.extend({ init: function(element, options) { var that = this; Widget.fn.init.call(this, element, options); element = that.element; that.panes = element.children(); that._wrapper(); that._panes(); that._effect(); element.on(CLICK + NS, proxy(that._click, that)); element.on(FLIPSTART + NS, proxy(that._flipStart, that)); element.on(FLIPEND + NS, proxy(that._flipEnd, that)); that._show(); }, options: { height: 0, name: "Flippable", duration: 800 }, events: [ CLICK, FLIPSTART, FLIPEND ], flipVertical: function() { this._flip(this.flipV); }, flipHorizontal: function() { this._flip(this.flipH); }, _flip: function(effect) { var reverse = this.reverse; effect.stop(); this._flipStart(this); reverse ? effect.reverse().then(this._flipEnd(this)) : effect.play().then(this._flipEnd(this)); this.reverse = !reverse; }, _flipStart: function(e) { this.trigger(FLIPSTART, { event: e }); }, _flipEnd: function(e) { this.trigger(FLIPEND, { event: e }); }, _wrapper: function() { var wrapper = this.element, panes = this.panes; var wrapperHeight = wrapper.height(); var frontHeight = panes.first().height(); height = this.options.height || (wrapperHeight > frontHeight ? wrapperHeight : frontHeight); wrapper.css({ position: "relative", height: height, }); }, _panes: function() { var panes = this.panes; panes.addClass('k-header'); panes.each(function() { var pane = $(this) pane.css({ position: "absolute", width: "100%", height: "100%" }); }); }, _effect: function() { var that = this, wrapper = that.element, panes = that.panes, back = panes.first(), front = panes.next(); that.flipH = kendo.fx(wrapper) .flipHorizontal(front, back) .duration(that.options.duration); that.flipV = kendo.fx(wrapper) .flipVertical(front, back) .duration(that.options.duration); that.reverse = false; }, _show: function() { var wrapper = this.element, panes = this.panes; panes.first().hide(); wrapper.show(); }, _click: function (e) { this.trigger(CLICK, { event: e }); } }); ui.plugin(Flippable); })(window.kendo.jQuery); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
JavaScript
0.000002
@@ -1161,16 +1161,38 @@ ght: 0,%0A + width: 0,%0A @@ -2444,16 +2444,68 @@ height,%0A + width: this.options.width %7C%7C %22auto%22%0A
e0bad532d86241f97d3f9e833b798ed80652380c
Automate confirmation clicking yes
test/unit/controllersSpec.js
test/unit/controllersSpec.js
'use strict'; /* jasmine specs for controllers go here */ describe('controllers', function(){ describe('ContactListCtrl', function() { var scope, ctrl, data; beforeEach(module('contactControllers', 'contactServices')); beforeEach(inject(function($controller, storageService) { scope = {}; data = [ { "name": "Lonnie Jackson", "id": 1, "phone": "(913)-384-0880", "address": "200 1st St." }, { "name": "Mark Scannell", "id": 2, "phone": "(913)-384-2645", "address": "300 2nd St." } ]; storageService.set('contactList', data); storageService.set('idCounter',2); ctrl = $controller('ContactListCtrl', { $scope:scope, storageService:storageService }); })); it('should have a controller ContactListCtrl', function() { expect(ctrl).toBeDefined(); }); it('should have 2 contacts', function() { expect(scope.contacts.length).toBe(2); }); }); describe('ContactDetailCtrl', function() { var scope, ctrl, storage; var rp, data; beforeEach(module('contactControllers', 'ngRoute', 'contactServices')); beforeEach(inject(function($controller, storageService, $routeParams) { scope = {}; data = [ { "name": "Lonnie Jackson", "id": 1, "phone": "(913)-384-0880", "address": "200 1st St." }, { "name": "Mark Scannell", "id": 2, "phone": "(913)-384-2645", "address": "300 2nd St." }, { "name": "Kyle Fisher", "id": 3, "phone": "(913)-384-2645", "address": "300 2nd St." } ]; storage = storageService; storage.set('contactList', data); rp = { "contactId": 2 }; ctrl = $controller('ContactDetailCtrl', { $scope:scope, $routeParams: rp, storageService:storage }); })); it('should have a controller ContactDetailCtrl', function() { expect(ctrl).toBeDefined(); }); it('should remove contact when clicking delete button', function() { expect(storage.has('contactList')).toBe(true); expect(storage.get('contactList').length).toBe(3); console.log(storage); scope.removeContact(); expect(storage.get('contactList').length).toBe(2); }); }); });
JavaScript
0.000448
@@ -1333,24 +1333,28 @@ var rp, data +, wY ;%0A%0A b @@ -1501,16 +1501,25 @@ teParams +, $window ) %7B%0A @@ -2330,16 +2330,229 @@ %7D;%0A + wY = %7B%0A confirm: function(msg) %7B%0A return true;%0A %7D,%0A location: %7B%0A href: '#/contacts/'%0A %7D%0A %7D;%0A @@ -2759,16 +2759,64 @@ :storage +,%0A $window:wY %0A
91470c366295c42872cd31d10f47b3b8496b5f71
FIX tests
test/unit/population.test.js
test/unit/population.test.js
import assert from 'assert'; import * as faker from 'faker'; import * as humansCollection from '../helper/humans-collection'; import * as RxDatabase from '../../dist/lib/rx-database'; import * as RxSchema from '../../dist/lib/rx-schema'; import * as RxDocument from '../../dist/lib/rx-document'; import * as util from '../../dist/lib/util'; describe('population.test.js', () => { describe('RxSchema.create', () => { describe('positive', () => { it('should allow to create a schema with a relation', async() => { const schema = RxSchema.create({ version: 0, properties: { bestFriend: { ref: 'human', type: 'string' } } }); assert.equal(schema.constructor.name, 'RxSchema'); }); it('should allow to create a schema with a relation in nested', async() => { const schema = RxSchema.create({ version: 0, properties: { foo: { type: 'object', properties: { bestFriend: { ref: 'human', type: 'string' } } } } }); assert.equal(schema.constructor.name, 'RxSchema'); }); it('should allow to create relation of array', async() => { const schema = RxSchema.create({ version: 0, properties: { friends: { type: 'array', items: { ref: 'human', type: 'string' } } } }); assert.equal(schema.constructor.name, 'RxSchema'); }); }); describe('negative', () => { it('throw if primary is ref', () => { assert.throws( () => RxSchema.create({ version: 0, properties: { bestFriend: { primary: true, ref: 'human', type: 'string' } } }), Error ); }); it('throw if ref-type is no string', () => { assert.throws( () => RxSchema.create({ version: 0, properties: { bestFriend: { ref: 'human' } } }), Error ); }); it('throw if ref-type is no string (array)', () => { assert.throws( () => RxSchema.create({ version: 0, properties: { friends: { type: 'array', items: { ref: 'human' } } } }), Error ); }); }); }); describe('RxDocument().populate()', () => { describe('positive', () => { it('populate top-level-field', async() => { const col = await humansCollection.createRelated(); const doc = await col.findOne().exec(); const friend = await doc.populate('bestFriend'); assert.equal(friend.constructor.name, 'RxDocument'); assert.equal(friend.name, doc.bestFriend); col.database.destroy(); }); it('populate nested field', async() => { const col = await humansCollection.createRelatedNested(); const doc = await col.findOne().exec(); const friend = await doc.populate('foo.bestFriend'); assert.equal(friend.constructor.name, 'RxDocument'); assert.equal(friend.name, doc.foo.bestFriend); col.database.destroy(); }); it('populate string-array', async() => { const db = await RxDatabase.create({ name: util.randomCouchString(10), adapter: 'memory' }); const col = await db.collection({ name: 'human', schema: { version: 0, type: 'object', properties: { name: { type: 'string', primary: true }, friends: { type: 'array', ref: 'human', items: { type: 'string' } } } } }); const friends = new Array(5).fill(0).map(() => { return { name: faker.name.firstName(), friends: [] }; }); await Promise.all(friends.map(friend => col.insert(friend))); const oneGuy = { name: 'Piotr', friends: friends.map(friend => friend.name) }; await col.insert(oneGuy); const doc = await col.findOne(oneGuy.name).exec(); const friendDocs = await doc.friends_; friendDocs.forEach(friend => { assert.equal(friend.constructor.name, 'RxDocument'); }); db.destroy(); }); }); }); describe('RxDocument populate via pseudo-proxy', () => { describe('positive', () => { it('populate top-level-field', async() => { const col = await humansCollection.createRelated(); const doc = await col.findOne().exec(); const friend = await doc.bestFriend_; assert.equal(friend.constructor.name, 'RxDocument'); assert.equal(friend.name, doc.bestFriend); col.database.destroy(); }); it('populate nested field', async() => { const col = await humansCollection.createRelatedNested(); const doc = await col.findOne().exec(); const friend = await doc.foo.bestFriend_; assert.equal(friend.constructor.name, 'RxDocument'); assert.equal(friend.name, doc.foo.bestFriend); col.database.destroy(); }); }); }); describe('issues', () => { it('#222 population not working when multiInstance: false', async() => { const db = await RxDatabase.create({ name: util.randomCouchString(10), adapter: 'memory', multiInstance: false // this must be false here }); const colA = await db.collection({ name: 'doca', schema: { name: 'doca', version: 0, properties: { name: { primary: true, type: 'string' }, refB: { ref: 'docb', // refers to collection human type: 'string' // ref-values must always be string (primary of foreign RxDocument) } } } }); const colB = await db.collection({ name: 'docb', schema: { name: 'docb', version: 0, properties: { name: { primary: true, type: 'string' }, somevalue: { type: 'string' } } } }); await colB.insert({ name: 'docB-01', somevalue: 'foobar' }); await colA.insert({ name: 'docA-01', refB: 'docB-01' }); const docA = await colA.findOne().where('name').eq('docA-01').exec(); const docB = await docA.populate('refB'); assert.ok(RxDocument.isInstanceOf(docB)); assert.equal(docB.somevalue, 'foobar'); db.destroy(); }); }); });
JavaScript
0.000001
@@ -5736,16 +5736,58 @@ y(5) -.fill(0) +%0A .fill(0)%0A .map @@ -5815,16 +5815,20 @@ + + return %7B @@ -5828,16 +5828,20 @@ eturn %7B%0A + @@ -5884,18 +5884,50 @@ stName() -,%0A + + util.randomCouchString(5),%0A @@ -5966,35 +5966,43 @@ -%7D;%0A + %7D;%0A @@ -7852,17 +7852,16 @@ : false - // this
c82f2d9ac8e6a1dfba7068ada5a112336e9ac532
fix typo in config file docs
src/js/config.js
src/js/config.js
/** * @description Game configuration object * @return {object} config Object containing the game settings */ var config = (function () { 'use strict'; var config = { bounds: { top: 121, right: 780, //808-28 bottom: 625, left: 0 }, rowHeight: 101, colWidth: 101, numRows: 8, numCols: 8, colImages: [ 'images/plain-sky-block.png', 'images/bridge-block.png', 'images/bridge-block.png', 'images/bridge-block.png', 'images/bridge-block.png', 'images/bridge-block.png', 'images/ground-block.png', 'images/plain-ground-block.png' ], playerStep: { x: 25, y: 101 }, /* Enemies speed ratio to fine-tune the speed*/ speedRatio: 10, collisionTolerance: { x: 30, y: 30, } }; return config; })();
JavaScript
0.000006
@@ -26,17 +26,17 @@ -c +C onfigura
1e02cc44c7101f9a313bf7674b0723bdde17b91a
Update hamlet.js
src/js/hamlet.js
src/js/hamlet.js
var GAME_SETUP = {npc: {hamlet: {happy: .4, // starting value scale 0..1 clarity: .5, operations: { anytime: { dagger_emote: { happy: [0, .55], // if happiness between these clarity: [.4, 1.0], p: 1/60, // once per minute target: "claudius", // or all or player effect: {claudius: [.04, 0], hamlet: [.05, 0], gertrude: [.02, 0]} // this model has the weakness // that claudius's and gertrude's responses should be a function of // their current state: if confused, then they may ignore the interaction. // if they are happy, then they should get confused not angry // if they are angry, it should amplify }, sword: { happy: [0, 0.05], // end game p: 0.5, // almost certain to occur in 5 seconds (1 - 0.5^5) target: "Claudius", endgame: "Claudius" // ends the game with claudius dead } }, drinks: { // shows how some operators can have different effects during different courses toast: { happy: [.6, 1.0], clarity: [0, 1.0], // anytime p: 1/(60 * 3), // once every 3 mins target: "all", effect: {ophelia: [0.1, 0], claudius: [0.05, 0], gertrude: [0.1, 0], hamlet: [0.05, 0]} } } }, appearance: [ // which image to use for each happiness x clarity range { happy: [0, .1], image: "hamlet_rage.jpg" } ] } }, course: { drinks: { start: 0, end: 45 // 0..45 seconds // image: drink.jpg, // x: ..., y: ... }, first: { start: 45, end: 105 }, main: { start: 105, end: 195 }, dessert: { start: 195, end: 240 } } }
JavaScript
0.000001
@@ -41,17 +41,17 @@ happy: . -4 +6 , // sta @@ -87,17 +87,17 @@ arity: . -5 +3 ,%0A op @@ -136,13 +136,11 @@ ger_ -emote +all : %7B%0A @@ -156,11 +156,12 @@ %5B0, -.55 +0.39 %5D, / @@ -205,15 +205,15 @@ y: %5B -.4, 1.0 +0, 0.39 %5D,%0A%09 @@ -252,24 +252,19 @@ arget: %22 -claudius +all %22, // or @@ -300,16 +300,18 @@ udius: %5B +-0 .04, 0%5D, @@ -311,25 +311,28 @@ 04, 0%5D, -hamlet +ophelia : %5B +-0 .05, 0%5D, @@ -343,16 +343,18 @@ trude: %5B +-0 .02, 0%5D%7D @@ -684,16 +684,188 @@ %09 %7D,%0A +%09 dagger_claudius: %7B%0A%09 %09happy: %5B0, 0.39%5D,%0A%09 %09clarity: %5B0.7, 1%5D,%0A%09 %09p: 1/60,%0A%09 %09target: %22claudius%22,%0A%09 %09effect: %7Bclaudius: %5B-0.02, 0%5D%7D%0A%09 %7D%0A%09 %7D%0A%09 %7D%0A %09 swo @@ -1483,35 +1483,342 @@ 0, . -1%5D,%0A image: %22hamlet_rage +39%5D,%0A clarity: %5B0, .39%5D,%0A image: %22hamlet_angry.jpg%22%0A %7D%0A %7B%0A %09happy: %5B.7, 1%5D,%0A %09clarity: %5B0, .39%5D,%0A %09image: %22hamlet_confused.jpg%22%0A %7D%0A %7B%0A %09happy: %5B0, .39%5D,%0A %09clarity: %5B.7, 1%5D,%0A %09image: %22hamlet_suspicious.jpg%22%0A %7D%0A %7B%0A %09happy: %5B.7, 1%5D,%0A %09clarity: %5B.7, 1%5D,%0A %09image: %22hamlet_excited.jpg%22%0A %7D%0A %7B%0A %09image: %22hamlet_neutral .jpg
7fde7e7afbb06f68b4d7076a3d063cae6bb96f46
Change google sign in menu item text
src/js/header.js
src/js/header.js
import { Link } from 'react-router'; import * as auth from './auth.js'; import logo from '../images/chalees-min-logo.png'; import logoHighDpi from '../images/chalees-min-logo@2x.png'; import mobileMenuIcon from '../images/icons/menu-icon.svg'; const Header = React.createClass({ showFacebookLoginPrompt: () => auth.showFacebookLoginPrompt(), showGoogleLoginPrompt: () => auth.showGoogleLoginPrompt(), getInitialState: () => ({}), componentWillMount: async function () { const user = await auth.authorize(); log('MOOOOOOOOOOOOOOOOO', user); if (user && user.hasOwnProperty('displayName') && !user.displayName) { this.setState({name: 'Account'}); } else if (user) { this.setState({name: user.displayName}); } }, logOut: async function () { await auth.signOut(); }, render: function () { const menuContents = ( <ul className="pure-menu-children"> <li className="pure-menu-item"> <a className="pure-menu-link" href="#" onClick={this.logOut}>Sign Out</a> </li> </ul> ); const userSection = this.state.name ? ( <ul className="pure-menu-list"> <li className="user-menu pure-menu-item pure-menu-has-children pure-menu-allow-hover main-nav-user-menu hidden-xs"> <a className="pure-menu-link" href="#">{this.state.name}</a> {menuContents} </li> <li className="user-menu pure-menu-item pure-menu-allow-hover main-nav-user-menu hidden-sm hidden-md hidden-lg hidden-xl"> <a className="pure-menu-link" href="#" style={{paddingRight: 0, paddingLeft: 0}}> <img src={mobileMenuIcon} style={{height: '100%', padding: 12}} /> </a> {menuContents} </li> </ul> ) : ( <ul className="pure-menu-list main-nav-user-menu"> <li className="user-menu pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <a className="pure-menu-link" href="#">Sign In</a> <ul className="pure-menu-children"> <li className="pure-menu-item"> <a href="#" onClick={this.showGoogleLoginPrompt} className="pure-menu-link"> <span>Sign In With Google</span> </a> </li> <li className="pure-menu-item"> <a href="#" onClick={this.showFacebookLoginPrompt} className="pure-menu-link"> <span>Sign In With Facebook</span> </a> </li> </ul> </li> </ul> ); return ( <header id="header" className="header"> <div className="container"> <div className="pure-g"> <div className="pure-u-1"> <nav className="home-menu pure-menu pure-menu-horizontal main-nav"> <Link to="/" className="header-brand"> <img src={logo} srcset={logo + " 1x, " + logoHighDpi + " 2x"} role="presentation" className="header-brand-logo" /> </Link> {userSection} </nav> </div> </div> </div> </header> ) } }) export default Header;
JavaScript
0.000003
@@ -2195,22 +2195,30 @@ In With +GMail ( Google +) %3C/span%3E%0A
c0d8bf8ffb242c29c4bb5a687cce655fea724609
enable pos sending after first ousedown on model
src/js/viewer.js
src/js/viewer.js
var processingMessage = false; var canSend = true; function initializeModelViewer() { showAllQuick(document.getElementById('viewer_object').runtime); document.getElementById('viewport').addEventListener('viewpointChanged', viewpointChanged); } function receiveViewpointMsg(extras){ //disable listening for changes in the viewport processingMessage = true; var cam = printPositionAndOrientation('Received', extras.position, extras.orientation); //apply new viewpoint document.getElementById('viewport').setAttribute('position', cam.pos); document.getElementById('viewport').setAttribute('orientation', cam.rot); //clear any previous timeout if(typeof reenableViewpointListeningTimeout != 'undefined'){ clearTimeout(reenableViewpointListeningTimeout); } //enable listening for changes in the viewport again some milliseconds after the last received msg reenableViewpointListeningTimeout = setTimeout(function(){processingMessage = false;} , 1000); } // Viewport section. function sendPositionAndOrientation(pos, rot) { //only send if there is a role environment the viewer is embedded in if(!isEmbeddedInRole){ return; } // Send through IWC! var viewpointMsg = {'position': pos, 'orientation': rot} //send to wrapper roleWrapper.postMessage("ViewpointUpdate " + JSON.stringify(viewpointMsg), "*"); } // Update position and rotation of the camera function viewpointChanged(evt) { // Prevent widgets from sending updates again and again // If we set the position because we received a message we do not want to send it back if(!evt || processingMessage) { return; } // You can only send data once every 0.1 seconds. if(!canSend) { document.getElementById('debugText').innerHTML = "Bypassing send!"; console.log("Bypassing send!"); return; } canSend = false; if(typeof sendTimeout != 'undefined'){ clearTimeout(sendTimeout); } sendTimeout = setTimeout(function(){ canSend = true; document.getElementById('debugText').innerHTML = "Can send again!"; console.log("Can send again!"); } , 100); printPositionAndOrientation('Updated', evt.position, evt.orientation); sendPositionAndOrientation(evt.position, evt.orientation); var intent = { 'component' :'', // recipient, empty for broadcast 'data' :'http://data.org/some/data', // data as URI 'dataType' :'text/xml', // data mime type 'action' :'ACTION_UPDATE', // action to be performed by receivers 'flags' :['PUBLISH_GLOBAL'], // control flags 'extras' :{'position': evt.position, 'orientation': evt.orientation}, // optional auxiliary data } console.info("subsite: intent: ", intent); } // Converts the position and orientation into a string and updates the view to display it. function printPositionAndOrientation(str, pos, rot) { var camPos = pos.x.toFixed(4) + ' ' + pos.y.toFixed(4) + ' ' + pos.z.toFixed(4); var camRot = rot[0].x.toFixed(4) + ' ' + rot[0].y.toFixed(4) + ' ' + rot[0].z.toFixed(4) + ' ' + rot[1].toFixed(4); document.getElementById('debugText').innerHTML = str + ' viewpoint position = ' + camPos + ' orientation = ' + camRot; return {'pos': camPos, 'rot': camRot}; } function showAllQuick(runtime, axis) { if (axis === undefined) axis = "negZ"; var scene = runtime.canvas.doc._viewarea._scene; scene.updateVolume(); var min = x3dom.fields.SFVec3f.copy(scene._lastMin); var max = x3dom.fields.SFVec3f.copy(scene._lastMax); var x = "x", y = "y", z = "z"; var sign = 1; var to, from = new x3dom.fields.SFVec3f(0, 0, -1); switch (axis) { case "posX": sign = -1; case "negX": z = "x"; x = "y"; y = "z"; to = new x3dom.fields.SFVec3f(sign, 0, 0); break; case "posY": sign = -1; case "negY": z = "y"; x = "z"; y = "x"; to = new x3dom.fields.SFVec3f(0, sign, 0); break; case "posZ": sign = -1; case "negZ": default: to = new x3dom.fields.SFVec3f(0, 0, -sign); break; } var viewpoint = scene.getViewpoint(); var fov = viewpoint.getFieldOfView(); var dia = max.subtract(min); var diaz2 = dia[z] / 2.0, tanfov2 = Math.tan(fov / 2.0); var dist1 = (dia[y] / 2.0) / tanfov2 + diaz2; var dist2 = (dia[x] / 2.0) / tanfov2 + diaz2; dia = min.add(dia.multiply(0.5)); dia[z] += sign * (dist1 > dist2 ? dist1 : dist2) * 1.01; var quat = x3dom.fields.Quaternion.rotateFromTo(from, to); var viewmat = quat.toMatrix(); viewmat = viewmat.mult(x3dom.fields.SFMatrix4f.translation(dia.negate())); runtime.canvas.doc._viewarea._scene.getViewpoint().setView(viewmat); };
JavaScript
0
@@ -24,16 +24,73 @@ false;%0A +//can I currently send an updated pose to other devices?%0A var canS @@ -105,19 +105,20 @@ = -tru +fals e;%0A%0Afunc @@ -309,16 +309,117 @@ anged);%0A + document.getElementById('viewer_object').addEventListener('mousedown', enableSendingOnFirstClick);%0A %7D%0A%0Afunct @@ -5000,8 +5000,342 @@ at);%0A%7D;%0A +%0A/**%0A * Enable sending of the updated pose after the first click.%0A * This prevents sending a pose when opening the model and the view get automatically updated.%0A */%0Afunction enableSendingOnFirstClick(evt)%7B%0A canSend = true;%0A document.getElementById('viewer_object').removeEventListener('mousedown', enableSendingOnFirstClick);%0A%7D%0A
fa3b58e291bc4a5f403dd677729852a15d34bd7e
update img picker with file comment
plugins/img_picker/img_picker.js
plugins/img_picker/img_picker.js
(function(exports) { 'use strict'; var requires = [require('bs_slider-js')]; require('bs_slider-css'); var defaultStateFunc = function(state) { console.log(state); }, stateFunction = defaultStateFunc; /** * Capitalizes the first letter of a string * @param String string The string to capitalize the first letter of * @return String The string with the first letter capitalized */ var capitalize = function(string) { return string.charAt(0).toUpperCase() + string.slice(1); }; /** * Deep copies an object and returns it * @param Object object The object to deep copy * @return Object The deep copy of the object */ var clone = function(object) { return { name: object.name, sample: object.sample.clone(), exposure: object.exposure, cycle: object.cycle }; }; var buildSlider = function (thisDiv, arr, setVal, update, type) { var retDiv, i, title; for (i = 0; i < arr.length; i += 1) { if (arr[i] === setVal) { setVal = i; break; } } title = $('<h2>' + capitalize(type) + '</h2>'); retDiv = $('<input type="text" />'); thisDiv.append(title).append($('<div>', {class: 'center-block', style: 'width:90%'}).append(retDiv)); retDiv.slider({ value: setVal, min: 0, max: arr.length - 1, tooltip_position: 'bottom', tooltip: 'always', formatter: function (value) { return arr[value]; } }).on('slideStop', function (e) { update(type, arr[e.value]); }); }; var displayData = function (data) { // var options = {}; var i, samps = data.list('names'), selected = { name: null, sample: null, exposure: 50, cycle: 'Post Wash' }, buildPageParts, update, $page_build = {}, main = {}; $page_build.div = $('<div>'); main.div = $page_build.div; main.change = function(customStateFunc) { if (typeof customStateFunc === 'function') { stateFunction = customStateFunc; stateFunction(clone(selected)); } else { console.error('The change function requires a function, not this', customStateFunc); } } buildPageParts = function () { $page_build.cyclePicker.empty(); $page_build.exposurePicker.empty(); buildSlider($page_build.cyclePicker, selected.sample.list('cycle'), selected.cycle, update, 'cycle'); buildSlider($page_build.exposurePicker, selected.sample.list('exposure'), selected.exposure, update, 'exposure'); }; //cycle picker update = function (key, value) { var j, c; if (selected[key] !== value) { selected[key] = value; if (key === 'name') { selected.sample = data.get({name: value, get_samples: true})[0]; buildPageParts(); } stateFunction(clone(selected)); } }; $page_build.img_picker = $('<div>', {class: 'row'}); //sample picker $page_build.samp_picker = $('<div>'); $('<h2>Sample</h2>').appendTo($page_build.samp_picker); $page_build.samp_dropdown = $('<select>', {class: 'form-control'}).appendTo($page_build.samp_picker); for (i = 0; i < samps.length; i += 1) { $page_build.samp_dropdown.append('<option value="' + samps[i] + '" >' + samps[i] + '</option>'); } $page_build.samp_picker.appendTo($('<div>', {class: 'col-sm-4 col-xs-12'}).appendTo($page_build.img_picker)); $page_build.samp_dropdown.change(function (evt) { update('name', $(this).val()); }); //set up for slide bars $page_build.cyclePicker = $('<div>', {class: 'col-sm-4 col-xs-12'}).appendTo($page_build.img_picker); $page_build.exposurePicker = $('<div>', {class: 'col-sm-4 col-xs-12'}).appendTo($page_build.img_picker); //Add it to the page $page_build.img_picker.appendTo($page_build.div); update('name', samps[0]); return main; }; exports.imagePicker = displayData; // var data1 = KINOME.get({level: '1.0.1'}); // Promise.all(requires).then(function() { // KINOME.addAnalysis('image_picker').append(exports.imagePicker(data1)); // }); }(KINOME));
JavaScript
0
@@ -1,8 +1,277 @@ +/**%0A * Image Picker%0A * Copyright 2017 Tim Kennell Jr.%0A * Licensed under the MIT License (http://opensource.org/licenses/MIT)%0A **%0A * Allows selection of samples, cycles, and exposures%0A **%0A * Dependencies%0A * * Bootstrap Slider (http://seiyria.com/bootstrap-slider/)%0A */%0A %0A(functi @@ -2838,32 +2838,149 @@ %7D%0A %7D +;%0A%0A main.disableSample = function() %7B%0A $page_build.samp_dropdown.prop('disabled', true);%0A %7D; %0A%0A buildP
01191c41e5a4bcc4e4011b0a8050661a948f457e
make the order match
tests/api.treatments.test.js
tests/api.treatments.test.js
'use strict'; var request = require('supertest'); var should = require('should'); describe('Treatment API', function ( ) { this.timeout(2000); var self = this; var api = require('../lib/api/'); beforeEach(function (done) { process.env.API_SECRET = 'this is my long pass phrase'; self.env = require('../env')(); self.env.settings.enable = ['careportal']; this.wares = require('../lib/middleware/')(self.env); self.app = require('express')(); self.app.enable('api'); require('../lib/bootevent')(self.env).boot(function booted(ctx) { self.ctx = ctx; self.app.use('/api', api(self.env, ctx)); done(); }); }); after(function () { delete process.env.API_SECRET; }); it('post single treatments', function (done) { var doneCalled = false; self.ctx.bus.on('data-loaded', function dataWasLoaded ( ) { self.ctx.ddata.treatments.length.should.equal(3); self.ctx.ddata.treatments[0].mgdl.should.equal(100); should.not.exist(self.ctx.ddata.treatments[0].eventTime); should.not.exist(self.ctx.ddata.treatments[0].notes); should.not.exist(self.ctx.ddata.treatments[1].eventTime); should.not.exist(self.ctx.ddata.treatments[1].glucose); should.not.exist(self.ctx.ddata.treatments[1].glucoseType); should.not.exist(self.ctx.ddata.treatments[1].units); self.ctx.ddata.treatments[1].insulin.should.equal(2); self.ctx.ddata.treatments[2].carbs.should.equal(30); //if travis is slow the 2 posts take long enough that 2 data-loaded events are emitted if (!doneCalled) { done(); } doneCalled = true; }); self.ctx.treatments().remove({ }, function ( ) { request(self.app) .post('/api/treatments/') .set('api-secret', self.env.api_secret || '') .send({eventType: 'BG Check', glucose: 100, preBolus: '0', glucoseType: 'Finger', units: 'mg/dl', notes: ''}) .expect(200) .end(function (err) { if (err) { done(err); } }); request(self.app) .post('/api/treatments/') .set('api-secret', self.env.api_secret || '') .send({eventType: 'Meal Bolus', carbs: '30', insulin: '2.00', preBolus: '15', glucoseType: 'Finger', units: 'mg/dl'}) .expect(200) .end(function (err) { if (err) { done(err); } }); }); }); it('post a treatment array', function (done) { var doneCalled = false; self.ctx.bus.on('data-loaded', function dataWasLoaded ( ) { self.ctx.ddata.treatments.length.should.equal(3); self.ctx.ddata.treatments[0].mgdl.should.equal(100); should.not.exist(self.ctx.ddata.treatments[0].eventTime); should.not.exist(self.ctx.ddata.treatments[0].notes); should.not.exist(self.ctx.ddata.treatments[1].eventTime); should.not.exist(self.ctx.ddata.treatments[1].glucose); should.not.exist(self.ctx.ddata.treatments[1].glucoseType); should.not.exist(self.ctx.ddata.treatments[1].units); self.ctx.ddata.treatments[1].insulin.should.equal(2); self.ctx.ddata.treatments[2].carbs.should.equal(30); //if travis is slow the 2 posts take long enough that 2 data-loaded events are emitted if (!doneCalled) { done(); } doneCalled = true; }); self.ctx.treatments().remove({ }, function ( ) { request(self.app) .post('/api/treatments/') .set('api-secret', self.env.api_secret || '') .send([ {eventType: 'BG Check', glucose: 100, preBolus: '0', glucoseType: 'Finger', units: 'mg/dl', notes: ''} , {eventType: 'Meal Bolus', carbs: '30', insulin: '2.00', preBolus: '15', glucoseType: 'Finger', units: 'mg/dl'} ]) .expect(200) .end(function (err) { if (err) { done(err); } }); }); }); it('post a treatment array and dedupe', function (done) { var doneCalled = false; self.ctx.bus.on('data-loaded', function dataWasLoaded ( ) { self.ctx.ddata.treatments.length.should.equal(3); self.ctx.ddata.treatments[0].mgdl.should.equal(100); //if travis is slow the 2 posts take long enough that 2 data-loaded events are emitted if (!doneCalled) { done(); } doneCalled = true; }); self.ctx.treatments().remove({ }, function ( ) { var now = (new Date()).toISOString(); request(self.app) .post('/api/treatments/') .set('api-secret', self.env.api_secret || '') .send([ {eventType: 'Meal Bolus', carbs: '30', insulin: '2.00', preBolus: '15', glucoseType: 'Finger', units: 'mg/dl'} , {eventType: 'BG Check', glucose: 100, created_at: now} , {eventType: 'BG Check', glucose: 100, created_at: now} , {eventType: 'BG Check', glucose: 100, created_at: now} , {eventType: 'BG Check', glucose: 100, created_at: now} , {eventType: 'BG Check', glucose: 100, created_at: now} , {eventType: 'BG Check', glucose: 100, created_at: now} , {eventType: 'BG Check', glucose: 100, created_at: now} , {eventType: 'BG Check', glucose: 100, created_at: now} ]) .expect(200) .end(function (err) { if (err) { done(err); } }); }); }); });
JavaScript
0.000002
@@ -4581,131 +4581,8 @@ ype: - 'Meal Bolus', carbs: '30', insulin: '2.00', preBolus: '15', glucoseType: 'Finger', units: 'mg/dl'%7D%0A , %7BeventType: 'BG @@ -5082,32 +5082,155 @@ reated_at: now%7D%0A + , %7BeventType: 'Meal Bolus', carbs: '30', insulin: '2.00', preBolus: '15', glucoseType: 'Finger', units: 'mg/dl'%7D%0A %5D)%0A
65bad76cb2f9674e2ee4ac7e1bbf9eca66606015
Add unit tests for the status code description
tests/helper.service.spec.js
tests/helper.service.spec.js
describe('Helper Service', function() { beforeEach(module('clientApp')); var appHelper; beforeEach(inject(function(_appHelper_){ appHelper = _appHelper_; })); describe('isValidResponse', function() { it('should check that the response is valid', function() { var invalidResponses = [ "", {}, {id: "foo"}, {status: 200}, {config: {}} ]; for (var invalid of invalidResponses) { expect(appHelper.isValidResponse(invalid)).toBeFalsy(); } var valid = {status: 200, config: {}}; expect(appHelper.isValidResponse(valid)).toBeTruthy(); }); }); describe('isHtml', function() { it('should not be blank', function() { expect(appHelper.isHtml()).toBeFalsy(); expect(appHelper.isHtml("")).toBeFalsy(); }); it('should be of type HTML', function() { expect(appHelper.isHtml("application/json")).toBeFalsy(); expect(appHelper.isHtml("text/html; charset=utf-8")).toBeTruthy(); expect(appHelper.isHtml("text/html")).toBeTruthy(); }); }); describe('calculateObjectSize', function() { it('should roughly calculate the size of the specifed object', function() { expect(appHelper.calculateObjectSize({})).toBe(0); var largeObject = {}; for (var x = 0; x <= 100; x++) { largeObject[x] = new Date().toUTCString(); } expect(appHelper.calculateObjectSize(largeObject)).toBeGreaterThan(1000); //TODO trigger an exception to test -1 is returned //expect(appHelper.calculateObjectSize({})).toBe(-1); }); }); });
JavaScript
0.000001
@@ -1599,13 +1599,1763 @@ );%0A %7D); +%0A%0A describe('determineStatus', function() %7B%0A it('should return the XMLHttpRequest value if the request failed', function() %7B%0A expect(appHelper.determineStatus(-1, %22error%22)).toBe(%22ERROR%22);%0A expect(appHelper.determineStatus(-1, %22foo%22)).toBe(%22FOO%22);%0A expect(appHelper.determineStatus(-1, %22%22)).toBe(%22%22);%0A expect(appHelper.determineStatus(-1, undefined)).toBe(%22%22);%0A %7D);%0A it('should return the status value if the request succeeded', function() %7B%0A expect(appHelper.determineStatus(200, %22foo%22)).toBe(%22200%22);%0A expect(appHelper.determineStatus(500, undefined)).toBe(%22500%22);%0A expect(appHelper.determineStatus(undefined, %22foo%22)).toBeUndefined();%0A %7D);%0A %7D);%0A%0A describe('determineStatusText', function() %7B%0A it('should return an unknown status text if none is available', function() %7B%0A expect(appHelper.determineStatusText(999, undefined)).toBe(HTTP_STATUS_DESCRIPTIONS.UNKNOWN);%0A expect(appHelper.determineStatusText(999, %22%22)).toBe(HTTP_STATUS_DESCRIPTIONS.UNKNOWN);%0A expect(appHelper.determineStatusText(%22%22, %22%22)).toBe(HTTP_STATUS_DESCRIPTIONS.UNKNOWN);%0A %7D);%0A it('should return a description for the provided status value', function() %7B%0A expect(appHelper.determineStatusText(200, %22foo%22)).toBe(HTTP_STATUS_DESCRIPTIONS.200);%0A expect(appHelper.determineStatusText(500, %22foo%22)).toBe(HTTP_STATUS_DESCRIPTIONS.500);%0A expect(appHelper.determineStatusText(ABORT, %22foo%22)).toBe(HTTP_STATUS_DESCRIPTIONS.ABORT);%0A %7D);%0A it('should return the status text from the response if no other status text is available', function() %7B%0A expect(appHelper.determineStatusText(999, %22foo%22)).toBe(%22foo%22);%0A expect(appHelper.determineStatusText(undefined, %22foo%22)).toBe(%22foo%22);%0A %7D);%0A %7D); %0A%7D);%0A
bf2d6499f6f4a7f1a8e9bb375c2534f67d825bb0
Replace legacy QUnit 1.x API with 2.x version.
tests/unit/deprecate-test.js
tests/unit/deprecate-test.js
import { deprecate } from '@ember/application/deprecations'; import { registerDeprecationHandler } from '@ember/debug'; import Ember from 'ember'; import { module, test, skip } from 'qunit'; const HANDLERS = Ember.Debug._____HANDLERS__DO__NOT__USE__SERIOUSLY__I_WILL_BE_MAD; let originalEnvValue; let originalDeprecateHandler; module('ember-debug', { setup() { originalEnvValue = Ember.ENV.RAISE_ON_DEPRECATION; originalDeprecateHandler = HANDLERS.deprecate; Ember.ENV.RAISE_ON_DEPRECATION = true; }, teardown() { HANDLERS.deprecate = originalDeprecateHandler; Ember.ENV.RAISE_ON_DEPRECATION = originalEnvValue; } }); test('Ember.deprecate does not throw if RAISE_ON_DEPRECATION is false', function(assert) { assert.expect(1); Ember.ENV.RAISE_ON_DEPRECATION = false; try { deprecate('Should not throw', false, { id: 'test', until: 'forever' }); assert.ok(true, 'Ember.deprecate did not throw'); } catch(e) { assert.ok(false, `Expected Ember.deprecate not to throw but it did: ${e.message}`); } }); test('Ember.deprecate re-sets deprecation level to RAISE if ENV.RAISE_ON_DEPRECATION is set', function(assert) { assert.expect(2); Ember.ENV.RAISE_ON_DEPRECATION = false; try { deprecate('Should not throw', false, { id: 'test', until: 'forever' }); assert.ok(true, 'Ember.deprecate did not throw'); } catch(e) { assert.ok(false, `Expected Ember.deprecate not to throw but it did: ${e.message}`); } Ember.ENV.RAISE_ON_DEPRECATION = true; assert.throws(function() { deprecate('Should throw', false, { id: 'test', until: 'forever' }); }, /Should throw/); }); test('When ENV.RAISE_ON_DEPRECATION is true, it is still possible to silence a deprecation by id', function(assert) { assert.expect(3); Ember.ENV.RAISE_ON_DEPRECATION = true; registerDeprecationHandler(function(message, options, next) { if (!options || options.id !== 'my-deprecation') { next(...arguments); } }); try { deprecate('should be silenced with matching id', false, { id: 'my-deprecation', until: 'forever' }); assert.ok(true, 'Did not throw when level is set by id'); } catch(e) { assert.ok(false, `Expected Ember.deprecate not to throw but it did: ${e.message}`); } assert.throws(function() { deprecate('Should throw with no matching id', false, { id: 'test', until: 'forever' }); }, /Should throw with no matching id/); assert.throws(function() { deprecate('Should throw with non-matching id', false, { id: 'other-id', until: 'forever' }); }, /Should throw with non-matching id/); }); test('Ember.deprecate throws deprecation if second argument is falsy', function(assert) { assert.expect(3); assert.throws(function() { deprecate('Deprecation is thrown', false, { id: 'test', until: 'forever' }); }); assert.throws(function() { deprecate('Deprecation is thrown', '', { id: 'test', until: 'forever' }); }); assert.throws(function() { deprecate('Deprecation is thrown', 0, { id: 'test', until: 'forever' }); }); }); test('Ember.deprecate does not throw deprecation if second argument is a function and it returns true', function(assert) { assert.expect(1); deprecate('Deprecation is thrown', function() { return true; }, { id: 'test', until: 'forever' }); assert.ok(true, 'deprecation was not thrown'); }); skip('Ember.deprecate throws if second argument is a function and it returns false', function(assert) { assert.expect(1); assert.throws(function() { deprecate('Deprecation is thrown', function() { return false; }, { id: 'test', until: 'forever' }); }); }); test('Ember.deprecate does not throw deprecations if second argument is truthy', function(assert) { assert.expect(1); deprecate('Deprecation is thrown', true, { id: 'test', until: 'forever' }); deprecate('Deprecation is thrown', '1', { id: 'test', until: 'forever' }); deprecate('Deprecation is thrown', 1, { id: 'test', until: 'forever' }); assert.ok(true, 'deprecations were not thrown'); }); test('Ember.assert throws if second argument is falsy', function(assert) { assert.expect(3); assert.throws(function() { assert('Assertion is thrown', false); }); assert.throws(function() { assert('Assertion is thrown', ''); }); assert.throws(function() { assert('Assertion is thrown', 0); }); }); test('Ember.deprecate does not throw a deprecation at log and silence levels', function(assert) { assert.expect(4); let id = 'ABC'; let until = 'forever'; let shouldThrow = false; registerDeprecationHandler(function(message, options) { if (options && options.id === id) { if (shouldThrow) { throw new Error(message); } } }); try { deprecate('Deprecation for testing purposes', false, { id, until }); assert.ok(true, 'Deprecation did not throw'); } catch(e) { assert.ok(false, 'Deprecation was thrown despite being added to blacklist'); } try { deprecate('Deprecation for testing purposes', false, { id, until }); assert.ok(true, 'Deprecation did not throw'); } catch(e) { assert.ok(false, 'Deprecation was thrown despite being added to blacklist'); } shouldThrow = true; assert.throws(function() { deprecate('Deprecation is thrown', false, { id, until }); }); assert.throws(function() { deprecate('Deprecation is thrown', false, { id, until }); }); });
JavaScript
0
@@ -353,13 +353,18 @@ %7B%0A -setup +beforeEach () %7B @@ -526,16 +526,17 @@ %0A%0A -teardown +afterEach () %7B
8714f84787cbd2ee8c9e7b1a6939e71ffa337249
code format
assets/scripts/module/common.js
assets/scripts/module/common.js
import Zooming from 'zooming'; export default { setThumbnailImage() { var container = document.getElementsByClassName('entry-image'); var length = container.length; if (length === 0) { return; } for (var i = 0; i < length; i += 1) { var imageUrl = container[i].dataset.thumbnailImage; if (!imageUrl) { continue; } var sheet = container[i].getElementsByClassName('image-sheet')[0]; var img = new Image(); img.onload = (function(element, url) { // set background image element.style.backgroundImage = 'url(' + url + ')'; })(sheet, imageUrl); img.src = imageUrl; } }, addExternalLink(entry) { var aTags = entry.getElementsByTagName('a'); var length = aTags.length; if (length === 0) { return; } var icon = document.createElement('i'); icon.classList.add('icon-open_in_new'); for (var i = 0; i < length; i++) { this.setExternalLinkIcon(aTags[i], icon.cloneNode(false)); } }, setExternalLinkIcon(element, icon) { var href = element.getAttribute('href'); // exclude javascript and anchor if ( href.substring(0, 10).toLowerCase() === 'javascript' || href.substring(0, 1) === '#' ) { return; } // check hostname if (element.hostname === location.hostname) { return; } // set target and rel element.setAttribute('target', '_blank'); element.setAttribute('rel', 'nofollow'); element.setAttribute('rel', 'noopener'); // set icon when childNode is text if (element.hasChildNodes()) { if (element.childNodes[0].nodeType === 3) { element.appendChild(icon.cloneNode(true)); } } }, zoomImage(element) { var entryImg = element.getElementsByTagName('img'); var length = entryImg.length; // entry has no img if (length === 0) { return; } var zoom = new Zooming({ scaleBase: 0.8, }); for (var i = 0; i < length; i += 1) { // parentNode is <a> Tag if ( entryImg[i].getAttribute('data-zoom-disabled') === 'true' || entryImg[i].parentNode.nodeName === 'A' ) { continue; } entryImg[i].style.cursor = 'zoom-in'; zoom.listen(entryImg[i]); } }, wrap(element, wrapper) { element.parentNode.insertBefore(wrapper, element); wrapper.appendChild(element); }, setTableContainer(entry) { var self = this; var tables = entry.querySelectorAll('table'); var length = tables.length; if (length === 0) { return; } var div = document.createElement('div'); div.classList.add('table-container'); for (var i = 0; i < length; i += 1) { var wrapper = div.cloneNode(false); self.wrap(tables[i], wrapper); } }, getStyleSheetValue(element, property) { if (!element || !property) { return null; } var style = window.getComputedStyle(element); var value = style.getPropertyValue(property); return value; }, };
JavaScript
0.999764
@@ -1152,23 +1152,16 @@ if ( -%0A href.sub @@ -1207,22 +1207,16 @@ ript' %7C%7C -%0A href.su @@ -1236,21 +1236,16 @@ === '#' -%0A ) %7B%0A @@ -2037,25 +2037,16 @@ if ( -%0A entryImg @@ -2097,24 +2097,16 @@ true' %7C%7C -%0A entryIm @@ -2137,23 +2137,16 @@ === 'A' -%0A ) %7B%0A
9908a8321065434c271d76f4ae5dabf17d01af76
optimize for pdf.js for linebreak and multiline selection
youdaodict.user.js
youdaodict.user.js
// ==UserScript== // @id youdaodict-greasemonkey-reverland-2015-09-26 // @name youdaodict // @version 1.0 // @namespace youdao // @author Liu Yuyang(sa@linuxer.me) // @description 一个可以在浏览器中自由使用的屏幕取词脚本 // @include * // @grant GM_xmlhttpRequest // ==/UserScript== window.document.body.addEventListener("mouseup", translate, false); function translate(e) { // remove previous .youdaoPopup if exists var previous = document.querySelector(".youdaoPopup"); if (previous) { document.body.removeChild(previous); } //console.log("translate start"); var selectObj = document.getSelection() // if #text node if (selectObj.anchorNode.nodeType == 3) { //GM_log(selectObj.anchorNode.nodeType.toString()); var word = selectObj.toString(); if (word == "") { return; } //console.log("word:", word); var ts = new Date().getTime(); //console.log("time: ", ts); var mx = e.clientX; var my = e.clientY; translate(word, ts); } function popup(mx, my, result) { //console.log(mx) //console.log(my) //console.log("popup window!") var youdaoWindow = document.createElement('div'); youdaoWindow.classList.toggle("youdaoPopup"); // parse var dictJSON = JSON.parse(result); console.log(dictJSON); var query = dictJSON['query']; var errorCode = dictJSON['errorCode']; if (dictJSON['basic']) { word(); } else { sentence(); } // main window // first insert into dom then there is offsetHeight!IMPORTANT! document.body.appendChild(youdaoWindow); youdaoWindow.style.color = "black"; youdaoWindow.style.textAlign = "left"; youdaoWindow.style.display = "block"; youdaoWindow.style.position = "fixed"; youdaoWindow.style.background = "lightblue"; youdaoWindow.style.borderRadius = "5px"; youdaoWindow.style.boxShadow = "0 0 5px 0" youdaoWindow.style.opacity = "0.9" youdaoWindow.style.width = "200px"; youdaoWindow.style.wordWrap = "break-word"; youdaoWindow.style.left = mx + 10 + "px"; if (mx + 200 + 30 >= window.innerWidth) { youdaoWindow.style.left = parseInt(youdaoWindow.style.left) - 200 + "px"; } if (my + youdaoWindow.offsetHeight + 30 >= window.innerHeight) { youdaoWindow.style.bottom = "20px"; } else { youdaoWindow.style.top = my + 10 + "px"; } youdaoWindow.style.padding = "5px"; youdaoWindow.style.zIndex = '999999' function word() { function play(word) { //console.log("[DEBUG] PLAYOUND") function playSound(buffer) { var source = context.createBufferSource(); source.buffer = buffer; source.connect(context.destination); source.start(0); } var context = new AudioContext() var soundUrl = `https://dict.youdao.com/dictvoice?type=2&audio=${word}` var ret = GM_xmlhttpRequest({ method: "GET", url: soundUrl, responseType: 'arraybuffer', onload: function(res) { try { context.decodeAudioData(res.response, function(buffer) { playSound(buffer); }) } catch(e) { console.log(e.message); } } }) } var basic = dictJSON['basic']; var header = document.createElement('p'); // header var span = document.createElement('span') span.innerHTML = query; header.appendChild(span) // phonetic if there is var phonetic = basic['phonetic']; if (phonetic) { var phoneticNode = document.createElement('span') phoneticNode.innerHTML = '[' + phonetic + ']' phoneticNode.style.cursor = "pointer"; header.appendChild(phoneticNode); var playLogo = document.createElement('span'); header.appendChild(phoneticNode); phoneticNode.addEventListener('mouseup', function(e){ if (e.target === phoneticNode) { } e.stopPropagation(); play(query)}, false); } header.style.color = "darkBlue"; header.style.margin = "0"; header.style.padding = "0"; span.style.fontweight = "900"; span.style.color = "black"; youdaoWindow.appendChild(header); var hr = document.createElement('hr') hr.style.margin = "0"; hr.style.padding = "0"; hr.style.height = "1px"; hr.style.borderTop = "dashed 1px black"; youdaoWindow.appendChild(hr); var ul = document.createElement('ul'); // ul style ul.style.margin = "0"; ul.style.padding = "0"; basic['explains'].map(function(trans) { var li = document.createElement('li'); li.style.listStyle = "none"; li.style.margin = "0"; li.style.padding = "0"; li.style.background = "none"; li.style.color = "inherit"; li.appendChild(document.createTextNode(trans)); ul.appendChild(li); }) youdaoWindow.appendChild(ul); } function sentence() { var ul = document.createElement('ul'); // ul style ul.style.margin = "0"; ul.style.padding = "0"; dictJSON['translation'].map(function(trans) { var li = document.createElement('li'); li.style.listStyle = "none"; li.style.margin = "0"; li.style.padding = "0"; li.style.background = "none"; li.style.color = "inherit"; li.appendChild(document.createTextNode(trans)); ul.appendChild(li); }) youdaoWindow.appendChild(ul); } } function translate(word, ts) { var reqUrl = `http://fanyi.youdao.com/openapi.do?type=data&doctype=json&version=1.1&relatedUrl=http%3A%2F%2Ffanyi.youdao.com%2F%23&keyfrom=fanyiweb&key=null&translate=on&q=${word}&ts=${ts}` //console.log("request url: ", reqUrl); var ret = GM_xmlhttpRequest({ method: "GET", url: reqUrl, headers: {"Accept": "application/json"}, // can be omitted... onreadystatechange: function(res) { //console.log("Request state changed to: " + res.readyState); }, onload: function(res) { var retContent = res.response; //console.log(retContent) popup(mx, my, retContent); }, onerror: function(res) { console.log("error"); } }); } }
JavaScript
0
@@ -847,24 +847,190 @@ turn;%0A %7D%0A + // linebreak wordwrap, optimize for pdf.js%0A word = word.replace('-%5Cn','');%0A // multiline selection, optimize for pdf.js%0A word = word.replace('%5Cn', ' ');%0A //consol
19a5bbdeed9061ec7dc914c7751a235593c9c267
Fix userCanPlay method in instant_win if badge is an empty object
widgets/instant_win/main.js
widgets/instant_win/main.js
/** * # Instant Win * * An instant-win is a game where the player finds out immediately if he or she * is a winner of one of the prizes the administrators put at stake. * * A player can play once a day provided he or she loses at each attempt. A * player that wins the prize will not be allowed to play the game anymore. * * ## Parameters * * - `provider`: The identity provider to log with before playing. By default it * will list all your identity providers. * - `delay`: Time in milliseconds to wait before displaying the game's results. * By default the results are displayed imediatly after that the server tell * us if the user has win or lost. */ define({ type: 'Hull', templates: [ /** * Show the button to play to the game. */ 'intro', /** * The play buttons partial. */ 'buttons', /** * Show a loading message. */ 'working', /** * Say to the user that he has won */ 'won', /** * Say to the user that he has lost. */ 'lost', /** * Say to the user that he has already played. */ 'played', /** * Say to the user that the game hasn't started yet. */ 'unstarted', /** * Say to the user that the game has ended. */ 'ended' ], refreshEvents: ['model.hull.me.change'], datasources: { /** * The InstantWin achievement */ achievement: ':id', /** * The user's badge for the InstantWin */ badge: function() { return this.loggedIn() ? this.api('hull/me/badges/' + this.options.id) : null; } }, actions: { /** * Ensure that the user is logged and call the `play` method. */ play: function(source, event, data) { if (this.loggedIn()) { this.play(); } else { var provider = data.provider || this.options.provider; this.sandbox.login(provider); this.autoPlay = true; } } }, initialize: function() { this.authProviders = _.map(this.sandbox.config.services.types.auth, function(s) { return s.replace(/_app$/, ''); }); }, beforeRender: function(data) { this.template = this.getInitialTemplate(); data.authProviders = this.authProviders; }, afterRender: function() { this.sandbox.emit('hull.instant_win.' + this.options.id + '.template.render', this.template); if (this.autoPlay) { this.autoPlay = false; this.play(); } }, /** * Return the template name that the user should see when he lands on the * game. * * - `intro`: if the user hasn't played during the current day. * - `won`: if the user has won a prize. * - `played`: if the user has played during the current day. * - `unstarted`: if the game hasn't started. * - `ended`: if the game has ended. * * @return {String} */ getInitialTemplate: function() { if (this.userHasWon()) { return 'won'; } else if (this.hasEnded()) { return 'ended'; } else if (this.hasStarted()) { return this.userCanPlay() ? 'intro' : 'played'; } else { return 'unstarted'; } }, /** * Determine if the game has started. return `true` if it has `false` if it * hasn't. * * @return {Boolean} */ hasStarted: function() { // TODO Need achievement `start_date` return true; }, /** * Determine if the game has ended. Return `true` if it has `false` if it * hasn't. * * @return {Boolean} */ hasEnded: function() { // TODO Need achievement `end_date` return false; }, /** * Determine if the user can play. Return `true` if he can `false` if he * cannot. * * @return {Boolean} */ userCanPlay: function() { if (!this.data.badge) { return true; } var d = new Date().toISOString().slice(0, 10); return !this.data.badge.data.attempts[d]; }, /** * Determine if user has won. Return `true` if the he has, `false` if he * hasn't. * * @return {Boolean} */ userHasWon: function() { if (!this.data.badge) { return false; } return this.data.badge.data.winner; }, /** * Play to the game and render a template: * * - `won`: if the user has won. * - `lost`: if the user has lost. * - `played`: if the user has played during the current day. * * When the function is called we render `working` and display it * until we know if the user has won. */ play: function() { if (this.userHasWon()) { return; } this.render('working'); this.api('hull/' + this.id + '/achieve', 'post', _.bind(function(res) { var template = 'played'; if (this.userCanPlay()) { template = res.data.winner ? 'won' : 'lost'; } _.delay(_.bind(function() { this.render(template); }, this), parseInt(this.options.delay, 10) || 0); }, this)); } });
JavaScript
0.000001
@@ -3759,32 +3759,61 @@ !this.data.badge + %7C%7C !this.data.badge.attempts ) %7B return true;
4275494cc6a8f51a1b8e8f8d097cbcbe4e326ba3
use click instead of change
list.js
list.js
M.wrap('github/jillix/bind-filter/dev/list.js', function (require, module, exports) { // TODO use bind for dom interaction/manipulation function get(s,c){ try{return (c||document).querySelector(s);} catch (err) {} } function buildItem (elem, content) { var elem = elem.cloneNode(); elem.innerHTML = content; return elem; } var getFieldLabel = require('./validate').getFieldLabel; function createFilterItem (hash) { var self = this; var item = buildItem(self.domRefs.listItem, self.domRefs.listItemContent); var checkbox = get(self.config.ui.item.onoff, item); var field = get(self.config.ui.item.field, item); var operator = get(self.config.ui.item.operator, item); var value = get(self.config.ui.item.value, item); var edit = get(self.config.ui.item.edit, item); var rm = get(self.config.ui.item.remove, item); // enable/disable filter if (self.filters[hash].disabled) { item.setAttribute('class', 'disabled'); if (checkbox) { checkbox.removeAttribute('checked'); } } // hide filter item if (self.filters[hash].hidden) { item.style.display = 'none'; } // set content if (field) { field.innerHTML = getFieldLabel.call(self, self.filters[hash].field); } if (operator) { var myOperator = self.filters[hash].operator; self.emit("message", myOperator, function (err, newOperator) { if(err) { return; } operator.innerHTML = newOperator.message; }); } if (value) { value.innerHTML = self.filters[hash].value === undefined ? '' : (typeof self.filters[hash].originalValue === 'string' ? self.filters[hash].originalValue : self.filters[hash].value); } // hide edit if it's a core field if (edit && self.filters[hash].field[0] === '_') { edit.style.display = 'none'; } if (!self.filters[hash].fixed) { if (checkbox) { checkbox.addEventListener('change', function (event) { self.emit('filtersChanged'); if (checkbox.checked) { self.emit('enableFilter', hash); } else { self.emit('disableFilter', hash); } }, false); } // edit filter if (edit) { edit.addEventListener(self.config.ui.events.itemEdit || 'click', function (event) { self.emit('filtersChanged'); event.stopPropagation(); event.preventDefault(); self.emit('editFilter', hash); }, false); delete edit.style.display; } // remove filter if (rm) { rm.addEventListener(self.config.ui.events.itemRemove || 'click', function (event) { self.emit('filtersChanged'); event.stopPropagation(); event.preventDefault(); self.emit('removeFilter', hash); }, false); } } else { // TODO handle attributes with bind item.setAttribute('class', 'fixed' + (self.filters[hash].disabled ? ' disabled' : '')); if (checkbox) { checkbox.setAttribute('disabled', true); } if (edit) { edit.style.display = 'none'; } } return item; } function save (hash) { var self = this; // create filter item var item = createFilterItem.call(self, hash); if (self.filters[hash].item) { // replace filter try { self.domRefs.list.replaceChild(item, self.filters[hash].item); } catch (e) {} //self.domRefs.list.appendChild(item); } else { // add new filter if (self.domRefs.list) { self.domRefs.list.appendChild(item); } } // update cache self.filters[hash].item = item; } function remove (hash) { var self = this; if (self.filters[hash]) { // remove dom element self.domRefs.list.removeChild(self.filters[hash].item); // remove from cache delete self.filters[hash]; } } exports.save = save; exports.remove = remove; return module; });
JavaScript
0
@@ -1998,21 +1998,20 @@ tener('c -hange +lick ', funct
0f98623fa137e67be6e5131a664816a067561d46
fix spelling of deprecated, https://github.com/phetsims/chipper/issues/515
js/ScoreboardPanel.js
js/ScoreboardPanel.js
// Copyright 2013-2015, University of Colorado Boulder /** * Scoreboard for a game. * * @author Chris Malley (PixelZoom, Inc.) * @deprectated use ScoreboardBar */ define( function( require ) { 'use strict'; // modules var Color = require( 'SCENERY/util/Color' ); var GameTimer = require( 'VEGAS/GameTimer' ); var inherit = require( 'PHET_CORE/inherit' ); var Node = require( 'SCENERY/nodes/Node' ); var Panel = require( 'SUN/Panel' ); var PhetFont = require( 'SCENERY_PHET/PhetFont' ); var SimpleClockIcon = require( 'SCENERY_PHET/SimpleClockIcon' ); var StringUtils = require( 'PHETCOMMON/util/StringUtils' ); var Text = require( 'SCENERY/nodes/Text' ); var TextPushButton = require( 'SUN/buttons/TextPushButton' ); var vegas = require( 'VEGAS/vegas' ); var Tandem = require( 'TANDEM/Tandem' ); // strings var startOverString = require( 'string!VEGAS/startOver' ); var labelLevelString = require( 'string!VEGAS/label.level' ); var labelScoreString = require( 'string!VEGAS/label.score' ); var pattern0Challenge1MaxString = require( 'string!VEGAS/pattern.0challenge.1max' ); /** * @param {Property.<number>} challengeIndexProperty which challenge is the user current playing? (index starts at 0, displayed starting at 1) * @param {Property.<number>} challengesPerGameProperty how many challenges are in the current game * @param {Property.<number>} levelProperty * @param {Property.<number>} scoreProperty * @param {Property.<number>} elapsedTimeProperty elapsed time in seconds * @param {Property.<number>} timerEnabledProperty is the timer enabled? * @param {function} startOverCallback * @param {Object} [options] * @constructor */ function ScoreboardPanel( challengeIndexProperty, challengesPerGameProperty, levelProperty, scoreProperty, elapsedTimeProperty, timerEnabledProperty, startOverCallback, options ) { options = _.extend( { // things that can be hidden levelVisible: true, challengeNumberVisible: true, // all text font: new PhetFont( 20 ), // "Start Over" button startOverButtonText: startOverString, startOverButtonBaseColor: new Color( 229, 243, 255 ), startOverButtonXMargin: 10, startOverButtonYMargin: 5, // Timer clockIconRadius: 15, // Panel minWidth: 0, xSpacing: 40, xMargin: 20, yMargin: 10, fill: 'rgb( 180, 205, 255 )', stroke: 'black', lineWidth: 1, align: 'center', tandem: null }, options ); Tandem.validateOptions( options ); // The tandem is required when brand==='phet-io' // Level var levelNode = new Text( '', { font: options.font, pickable: false } ); levelProperty.link( function( level ) { levelNode.text = StringUtils.format( labelLevelString, level + 1 ); } ); // Challenge number var challengeNumberNode = new Text( '', { font: options.font, pickable: false } ); challengeIndexProperty.link( function( challengeIndex ) { challengeNumberNode.text = StringUtils.format( pattern0Challenge1MaxString, challengeIndex + 1, challengesPerGameProperty.get() ); } ); // Score var scoreNode = new Text( '', { font: options.font, pickable: false } ); scoreProperty.link( function( score ) { scoreNode.text = StringUtils.format( labelScoreString, score ); } ); // Timer, always takes up space even when hidden. var timerNode = new Node( { pickable: false } ); var clockIcon = new SimpleClockIcon( options.clockIconRadius ); var timeValue = new Text( '', { font: options.font } ); timerNode.addChild( clockIcon ); timerNode.addChild( timeValue ); timeValue.left = clockIcon.right + 8; timeValue.centerY = clockIcon.centerY; elapsedTimeProperty.link( function( elapsedTime ) { timeValue.text = GameTimer.formatTime( elapsedTime ); } ); timerEnabledProperty.link( function( timerEnabled ) { timerNode.visible = timerEnabled; } ); // Start Over button var startOverButton = new TextPushButton( options.startOverButtonText, { listener: startOverCallback, font: options.font, baseColor: options.startOverButtonBaseColor, xMargin: options.startOverButtonXMargin, yMargin: options.startOverButtonYMargin, tandem: options.tandem ? options.tandem.createTandem( 'startOverButton' ) : null } ); // Content for the panel, one row. var content = new Node(); var nodes = [ levelNode, challengeNumberNode, scoreNode, timerNode, startOverButton ]; if ( !options.levelVisible ) { nodes.splice( nodes.indexOf( levelNode ), 1 ); } if ( !options.challengeNumberVisible ) { nodes.splice( nodes.indexOf( challengeNumberNode ), 1 ); } for ( var i = 0; i < nodes.length; i++ ) { content.addChild( nodes[ i ] ); if ( i > 0 ) { nodes[ i ].left = nodes[ i - 1 ].right + options.xSpacing; nodes[ i ].centerY = nodes[ i - 1 ].centerY; } } Panel.call( this, content, options ); } vegas.register( 'ScoreboardPanel', ScoreboardPanel ); return inherit( Panel, ScoreboardPanel ); } );
JavaScript
0.000019
@@ -134,17 +134,16 @@ @deprec -t ated use
9e6b8ad17000a262d216885a7ed09cc2d198f4a0
Update head-newsletter.js
js/head-newsletter.js
js/head-newsletter.js
document.write('\ \ <meta name="description" content="Noticias semanales sobre Anime.">\ <meta name="author" content="Rubén - twitter.com/cont3mpo">\ <meta name="viewport" content="width=device-width, shrink-to-fit=no, initial-scale=1">\ <link rel="shortcut icon" type="image/png" href="img/favicon-newsletter.png">\ <link rel="stylesheet" href="css/normalize.css">\ <link rel="stylesheet" href="css/style.css">\ \ ');
JavaScript
0
@@ -323,32 +323,40 @@ %3E%5C%0A %3Clink rel=%22 +preload stylesheet%22 href @@ -375,16 +375,27 @@ ize.css%22 + as=%22style%22 %3E%5C%0A %3Cli @@ -402,16 +402,24 @@ nk rel=%22 +preload styleshe @@ -442,16 +442,27 @@ yle.css%22 + as=%22style%22 %3E%5C%0A%5C%0A');
faecda854eadb14f5615904fa02fa6367170a69d
Improve inspector-forced panning
js/id/modes/select.js
js/id/modes/select.js
iD.modes.Select = function (entity) { var mode = { id: 'select', button: 'browse', entity: entity }; var inspector = iD.ui.inspector(), behaviors; function remove() { if (entity.type === 'way') { mode.history.perform( iD.actions.DeleteWay(entity.id), 'deleted a way'); } else if (entity.type === 'node') { var parents = mode.history.graph().parentWays(entity), operations = [iD.actions.DeleteNode(entity.id)]; parents.forEach(function(parent) { if (_.uniq(parent.nodes).length === 1) operations.push(iD.actions.DeleteWay(parent.id)); }); mode.history.perform.apply(mode.history, operations.concat(['deleted a node'])); } mode.controller.exit(); } function changeTags(d, tags) { if (!_.isEqual(entity.tags, tags)) { mode.history.perform( iD.actions.ChangeEntityTags(d.id, tags), 'changed tags'); } } mode.enter = function () { var surface = mode.map.surface; behaviors = [ iD.behavior.Hover(), iD.behavior.DragNode(mode), iD.behavior.DragWay(mode), iD.behavior.DragMidpoint(mode)]; behaviors.forEach(function(behavior) { behavior(surface); }); d3.select('.inspector-wrap') .style('display', 'block') .style('opacity', 1) .datum(entity) .call(inspector); // Pan the map if the clicked feature intersects with the position // of the inspector var inspector_size = d3.select('.inspector-wrap').size(), map_size = mode.map.size(), entity_extent = entity.extent(mode.history.graph()), left_edge = map_size[0] - inspector_size[0], left = mode.map.projection(entity_extent[0])[0], right = mode.map.projection(entity_extent[1])[0]; if (left > left_edge && right > left_edge) mode.map.centerEase( mode.map.projection.invert([(window.innerWidth), d3.event.y])); inspector .on('changeTags', changeTags) .on('changeWayDirection', function(d) { mode.history.perform( iD.actions.ReverseWay(d.id), 'reversed a way'); }).on('splitWay', function(d) { mode.history.perform( iD.actions.SplitWay(d.id), 'split a way on a node'); }).on('remove', function() { remove(); }).on('close', function() { mode.controller.exit(); }); // Exit mode if selected entity gets undone mode.history.on('change.entity-undone', function() { var old = entity; entity = mode.history.graph().entity(entity.id); if (!entity) { mode.controller.enter(iD.modes.Browse()); } else if(!_.isEqual(entity.tags, old.tags)) { inspector.tags(entity.tags); } }); function click() { var datum = d3.select(d3.event.target).datum(); if (datum instanceof iD.Entity) { mode.controller.enter(iD.modes.Select(datum)); } else { mode.controller.enter(iD.modes.Browse()); } } function dblclick() { var datum = d3.select(d3.event.target).datum(); if (datum instanceof iD.Entity && (datum.geometry() === 'area' || datum.geometry() === 'line')) { var choice = iD.util.geo.chooseIndex(datum, d3.mouse(mode.map.surface.node()), mode.map), node = iD.Node({ loc: choice.loc }); mode.history.perform( iD.actions.AddNode(node), iD.actions.AddWayNode(datum.id, node.id, choice.index), 'added a point to a road'); d3.event.preventDefault(); d3.event.stopPropagation(); } } surface.on('click.select', click) .on('dblclick.browse', dblclick); mode.map.keybinding().on('⌫.select', function(e) { remove(); e.preventDefault(); }); surface.selectAll("*") .filter(function (d) { return d === entity; }) .classed('selected', true); }; mode.exit = function () { var surface = mode.map.surface; entity && changeTags(entity, inspector.tags()); d3.select('.inspector-wrap') .style('display', 'none') .html(''); behaviors.forEach(function(behavior) { behavior.off(surface); }); surface.on("click.select", null); mode.map.keybinding().on('⌫.select', null); mode.history.on('change.entity-undone', null); surface.selectAll(".selected") .classed('selected', false); }; return mode; };
JavaScript
0.000001
@@ -1824,84 +1824,58 @@ -entity_extent = entity.extent(mode.history.graph()),%0A left_edge = +offset = 50,%0A shift_left = d3.event.x - map @@ -1883,17 +1883,17 @@ size%5B0%5D -- ++ inspect @@ -1902,16 +1902,25 @@ _size%5B0%5D + + offset ,%0A @@ -1929,117 +1929,56 @@ -left = mode.map.projection(entity_extent%5B0%5D)%5B0%5D,%0A right = mode.map.projection(entity_extent%5B1%5D)%5B0%5D +center = (map_size%5B0%5D / 2) + shift_left + offset ;%0A%0A @@ -1992,58 +1992,71 @@ if ( +shift_ left %3E -left_edge &&%0A right %3E left_edge) +0 && inspector_size%5B1%5D %3E d3.event.y) %7B%0A mod @@ -2072,33 +2072,16 @@ terEase( -%0A mode.map @@ -2104,43 +2104,43 @@ rt(%5B -(window.innerWidth), d3.event.y%5D)); +center, map_size%5B1%5D/2%5D));%0A %7D %0A%0A
9ce93ee534891cb6aae372e141a975152cc895d5
Fix to avoid shadow zooming boxes when clicking on images
js/jquery.gangZoom.js
js/jquery.gangZoom.js
(function ($) { $.fn.gangZoom = function (options) { var opts = $.extend({}, $.fn.gangZoom.defaults, options); if (! $.fn.gangZoom.styleAdded && opts.defaultStyle) { $("<style type='text/css'>" + opts.defaultStyle + "</style>").appendTo("head"); $.fn.gangZoom.styleAdded = true; } return this.each(function() { var self = this; self.img = $(self); self.mouseDown = false; self.getTimes = function () { var timeSpan = opts.endTime - opts.startTime; var graphWidth = self.img.width() - (opts.paddingLeft + opts.paddingRight); var secondsPerPixel = timeSpan / graphWidth; var selWidth = self.float.width(); var selStart = self.float.position().left - self.img.offset().left; var selStartTime = opts.startTime + ((selStart - opts.paddingLeft) * secondsPerPixel); var selEndTime = selWidth * secondsPerPixel + selStartTime; return { startTime: selStartTime, endTime: selEndTime }; } self.setMouseDown = function (down) { self.mouseDown = down; if (down) { $(document.body).css("cursor", "crosshair"); } else { $(document.body).css("cursor", "default"); } } self.cancel = function () { self.setMouseDown(false); var box = self.getTimes(); opts.cancel(box.startTime, box.endTime); }; self.go = function () { self.setMouseDown(false); var box = self.getTimes(); opts.done(box.startTime, box.endTime); }; self.updateOverlay = function (evt) { var curX = evt.pageX; if (self.startX > curX) { if (curX < self.minWidth) { curX = self.minWidth; } self.float.css({ left: curX }); } else if (curX > self.maxWidth) { curX = self.maxWidth; } self.float.width(Math.abs(curX - self.startX)); }; $(document.body).mouseup(function (event) { if (self.mouseDown) { if (event.target == self.img || event.target == self.float[0]) { self.go(); } else { self.cancel(); } } }) .mousemove(function (event) { if (self.mouseDown) { if (event.target == self.float[0]) { self.updateOverlay(event); } } }) .keyup(function (event) { if (event.keyCode == 27 && self.mouseDown) { self.cancel(); } }); self.img.mousedown(function (event) { event.preventDefault(); self.shouldStopClick = false; var evt = event; setTimeout(function () { evt.stopPropagation(); var clickX = evt.pageX; var clickY = evt.pageY; self.startX = clickX; $("#" + opts.floatId).remove(); self.minWidth = self.img.offset().left + opts.paddingLeft; self.maxWidth = self.img.offset().left + (self.img.width() - opts.paddingRight); if ((clickX > self.maxWidth) || (clickX < self.minWidth)) { return; } self.shouldStopClick = true; self.setMouseDown(true); var float = $("<div id='" + opts.floatId + "'>") .css({ position: "absolute", left: clickX, top: self.img.position().top + opts.paddingTop, zIndex: 1000, height: self.img.height() - (opts.paddingBottom + opts.paddingTop) }) .width(10) .mousemove(function(evt) { return true; }) .mouseup(function() { return true; }) .keyup(function() { return true; }) .appendTo(document.body); self.float = float; }, opts.clickTimeout); }) .mousemove(function (evt) { if (self.mouseDown && self.float) { self.updateOverlay(evt); } }) .mouseup(function (evt) { if (self.mouseDown) { self.go(); } }) .click(function (event) { if (self.shouldStopClick) { event.preventDefault(); } }); }); } $.fn.gangZoom.defStyle = "#gangZoomFloater {"; $.fn.gangZoom.defStyle += "border: 1px solid black;"; $.fn.gangZoom.defStyle += "background: white;"; $.fn.gangZoom.defStyle += "opacity: 0.7;"; $.fn.gangZoom.defStyle += "position: absolute;"; $.fn.gangZoom.defStyle += "top: 0;"; $.fn.gangZoom.defStyle += "height: 100%;"; $.fn.gangZoom.defaults = { clickTimeout: 500, floatId: 'gangZoomFloater', defaultStyle: $.fn.gangZoom.defStyle, startTime: ((new Date()).getTime() / 1000) - 3600, endTime: (new Date()).getTime() / 1000, paddingLeft: 20, paddingRight: 20, paddingTop: 20, paddingBottom: 40, done: function (startTime, endTime) {}, cancel: function (startTime, endTime) {} } $.fn.gangZoom.styleAdded = false; })(jQuery);
JavaScript
0
@@ -2526,76 +2526,8 @@ ();%0A - %7D else %7B%0A self.cancel();%0A @@ -3125,16 +3125,54 @@ false;%0A + self.stopped = false;%0A @@ -3230,32 +3230,126 @@ t(function () %7B%0A + if (self.stopped) %7B%0A return;%0A %7D%0A @@ -4978,32 +4978,92 @@ self.go();%0A + %7D else %7B%0A self.cancel();%0A @@ -5197,32 +5197,98 @@ eventDefault();%0A + %7D else %7B%0A self.stopped = true;%0A
ecb1023c667ed22336c1f9b0d5040ed1e7f70290
Fix user bio placeholder not showing up
js/lib/models/User.js
js/lib/models/User.js
/*global ColorThief*/ import Model from 'flarum/Model'; import mixin from 'flarum/utils/mixin'; import stringToColor from 'flarum/utils/stringToColor'; import ItemList from 'flarum/utils/ItemList'; import computed from 'flarum/utils/computed'; import Badge from 'flarum/components/Badge'; export default class User extends mixin(Model, { username: Model.attribute('username'), email: Model.attribute('email'), isConfirmed: Model.attribute('isConfirmed'), password: Model.attribute('password'), avatarUrl: Model.attribute('avatarUrl'), bio: Model.attribute('bio'), bioHtml: computed('bio', bio => '<p>' + $('<div/>').text(bio).html() + '</p>'), preferences: Model.attribute('preferences'), groups: Model.hasMany('groups'), joinTime: Model.attribute('joinTime', Model.transformDate), lastSeenTime: Model.attribute('lastSeenTime', Model.transformDate), readTime: Model.attribute('readTime', Model.transformDate), unreadNotificationsCount: Model.attribute('unreadNotificationsCount'), discussionsCount: Model.attribute('discussionsCount'), commentsCount: Model.attribute('commentsCount'), canEdit: Model.attribute('canEdit'), canDelete: Model.attribute('canDelete'), avatarColor: null, color: computed('username', 'avatarUrl', 'avatarColor', function(username, avatarUrl, avatarColor) { // If we've already calculated and cached the dominant color of the user's // avatar, then we can return that in RGB format. If we haven't, we'll want // to calculate it. Unless the user doesn't have an avatar, in which case // we generate a color from their username. if (avatarColor) { return 'rgb(' + avatarColor.join(', ') + ')'; } else if (avatarUrl) { this.calculateAvatarColor(); return ''; } return '#' + stringToColor(username); }) }) { /** * Check whether or not the user has been seen in the last 5 minutes. * * @return {Boolean} * @public */ isOnline() { return this.lastSeenTime() > moment().subtract(5, 'minutes').toDate(); } /** * Get the Badge components that apply to this user. * * @return {ItemList} */ badges() { const items = new ItemList(); const groups = this.groups(); if (groups) { groups.forEach(group => { const name = group.nameSingular(); items.add('group' + group.id(), Badge.component({ label: app.trans('core.group_' + name.toLowerCase(), undefined, name), icon: group.icon(), style: {backgroundColor: group.color()} }) ); }); } return items; } /** * Calculate the dominant color of the user's avatar. The dominant color will * be set to the `avatarColor` property once it has been calculated. * * @protected */ calculateAvatarColor() { const image = new Image(); const user = this; image.onload = function() { const colorThief = new ColorThief(); user.avatarColor = colorThief.getColor(this); user.freshness = new Date(); m.redraw(); }; image.src = this.avatarUrl(); } }
JavaScript
0.000001
@@ -605,16 +605,22 @@ , bio =%3E + bio ? '%3Cp%3E' + @@ -657,16 +657,21 @@ + '%3C/p%3E' + : '' ),%0A pre
16b873a82d85db94fc0402e2c23d5039b3737864
fix the update available message
js/offline-manager.js
js/offline-manager.js
function updateFound() { var installingWorker = this.installing; // Wait for the new service worker to be installed before prompting to update. installingWorker.addEventListener('statechange', function() { switch (installingWorker.state) { case 'installed': // Only show the prompt if there is currently a controller so it is not // shown on first load. if (navigator.serviceWorker.controller && window.confirm('An updated version of this page is available, would you like to update?')) { window.location.reload(); return; } break; case 'redundant': console.error('The installing service worker became redundant.'); break; } }); } if ('serviceWorker' in navigator) { navigator.serviceWorker.register('offline-worker.js').then(function(registration) { console.log('offline worker registered'); registration.addEventListener('updatefound', updateFound); }); }
JavaScript
0.000002
@@ -484,17 +484,37 @@ of -this page +Musique Concr&egrave;te Choir is