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
82680c4664c478fe6d15615748f8bec255d0dec5
Delete space
src/File.js
src/File.js
let md5 = require('md5'); let path = require('path'); let fs = require('fs-extra'); let uglify = require('uglify-js'); let UglifyCss = require('clean-css'); class File { /** * Create a new instance. * * @param {string} filePath */ constructor(filePath) { this.absolutePath = path.resolve(filePath); this.filePath = this.relativePath(); this.segments = this.parse(); } /** * Static constructor. * * @param {string} file */ static find(file) { return new File(file); } /** * Get the size of the file. */ size() { return fs.statSync(this.path()).size; } /** * Determine if the given file exists. * * @param {string} file */ static exists(file) { return fs.existsSync(file); } /** * Delete/Unlink the current file. */ delete() { if (fs.existsSync(this.path())) { fs.unlinkSync(this.path()); } } /** * Get the name of the file. */ name() { return this.segments.file; } /** * Get the name of the file, minus the extension. */ nameWithoutExtension() { return this.segments.name; } /** * Get the extension of the file. */ extension() { return this.segments.ext; } /** * Get the absolute path to the file. */ path() { return this.absolutePath; } /** * Get the relative path to the file, from the project root. */ relativePath() { return this.path().replace(Mix.paths.root() + path.sep, ''); } /** * Get the absolute path to the file, minus the extension. */ pathWithoutExtension() { return this.segments.pathWithoutExt; } /** * Force the file's relative path to begin from the public path. * * @param {string|null} publicPath */ forceFromPublic(publicPath) { publicPath = publicPath || Config.publicPath; if (! this.relativePath().startsWith(publicPath)) { return new File(path.join(publicPath, this.relativePath())); } return this; } /** * Get the path to the file, starting at the project's public dir. * * @param {string|null} publicPath */ pathFromPublic(publicPath) { publicPath = publicPath || Config.publicPath; let extra = this.filePath.startsWith(publicPath) ? publicPath : ''; return this.path().replace(Mix.paths.root(extra), ''); } /** * Get the base directory of the file. */ base() { return this.segments.base; } /** * Determine if the file is a directory. */ isDirectory() { return this.segments.isDir; } /** * Determine if the path is a file, and not a directory. */ isFile() { return this.segments.isFile; } /** * Write the given contents to the file. * * @param {string} body */ write(body) { if (typeof body === 'object') { body = JSON.stringify(body, null, 4); } fs.writeFileSync(this.absolutePath, body); return this; } /** * Read the file's contents. */ read() { return fs.readFileSync(this.path(), { encoding: 'utf-8' }); } /** * Calculate the proper version hash for the file. */ version() { return md5(this.read()).substr(0, 20); } /** * Create all nested directories. */ makeDirectories() { fs.ensureDirSync(this.base()); return this; } /** * Copy the current file to a new location. * * @param {string} destination */ copyTo(destination) { fs.copySync(this.path(), destination); return this; } /** * Minify the file, if it is CSS or JS. */ minify() { if (this.extension() === '.js') { this.write(uglify.minify(this.path(), Config.uglify).code); } if (this.extension() === '.css') { this.write( new UglifyCss(Config.cleanCss).minify(this.read()).styles ); } return this; } /** * Rename the file. * * @param {string} to */ rename(to) { to = path.join(this.base(), to); fs.renameSync(this.path(), to); return new File(to); } /** * It can append to the current path. * * @param {string} append */ append(append) { return new File(path.join(this.path(), append)); } /** * Determine if the file path contains the given text. * * @param {string} text */ contains(text) { return this.path().includes(text); } /** * Parse the file path. */ parse() { let parsed = path.parse(this.absolutePath); return { path: this.filePath, absolutePath: this.absolutePath, pathWithoutExt: path.join(parsed.dir, `${parsed.name}`), isDir: ! parsed.ext, isFile: !! parsed.ext, name: parsed.name, ext: parsed.ext, file: parsed.base, base: parsed.dir }; } } module.exports = File;
JavaScript
0.003279
@@ -1116,18 +1116,16 @@ %7D%0A%0A%0A -%0A%0A /**%0A
3e6b79a6f71697765d93948b724f441bd97f5d16
rename set/isItemSelected
mixins/Selection.js
mixins/Selection.js
define(["dojo/_base/declare", "dojo/_base/array", "dojo/_base/lang"], function(declare, arr, lang){ return declare(null, { // summary: // Mixin for classes for widgets that manage a list of selected data items. Receiving class must extend // dijit/_WidgetBase. constructor: function(){ this.selectedItems = []; }, // selectionMode: String // Valid values are: // // 1. "none": No selection can be done. // 2. "single": Only one item can be selected at a time. // 3. "multiple": Several item can be selected using the control key modifier. // Default value is "single". selectionMode: "single", _setSelectionModeAttr: function(value){ if(value != "none" && value != "single" && value != "multiple"){ throw new Error("selectionModel invalid value"); } if(value != this.selectionMode){ this.selectionMode = value; if(value == "none"){ this.set("selectedItems", null); }else if(value == "single"){ this.set("selectedItem", this.selectedItem); // null or last selected item } } }, // selectedItem: Object // In single selection mode, the selected item or in multiple selection mode the last selected item. // Warning: Do not use this property directly, make sure to call set() or get() methods. selectedItem: null, _setSelectedItemAttr: function(value){ if(this.selectedItem != value){ this._set("selectedItem", value); this.set("selectedItems", value ? [value] : null); } }, // selectedItems: Object[] // The list of selected items. // Warning: Do not use this property directly, make sure to call set() or get() methods. selectedItems: null, _setSelectedItemsAttr: function(value){ var oldSelectedItems = this.selectedItems; this.selectedItems = value; this.selectedItem = null; if(oldSelectedItems != null && oldSelectedItems.length>0){ this.updateRenderers(oldSelectedItems, true); } if(this.selectedItems && this.selectedItems.length>0){ this.selectedItem = this.selectedItems[0]; this.updateRenderers(this.selectedItems, true); } }, _getSelectedItemsAttr: function(){ return this.selectedItems == null ? [] : this.selectedItems.concat(); }, isItemSelected: function(item){ // summary: // Returns wether an item is selected or not. // item: Object // The item to test the selection for. if(this.selectedItems == null || this.selectedItems.length== 0){ return false; } return arr.some(this.selectedItems, lang.hitch(this, function(sitem){ return this.getIdentity(sitem) == this.getIdentity(item); })); }, getIdentity: function(item){ // summary: // This function must be implemented to return the id of a item. // item: Object // The item to query the identity for. }, setItemSelected: function(item, value){ // summary: // Change the selection state of an item. // item: Object // The item to change the selection state for. // value: Boolean // True to select the item, false to deselect it. if(this.selectionMode == "none" || item == null){ return; } // copy is returned var sel = this.get("selectedItems"); if(this.selectionMode == "single"){ if(value){ this.set("selectedItem", item); }else if(this.isItemSelected(item)){ this.set("selectedItems", null); } }else{ // multiple if(value){ if(this.isItemSelected(item)){ return; // already selected } if(sel == null){ sel = [item]; }else{ sel.unshift(item); } this.set("selectedItems", sel); }else{ var res = arr.filter(sel, function(sitem){ return sitem.id != item.id; }); if(res == null || res.length == sel.length){ return; // already not selected } this.set("selectedItems", res); } } }, selectFromEvent: function(e, item, renderer, dispatch){ // summary: // Applies selection triggered by an user interaction // e: Event // The source event of the user interaction. // item: Object // The render item that has been selected/deselected. // renderer: Object // The visual renderer of the selected/deselected item. // dispatch: Boolean // Whether an event must be dispatched or not. // returns: Boolean // Returns true if the selection has changed and false otherwise. // tags: // protected if(this.selectionMode == "none"){ return false; } var changed; var oldSelectedItem = this.get("selectedItem"); var selected = item ? this.isItemSelected(item): false; if(item == null){ if(!e.ctrlKey && this.selectedItem != null){ this.set("selectedItem", null); changed = true; } }else if(this.selectionMode == "multiple"){ if(e.ctrlKey){ this.setItemSelected(item, !selected); changed = true; }else{ this.set("selectedItem", item); changed = true; } }else{ // single if(e.ctrlKey){ //if the object is selected deselects it. this.set("selectedItem", selected ? null : item); changed = true; }else{ if(!selected){ this.set("selectedItem", item); changed = true; } } } if(dispatch && changed){ this.dispatchSelectionChange(oldSelectedItem, this.get("selectedItem"), renderer, e); } return changed; }, dispatchSelectionChange: function(oldSelectedItem, newSelectedItem, renderer, triggerEvent){ // summary: // Dispatch a selection change event. // oldSelectedItem: Object // The previously selectedItem. // newSelectedItem: Object // The new selectedItem. // renderer: Object // The visual renderer of the selected/deselected item. // triggerEvent: Event // The event that lead to the selection of the item. // we assume we are a WidgetBase and we have an emit method this.emit("selection-change", { oldValue: oldSelectedItem, newValue: newSelectedItem, renderer: renderer, triggerEvent: triggerEvent }); } }); });
JavaScript
0.000003
@@ -2239,20 +2239,16 @@ %0A%09%09%0A%09%09is -Item Selected @@ -2296,16 +2296,17 @@ eturns w +h ether an @@ -2833,20 +2833,16 @@ %09%09%0A%09%09set -Item Selected
b71ac85f6e77dd59043c2286df94f3a9f13ddf88
Include all associated users as field device_users in phonelog view
phonelog/_design/views/devicelog_data/map.js
phonelog/_design/views/devicelog_data/map.js
function(doc) { function clone(obj){ if(obj == null || typeof(obj) != 'object') return obj; var temp = obj.constructor(); // changed for(var key in obj) temp[key] = clone(obj[key]); return temp; } var error_tags = ['exception', 'rms-repair', 'rms-spill'], warning_tags = ['case-recreate', 'permissions_notify', 'time message']; if (doc.xmlns == 'http://code.javarosa.org/devicereport') { var logged_in_user = "unknown"; for (var i in doc.form.log_subreport.log) { // need to clone because you can't set the property on the actual doc var entry = clone(doc.form.log_subreport.log[i]); entry.version = doc.form.app_version; entry.device_id = doc.form.device_id; if(entry.type == 'login') logged_in_user = entry.msg.substring(entry.msg.indexOf('-') + 1); entry.user = logged_in_user; if (entry.type && entry['@date']) { // Basic emit([doc.domain, "basic", entry['@date']], entry); var is_error = (error_tags.indexOf(entry.type) >= 0), is_warning = (warning_tags.indexOf(entry.type) >= 0); if (is_warning === true || is_error === true) { entry.isWarning = is_warning; entry.isError = is_error; emit([doc.domain, "errors_only", logged_in_user, entry['@date']], entry); emit([doc.domain, "all_errors_only", entry['@date']], entry); } // Single Parameters emit([doc.domain, "username", logged_in_user, entry['@date']], entry); emit([doc.domain, "tag", entry.type, entry['@date']], entry); emit([doc.domain, "device", doc.form.device_id, entry['@date']], entry); // Coupled Parameters emit([doc.domain, "tag_username", entry.type, logged_in_user, entry['@date']], entry); emit([doc.domain, "tag_device", entry.type, doc.form.device_id, entry['@date']], entry); emit([doc.domain, "username_device", logged_in_user, doc.form.device_id, entry['@date']], entry); // Tripled Parameters emit([doc.domain, "tag_username_device", entry.type, logged_in_user, doc.form.device_id, entry['@date']], entry); } } } }
JavaScript
0
@@ -457,24 +457,278 @@ ereport') %7B%0A + var user_subreport_usernames = %5B%5D;%0A if (doc.form.user_subreport) %7B%0A for (var i in doc.form.user_subreport.user) %7B%0A user_subreport_usernames.push(doc.form.user_subreport.user%5Bi%5D.username);%0A %7D%0A %7D%0A%0A var @@ -947,24 +947,83 @@ rt.log%5Bi%5D);%0A + entry.device_users = user_subreport_usernames;%0A @@ -2767,8 +2767,9 @@ %0A %7D%0A%7D +%0A
c90f7228c324f54835b3c3ad6608198e28b2ada6
set fb prod token correctly
client/internals/webpack/webpack.prod.babel.js
client/internals/webpack/webpack.prod.babel.js
// Important modules this config uses const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const OfflinePlugin = require('offline-plugin'); module.exports = require('./webpack.base.babel')({ // In production, we skip all hot-reloading stuff entry: [ path.join(process.cwd(), 'app/app.js'), ], // Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets output: { filename: '[name].[chunkhash].js', chunkFilename: '[name].[chunkhash].chunk.js', }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', children: true, minChunks: 2, async: true, }), // Minify and optimize the index.html new HtmlWebpackPlugin({ template: 'app/index.html', minify: { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true, }, inject: true, }), // Put it in the end to capture all the HtmlWebpackPlugin's // assets manipulations and do leak its manipulations to HtmlWebpackPlugin new OfflinePlugin({ relativePaths: false, publicPath: '/', // No need to cache .htaccess. See http://mxs.is/googmp, // this is applied before any match in `caches` section excludes: ['.htaccess'], caches: { main: [':rest:'], // All chunks marked as `additional`, loaded after main section // and do not prevent SW to install. Change to `optional` if // do not want them to be preloaded at all (cached only when first loaded) additional: ['*.chunk.js'], }, // Removes warning for about `additional` section usage safeToUseOptionalCaches: true, AppCache: false, updateStrategy: 'changed', autoUpdate: 1000 * 10, // After X milliseconds for SW to reload content ServiceWorker: { events: true, navigateFallbackURL: '/', }, }), new webpack.DefinePlugin({ API_URL: JSON.stringify('https://r3-go.herokuapp.com'), FACEBOOK_APP_ID: '347163215686508', }), new CopyWebpackPlugin([{ from: 'public' }]), ], performance: { assetFilter: (assetFilename) => !(/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename)), }, });
JavaScript
0.000001
@@ -2413,19 +2413,19 @@ 3471 -63215686508 +37092355787 ',%0A
63c6bec3f9c53b6bb972f2936d96d1984de7619b
debug mode
lib/shower/Shower.js
lib/shower/Shower.js
/** * @fileOverview */ modules.define('shower', [ 'event.Emitter', 'shower.Container', 'shower.Parser', 'shower.Player', 'shower.History', 'util.extend' ], function (provide, EventEmitter, Container, Parser, Player, History, extend) { /** * @name Shower * @constructor */ function Shower () { this.events = new EventEmitter(); /** * Shower options. * @field * @type {Object} */ this.options = {}; this.container = null; this.player = null; this._history = null; this._slideParser = null; this._slides = []; this._isReady = false; } extend(Shower.prototype, /** @lends Shower.prototype */{ /** * Init shower. * @param {HTMLElement | String} containerElement Container element or selector. * @param {Object} [options] Shower options. * @param {String} [options.slideSelector = '.shower--list > section'] Slide selector. */ init: function (containerElement, options) { this.options = extend({ //default options slideSelector: '.shower > section', parser: Parser }, options); if (typeof containerElement == 'string') { containerElement = document.querySelector(containerElement); } this.container = new Container(this, containerElement); this.player = new Player(this); this._slideParser = new this.options.parser(containerElement); this._parseSlides(); this._history = new History(this); this._isReady = true; this.events.emmit('ready'); return this; }, destroy: function () { this.events.emmit('destroy'); this.container.destroy(); this.player.destroy(); this._slides.length = 0; }, /** * @param {Function} callback */ ready: function (callback) { if (this._isReady) { callback(); } else { this.events.on('ready', callback); } }, /** * @param {Slide | Slide[]} slide * @returns {Shower} */ add: function (slide) { if (Array.isArray(slide)) { for (var i = 0, k = slide.length; i < k; i++) { this._addSlide(slide[i]); } } else { this._addSlide(slide); } return this; }, /** * @param {Slide | Number} slide * @returns {Shower} */ remove: function (slide) { var slidePosition; if (typeof slide == 'number') { slidePosition = slide; } else if (this._slides.indexOf(slide) != -1) { slidePosition = this._slides.indexOf(slide); } else { throw new Error('Slide not found'); } slide = this._slides.splice(slidePosition, 1); this.events.emmit('slideremove', { slide: slide }); slide.destroy(); return this; }, /** * @param {Number} index Slide index. * @returns {Slide} Slide by index. */ get: function (index) { return this._slides[index]; }, /** * @returns {Slide[]} */ getSlidesArray: function () { return this._slides.slice(); }, /** * @returns {Number} Slides count. */ getSlidesCount: function () { return this._slides.length; }, /** * @borrows shower.Player.next * @returns {Shower} */ next: function () { this.player.next(); return this; }, /** * @borrows shower.Player.prev * @returns {Shower} */ prev: function () { this.player.prev(); return this; }, /** * @borrows shower.Player.first * @returns {Shower} */ first: function () { this.player.first(); return this; }, /** * @borrows shower.Player.last * @returns {Shower} */ last: function () { this.player.last(); return this; }, go: function (index) { this.player.go(index); return this; }, _parseSlides: function () { this.add(this._slideParser.parse(this.options.slideSelector)); }, _addSlide: function (slide) { this._slides.push(slide); // TODO: ? // slide.setParent(this); this.events.emmit('slideadd', { slide: slide }); } }); provide(new Shower()); });
JavaScript
0
@@ -1145,17 +1145,18 @@ // -d + D efault o @@ -1161,16 +1161,51 @@ options +.%0A debugMode: false, %0A @@ -1715,32 +1715,189 @@ History(this);%0A%0A + if (this.options.debugMode) %7B%0A document.body.classList.add('debug');%0A console.log('Debug mode on');%0A %7D%0A%0A this
47103c7ad9989bcec08215a26a0b649fde0e20d1
Fix incorrectly referenced variable
manifest.js
manifest.js
/** * Events: * dependenciesChange(differences, manifest, url) - When one or more dependencies for a manifest change * retrieve(manifest, url) - The first time a manifest is retrieved */ var events = require('events'); var request = require('request'); var moment = require('moment'); var exports = new events.EventEmitter(); function Manifest(data) { this.data = data; this.expires = moment().add(Manifest.TTL); } Manifest.TTL = moment.duration({hours: 1}); var manifests = {}; function PackageDiff(name, version, previous) { this.name = name; this.version = version; this.previous = previous; } function getDependencyDiffs(deps1, deps2) { deps1 = deps1 || {}; deps2 = deps2 || {}; var keys1 = Object.keys(deps1); var keys2 = Object.keys(deps2); var diffs = []; // Check for deletions and changes keys1.forEach(function(key) { if(!deps2[key]) { // Dep has been deleted diffs.push(new PackageDiff(key, null, deps1[key])); } else if(dep1[key] !== dep2[key]) { // Dep has been changed diffs.push(new PackageDiff(key, deps2[key], deps1[key])); } }); // Check for additions keys2.forEach(function(key) { if(!deps1[key]) { diffs.push(new PackageDiff(key, deps2[key], null)); } }); return diffs; } exports.getManifest = function(url, callback) { var manifest = manifests[url]; if(manifest && manifest.expires > new Date()) { console.log('Using cached manifest', manifest.data.name, manifest.data.version); callback(null, JSON.parse(JSON.stringify(manifest.data))); return; } request(url, function(err, response, body) { if(!err && response.statusCode == 200) { console.log('Successfully retrieved package.json'); var data = JSON.parse(body); if(!data) { callback(new Error('Failed to parse package.json: ' + body)); } else { console.log('Got manifest', data.name, data.version); var oldManifest = manifest; var oldDependencies = oldManifest ? oldManifest.data.dependencies : {}; manifest = new Manifest(data); manifests[url] = manifest; callback(null, manifest.data); if(!oldManifest) { exports.emit('retrieve', JSON.parse(JSON.stringify(data)), url); } else { var diffs = getDependencyDiffs(oldDependencies, data.dependencies); if(diffs.length) { exports.emit('dependenciesChange', diffs, JSON.parse(JSON.stringify(data)), url); } } } } else if(!err) { callback(new Error(response.statusCode + ' Failed to retrieve manifest from ' + url)); } else { callback(err); } }); }; exports.getGithubManifestUrl = function(username, repo) { return 'https://raw.github.com/' + username + '/' + repo + '/master/package.json'; }; /** * Set the TTL for cached manifests. * * @param {moment.duration} duration Time period the manifests will be cahced for, expressed as a moment.duration. */ exports.setCacheDuration = function(duration) { Manifest.TTL = duration; }; module.exports = exports;
JavaScript
0.000002
@@ -980,16 +980,17 @@ e if(dep +s 1%5Bkey%5D ! @@ -995,16 +995,17 @@ !== dep +s 2%5Bkey%5D)
9289e0ccbdd25ac4486a1eee428486beb10f2212
send template name as url param when rendering a report
src/helpers/preview.js
src/helpers/preview.js
import isObject from 'lodash/isObject' import resolveUrl from '../helpers/resolveUrl.js' function addInput (form, name, value) { const input = document.createElement('input') input.type = 'hidden' input.name = name input.value = value form.appendChild(input) } export default function (request, target) { delete request.template._id request.template.content = request.template.content || ' ' request.options = request.options || {} request.options.preview = true if (target === '_self') { delete request.options.preview request.options.download = true } const mapForm = document.createElement('form') mapForm.target = target mapForm.method = 'POST' mapForm.action = resolveUrl('/api/report') function addBody (path, body) { if (body === undefined) { return } for (const key in body) { if (isObject(body[ key ])) { // somehow it skips empty array for template.scripts, this condition fixes that if (body[ key ] instanceof Array && body[ key ].length === 0) { addInput(mapForm, path + '[' + key + ']', []) } addBody(path + '[' + key + ']', body[ key ]) } else { if (body[ key ] !== undefined && !(body[ key ] instanceof Array)) { addInput(mapForm, path + '[' + key + ']', body[ key ]) } } } } addBody('template', request.template) addBody('options', request.options) if (request.data) { addInput(mapForm, 'data', request.data) } document.body.appendChild(mapForm) mapForm.submit() }
JavaScript
0
@@ -582,16 +582,61 @@ ue%0A %7D%0A%0A + const templateName = request.template.name%0A const @@ -676,16 +676,17 @@ 'form')%0A +%0A mapFor @@ -733,26 +733,244 @@ ST'%0A - mapForm.action = +%0A // we set the template name in url just to show a title in the preview iframe, the name%0A // won't be using at all on server side logic%0A mapForm.action = templateName ? resolveUrl(%60/api/report/$%7BencodeURIComponent(templateName)%7D%60) : res @@ -1811,13 +1811,12 @@ .submit()%0A%7D%0A -%0A
d6ba3bccb532ee45321ca6426835809040362933
Remove selection restoring from auto list
src/wysihtml5/text_substitutions/auto_list.js
src/wysihtml5/text_substitutions/auto_list.js
import { Composer } from "../views/composer"; import { Constants } from "../constants"; var autoList = function(editor, composer, range, textContent, e) { var selectedNode = range.startContainer; var blockElement = composer.parentElement(selectedNode, { nodeName: ["P", "DIV", "LI"] }); if (blockElement && blockElement.nodeName != "LI") { if (composer.selection.caretIsAtStartOfNode(blockElement, range, selectedNode)) { composer.selection.executeAndRestore(function() { var orderedList = hasPrefix(textContent, "1."); var deleteRange = document.createRange(); deleteRange.setStart(range.startContainer, 0); deleteRange.setEnd(range.startContainer, orderedList ? 2 : 1); deleteRange.deleteContents(); var selection = composer.selection.getSelection().nativeSelection; selection.removeAllRanges(); selection.addRange(range); var command = orderedList ? "insertOrderedList" : "insertUnorderedList"; composer.commands.exec(command); }); return true; } } return false; }; var hasPrefix = function(string, prefix) { return string.indexOf(prefix) == 0 }; var isListPrefix = function(textContent, exact) { if (exact) { return (textContent == "1." || textContent == "•" || textContent == "*" || textContent == "-"); } else { return ( hasPrefix(textContent, "1.") || hasPrefix(textContent, "•") || hasPrefix(textContent, "*") || hasPrefix(textContent, "-") ); } }; Composer.RegisterTextSubstitution(function(textContent) { return isListPrefix(textContent, true); }, function(editor, composer, range, textContent, e) { if (autoList(editor, composer, range, textContent, e)) { if (e.type === "keydown" && e.keyCode == Constants.SPACE_KEY) { e.preventDefault(); } } }, { word: true, sentence: false }); Composer.RegisterTextSubstitution(function(textContent) { return isListPrefix(textContent); }, autoList, { word: false, sentence: true });
JavaScript
0
@@ -436,66 +436,8 @@ ) %7B%0A - composer.selection.executeAndRestore(function() %7B%0A @@ -483,26 +483,24 @@ nt, %221.%22);%0A%0A - var de @@ -533,34 +533,32 @@ eRange();%0A - deleteRange.setS @@ -588,18 +588,16 @@ er, 0);%0A - de @@ -659,26 +659,24 @@ : 1);%0A - - deleteRange. @@ -690,26 +690,24 @@ ontents();%0A%0A - var se @@ -765,34 +765,32 @@ election;%0A - selection.remove @@ -804,26 +804,24 @@ es();%0A - - selection.ad @@ -832,26 +832,24 @@ ge(range);%0A%0A - var co @@ -915,18 +915,16 @@ dList%22;%0A - co @@ -958,18 +958,8 @@ d);%0A - %7D);%0A
8c1650f937701d3cb19fc35eebcd74e6c9479d50
Fix default state in tactic reducer
src/reducers/tactics.js
src/reducers/tactics.js
import { combineReducers } from 'redux'; import * as types from '../constants/ActionTypes'; const tactic = (state = { teams: {} }, action) => { switch (action.type) { case types.CREATE_TACTIC_FULFILLED: { const id = action.payload.data.id; return { [id]: { id, ...action.meta.data } }; } default: return state; } }; const byId = (state = {}, action) => { switch (action.type) { case types.CREATE_TACTIC_FULFILLED: return { ...state, ...tactic(state, action) }; default: return state; } }; const items = (state = [], action) => { switch (action.type) { case types.CREATE_TACTIC_FULFILLED: return [action.payload.data.id, ...state]; case types.FETCH_TACTICS_FULFILLED: return [...state, ...action.payload.tactics]; default: return state; } }; const status = (state = { isFetching: false, error: false }, action) => { switch (action.type) { case types.FETCH_TACTICS_PENDING: return { ...state, isFetching: true }; case types.FETCH_TACTICS_REJECTED: return { ...state, isFetching: false, error: true }; case types.FETCH_TACTICS_FULFILLED: return { ...state, isFetching: false, error: false }; default: return state; } }; export default combineReducers({ byId, items, status });
JavaScript
0.000002
@@ -119,18 +119,18 @@ teams: -%7B%7D +%5B%5D %7D, acti @@ -292,16 +292,26 @@ eta.data +, ...state %7D %7D;%0A @@ -494,21 +494,25 @@ .tactic( -state +undefined , action
7af48d2f7047a32f04bbe4220c8fdd6e5babafd6
fix bug: change set of options
src/Game.js
src/Game.js
import React, { Component } from 'react'; import { Alert, Button } from 'react-bootstrap'; import banana from './images/banana.jpg'; import koala from './images/koala.jpg'; import panda1 from './images/panda1.jpg'; import panda2 from './images/panda2.jpg'; import panda3 from './images/panda3.jpg'; import popândău1 from './images/popândău1.jpg'; import popândău2 from './images/popândău2.jpg'; import popice1 from './images/popice1.jpg'; import popice2 from './images/popice1.jpg'; import păpădie1 from './images/păpădie1.jpg'; import păpădie2 from './images/păpădie2.jpg'; import Question from './Question'; const questions = [ [ { name: 'urs koala', images: [koala] }, { name: 'urs panda', images: [panda1, panda2, panda3] }, { name: 'banană', images: [banana] } ], [ { name: 'popândău', images: [popândău1, popândău2] }, { name: 'popice', images: [popice1, popice2] }, { name: 'păpădie', images: [păpădie1, păpădie2] } ] ]; function chooseQuestion() { const questionIndex = Math.floor(Math.random() * questions.length); const question = questions[questionIndex]; return question.map(option => ({ name: option.name, image: option.images[Math.floor(Math.random() * option.images.length)] })); } class Game extends Component { constructor() { super(); this.handleWrongAnswer = this.handleWrongAnswer.bind(this); this.handleCorrectAnswer = this.handleCorrectAnswer.bind(this); this.nextQuestion = this.nextQuestion.bind(this); this.state = { isAnswerCorrect: undefined, question: chooseQuestion(), correctIndex: Math.floor(Math.random() * 3), }; } render() { let result = null; if (this.state.isAnswerCorrect) { result = ( <Alert bsStyle='success'> Bravo!&nbsp; <Button onClick={this.nextQuestion}>Mai departe &gt;</Button> </Alert> ); } else if (this.state.isAnswerCorrect === false) { result = <Alert bsStyle='warning'>Mai încearcă...</Alert>; } return ( <div> <Question correctAnswerIndex={this.state.correctIndex} allItems={this.state.question} handleWrongAnswer={this.handleWrongAnswer} handleCorrectAnswer={this.handleCorrectAnswer} /> {result} </div> ); } handleWrongAnswer() { this.setState({ isAnswerCorrect: false }); } handleCorrectAnswer() { this.setState({ isAnswerCorrect: true }); } nextQuestion() { this.setState({ isAnswerCorrect: undefined, correctIndex: Math.floor(Math.random() * 3), pandaIndex: Math.floor(Math.random() * 3) }); } } export default Game;
JavaScript
0.000003
@@ -2811,50 +2811,33 @@ -correctIndex: Math.floor(Math.random() * 3 +question: chooseQuestion( ),%0A @@ -2847,21 +2847,23 @@ -panda +correct Index: M @@ -2890,16 +2890,17 @@ m() * 3) +, %0A
dbfb95de81ef664257f5108cf4e222fb9b034731
Add activityTypeSelection reactive var
client/views/activities/latest/latestByType.js
client/views/activities/latest/latestByType.js
Template.latestActivitiesByType.created = function () { // Create 'instance' variable for use througout template logic var instance = this; // Subscribe to all activity types instance.subscribe('allActivityTypes'); }; Template.latestActivitiesByType.helpers({ 'activityTypeOptions': function () { // Get all activity types activityTypes = ActivityTypes.find().fetch(); return activityTypes; } });
JavaScript
0
@@ -216,17 +216,124 @@ Types'); - +%0A%0A // Create variable to hold activity type selection%0A instance.activityTypeSelection = new ReactiveVar(); %0A%7D;%0A%0ATem
c5a83b24ec2259c51f9bd36f95c5eaed71c9a34d
set default to null to avoid truthy test
lib/superapi/api.js
lib/superapi/api.js
// closure var serviceHandler = function(service) { /* * Below are the supported options for the serviceHandler: * * - data (object): request data payload * - params (object): use to replace the tokens in the url * - query (object): use to build the query string appended to the url * - callback (function): callback to use, with a default which emits 'success' or 'error' * event depending on res.ok value * - edit (function): callback to use, to tweak req if needed. */ return function(options) { options = options || {}; var data = options.data || {}; var params = options.params || {}; var query = options.query || {}; var callback = options.callback || {}; var edit = options.edit || {}; var req = this.request(service, data, params, query); if ("function" === typeof edit) { edit(req); } req.end(callback ? callback : function(res) { req.emit(res.ok ? "success" : "error", res, data, params); }); return req; }; }; function Api(config) { this.config = config; // create a hash-liked object where all the services handlers are registered this.api = Object.create(null); for (var name in config.services) { if (!Object.prototype.hasOwnProperty(this, name)) { // syntatic sugar: install a service handler available on // the api instance with service name this.api[name] = serviceHandler(name).bind(this); } } } Api.prototype = { paramsPattern: /:(\w+)/g, service: function(id) { return this.config.services[id]; }, url: function(id) { var url = this.config.baseUrl; var resource = this.service(id); // from time being it"s a simple map if (resource) { var path; if (typeof resource === "string") { path = resource; } if (typeof resource === "object" && resource.path !== undefined) { path = resource.path; } if (!path) { throw new Error("path is not defined for route $" + id); } url += path[0] === "/" ? path : "/" + path; } return url; }, replaceUrl: function(url, params) { var tokens = url.match(this.paramsPattern); if (!tokens || !tokens.length) { return url; } for (var i = 0, len = tokens.length; i < len; i += 1) { var token = tokens[i]; var name = token.substring(1); if (params[name]) { url = url.replace(token, params[name]); } } return url; }, buildUrlQuery: function(query) { if (!query) { return ''; } var queryString; if (typeof query === "string") { queryString = query; } else { var queryArgs = []; for (var queryArg in query) { queryArgs.push(queryArg + '=' + query[queryArg]); } queryString = queryArgs.join("&"); } return queryString ? '?' + queryString : ''; }, buildUrl: function(id, params, query) { var url = this.url(id); if (params) { url = this.replaceUrl(url, params); } if (query) { url += this.buildUrlQuery(query); } return url; }, request: function(id, data, params, query) { var service = this.service(id); var method = (typeof service === "string" ? "get" : service.method || "get").toLowerCase(); // fix for delete being a reserved word if (method === "delete") { method = "del"; } if (!this.agent) { throw new Error('missing superagent or any api compatible agent.') } var request = this.agent[method]; if (!request) { throw new Error("Invalid method [" + service.method + "]"); } var _req = request(this.buildUrl(id, params, query), data); // add global headers this._setHeaders(_req, this.config.headers); // add global options to request headers this._setOptions(_req, this.config.options); // add service options to request headers this._setOptions(_req, service.options); // add service headers this._setHeaders(_req, service.headers); // add runtime headers this._setHeaders(_req, this.headers); // set credentials if (this.config.withCredentials) { _req.withCredentials(); } return _req; }, addHeader: function(name, value) { this.headers = this.headers || {}; this.headers[name] = value; }, removeHeader: function(name) { if (this.headers && this.headers[name]) { delete this.headers[name]; } }, _setHeaders: function(req, headers) { for (var header in headers) { req.set(header, headers[header]); } }, _setOptions: function(req, options) { for (var option in options) { req[option](options[option]); } } }; export default Api;
JavaScript
0
@@ -700,26 +700,28 @@ callback %7C%7C -%7B%7D +null ;%0A var ed @@ -741,18 +741,20 @@ edit %7C%7C -%7B%7D +null ;%0A%0A v @@ -806,24 +806,73 @@ query);%0A - if ( +%0A // edit request if function defined%0A if (edit && %22functio
a662d6b4bb79fab7554249568d5d6bdad26919f6
Remove unnecessary, deprecated import
lib/simple-notify.js
lib/simple-notify.js
const { Cc, Ci } = require('chrome'), data = require('sdk/self').data, prefs = require('sdk/preferences/service'), tabbrowser = require('sdk/deprecated/tab-browser'), timer = require('sdk/timers'), windowutils = require('sdk/deprecated/window-utils'); const addon_name = 'Copy ShortURL', addon_icon = data.url('img/ruler.png'), addon_icon32 = data.url('img/ruler32.png'), // Preferences notification_pref = 'extensions.copyshorturl.notifications', notification_default = 2; /** Growl notifications with notificationbox fallback */ function notify(txt) { /* Set URL preference if not set. */ if (!prefs.has(notification_pref)) prefs.set(notification_pref, notification_default); switch (prefs.get(notification_pref, notification_default)) { // No notifications case 0: return; // Box only case 1: boxNotify(txt); break; // Growl with box fallback default: case 2: try { growlNotify(txt); } catch (e) { boxNotify(txt); } break; } } /** Notify via Growl. Throws exception if unavailable. */ function growlNotify(txt) { // Ugly: Import alert service. If unavailable, throws exception. // Would use notifications.notify if that let me know when Growl is // unavailable. let alertServ = Cc["@mozilla.org/alerts-service;1"]. getService(Ci.nsIAlertsService); alertServ.showAlertNotification( addon_icon32, // icon addon_name, // title txt // text ); } /** Notify via notification box. */ function boxNotify(txt) { let nb = getNotificationBox(), notification = nb.appendNotification( txt, 'jetpack-notification-box', addon_icon || 'chrome://browser/skin/Info.png', nb.PRIORITY_INFO_MEDIUM, [] ); timer.setTimeout(function() { if (notification && notification.close) { notification.close(); } }, 10 * 1000); } /** * Get notification box ("yellow bar"). * Courtesy of bug 533649. */ function getNotificationBox() { let browser = windowutils.activeBrowserWindow.gBrowser, notificationBox = browser.getNotificationBox(); return notificationBox; } /* Exports */ exports.notify = notify; exports.growlNotify = growlNotify; exports.boxNotify = boxNotify;
JavaScript
0.000011
@@ -124,66 +124,8 @@ '),%0A - tabbrowser = require('sdk/deprecated/tab-browser'),%0A
598a5ef291210bbf00af4304de772a2dcdba580c
Add markdown renderer title
lib/react/components/MarkdownEditor/index.js
lib/react/components/MarkdownEditor/index.js
import React from 'react'; import PropTypes from 'prop-types'; import autobind from 'core-decorators/es/autobind'; import { Tab2, Tabs2 } from "@blueprintjs/core"; import MediaQuery from 'react-responsive'; import bp from '../utility/bp'; import MarkdownRenderer from '../MarkdownRenderer'; import MarkdownInput from './MarkdownInput'; import MarkdownReference from './MarkdownReference'; import '../../scss/components/_markdownEditor.scss'; @autobind class MarkdownEditor extends React.Component { static propTypes = { defaultContent: PropTypes.string, content: PropTypes.string, onChange: PropTypes.func, hidePreview: PropTypes.bool, hideHelp: PropTypes.bool, disabled: PropTypes.bool, } static defaultProps = { showPreview: true, showHelp: true, disabled: false } state = { content: this.props.content ? this.props.content : (this.props.defaultContent ? this.props.defaultContent : null), selectedTabId: 'editor' } handleEditorChange(event) { this.setState({ content: event.target.value }); } handleTabChange(selectedTabId) { this.setState({ selectedTabId }); } render() { const onChange = this.props.onChange ? this.props.onChange : this.handleEditorChange; const readOnly = onChange ? false : true; return ( <div className='markdown editor'> <Tabs2 onChange={this.handleTabChange} selectedTabId={this.state.selectedTabId} renderActiveTabPanelOnly={true} key='horizontal' animate={true}> <MediaQuery maxWidth={bp.xs}> <div className='heading'>Editor</div> </MediaQuery> <MediaQuery minWidth={bp.xs + 1}> <div className='heading'>Markdown Editor</div> </MediaQuery> <Tab2 id='editor' title='Editor' panel={ <MarkdownInput src={this.props.content || this.state.content} onChange={onChange} readOnly={readOnly} disabled={this.props.disabled}/> }/> {this.props.hidePreview ? null : <Tab2 id='renderer' title='Preview' panel={ <MarkdownRenderer className='markdown-content' src={this.props.content || this.state.content}/> }/> } {this.props.hideHelp ? null : <Tab2 id='help' title='Help' panel={ <MarkdownRenderer className='help' src={MarkdownReference}/> }/> } <Tabs2.Expander/> </Tabs2> </div> ); } } export default MarkdownEditor;
JavaScript
0
@@ -697,16 +697,42 @@ s.bool,%0A +%09%09title: PropTypes.string%0A %09%7D%0A%0A%09sta @@ -1146,16 +1146,90 @@ der() %7B%0A +%09%09const %7B title, content, disabled, hideHelp, hidePreview %7D = this.props;%0A %09%09const @@ -1649,22 +1649,42 @@ eading'%3E +%7Btitle ? title : ' Editor +'%7D %3C/div%3E%0A%09 @@ -1771,16 +1771,34 @@ eading'%3E +%7Btitle ? title : ' Markdown @@ -1804,16 +1804,18 @@ n Editor +'%7D %3C/div%3E%0A%09 @@ -1901,35 +1901,24 @@ nInput src=%7B -this.props. content %7C%7C t @@ -1986,27 +1986,16 @@ sabled=%7B -this.props. disabled @@ -2010,35 +2010,24 @@ %09%7D/%3E%0A%0A%09%09%09%09%09%7B -this.props. hidePreview @@ -2144,27 +2144,16 @@ t' src=%7B -this.props. content @@ -2196,27 +2196,16 @@ %0A%0A%09%09%09%09%09%7B -this.props. hideHelp
e0d69c921fa858bd0682c596706bab8dcd2fe9be
Revert "Remap map data to {name, value}."
src/hierarchy/index.js
src/hierarchy/index.js
import node_count from "./count.js"; import node_each from "./each.js"; import node_eachBefore from "./eachBefore.js"; import node_eachAfter from "./eachAfter.js"; import node_find from "./find.js"; import node_sum from "./sum.js"; import node_sort from "./sort.js"; import node_path from "./path.js"; import node_ancestors from "./ancestors.js"; import node_descendants from "./descendants.js"; import node_leaves from "./leaves.js"; import node_links from "./links.js"; import node_iterator from "./iterator.js"; export default function hierarchy(data, children) { if (data instanceof Map) return hierarchy([undefined, data], children === undefined ? mapChildren : children).each(mapData); if (children === undefined) children = objectChildren; var root = new Node(data), node, nodes = [root], child, childs, i, n; while (node = nodes.pop()) { if ((childs = children(node.data)) && (n = (childs = Array.from(childs)).length)) { node.children = childs; for (i = n - 1; i >= 0; --i) { nodes.push(child = childs[i] = new Node(childs[i])); child.parent = node; child.depth = node.depth + 1; } } } return root.each(computeHeight); } function node_copy() { return hierarchy(this).each(copyData); } function objectChildren(d) { return d.children; } function mapChildren(d) { return Array.isArray(d) ? d[1] : null; } function mapData(node) { if (Array.isArray(node.data)) { node.data = {name: node.data[0], value: node.data[1]}; } } function copyData(node) { if (node.data.value !== undefined) node.value = node.data.value; node.data = node.data.data; } export function computeHeight(node) { var height = 0; do node.height = height; while ((node = node.parent) && (node.height < ++height)); } export function Node(data) { this.data = data; this.depth = this.height = 0; this.parent = null; } Node.prototype = hierarchy.prototype = { constructor: Node, count: node_count, each: node_each, eachAfter: node_eachAfter, eachBefore: node_eachBefore, find: node_find, sum: node_sum, sort: node_sort, path: node_path, ancestors: node_ancestors, descendants: node_descendants, leaves: node_leaves, links: node_links, copy: node_copy, [Symbol.iterator]: node_iterator };
JavaScript
0
@@ -588,33 +588,29 @@ of Map) -return hierarchy( +%7B%0A data = %5Bundefin @@ -618,18 +618,26 @@ d, data%5D -, +;%0A if ( children @@ -654,23 +654,19 @@ ined - ? mapC +) c hildren : ch @@ -665,36 +665,31 @@ ren -: c += mapC hildren -).each(mapData);%0A +;%0A %7D else if @@ -704,32 +704,38 @@ n === undefined) + %7B%0A children = obje @@ -745,16 +745,20 @@ hildren; +%0A %7D %0A%0A var @@ -1211,16 +1211,22 @@ oot.each +Before (compute @@ -1289,16 +1289,22 @@ is).each +Before (copyDat @@ -1437,133 +1437,8 @@ %0A%7D%0A%0A -function mapData(node) %7B%0A if (Array.isArray(node.data)) %7B%0A node.data = %7Bname: node.data%5B0%5D, value: node.data%5B1%5D%7D;%0A %7D%0A%7D%0A%0A func
b0c2ff006ad5132db709e8d9171b90ce9039d925
adding missing semi-colons
src/Game.js
src/Game.js
'use strict' var updateCellNeighbor = function(neighbors, coordinates, position) { var index = (coordinates[0] + position[0]) + ',' + (coordinates[1] + position[1]); if (neighbors[index]) { neighbors[index].n++; } else { neighbors[index] = {'x': coordinates[0] + position[0], 'y': coordinates[1] + position[1], 'n': 1}; } } var evolve = function(shape) { if (!shape) { return []; } var neighbors = {}; var evolvedShape = []; var positions = [ [-1, -1], // top left [0, -1], // top center [1, -1], // top right [1, 0], // right [1, 1], // bottom right [0, 1], // bottom center [-1, 1], // bottom left [-1, 0], // left ]; shape.forEach(function(coordinates, i) { positions.forEach(function(position) { updateCellNeighbor(neighbors, coordinates, position); }); }); shape.forEach(function(coordinates) { var index = coordinates[0] + ',' + coordinates[1]; if (neighbors[index]) { neighbors[index].populated = true; } }); Object.keys(neighbors).forEach(function(key) { var neighbor = neighbors[key]; if (neighbor.n === 3 || neighbor.n === 2 && neighbor.populated) { evolvedShape.push([neighbor.x, neighbor.y]); } }); return evolvedShape; }
JavaScript
0.999711
@@ -333,16 +333,17 @@ %7D;%0A %7D%0A%7D +; %0A%0Avar ev @@ -1272,9 +1272,10 @@ Shape;%0A%7D +; %0A
a8192cfae7a14860c0176974ec72f712da6ff27c
Add autorun to update resident activities
client/views/activities/latest/latestByType.js
client/views/activities/latest/latestByType.js
Template.latestActivitiesByType.created = function () { // Create 'instance' variable for use througout template logic var instance = this; // Subscribe to all activity types instance.subscribe('allActivityTypes'); // Create variable to hold activity type selection instance.activityTypeSelection = new ReactiveVar(); // Create latest resident activity placeholder instance.latestResidentsActivityByType = new ReactiveVar(); }; Template.latestActivitiesByType.helpers({ 'activityTypeOptions': function () { // Get all activity types activityTypes = ActivityTypes.find().fetch(); return activityTypes; } }); Template.latestActivitiesByType.events({ 'change #activity-type-select': function (event, template) { // Create instance variable for consistency var instance = Template.instance(); var selectedActivityType = event.target.value; instance.activityTypeSelection.set(selectedActivityType); } });
JavaScript
0
@@ -436,16 +436,650 @@ veVar(); +%0A%0A instance.autorun(function () %7B%0A // Get activity type selection%0A var activityTypeSelection = instance.activityTypeSelection.get();%0A%0A if (activityTypeSelection) %7B%0A // Get latest resident activities for selected activity type%0A Meteor.call(%0A 'getResidentsLatestActivityByType',%0A activityTypeSelection,%0A function (error, latestActivity) %7B%0A if (error) %7B%0A console.log(error);%0A %7D else %7B%0A // Update the reactive variable with latest resident activity%0A instance.latestResidentsActivityByType.set(latestActivity);%0A %7D%0A %7D);%0A %7D;%0A %7D); %0A%7D;%0A%0ATem
f88617d701395fd88a0d6127226c5bf5840050fa
remove comments
test/application-test.js
test/application-test.js
// init the test client var client = restify.createJsonClient({ version: '*', url: 'http://0.0.0.0:8080' }); var jobId = "NEW" describe('service: applications', function() { beforeEach(function(done){ var collections = ["jobs", "applications"] var db = mongojs.connect("test", collections); db.jobs.insert({position:"test position",description:"test description"}, function(err, job) { jobId = job[0]._id done(); }); }); after(function(done){ done(); }); // beforeEach(){ // db.jobs.insert({position:"test position",description:"test description"}, function(err, job) { // }); // } describe('get response check', function() { it('should not get a 200 response', function(done) { client.get('/applications', function(err, req, res, obj) { if (res.statusCode == 200) { throw new Error('invalid response from /applications'); } done(); }); }); }); describe('post response check', function() { it('should get a 400 response because missing description', function(done) { client.post('/applications', { application: { invalid: 'object' } }, function(err, req, res, obj) { if (res.statusCode != 400) { throw new Error('invalid response from /applications'); } done(); }); }); it('should get a 400 response with missing jobId', function(done) { client.post('/applications', { application: { name: 'my name', justification: "I am really nice.", code:"https://github.com/tgsoverly/apply"} }, function(err, req, res, obj) { if (res.statusCode != 400) { throw new Error('invalid response from /applications'); } done(); }); }); it('should get a 200 response with valid application', function(done) { client.post('/applications', { application: { name: 'my name', justification: "I am really nice.", code:"https://github.com/tgsoverly/apply", jobId:jobId } }, function(err, req, res, obj) { if (res.statusCode != 200) { throw new Error('invalid response from /applications'); } done(); }); }); }); });
JavaScript
0
@@ -512,144 +512,8 @@ );%0A%0A -// beforeEach()%7B%0A// db.jobs.insert(%7Bposition:%22test position%22,description:%22test description%22%7D, function(err, job) %7B%0A// %7D);%0A// %7D%0A%0A de
346640a5f74c7f59068ef43ba6c242c990c7c557
Rely on string for scolarite Enum
lib/simulation/openfisca/mapping/individu.js
lib/simulation/openfisca/mapping/individu.js
var moment = require('moment'); var _ = require('lodash'); function formatDate(date) { return moment(date).format('YYYY-MM-DD'); } module.exports = { date_naissance: { src: 'dateDeNaissance', fn: formatDate }, age: { src: 'dateDeNaissance', fn: function (dateDeNaissance, individu, situation) { return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'years'); } }, age_en_mois: { src: 'dateDeNaissance', fn: function (dateDeNaissance, individu, situation) { return moment(situation.dateDeValeur).diff(moment(dateDeNaissance), 'months'); } }, statut_marital: { src: 'statutMarital', values: { seul: 'Célibataire', // Enum value 2 in OpenFisca mariage: 'Marié',// Enum value 1 in OpenFisca pacs: 'Pacsé', // Enum value 5 in OpenFisca union_libre: 'Célibataire', // Enum value 2 in OpenFisca } }, id: { src: 'id', copyTo3PreviousMonths: false }, enceinte: 'enceinte', ass_precondition_remplie: 'assPreconditionRemplie', date_arret_de_travail: { src: 'dateArretDeTravail', fn: formatDate }, activite: { src: 'specificSituations', fn: function(value) { var returnValue; _.forEach({ demandeur_emploi: 1, etudiant: 2, retraite: 3 }, function(situationIndex, situation) { if (value.indexOf(situation) >= 0) { returnValue = situationIndex; } }); return returnValue; } }, handicap: { src: 'specificSituations', fn: function(specificSituations) { return specificSituations.indexOf('handicap') >= 0; } }, taux_incapacite: { fn: function(individu) { var handicap = individu.specificSituations.indexOf('handicap') >= 0; var tauxMap = { moins50: 0.3, moins80: 0.7, plus80: 0.9 }; return handicap && tauxMap[individu.tauxIncapacite]; } }, inapte_travail: { src: 'specificSituations', fn: function(specificSituations) { return specificSituations.indexOf('inapte_travail') >= 0; } }, perte_autonomie: 'perteAutonomie', etudiant: { src: 'specificSituations', fn: function(specificSituations) { return specificSituations.indexOf('etudiant') >= 0; } }, boursier: { fn: function(individu) { return individu.boursier || individu.echelonBourse >= 0; // backward compatibility for boursier; cannot write a migration because the exact echelon is not known } }, echelon_bourse: 'echelonBourse', scolarite: { fn: function(individu) { var values = { 'inconnue': 0, 'college': 1, 'lycee': 2 }; return values[individu.scolarite]; } }, enfant_a_charge: { // variable liée à l'année fiscale : on la définit sur l'année fn: function(individu, situation) { var year = situation.dateDeValeur.getFullYear(); var result = {}; result[year] = individu.aCharge || (! individu.fiscalementIndependant); return result; }, copyTo3PreviousMonths: false, }, enfant_place: 'place', garde_alternee: 'gardeAlternee', habite_chez_parents: 'habiteChezParents', /* Revenus du patrimoine */ interets_epargne_sur_livrets: { src: 'epargneSurLivret', fn: function(value) { return { '2012-01': 0.01 * value || 0 }; }, copyTo3PreviousMonths: false, }, epargne_non_remuneree: { src: 'epargneSansRevenus', fn: function (value) { return { '2012-01': value || 0 }; }, copyTo3PreviousMonths: false }, valeur_locative_immo_non_loue: { src: 'valeurLocativeImmoNonLoue', fn: function (value) { return { '2012-01': value || 0 }; }, copyTo3PreviousMonths: false, }, valeur_locative_terrains_non_loue: { src: 'valeurLocativeTerrainNonLoue', fn: function (value) { return { '2012-01': value || 0 }; }, copyTo3PreviousMonths: false, }, /* Activités non-salarié */ tns_autres_revenus_type_activite: 'tns_autres_revenus_type_activite', tns_auto_entrepreneur_type_activite: 'autoEntrepreneurActiviteType', tns_micro_entreprise_type_activite: 'microEntrepriseActiviteType', };
JavaScript
0.99939
@@ -3035,17 +3035,26 @@ onnue': -0 +'Inconnue' ,%0A @@ -3074,17 +3074,25 @@ llege': -1 +'Coll%C3%A8ge' ,%0A @@ -3109,18 +3109,24 @@ 'lycee': - 2 +'Lyc%C3%A9e', %0A
75a2a042c1839c669270bcc8379e03398471e237
Limit concurrent command operation to 2
execqueue.js
execqueue.js
// Copyright 2012, 2013 Patrick Wang <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var exec = require('child_process').exec, limit = 5, running = 0; var cmdQueue = []; function runQueue() { var queuedItem; if (running < limit) { while (!queuedItem && cmdQueue.length > 0) { queuedItem = cmdQueue.shift(); } if (queuedItem) { running++; exec(queuedItem.cmd, function() { var args = Array.prototype.slice.call(arguments); // Callback, then run next task. queuedItem.cb.apply(this, args); running--; setTimeout(runQueue(), 0); }); } } }; exports.exec = function execEnqueue(cmd, callback) { cmdQueue.push({ cmd: cmd, cb: callback }); setTimeout(runQueue, 0); };
JavaScript
0.999997
@@ -620,16 +620,19 @@ ar exec + = requir @@ -670,11 +670,13 @@ mit + = -5 +2 ,%0A
232b0af4541fa2ce5fd6ee62760c997ae0667622
Update PNTSLoader.js
src/three/PNTSLoader.js
src/three/PNTSLoader.js
import { PNTSLoaderBase } from '../base/PNTSLoaderBase.js'; import { Points, PointsMaterial, BufferGeometry, BufferAttribute } from 'three'; export class PNTSLoader extends PNTSLoaderBase { constructor( manager ) { super(); this.manager = manager; } parse( buffer ) { const result = super.parse( buffer ); const { featureTable } = result; window.data = result // global semantics const POINTS_LENGTH = featureTable.getData( 'POINTS_LENGTH' ); // RTC_CENTER // QUANTIZED_VOLUME_OFFSET // QUANTIZED_VOLUME_SCALE // CONSTANT_RGBA // BATCH_LENGTH const POSITION = featureTable.getData( 'POSITION', POINTS_LENGTH, 'FLOAT', 'VEC3' ); const RGB = featureTable.getData( 'RGB', POINTS_LENGTH, 'UNSIGNED_BYTE', 'VEC3' ); // POSITION_QUANTIZED // RGBA // RGB565 // NORMAL // NORMAL_OCT16P // BATCH_ID if ( POSITION === null ) { throw new Error( 'PNTSLoader : POSITION_QUANTIZED feature type is not supported.' ); } const geometry = new BufferGeometry(); geometry.setAttribute( 'position', new BufferAttribute( POSITION, 3, false ) ); const material = new PointsMaterial(); material.size = 2; material.sizeAttenuation = false; if ( RGB !== null ) { geometry.setAttribute( 'color', new BufferAttribute( RGB, 3, true ) ); material.vertexColors = true; } const object = new Points( geometry, material ); result.scene = object; return result; } }
JavaScript
0
@@ -352,31 +352,8 @@ ult; -%0A%09%09window.data = result %0A%0A%09%09
e3cfcdfb9c99d3182c43f364c0122acca1591199
Remove silly exit
scripts/run-android-ci-instrumentation-tests.js
scripts/run-android-ci-instrumentation-tests.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. */ 'use strict'; /** * This script runs instrumentation tests one by one with retries * Instrumentation tests tend to be flaky, so rerunning them individually increases * chances for success and reduces total average execution time. * * We assume that all instrumentation tests are flat in one folder * Available arguments: * --path - path to all .java files with tests * --package - com.facebook.react.tests * --retries [num] - how many times to retry possible flaky commands: npm install and running tests, default 1 */ const { echo, exec, exit, ls, } = require('shelljs'); console.log(echo, exec, exit, ls); exit(0); const argv = require('yargs').argv; const numberOfRetries = argv.retries || 1; const tryExecNTimes = require('./try-n-times'); const path = require('path'); // Flaky tests ignored on Circle CI. They still run internally at fb. const ignoredTests = [ 'ReactScrollViewTestCase', 'ReactHorizontalScrollViewTestCase' ]; // ReactAndroid/src/androidTest/java/com/facebook/react/tests/ReactHorizontalScrollViewTestCase.java const testClasses = ls(`${argv.path}/*.java`) .map(javaFile => { // ReactHorizontalScrollViewTestCase return path.basename(javaFile, '.java'); }).filter(className => { return ignoredTests.indexOf(className) === -1; }).map(className => { // com.facebook.react.tests.ReactHorizontalScrollViewTestCase return argv.package + '.' + className; }); let exitCode = 0; testClasses.forEach((testClass) => { if (tryExecNTimes( () => { echo(`Starting ${testClass}`); // any faster means Circle CI crashes exec('sleep 10s'); return exec(`./scripts/run-instrumentation-tests-via-adb-shell.sh ${argv.package} ${testClass}`).code; }, numberOfRetries)) { echo(`${testClass} failed ${numberOfRetries} times`); exitCode = 1; } }); exit(exitCode);
JavaScript
0.000001
@@ -905,54 +905,8 @@ );%0A%0A -console.log(echo, exec, exit, ls);%0A%0Aexit(0);%0A%0A cons
6491dd85d884839da5b3d72fd036d20c28b8d1c4
remove unused crap
import-infobot.js
import-infobot.js
var storageDir = ''; //set this to the localStorage directory used by your bot var dbFile = ''; //set this to the db you wish to use for your new bot. You may want to create it first by simply running the bot with the new module. if (typeof localStorage === "undefined" || localStorage === null) { var LocalStorage = require('node-localstorage').LocalStorage; } var ueberDB = require('ueberDB'); var ubr = new ueberDB.database("sqlite", {filename:dbFile||'db.db'}, {writeInterval:1000}); var fs = require('fs'); var output = {}; var db = new LocalStorage(storageDir||'.'); var keys = db.keys; console.log("Starting import"); process.stdout.write("Exporting: "); ubr.init(function(err){ if(err) { console.log(err); process.exit(); } else for (var key in keys) { process.stdout.write(keys[key]+" "); var factoid = JSON.parse(db.getItem(keys[key])); factoid.definition = [factoid.definition]; ubr.set(keys[key],factoid); db.removeItem(keys[key]); } ubr.close(function(){console.log("\nDone!"); process.exit()}); });
JavaScript
0.000002
@@ -497,49 +497,8 @@ %7D);%0A -var fs = require('fs');%0Avar output = %7B%7D;%0A var
65536ca5da272971b49be51116a9963e9fb3d586
Fix trainingCtrl
project/src/js/ui/training/trainingCtrl.js
project/src/js/ui/training/trainingCtrl.js
import last from 'lodash/array/last'; import chessground from 'chessground'; import { partialf } from '../../utils'; import data from './data'; import chess from './chess'; import puzzle from './puzzle'; import sound from '../../sound'; import actions from './actions'; import settings from '../../settings'; import menu from './menu'; import * as xhr from './xhr'; import m from 'mithril'; import helper from '../helper'; import socket from '../../socket'; export default function ctrl() { helper.analyticsTrackView('Puzzle'); socket.createDefault(); this.data = null; this.menu = menu.controller(this); var attempt = function(winFlag) { xhr.attempt(this.data.puzzle.id, this.data.startedAt, winFlag) .then(function(cfg) { cfg.progress = this.data.progress; this.reload(cfg); }.bind(this)); }.bind(this); var userMove = function(orig, dest) { var res = puzzle.tryMove(this.data, [orig, dest]); var newProgress = res[0]; var newLines = res[1]; var lastMove = last(newProgress); var promotion = lastMove ? lastMove[4] : undefined; m.startComputation(); switch (newLines) { case 'retry': setTimeout(partialf(this.revert, this.data.puzzle.id), 500); this.data.comment = 'retry'; break; case 'fail': setTimeout(function() { if (this.data.mode === 'play') { this.chessground.stop(); attempt(false); } else this.revert(this.data.puzzle.id); }.bind(this), 500); this.data.comment = 'fail'; break; default: this.userFinalizeMove([orig, dest, promotion], newProgress); if (newLines === 'win') { setTimeout(function() { this.chessground.stop(); attempt(true); }.bind(this), 300); } else setTimeout(partialf(this.playOpponentNextMove, this.data.puzzle.id), 1000); break; } m.endComputation(); // give feedback ASAP, don't wait for delayed action }.bind(this); var onMove = function(orig, dest, captured) { if (captured) sound.capture(); else sound.move(); }; this.revert = function(id) { if (id !== this.data.puzzle.id) return; this.chessground.set({ fen: this.data.chess.fen(), lastMove: chess.lastMove(this.data.chess), turnColor: this.data.puzzle.color, check: null, movable: { dests: this.data.chess.dests() } }); m.redraw(); if (this.data.chess.in_check()) this.chessground.setCheck(); }.bind(this); this.userFinalizeMove = function(move, newProgress) { chess.move(this.data.chess, move); this.data.comment = 'great'; this.data.progress = newProgress; this.chessground.set({ fen: this.data.chess.fen(), lastMove: move, turnColor: this.data.puzzle.opponentColor, check: null }); if (this.data.chess.in_check()) this.chessground.setCheck(); }.bind(this); this.playOpponentMove = function(move) { onMove(move[0], move[1], this.chessground.data.pieces[move[1]]); m.startComputation(); chess.move(this.data.chess, move); this.chessground.set({ fen: this.data.chess.fen(), lastMove: move, movable: { dests: this.data.chess.dests() }, turnColor: this.data.puzzle.color, check: null }); if (this.data.chess.in_check()) this.chessground.setCheck(); setTimeout(this.chessground.playPremove, this.chessground.data.animation.duration); m.endComputation(); }.bind(this); this.playOpponentNextMove = function(id) { if (id !== this.data.puzzle.id) return; var move = puzzle.getOpponentNextMove(this.data); this.playOpponentMove(puzzle.str2move(move)); this.data.progress.push(move); if (puzzle.getCurrentLines(this.data) == 'win') setTimeout(() => attempt(true), 300); }.bind(this); this.playInitialMove = function(id) { if (id !== this.data.puzzle.id) return; this.playOpponentMove(this.data.puzzle.initialMove); this.data.startedAt = new Date(); }.bind(this); this.giveUp = function() { attempt(false); }.bind(this); this.jump = function(to) { const history = this.data.replay.history; const step = this.data.replay.step; if (!(step !== to && to >= 0 && to < history.length)) return; chessground.anim(puzzle.jump, this.chessground.data)(this.data, to); }.bind(this); this.jumpPrev = function() { this.jump(this.data.replay.step - 1); }.bind(this); this.jumpNext = function() { this.jump(this.data.replay.step + 1); }.bind(this); this.initiate = function() { if (this.data.mode !== 'view') setTimeout(this.playInitialMove.bind(this, this.data.puzzle.id), 1000); }.bind(this); this.reload = function(cfg) { this.data = data(cfg); chessground.board.reset(this.chessground.data); chessground.anim(puzzle.reload, this.chessground.data)(this.data, cfg); this.initiate(); }.bind(this); this.init = function(cfg) { this.data = data(cfg); if (this.actions) this.actions.close(); else this.actions = new actions.controller(this); var chessgroundConf = { fen: this.data.puzzle.fen, orientation: this.data.puzzle.color, turnColor: this.data.puzzle.opponentColor, movable: { free: false, color: this.data.mode !== 'view' ? this.data.puzzle.color : null, showDests: settings.general.pieceDestinations(), events: { after: userMove } }, events: { move: onMove }, animation: { enabled: true, duration: 300 }, premovable: { enabled: true }, draggable: { distance: 3, squareTarget: true } }; if (this.chessground) this.chessground.set(chessgroundConf); else this.chessground = new chessground.controller(chessgroundConf); this.initiate(); }.bind(this); this.newPuzzle = function() { xhr.newPuzzle().then(this.init); }.bind(this); this.retry = function() { xhr.retry(this.data.puzzle.id).then(this.reload); }.bind(this); this.setDifficulty = function(id) { xhr.setDifficulty(id); }; this.newPuzzle(); window.plugins.insomnia.keepAwake(); this.onunload = function() { socket.destroy(); window.plugins.insomnia.allowSleepAgain(); }; }
JavaScript
0.000001
@@ -234,41 +234,8 @@ d';%0A -import actions from './actions';%0A impo @@ -5014,106 +5014,8 @@ g);%0A - if (this.actions) this.actions.close();%0A else this.actions = new actions.controller(this);%0A
9c55162ba7456ef7282c27ac1b6cdf785178727d
Add input search action filter directive unit tests
dataprep-webapp/src/components/suggestions-stats/actions-suggestions/actions-suggestions-directive.spec.js
dataprep-webapp/src/components/suggestions-stats/actions-suggestions/actions-suggestions-directive.spec.js
describe('Actions suggestions-stats directive', function() { 'use strict'; var scope, element, createElement; beforeEach(module('data-prep.actions-suggestions')); beforeEach(module('htmlTemplates')); beforeEach(module('pascalprecht.translate', function ($translateProvider) { $translateProvider.translations('en', { 'COLON': ': ' }); $translateProvider.preferredLanguage('en'); })); beforeEach(inject(function($rootScope, $compile) { scope = $rootScope.$new(); createElement = function() { scope = $rootScope.$new(); element = angular.element('<actions-suggestions></actions-suggestions>'); $compile(element)(scope); scope.$digest(); }; })); afterEach(function() { scope.$destroy(); element.remove(); }); it('should set "Action" in title when no column is selected', inject(function(SuggestionService) { //given SuggestionService.currentColumn = null; //when createElement(); //then expect(element.find('.title').text().trim()).toBe('Actions'); })); it('should set column name in title', inject(function(SuggestionService) { //given SuggestionService.currentColumn = {name: 'Col 1'}; //when createElement(); //then expect(element.find('.title').text().trim()).toBe('Actions: Col 1'); })); });
JavaScript
0
@@ -112,17 +112,56 @@ lement;%0A + var body = angular.element('body'); %0A - befo @@ -569,25 +569,24 @@ ope.$new();%0A -%0A crea @@ -731,24 +731,58 @@ estions%3E');%0A + body.append(element);%0A @@ -1533,24 +1533,24 @@ s: Col 1');%0A - %7D));%0A%7D); @@ -1546,12 +1546,1361 @@ %7D));%0A +%0A it('should display all suggested actions', inject(function(ColumnSuggestionService) %7B%0A //when%0A createElement();%0A ColumnSuggestionService.transformations = %5B%0A %7B%0A 'name': 'ceil_value',%0A 'label': 'Ceil value'%0A %7D,%0A %7B%0A 'name': 'floor_value',%0A 'label': 'Floor value'%0A %7D,%0A %7B%0A 'name': 'round_value',%0A 'label': 'Round value'%0A %7D%0A %5D;%0A scope.$digest();%0A%0A //then%0A expect(element.find('.accordion').length).toBe(3);%0A %7D));%0A%0A it('should display searched suggested actions', inject(function(ColumnSuggestionService) %7B%0A //when%0A createElement();%0A ColumnSuggestionService.transformations = %5B%0A %7B%0A 'name': 'ceil_value',%0A 'label': 'Ceil value'%0A %7D,%0A %7B%0A 'name': 'floor_value',%0A 'label': 'Floor value'%0A %7D,%0A %7B%0A 'name': 'round_value',%0A 'label': 'Round value'%0A %7D%0A %5D;%0A scope.$digest();%0A%0A element.controller('actionsSuggestions').searchActionString ='oo';%0A scope.$digest();%0A%0A //then%0A expect(element.find('.accordion').length).toBe(1);%0A %7D));%0A%0A %7D);%0A
bec773ab1f4003d5b2ed20a749835eb645990607
Remove text from notice
public/js/experiment.js
public/js/experiment.js
/** * Experiment view blocks for jsSART */ (function(){ var experiment = []; var participant_id = getParticipantId(); var conditions = generateConditions(); // prospective survey notice and questions var prospective_survey_text = "<p>Before we begin, we would like to know what you <strong>expect to experience</strong> on this <strong>attention task</strong>. The <strong>attention task</strong> that will follow is identical to the practice trial you have just completed, although it will be longer.</p>"; var prospective_survey_notice = createTextBlock(prospective_survey_text); var prospective_survey = generateMultiChoiceSurvey( jsSART.QUESTIONS.ANTICIPATION, true); // randomize order var realtime_notice = createTextBlock("<p>Throughout the attention task, you will be asked at various time points to report how you feel <strong>at that exact moment</strong>.</p><p>Please report how you feel as accurately as possible, even if your rating is the same as (or higher or lower than) your last rating — we are interested in the accurate reporting of how you feel during the attention task moment by moment.</p>"); experiment.push( prospective_survey_notice, prospective_survey, realtime_notice ); // pre-experiment notice var experiment_notice_text = "<p>This was an overview of the task, and you have completed the practice trials.</p> <p>The <strong>attention task</strong> that will follow is identical to the practice trial you have just completed.</p> <p>Remember, if you get lost, just jump back in because we can’t stop the experiment once it has started. At several points in the task you will pause briefly to report your experience and then continue with the task.</p> <p>The <strong>attention task</strong> will now follow."; var experiment_notice = createTextBlock(experiment_notice_text); experiment.push(experiment_notice); // generate the experiment blocks var formatted_block_stimuli = generateSartBlockStimuli(conditions); experiment = experiment.concat(formatted_block_stimuli); // post-experiment valance and arousal questions (randomized order) var valence_and_arousal = generateMultiChoiceSurvey( jsSART.QUESTIONS.AROUSAL, true ); experiment.push(valence_and_arousal); // end notice var experiment_end_notice = createTextBlock( "<p><strong>You have completed the attention task.</strong></p>" ); experiment.push(experiment_end_notice); // add generated experiment settings to saved data jsPsych.data.addProperties({ num_trials: conditions.num_trials, trials_per_block: conditions.trials_per_block, participant_id: participant_id, }); jsPsych.init({ display_element: $('#jspsych-target'), timeline: experiment, on_finish: function() { var redirect_url = 'follow_up?pid=' + participant_id; postDataToDb(jsPsych.data.getData(), participant_id, redirect_url); } }); })();
JavaScript
0
@@ -985,34 +985,8 @@ e as - (or higher or lower than) you
510dcd14edabea589095a0e3101d2b8a37514bb8
fix untranslated validation message on course grader LEARNER-2450
cms/static/js/models/settings/course_grader.js
cms/static/js/models/settings/course_grader.js
define(['backbone', 'underscore', 'gettext'], function(Backbone, _, gettext) { var CourseGrader = Backbone.Model.extend({ defaults: { 'type': '', // must be unique w/in collection (ie. w/in course) 'min_count': 1, 'drop_count': 0, 'short_label': '', // what to use in place of type if space is an issue 'weight': 0 // int 0..100 }, parse: function(attrs) { // round off values while converting them to integer if (attrs['weight']) { attrs.weight = Math.round(attrs.weight); } if (attrs['min_count']) { attrs.min_count = Math.round(attrs.min_count); } if (attrs['drop_count']) { attrs.drop_count = Math.round(attrs.drop_count); } return attrs; }, validate: function(attrs) { var errors = {}; if (_.has(attrs, 'type')) { if (_.isEmpty(attrs['type'])) { errors.type = 'The assignment type must have a name.'; } else { // FIXME somehow this.collection is unbound sometimes. I can't track down when var existing = this.collection && this.collection.some(function(other) { return (other.cid != this.cid) && (other.get('type') == attrs['type']); }, this); if (existing) { errors.type = gettext("There's already another assignment type with this name."); } } } if (_.has(attrs, 'weight')) { var intWeight = Math.round(attrs.weight); // see if this ensures value saved is int if (!isFinite(intWeight) || /\D+/.test(attrs.weight) || intWeight < 0 || intWeight > 100) { errors.weight = gettext('Please enter an integer between 0 and 100.'); } else { attrs.weight = intWeight; if (this.collection && attrs.weight > 0) { // FIXME b/c saves don't update the models if validation fails, we should // either revert the field value to the one in the model and make them make room // or figure out a holistic way to balance the vals across the whole // if ((this.collection.sumWeights() + attrs.weight - this.get('weight')) > 100) // errors.weight = "The weights cannot add to more than 100."; } } } if (_.has(attrs, 'min_count')) { var intMinCount = Math.round(attrs.min_count); if (!isFinite(intMinCount) || /\D+/.test(attrs.min_count) || intMinCount < 1) { errors.min_count = gettext('Please enter an integer greater than 0.'); } else attrs.min_count = intMinCount; } if (_.has(attrs, 'drop_count')) { var dropCount = attrs.drop_count; var intDropCount = Math.round(dropCount); if (!isFinite(intDropCount) || /\D+/.test(dropCount) || (_.isString(dropCount) && _.isEmpty(dropCount.trim())) || intDropCount < 0) { errors.drop_count = gettext('Please enter non-negative integer.'); } else attrs.drop_count = intDropCount; } if (_.has(attrs, 'min_count') && _.has(attrs, 'drop_count') && !_.has(errors, 'min_count') && !_.has(errors, 'drop_count') && attrs.drop_count > attrs.min_count) { var template = _.template( gettext('Cannot drop more <%= types %> assignments than are assigned.') ); errors.drop_count = template({types: attrs.type}); } if (!_.isEmpty(errors)) return errors; } }); return CourseGrader; }); // end define()
JavaScript
0.000174
@@ -1065,16 +1065,24 @@ .type = +gettext( 'The ass @@ -1112,16 +1112,17 @@ a name.' +) ;%0A
4f7f89c74ff34678d502bd0756f2b3b654652618
Fix messageclient format for incoming data
lib/system/audio.js
lib/system/audio.js
'use strict'; var sprintf = require('sprintf').sprintf, utils = require('radiodan-client').utils, systemExec = utils.promise.denodeify(require('child_process').exec), validateVolume = require('../validators/actions/player/volume'), boundVolume = require('../utils/bound-volume'), volumeCommands = function() { var alsaDevice = "$(amixer | grep -o -m 1 \"'[^']*'\" | tr -d \"'\")"; return { alsa: { set: "amixer -M set "+alsaDevice+" %d%% unmute | grep -o -m 1 '[[:digit:]]*%%' | tr -d '%%'", get: "amixer -M sget "+alsaDevice+" | grep -o -m 1 '[[:digit:]]*%' | tr -d '%'" }, coreaudio: { set: "osascript -e 'set volume output volume %d'; osascript -e 'output volume of (get volume settings)'", get: "osascript -e 'output volume of (get volume settings)'" } }; }(); module.exports = {create: create}; function create(id) { var serviceType = 'audio', serviceInstance = id, eventTopicKey = 'event.'+serviceType+'.'+serviceInstance+'.volume'; return { listen: listen }; function listen(messagingClient, platform, exec, logger) { var audioType, commands, worker, publisher; platform = platform || process.platform; exec = exec || systemExec; logger = logger || utils.logger('system-audio'); audioType = audioTypeForPlatform(platform); if (audioType === false) { logger.warn("Cannot for "+platform); return false; } else { logger.debug('audio type', audioType); } commands = volumeCommands[audioType]; publisher = messagingClient.Publisher.create(); worker = messagingClient.Worker.create('audio'); worker.addService({ serviceType: serviceType, serviceInstances: [serviceInstance] }); worker.ready(); worker.events.on('request', function(req){ var sender = req.sender, correlationId = req.correlationId; logger.debug('req', req); switch(req.command) { case "volume": return respondToVolume(); case "status": return respondToStatus(); default: logger.error("Unknown action", action); } function respondToVolume() { return validateVolume(req.data) .then(setVolume) .then( respondToCommand(sender, correlationId), respondToCommand(sender, correlationId, true) ) .then(emitVolume) .then(null, utils.failedPromiseHandler(logger)); } function respondToStatus() { return getVolume().then( respondToCommand(sender, correlationId), respondToCommand(sender, correlationId, true) ).then(null, utils.failedPromiseHandler(logger)); } }); function audioTypeForPlatform(platform) { switch(platform) { case 'darwin': return 'coreaudio'; case 'freebsd': case 'linux': case 'sunos': //assume ALSA return 'alsa'; default: logger.error('No known volume control method for '+platform); return false; } } function getVolume() { logger.debug(commands.get); return exec(commands.get); } function setVolume(newLevel) { if(newLevel.diff) { return getVolume() .then(function(currentLevel) { var vol = boundVolume( parseInt(currentLevel, 10), newLevel.diff ); return utils.promise.resolve(vol); }) .then(setVolumeExec); } else { return setVolumeExec(newLevel.value); } } function setVolumeExec(volume) { var cmd = sprintf(commands.set, parseInt(volume, 10)); logger.debug(cmd); return exec(cmd); } function respondToCommand(sender, correlationId, error) { if(typeof sender === 'undefined') { var replyErr = "Cannot reply, sender undefined"; logger.warn(replyErr); return utils.promise.reject(replyErr); } error = (error === true); return function (response) { var msg = { error: error }; if(error) { msg.error = response.toString(); } else { msg.response = {volume: parseInt(response, 10)}; } logger.debug("replying", sender, msg); worker.respond(sender, correlationId, msg); if(error) { return utils.promise.reject(response.toString()); } else { return response; } }; } function emitVolume(vol) { var msg = {value: parseInt(vol, 10)}; publisher.publish(eventTopicKey, msg); return utils.promise.resolve(); } } }
JavaScript
0.000008
@@ -2333,12 +2333,14 @@ req. -data +params )%0A
ca1353cb6e9fba9167a8f38d5b18225de4032dd3
Include song duration in library response
server/api/routes/library.js
server/api/routes/library.js
import KoaRouter from 'koa-router' import Providers from '../provider/index' let router = KoaRouter() let debug = require('debug') let error = debug('app:library:error') let isScanning // get all artists and songs router.get('/api/library', async (ctx, next) => { const log = debug('app:library:get') let res = { artistIds: [], // results songIds: [], // results artists: {}, // entities songs: {}, // entities } // get artists let artists = await ctx.db.all('SELECT artistId, name FROM artists ORDER BY name') artists.forEach(function(row){ res.artistIds.push(row.artistId) res.artists[row.artistId] = row res.artists[row.artistId].songIds = [] }) // assign songs to artists let songs = await ctx.db.all('SELECT artistId, plays, provider, title, songId FROM songs ORDER BY title') songs.forEach(function(row){ if (typeof res.artists[row.artistId] === 'undefined') { log('Warning: Invalid song (songId: %s, artistId: %s)', row.songId, row.artistId) return } res.songIds.push(row.songId) res.songs[row.songId] = row res.artists[row.artistId].songIds.push(row.songId) }) ctx.body = { artists: {result: res.artistIds, entities: res.artists}, songs: {result: res.songIds, entities: res.songs} } }) // scan for new songs router.get('/api/library/scan', async (ctx, next) => { const log = debug('app:library:scan') if (isScanning) { log('Scan already in progress; skipping request') return } isScanning = true // get provider configs let cfg = {} let rows = await ctx.db.all('SELECT * FROM config WHERE domain LIKE "%.provider"') rows.forEach(function(row){ const provider = row.domain.substr(0, row.domain.lastIndexOf('.provider')) cfg[provider] = JSON.parse(row.data) }) for (let provider in cfg) { if (!cfg[provider].enabled) { log('Provider "%s" not enabled; skipping', provider) continue } if (!Providers[provider]) { error('Provider "%s" is enabled but not loaded', provider) continue } // call each provider's scan method, passing config object and // koa context (from which we can access the db, and possibly // send progress updates down the wire?) log('Provider "%s" starting scan', provider) await Providers[provider].scan(ctx, cfg[provider]) log('Provider "%s" finished scan', provider) } // delete artists having no songs let res = await ctx.db.run('DELETE FROM artists WHERE artistId IN (SELECT artistId FROM artists LEFT JOIN songs USING(artistId) WHERE songs.artistId IS NULL)') log('cleanup: removed %s artists with no songs', res.changes) isScanning = false log('Library scan complete') }) export default router
JavaScript
0
@@ -757,32 +757,40 @@ x.db.all('SELECT + songId, artistId, plays @@ -784,16 +784,33 @@ tistId, +title, duration, plays, p @@ -820,23 +820,8 @@ ider -, title, songId FRO
92aaf3812d45313c76c4531be4cfc0b959e116e1
Fix bug in example
examples/botkit/bot.js
examples/botkit/bot.js
/** * Cisco Spark WebSocket example using BotKit */ var accessToken = process.env.SPARK_TOKEN; if (!accessToken) { console.log("No Cisco Spark access token found in env variable SPARK_TOKEN"); process.exit(2); } var PORT = process.env.PORT || 3000; // Spark Websocket Intialization var SparkWebSocket = require('ciscospark-websocket-events'); sparkwebsocket = new SparkWebSocket(accessToken); sparkwebsocket.connect(function (err, res) { if (!err) { sparkwebsocket.setWebHookURL("http://localhost:" + PORT + "/ciscospark/receive"); } else { console.log("Error starting up websocket: " + err); } }) //////// Bot Kit ////// var Botkit = require('botkit'); var controller = Botkit.sparkbot({ debug: true, log: true, public_address: "https://localhost", ciscospark_access_token: accessToken }); var bot = controller.spawn({ }); controller.setupWebserver(PORT, function (err, webserver) { //setup incoming webhook handler webserver.post('/ciscospark/receive', function (req, res) { controller.handleWebhookPayload(req, res, bot); }); }); // // Bot custom logic // controller.hears('hello', 'direct_message,direct_mention', function (bot, message) { bot.reply(message, 'Hi'); }); controller.on('direct_mention', function (bot, message) { bot.reply(message, 'You mentioned me and said, "' + message.text + '"'); }); controller.on('direct_message', function (bot, message) { bot.reply(message, 'I got your private message. You said, "' + message.text + '"'); });
JavaScript
0.000001
@@ -1042,24 +1042,52 @@ req, res) %7B%0A + res.sendStatus(200)%0A cont @@ -1561,28 +1561,29 @@ ' + message.text + '%22');%0A%7D); +%0A
97c94d483215d12045cc81911da38ff026760010
allow special symbols ?*" in search again (publicly documented lucene symbols)
collections-online/app/scripts-browserify/search/get-parameters.js
collections-online/app/scripts-browserify/search/get-parameters.js
const config = require('collections-online/shared/config'); /** * This module generates search parameters that will lead to a specific * filtering and sorting being activated, based on the querystring. * This is the inverse of generate-querystring. */ var querystring = require('querystring'); const DEFAULT_SORTING = require('./default-sorting'); module.exports = function() { var urlParams = window.location.search.substring(1); var parameters = querystring.parse(urlParams); // Extract the sorting query parameter var sorting = parameters.sort || DEFAULT_SORTING; delete parameters.sort; var filters = {}; // Holds the centerpoint and zoom-level of the map. Empty if we're not viewing // the map. var map = ''; // Same, but for our Historisk Atlas map var smap =''; // The rest are filters Object.keys(parameters).forEach(function(field) { // TODO: Look for the skipSplit config parameter var filter = config.search.filters[field]; if(filter) { var value = parameters[field]; if(!filter.skipSplit) { value = value.split(','); } // Escape all Lucene special characters, to avoid syntax errors in // Elastic Search query, c.f. // https://lucene.apache.org/core/3_0_3/queryparsersyntax.html#Escaping%20Special%20Characters [ '\\+', '\\-', '\&\&', '\\|\\|', '!', '\\(', '\\)', '\\{', '\\}', '\\[', '\\]', '\\^', '"', '~', '\\*', '\\?', '\\:', '\\\\' ].forEach((luceneSpecialCharacter) => { const characterGlobalPattern = new RegExp(luceneSpecialCharacter, 'g'); if(Array.isArray(value)) { value = value.map((part) => part.replace(characterGlobalPattern, ' ')); } else { value = value.replace(characterGlobalPattern, ' '); } }); filters[field] = value; } else if (field === 'map') { map = parameters[field]; } else if (field === 'smap') { smap = parameters[field]; } else { console.warn('Skipping an unexpected search parameter:', field); } }); return { filters: filters, sorting: sorting, map: map, smap: smap }; };
JavaScript
0
@@ -1310,16 +1310,70 @@ racters%0A + // BUT with the note that we allow ?, %22, and *.%0A %5B%0A @@ -1479,28 +1479,9 @@ ', ' -%22', '~', '%5C%5C*', '%5C%5C? +~ ', '
9df62e9025a4fbf927d406909e830f930280ba89
Fix RDPBuilder
src/saga/rdp-builder.js
src/saga/rdp-builder.js
const BASE_CONFIG_FILE = 'session bpp:i:32\n' + 'winposstr:s:0,3,0,0,800,600\n' + 'compression:i:1\n' + 'keyboardhook:i:2\n' + 'audiocapturemode:i:0\n' + 'videoplaybackmode:i:1\n' + 'connection type:i:2\n' + 'displayconnectionbar:i:1\n' + 'disable wallpaper:i:1\n' + 'allow font smoothing:i:0\n' + 'allow desktop composition:i:0\n' + 'disable full window drag:i:1\n' + 'disable menu anims:i:1\n' + 'disable themes:i:0\n' + 'disable cursor setting:i:0\n' + 'bitmapcachepersistenable:i:1\n' + 'audiomode:i:0\n' + 'redirectcomports:i:0\n' + 'redirectposdevices:i:0\n' + 'redirectdirectx:i:1\n' + 'autoreconnection enabled:i:1\n' + 'prompt for credentials:i:1\n' + 'negotiate security layer:i:1\n' + 'remoteapplicationmode:i:0\n' + 'alternate shell:s:\n' + 'shell working directory:s:\n' + 'gatewayhostname:s:\n' + 'gatewayusagemethod:i:4\n' + 'gatewaycredentialssource:i:4\n' + 'gatewayprofileusagemethod:i:0\n' + 'promptcredentialonce:i:1\n' + 'use redirection server name:i:0' export default class RDPBuilder { constructor ({ vmName, username, domain, fqdn }) { this.address = fqdn || vmName this.guestID = '' this.fullScreen = true this.fullScreenTitle this.width = 640 this.height = 480 this.authenticationLevel = 2 this.useLocalDrives this.redirectPrinters = false this.redirectClipboard = true this.redirectSmartCards = false this.username = username this.domain = domain } getUsername () { const atPosition = this.username.indexOf('@') if (atPosition !== -1) { this.username = this.username.slice(0, atPosition) } return `${this.username}@${this.domain}` } getFullScreen () { return this.fullScreen } setFullScreen (fullScreen) { this.fullScreen = fullScreen } getWidth () { return this.width } setWidth (width) { this.width = width } getHeight () { return this.height } setHeight (height) { this.height = height } getAuthenticationLevel () { return this.authenticationLevel } setAuthenticationLevel (authenticationLevel) { this.authenticationLevel = authenticationLevel } getRedirectPrinters () { return this.redirectPrinters } setRedirectPrinters (redirectPrinters) { this.redirectPrinters = redirectPrinters } getRedirectClipboard () { return this.redirectClipboard } setRedirectClipboard (redirectClipboard) { this.redirectClipboard = redirectClipboard } getRedirectSmartCards () { return this.redirectSmartCards } setRedirectSmartCards (redirectSmartCards) { this.redirectSmartCards = redirectSmartCards } getAddress () { return this.address } setAddress (value) { this.address = value } getGuestID () { return this.guestID } setGuestID (value) { this.guestID = value } getUseLocalDrives () { return this.useLocalDrives } setUseLocalDrives (value) { this.useLocalDrives = value } booleanToInt (b) { if (b == null || b === false) { return 0 } return 1 } getScreenMode () { if (this.getFullScreen()) { return 2 } return 1 } getredirectDrivesLines () { if (this.getUseLocalDrives()) { return '\ndrivestoredirect:s:*' } else { return '\ndrivestoredirect:s:' } } getEnableCredSspSupport () { return true } buildRDP () { let result = BASE_CONFIG_FILE result += `\nscreen mode id:i:${this.getScreenMode()}` + `\ndesktopwidth:i:${this.getWidth()}` + `\ndesktopheight:i:${this.getHeight()}` + `\nauthentication level:i:${this.getAuthenticationLevel()}` + `\nfull address:s:${this.getAddress()}` + `\nenablecredsspsupport:i:${this.booleanToInt(this.getEnableCredSspSupport())}` + `${this.getredirectDrivesLines()}` + `\nredirectprinters:i:${this.booleanToInt(this.getRedirectPrinters())}` + `\nredirectsmartcards:i:${this.booleanToInt(this.getRedirectSmartCards())}` + `\nredirectclipboard:i:${this.booleanToInt(this.getRedirectClipboard())}` + `\nusername:s:${this.getUsername()}` return result } }
JavaScript
0.000001
@@ -1950,33 +1950,8 @@ rue%0A - this.fullScreenTitle%0A @@ -2045,16 +2045,24 @@ alDrives + = false %0A thi
23a33a5ece7e888d01bdd19e3dcf0e4bf12e5470
Add error snackbar to QuestionCreateForm
frontend/src/components/Question/CreateForm.js
frontend/src/components/Question/CreateForm.js
import React from 'react'; import PropTypes from 'prop-types'; import CreateConnector from './CreateConnector'; import QuestionForm from './Form'; import { formValuesToRequest } from './transforms'; import FAButton from '../FAButton'; import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import Router from 'next/router'; import CancelDialog from './CancelDialog'; import { withSnackbar } from 'notistack'; const createHandleSubmit = (createQuestion, enqueueSnackbar) => (values, addHandlers) => { console.log('VALUES: '); console.log(values); // This is where `addHandlers` comes in handy as the form controls its state addHandlers( createQuestion({ variables: { input: formValuesToRequest(values) }, }) .then(resp => { console.log('addHandlers OK!'); console.log('Response: '); console.log(resp); enqueueSnackbar('Questão salva com sucesso', { variant: 'success', autoHideDuration: 6000, }); }) .catch(error => { // The component is and should not be aware of this being a GraphQL error. console.log('addHandlers ERROR:'); console.log(error); // this.props.showApiErrorNotification(error); }), ); }; const questionInitialValues = { type: 'OPEN_ENDED', wording: '', imageUrl: '', secondaryWording: '', // These empty choices are here so that Formik can render the input fields choices: [{ text: '' }, { text: '' }, { text: '' }, { text: '' }, { text: '' }], }; class QuestionCreateForm extends React.Component { state = { warningDialogOpen: false, }; handleClickOpen = () => { this.setState({ warningDialogOpen: true }); }; handleClose = () => { this.setState({ warningDialogOpen: false }); }; createBackToListHandler = isDirty => () => { // If the user entered any input, show a warning dialog to confirm // before discarding the draft. if (isDirty) { this.setState({ warningDialogOpen: true }); return; } Router.push('/admin/questoes'); }; render() { const { enqueueSnackbar } = this.props; const { warningDialogOpen } = this.state; return ( <CreateConnector> {({ createQuestion }) => ( <QuestionForm initialValues={questionInitialValues} onSubmit={createHandleSubmit(createQuestion, enqueueSnackbar)} > {({ form, isDirty }) => ( <React.Fragment> <FAButton onClick={this.createBackToListHandler(isDirty)} aria-label="Voltar pra lista de questões" > <ArrowBackIcon /> </FAButton> <CancelDialog open={warningDialogOpen} onCancel={this.handleClose} onContinue={() => { Router.push('/admin/questoes'); }} /> {form} </React.Fragment> )} </QuestionForm> )} </CreateConnector> ); } } QuestionCreateForm.propTypes = { enqueueSnackbar: PropTypes.func.isRequired, }; export default withSnackbar(QuestionCreateForm);
JavaScript
0
@@ -1109,70 +1109,99 @@ -console.log('addHandlers ERROR:');%0A console.log( +enqueueSnackbar(%60Erro ao salvar quest%C3%A3o: %22$%7Berror.message%7D%22%60, %7B%0A variant: ' error -); +', %0A @@ -1209,52 +1209,43 @@ -// this.props.showApiErrorNotification(error + autoHideDuration: 6000,%0A %7D );%0A
0c6787d84e5c8b9275b55dc48f1e1242c937128f
use angularString instead of angular.String
src/JSON.js
src/JSON.js
'use strict'; var array = [].constructor; /** * @workInProgress * @ngdoc function * @name angular.toJson * @function * * @description * Serializes the input into a JSON formated string. * * @param {Object|Array|Date|string|number} obj Input to jsonify. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { var buf = []; toJsonArray(buf, obj, pretty ? "\n " : null, []); return buf.join(''); } /** * @workInProgress * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a string in the JSON format. * * @param {string} json JSON string to deserialize. * @param {boolean} [useNative=false] Use native JSON parser if available * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json, useNative) { if (!isString(json)) return json; var obj; try { if (useNative && window.JSON && window.JSON.parse) { obj = JSON.parse(json); return transformDates(obj); } return parser(json, true).primary()(); } catch (e) { error("fromJson error: ", json, e); throw e; } // TODO make forEach optionally recursive and remove this function function transformDates(obj) { if (isString(obj) && obj.length === DATE_ISOSTRING_LN) { return angularString.toDate(obj); } else if (isArray(obj) || isObject(obj)) { forEach(obj, function(val, name) { obj[name] = transformDates(val); }); } return obj; } } angular.toJson = toJson; angular.fromJson = fromJson; function toJsonArray(buf, obj, pretty, stack) { if (isObject(obj)) { if (obj === window) { buf.push('WINDOW'); return; } if (obj === document) { buf.push('DOCUMENT'); return; } if (includes(stack, obj)) { buf.push('RECURSION'); return; } stack.push(obj); } if (obj === null) { buf.push($null); } else if (obj instanceof RegExp) { buf.push(angular.String.quoteUnicode(obj.toString())); } else if (isFunction(obj)) { return; } else if (isBoolean(obj)) { buf.push('' + obj); } else if (isNumber(obj)) { if (isNaN(obj)) { buf.push($null); } else { buf.push('' + obj); } } else if (isString(obj)) { return buf.push(angular.String.quoteUnicode(obj)); } else if (isObject(obj)) { if (isArray(obj)) { buf.push("["); var len = obj.length; var sep = false; for(var i=0; i<len; i++) { var item = obj[i]; if (sep) buf.push(","); if (!(item instanceof RegExp) && (isFunction(item) || isUndefined(item))) { buf.push($null); } else { toJsonArray(buf, item, pretty, stack); } sep = true; } buf.push("]"); } else if (isElement(obj)) { // TODO(misko): maybe in dev mode have a better error reporting? buf.push('DOM_ELEMENT'); } else if (isDate(obj)) { buf.push(angular.String.quoteUnicode(angular.Date.toString(obj))); } else { buf.push("{"); if (pretty) buf.push(pretty); var comma = false; var childPretty = pretty ? pretty + " " : false; var keys = []; for(var k in obj) { if (obj.hasOwnProperty(k) && obj[k] !== undefined) { keys.push(k); } } keys.sort(); for ( var keyIndex = 0; keyIndex < keys.length; keyIndex++) { var key = keys[keyIndex]; var value = obj[key]; if (!isFunction(value)) { if (comma) { buf.push(","); if (pretty) buf.push(pretty); } buf.push(angular.String.quote(key)); buf.push(":"); toJsonArray(buf, value, childPretty, stack); comma = true; } } buf.push("}"); } } if (isObject(obj)) { stack.pop(); } }
JavaScript
0.000207
@@ -2073,33 +2073,32 @@ buf.push(angular -. String.quoteUnic @@ -2115,24 +2115,24 @@ String()));%0A + %7D else if @@ -2387,33 +2387,32 @@ buf.push(angular -. String.quoteUnic @@ -3055,33 +3055,32 @@ buf.push(angular -. String.quoteUnic @@ -3695,32 +3695,32 @@ y);%0A %7D%0A + buf.pu @@ -3729,17 +3729,16 @@ (angular -. String.q
167e15d6fdf3d85ded1b655dcc5cc6e265cd2111
Fix typo in sha1 code
lib/sha1.js
lib/sha1.js
var Array32 = typeof Uint8Array === "function" ? Uint8Array : Array; module.exports = function sha1(buffer) { if (buffer === undefined) return create(); var shasum = create(); shasum.update(buffer); return shasum.digest(); }; // A streaming interface for when nothing is passed in. function create() { var h0 = 0x67452301; var h1 = 0xEFCDAB89; var h2 = 0x98BADCFE; var h3 = 0x10325476; var h4 = 0xC3D2E1F0; // The first 64 bytes (16 words) is the data chunk var block = new Array32(80), offset = 0, shift = 24; var totalLength = 0; return { update: update, digest: digest }; // The user gave us more data. Store it! function update(chunk) { if (typeof chunk === "string") return updateString(chunk); var length = chunk.length; totalLength += length * 8; for (var i = 0; i < length; i++) { write(chunk[i]); } } function updateString(string) { var length = string.length; totalLength += length * 8; for (var i = 0; i < length; i++) { write(string.charCodeAt(i)); } } function write(byte) { block[offset] |= (byte & 0xff) << shift; if (shift) { shift -= 8; } else { offset++; shift = 24; } if (offset === 16) processBlock(); } // No more data will come, pad the block, process and return the result. function digest() { // Pad write(0x80); if (offset > 14 || (offset === 14 && shift < 24)) { processBlock(); } offset = 14; shift = 24; // 64-bit length big-endian write(0x00); // numbers this big aren't accurate in javascript anyway write(0x00); // ..So just hard-code to zero. write(totalLength > 0xffffffffff ? totalLength / 0x10000000000 : 0x00); write(totalLength > 0xffffffff ? totalLength / 0x100000000 : 0x00); for (var s = 24; s >= 0; s -= 8) { write(totalLength >> s); } // At this point one last processBlock() should trigger and we can pull out the result. return toHex(h0) + toHex(h1) + toHex(h2) + toHex(h3) + toHex(h4); } // We have a full block to process. Let's do it! function processBlock() { // Extend the sixteen 32-bit words into eighty 32-bit words: for (var i = 16; i < 80; i++) { var w = block[i - 3] ^ block[i - 8] ^ block[i - 14] ^ block[i - 16]; block[i] = (w << 1) | (w >>> 31); } // log(block); // Initialize hash value for this chunk: var a = h0; var b = h1; var c = h2; var d = h3; var e = h4; var f, k; // Main loop: for (i = 0; i < 80; i++) { if (i < 20) { f = d ^ (b & (c ^ d)); k = 0x5A827999; } else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; } else if (i < 60) { f = (b & c) | (d & (b | c)); k = 0x8F1BBCDC; } else { f = b ^ c ^ d; k = 0xCA62C1D6; } var temp = (a << 5 | a >>> 27) + f + e + k + (block[i]|0); e = d; d = c; c = (b << 30 | b >>> 2); b = a; a = temp; } // Add this chunk's hash to result so far: h0 = (h0 + a) | 0; h1 = (h1 + b) | 0; h2 = (h2 + c) | 0; h3 = (h3 + d) | 0; h4 = (h4 + e) | 0; // The block is now reusable. offset = 0; for (i = 0; i < 16; i++) { block[i] = 0; } } function toHex(word) { var hex = ""; for (var i = 28; i >= 0; i -= 4) { hex += ((word >> i) & 0xf).toString(16); } return hex; } }
JavaScript
0.999929
@@ -14,25 +14,26 @@ typeof Uint -8 +32 Array === %22f @@ -47,17 +47,18 @@ %22 ? Uint -8 +32 Array :
cd1edce3ddb25364a5913adb26f5a534b620ad24
Fix build
src/utils/typography.js
src/utils/typography.js
/* eslint-env node */ import Typography from 'typography' import TypographyTheme from 'typography-theme-wordpress-2016' TypographyTheme.overrideThemeStyles = () => { return { a: { boxShadow: `none`, }, 'a.social': { borderBottom: '1px solid currentColor', }, 'a.gatsby-resp-image-link': { borderBottom: 'none', }, 'a.anchor': { borderBottom: 'none', }, small: { fontSize: '16px', }, blockquote: { fontSize: TypographyTheme.baseFontSize, }, ':not(pre)>code': { fontFamily: codeFontFamily.join(','), fontSize: '16px', fontWeight: 400, lineHeight: 1.58, letterSpacing: '-.003em', wordBreak: 'break-word', textRendering: 'optimizeLegibility', background: 'rgba(0, 0, 0, .05)', padding: '3px 4px', margin: '0 2px', }, } } // Override base font for Japanese // const FONT_FOR_JAPANESE = 'M PLUS Rounded 1c' const textFontFamily = [ 'Avenir Next', 'Helvetica Neue', 'Segoe UI', 'Helvetica', 'Arial', 'sans-serif', ] const codeFontFamily = [ 'Menlo', 'Monaco', '"Courier New"', 'Courier', 'monospace', ] TypographyTheme.headerFontFamily = textFontFamily TypographyTheme.bodyFontFamily = textFontFamily TypographyTheme.baseFontSize = '16px' TypographyTheme.headerWeight = 700 delete TypographyTheme.googleFonts const typography = new Typography(TypographyTheme) // Hot reload typography in development. if (process.env.NODE_ENV !== `production`) { typography.injectStyles() }
JavaScript
0.000001
@@ -1545,8 +1545,35 @@ les()%0A%7D%0A +%0Aexport default typography%0A
286131a618a3ff3f458678d30b83a099cb162593
Make sure the filter is cleared when switching levels.
opennms-webapp/src/main/webapp/js/onms-ksc/wizard.js
opennms-webapp/src/main/webapp/js/onms-ksc/wizard.js
/** * @author Alejandro Galue <[email protected]> * @copyright 2016 The OpenNMS Group, Inc. */ 'use strict'; angular.module('onms-ksc-wizard', [ 'ui.bootstrap', 'angular-growl' ]) .config(['growlProvider', function(growlProvider) { growlProvider.globalTimeToLive(3000); growlProvider.globalPosition('bottom-center'); }]) .filter('startFrom', function() { return function(input, start) { start = +start; // convert it to integer if (input) { return input.length < start ? input : input.slice(start); } return []; }; }) .controller('KSCResourceCtrl', ['$scope', '$filter', '$http', '$window', 'growl', function($scope, $filter, $http, $window, growl) { $scope.level = 0; // 0: Top-Level, 1: Resource-Level, 2: Graph-Level $scope.selectedNode = null; $scope.selectedResource = null; $scope.resources = []; $scope.filteredResources = []; $scope.pageSize = 10; $scope.maxSize = 5; $scope.totalItems = 0; $scope.goBack = function() { $scope.setLevel($scope.level - 1, true); }; $scope.setLevel = function(level, reset) { $scope.level = level; var resources = []; switch (level) { case 0: $http.get('rest/resources?depth=0').success(function(data) { $scope.resources = data.resource; $scope.filteredResources = angular.copy($scope.resources); $scope.updateResources(); }); break; case 1: if (reset) { $scope.selectedResource = angular.copy($scope.selectedNode); } else { $scope.selectedNode = angular.copy($scope.selectedResource); } $http.get('rest/resources/' + $scope.getSelectedId()).success(function(data) { $scope.resources = data.children.resource; $scope.filteredResources = angular.copy($scope.resources); $scope.updateResources(); }); break; case 2: $scope.resources = []; $scope.filteredResources = []; break; } }; $scope.getSelectedId = function() { return escape($scope.selectedResource.id.replace('%3A',':')); }; $scope.chooseResource = function() { if ($scope.selectedResource == null) { growl.warning('Please select a resource from the list.'); return; } $window.document.location.href = 'KSC/customGraphEditDetails.htm?resourceId=' + $scope.getSelectedId(); }; $scope.selectResource = function(resource) { $scope.selectedResource = resource; }; $scope.viewResource = function() { if ($scope.selectedResource == null) { growl.warning('Please select a resource from the list.'); return; } $scope.setLevel($scope.level + 1); }; $scope.updateResources = function() { $scope.currentPage = 1; $scope.totalItems = $scope.filteredResources.length; $scope.numPages = Math.ceil($scope.totalItems / $scope.pageSize); }; $scope.$watch('resourceFilter', function() { $scope.filteredResources = $filter('filter')($scope.resources, $scope.resourceFilter); $scope.updateResources(); }); $scope.setLevel(0); }]) .controller('KSCWizardCtrl', ['$scope', '$filter', '$http', '$window', 'growl', function($scope, $filter, $http, $window, growl) { $scope.resources = []; $scope.filteredResources = []; $scope.pageSize = 10; $scope.maxSize = 5; $scope.totalItems = 0; $scope.reportSelected = null; $scope.reports = []; $scope.filteredReports = []; $scope.kscPageSize = 10; $scope.kscMaxSize = 5; $scope.kscTotalItems = 0; $scope.actionUrl = 'KSC/formProcMain.htm'; $scope.reloadConfig = function() { bootbox.dialog({ message: 'Are you sure you want to do this?<br/>', title: 'Reload KSC Configuration', buttons: { reload: { label: 'Yes', className: 'btn-success', callback: function() { $http.put('rest/ksc/reloadConfig') .success(function() { growl.success('The configuration has been reloaded.'); }) .error(function(msg) { growl.error(msg); }); } }, main: { label: 'No', className: 'btn-danger' } } }); }; $scope.viewReport = function() { if ($scope.reportSelected == null) { growl.warning('Please select the report you want to view.'); return; } $window.location.href = $scope.actionUrl + '?report_action=View&report=' + $scope.reportSelected.id; }; $scope.customizeReport = function() { if ($scope.reportSelected == null) { growl.warning('Please select the report you want to customize.'); return; } $window.location.href = $scope.actionUrl + '?report_action=Customize&report=' + $scope.reportSelected.id; }; $scope.createReport = function() { $window.location.href = $scope.actionUrl + '?report_action=Create'; }; $scope.createReportFromExisting = function() { if ($scope.reportSelected == null) { growl.warning('Please select the report you want to copy.'); return; } $window.location.href = $scope.actionUrl + '?report_action=CreateFrom&report=' + $scope.reportSelected.id; }; $scope.deleteReport = function() { if ($scope.reportSelected == null) { growl.warning('Please select the report you want to delete.'); return; } $window.location.href = $scope.actionUrl + '?report_action=Delete&report=' + $scope.reportSelected.id; }; $scope.selectReport = function(id) { $scope.reportSelected = id; }; $scope.selectResource = function(resource) { $window.location.href = "KSC/customView.htm?type=node&report=" + resource.name; }; $scope.updateResources = function() { $scope.currentPage = 1; $scope.totalItems = $scope.filteredResources.length; $scope.numPages = Math.ceil($scope.totalItems / $scope.pageSize); }; $scope.updateReports = function() { $scope.kscCurrentPage = 1; $scope.kscTotalItems = $scope.filteredReports.length; $scope.kscNumPages = Math.ceil($scope.kscTotalItems / $scope.kscPageSize); }; $http.get('rest/resources?depth=0').success(function(data) { $scope.hasResources = data.resource.length > 0; $scope.resources = data.resource; $scope.filteredResources = $scope.resources; $scope.updateResources(); }); $http.get('rest/ksc').success(function(data) { $scope.hasResources = data.kscReport.length > 0; $scope.reports = data.kscReport; $scope.filteredReports = $scope.reports; $scope.updateReports(); }); $scope.$watch('resourceFilter', function() { $scope.filteredResources = $filter('filter')($scope.resources, $scope.resourceFilter); $scope.updateResources(); }); $scope.$watch('reportFilter', function() { $scope.filteredReports = $filter('filter')($scope.reports, $scope.reportFilter); $scope.updateReports(); }); }]);
JavaScript
0
@@ -1075,24 +1075,56 @@ l, reset) %7B%0A + $scope.resourceFilter = '';%0A $scope.l
99c8ee2cd23a153dc5be8b86c8bbd0ac3050fb47
create a function named mystery
code-school/JS-RoadTrip-3/tracking-a-closure.js
code-school/JS-RoadTrip-3/tracking-a-closure.js
//Chris Samuel //[email protected] //Tracing a Closure 1 // Examine the code below(i.e., manually trace it), in your head determine the final // value of the result variable, and alert the value as a numer using one line of code. // You must give only 1 number literal as the argument to alert. // Do not do any calculations. So, for example, don't use *. (Definitely do some math // in your head though!) // Don't pass in a string. // The number must be a whole number. No Decimal points.
JavaScript
0.999999
@@ -520,9 +520,72 @@ s.%0A%0A +function mystery()%7B%7D // create a function with the name mystery %0A
1e3ce4c16aae17afa10188e121edb52238816c75
Return some old code.
src/utils/underscore.js
src/utils/underscore.js
export default { cloneDeep(obj) { let out; let i; const pureJSType = obj && obj.toJSON ? obj.toJSON() : obj; //converting Backbone to js if (Array.isArray(pureJSType)) { out = []; for (i = pureJSType.length; i; ) { --i; out[i] = _.cloneDeep(pureJSType[i]); } return out; } if (_.isObject(pureJSType) && typeof pureJSType !== 'function') { out = {}; Object.entries(pureJSType).forEach(entrie => (out[entrie[0]] = _.cloneDeep(entrie[1]))); return out; } return pureJSType; } };
JavaScript
0.000317
@@ -23,16 +23,27 @@ loneDeep +: function (obj) %7B%0A @@ -50,19 +50,19 @@ -let +var out;%0A @@ -71,11 +71,11 @@ -let +var i;%0A @@ -86,13 +86,11 @@ -const +var pur @@ -180,21 +180,17 @@ if ( -Array +_ .isArray @@ -269,17 +269,16 @@ ngth; i; - ) %7B%0A @@ -509,94 +509,110 @@ -Object.entries(pureJSType).forEach(entrie =%3E (out%5Bentrie%5B0%5D%5D = _.cloneDeep(entrie%5B1%5D)) +_.map(pureJSType, function (value, key) %7B%0A out%5Bkey%5D = _.cloneDeep(value);%0A %7D );%0A%0A
fc0f1ceb1b96c74728e5f062957feab12239709e
Remove console log
stockflux-core/src/services/StockFluxService.js
stockflux-core/src/services/StockFluxService.js
import moment from 'moment'; import fetch from 'isomorphic-fetch'; // written in the same structure as d3fc-financial-feed export default function getStockFluxData() { var product, start, end; var stockFlux = function(cb) { var params = []; // defaulting data to 2016-01-01 as currently UI has no influence over dates if (start != null) { params.push('/' + moment(start).format('YYYY-MM-DD')); } if (end != null) { params.push('/' + moment(end).format('YYYY-MM-DD')); } // change to AWS endpoint var url = 'https://bkep4zhkka.execute-api.eu-west-2.amazonaws.com/dev/ohlc/' + product + '/2016-01-01'; fetch(url, { method: 'GET' }).then(function(response) { return response.json(); }) .then(function(stockData) { if (stockData.success) { cb(undefined, stockData.data.map(function(item) { return { open: item.open, close: item.close, high: item.high, low: item.low, volume: item.volume, date: new Date(item.date) }; })) } else if (!stockData.success) { cb(stockData); } } ).catch(function(error) { cb(error); }); }; stockFlux.product = function(x) { if (!arguments.length) { return product; } product = x; return stockFlux; }; stockFlux.start = function(x) { if (!arguments.length) { return start; } start = x; return stockFlux; }; stockFlux.end = function(x) { if (!arguments.length) { return end; } end = x; return stockFlux; }; return stockFlux; } export function stockFluxSearch(item) { var url = 'https://bkep4zhkka.execute-api.eu-west-2.amazonaws.com/dev/securities/search/' + item; return fetch(url, { method: 'GET' }).then(function(response) { return response.json(); }) .then(function(stockData) { if (stockData.success) { console.log(stockData); return stockData.data.map(item => { return { code: item.symbol, name: item.name } }) } else if (!stockData.success) { return []; } } ).catch(function(error) { console.log(error); return []; }); }
JavaScript
0.000002
@@ -2449,48 +2449,8 @@ ) %7B%0A - console.log(stockData);%0A
17f729a41d2b1f14e235f8c250257f27021bfe71
update verification controller
public/app/controllers/verifyController.js
public/app/controllers/verifyController.js
app.controller("VerifyController", [ "$scope", "$location", "$log", "$localStorage", "Request", "domainBase", "whoisUrl", "verifyUrl", function ($scope, $location, $log, $localStorage, Request, domainBase, whoisUrl, verifyUrl) { 'use strict'; if (!!!$localStorage.domain) { $location.path('/'); } var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi; var regex = new RegExp(expression); function init() { // body... $scope.domainData = $localStorage.domain; console.log($scope.domainData); } $scope.whois = function (forced) { forced = !!forced; $scope.error = null; $scope.warn = null; $scope.status = null; $scope.disableBtn = true; if (!!!$scope.domain.match(regex)) { $scope.error = "Your input is not a valid domain name."; $scope.status = 400; } else { var data = ($.url($scope.domain)).attr(); var requestUrl = domainBase + whoisUrl; data.base = data.protocol ? data.base : 'http://' + data.base; data.forced = forced; Request.fetch(requestUrl, data) .then(function (response) { // body... if (!response.success) { $scope.warn = response.message; $scope.status = response.status + ' -'; } $localStorage.domain = response.data; $location.path('/verify'); }, function (error) { // body... console.log(error); $scope.error = "We cannot verify your domain at this time."; // $scope.status = error.status + ' -'; }); } $scope.disableBtn = false; }; $scope.verify = function (type) { $scope.disableBtn = true; var requestUrl = domainBase + verifyUrl; var data = $scope.domainData; data.verification_type = type; Request.fetch(requestUrl, data) .then(function (response) { // body... if (!response.data.success) { $scope.warn = response.message; $scope.status = response.status + ' -'; } else { console.log(response); $localStorage.verified = response.data.success; console.log(response); $location.path('/signup'); } }, function (error) { // body... console.log(error); alert('Cannot verify your domain name. Please try again'); $scope.error = "We've notified the developers."; $scope.status = error.status + ' -'; }); $scope.disableBtn = false; } init(); $log.debug("Verify Controller Initialized"); }]);
JavaScript
0
@@ -625,51 +625,8 @@ in;%0A - console.log($scope.domainData); %0A
3454cc1830449a2056855b066d3985c29644e2ca
add tests for ColorUtils.isString()
test/color-utils_test.js
test/color-utils_test.js
"use strict"; const expect = require("chai").expect; const ColorUtils = require("../lib/color-utils").ColorUtils; describe("ColorUtils", function() { describe("decimalRound", function() { it("expects to return 3.14 when 3.14159 and 2 are passed", function() { expect(ColorUtils.decimalRound(3.14159, 2)).to.equal(3.14); }); it("expects to return 3.1416 when 3.14159 and 4 are passed", function() { expect(ColorUtils.decimalRound(3.14159, 4)).to.equal(3.1416); }); }); describe("isUpperCase", function() { it("expects to return true when 'U' is passed", function() { expect(ColorUtils.isUpperCase("U")).to.be.true; }); it("expects to return false when 'u' is passed", function() { expect(ColorUtils.isUpperCase("u")).to.be.false; }); }); });
JavaScript
0
@@ -497,16 +497,461 @@ %0A %7D);%0A%0A + describe(%22isString%22, function() %7B%0A it(%22expects to return true when 'string' is passed%22, function() %7B%0A expect(ColorUtils.isString(%22string%22)).to.be.true;%0A %7D);%0A%0A it(%22expects to return false when 123 is passed%22, function() %7B%0A expect(ColorUtils.isString(123)).to.be.false;%0A %7D);%0A%0A it(%22expects to return false when %5B'string'%5D is passed%22, function() %7B%0A expect(ColorUtils.isString(%5B%22string%22%5D)).to.be.false;%0A %7D);%0A %7D);%0A%0A descri
127532e12280d5546f467ad5758cda4f48189425
Update Main.js
src/Main.js
src/Main.js
//Gets links and writes dump of profile data to file // var async = require("async"); var fs = require('fs'); var p = require('./parseProjDatafromJSON'); var split = require('./SplitTxtEachProj.js'); var request = require("request"); function writeToFile(data, callback) { fs.writeFile('rawProfileContent2.txt', data, function () { console.log('file written - ' + 'rawProfileContent2.txt'); callback(); }) } // import function to get links var GetProfileLinks = require('./GetProfileLinks_FromDump.js'); // calls function from getlinksfromdump module that parses JSON object and returns array of profile links var linksArr = GetProfileLinks.getProfileLinks; // all profile urls consist of this url var baseURL = 'https://www.lendwithcare.org/'; // t termporarily stoes data for each scrape to dump to file var t = []; function scrapeProfiles(callback) { var limit = 4; var counter=0; async.eachLimit((linksArr), limit, function (url, index) { //The second argument (callback) is the continues the control flow var urlCur = baseURL + url; request(urlCur, function (error, response, body) { if(error){ console.log(error + ' ' +urlCur); return; } if(response) { t.push(body); console.log(url); counter++; if(counter ==limit){ writeToFile(t, callback); } } }, function(error){ if( err ) { console.log(error); } }); }); } async.series([ function Write_Scraped_Profiles_Dump_To_File(callback){ console.log('scrapping..'); scrapeProfiles(function(){ console.log('ok done.'); callback(null, 'two'); }); }, function Split_Scraped_Profiles_To_JSON(callback){ // split files from dumped contents to individual projs and write to individualprojectsRaw.json console.log('splitting...'); split.split ( function() { console.log('ok done.'); callback(null, 'three'); }); }, function Regex_Gets_Attributes_ForEach_Project_Then_Writes_ToFile(callback){ // get links from casper links collection and scrape each profile then dump all contents console.log('parsing...'); p.parsey(function(){ console.log('ok done.'); callback(null, 'four');}); } ], // optional callback function(err, results){ // results is now equal to if(err){ console.log(err); } });
JavaScript
0.000001
@@ -838,16 +838,63 @@ t = %5B%5D;%0A +%0A%0Avar requestCounter=0;%0Avar responseCounter=0;%0A function @@ -921,20 +921,111 @@ back) %7B%0A +%0A +// while loops until each batch of requests is done%0A while(requestCounter%3C4) %7B%0A var limi @@ -1039,23 +1039,8 @@ -var counter=0;%0A @@ -1205,16 +1205,115 @@ + url;%0A + console.log(requestCounter + ' ' + urlCur); %0A requestCounter++;%0A @@ -1363,24 +1363,25 @@ se, body) %7B%0A +%0A @@ -1390,23 +1390,25 @@ if + (error) + %7B%0A @@ -1450,16 +1450,17 @@ + ' ' + + urlCur); @@ -1536,16 +1536,17 @@ if + (respons @@ -1654,17 +1654,25 @@ -c +responseC ounter++ @@ -1703,27 +1703,52 @@ if -(counter ==limit)%7B%0A + (responseCounter == requestCounter) %7B%0A @@ -1849,32 +1849,36 @@ %7D%0A + %7D,%0A f @@ -1872,32 +1872,36 @@ + + function (error)%7B%0A @@ -1888,23 +1888,25 @@ function + (error) + %7B%0A @@ -1919,20 +1919,31 @@ + -if( + if ( err - ) %7B%0A + @@ -1982,34 +1982,42 @@ + -%7D%0A + %7D%0A %7D);%0A @@ -2020,19 +2020,55 @@ %7D);%0A -%7D); + %7D);%0A // requestCounter++%0A %7D %0A%7D%0A%0Aasyn
9e676e76bb770fd09bdb2b01c2a2fe0ff6c3845c
remove useless variable
js/Members.js
js/Members.js
var Members = Ext.extend(Ext.Panel, { initComponent : function(test) { var form = new Kwf.Auto.FormPanel({ controllerUrl : '/member', region : 'center' }); var contacts = new Kwf.Auto.GridPanel({ controllerUrl : '/member-contacts', region : 'south', height : 200, resizable : true, split : true, collapsible : true, title : trl('Contacts') }); var grid = new Kwf.Auto.GridPanel({ controllerUrl : '/members', region : 'west', width : 300, resizable : true, split : true, collapsible : true, title : trl('Customers'), bindings: [form, { queryParam: 'member_id', item: contacts }] }); this.layout = 'border'; this.items = [grid, { layout: 'border', region: 'center', items: [form, contacts] }]; Members.superclass.initComponent.call(this); } });
JavaScript
0.000738
@@ -64,12 +64,8 @@ ion( -test )%0A
617dda948ce441f20ff135ed280529a8b609c4bc
Fix #1
lib/steganography.js
lib/steganography.js
/** Based on the idea outlined here: http://domnit.org/blog/2007/02/stepic-explanation.html */ var lwip = require('lwip'); var fs = require('fs'); var crypto = require('crypto'); var Q = require('q'); var _index = 0; var _width = 0; var _height = 0; var _clone; var _batch; var _password; /* Reads the least significant bits of the pixel (Red, Green and Blue) and add them to the corresponding position of the byte being constructed */ var unpackBit = function (b, pixel, position) { switch (position % 3) { case 0: color = 'r'; break; case 1: color = 'g'; break; case 2: color = 'b'; break; } // if pixel is set if (pixel[color] & (1 << 0)) { b |= 1 << (7 - position); } return b; }; /* Sets the least significant bit to 1 or 0 (depending on the bit to set) */ var packBit = function (pixel, position, bit) { var color; switch (position % 3) { case 0: color = 'r'; break; case 1: color = 'g'; break; case 2: color = 'b'; break; } if (bit) { pixel[color] |= 1 << 0; } else { pixel[color] &= ~(1 << 0); } return pixel; }; /* Reads the next section (a section ends when the least significant bit of the blue component of the third pixel is 0) See http://domnit.org/blog/2007/02/stepic-explanation.html */ var digUpNextSection = function () { var b; var pixel; var buffer = []; while (_index < _width * _height) { b = 0; for (var i = 0; i < 8; i++) { if (i % 3 == 0) { pixel = _clone.getPixel(_index % _width, Math.floor(_index / _width)); _index++; } b = unpackBit(b, pixel, i); } buffer.push(b); if (pixel.b & (1 << 0)) { break; } } buffer = new Buffer(buffer); if (_password) { var decipher = crypto.createDecipher('aes-256-ctr', _password); buffer = Buffer.concat([decipher.update(buffer), decipher.final()]); } return buffer; }; /* Embeds a buffer of data See http://domnit.org/blog/2007/02/stepic-explanation.html */ var embedSection = function (buffer) { var pixel; if (_password) { var cipher = crypto.createCipher('aes-256-ctr', _password); buffer = Buffer.concat([cipher.update(buffer), cipher.final()]); } var bit; // TODO: I have the impression that this algorithm can be simplified... var octect; for (var i = 0; i < buffer.length; i++) { octect = buffer[i]; for (var j = 0; j < 8; j++) { if (j % 3 == 0) { if (pixel) { _batch.setPixel(_index % _width, Math.floor(_index / _width), pixel); _index++; } pixel = _clone.getPixel(_index % _width, Math.floor(_index / _width)); } if (octect & (1 << (7 - j))) { bit = 1; } else { bit = 0; } pixel = packBit(pixel, j, bit); } if (i == (buffer.length - 1)) { pixel.b |= 1 << 0; } else { pixel.b &= ~(1 << 0); } _batch.setPixel(_index % _width, Math.floor(_index / _width), pixel); _index++; pixel = undefined; } }; module.exports = { digUp: function (imageFile, outputFolder, password) { var d = Q.defer(); _password = password ? password : null; lwip.open(imageFile, function (err, image) { if (!err) { _width = image.width(); _height = image.height(); _clone = image; var buffer = digUpNextSection(); var fileName = buffer.toString(); buffer = digUpNextSection(); var embededShasum = digUpNextSection(); var bufferShasum = crypto.createHash('sha1'); bufferShasum.update(buffer); var output = outputFolder ? outputFolder : '.'; if (embededShasum.equals(bufferShasum.digest())) { fs.writeFile(output + '/digged-' + fileName, buffer, function (err) { if (err) { d.reject(err); } console.log('Embedded file ' + fileName + ' found'); d.resolve(); }); } else { console.log('Nothing to do here...'); d.resolve(); } } else { d.reject(err); } } ); return d.promise; }, embed: function (imageFile, fileToEmbed, outputFile, password) { var d = Q.defer(); _password = password ? password : null; var fileName = new Buffer(fileToEmbed.match(/([^\/]*)$/)[1]); fs.readFile(fileToEmbed, function (err, data) { if (!err) { var shasum = crypto.createHash('sha1'); shasum.update(data); lwip.open(imageFile, function (err, image) { if (!err) { image.clone(function (err, clone) { if (!err) { _clone = clone; _width = clone.width(); _height = clone.height(); _batch = clone.batch(); embedSection(fileName); embedSection(data); embedSection(shasum.digest()); outputFile = outputFile ? outputFile : 'output'; _batch.writeFile(outputFile + '.png', function (err) { if (err) { d.reject(err); } d.resolve(); }); } else { d.reject(err); } }); } else { d.reject(err); } } ); } else { d.reject(err); } }); return d.promise; } };
JavaScript
0.000003
@@ -481,16 +481,32 @@ ion) %7B%0A%0A + var color;%0A %0A switch @@ -905,16 +905,19 @@ color;%0A + %0A switch
5bcebfcced7081ae8a87ee3aa77ce9b6b45b92d7
remove i from import
frontend/src/reducers/authenticationReducer.js
frontend/src/reducers/authenticationReducer.js
import initialAuthValues from '../constants/initialAuthValues'; import * as types from '../constants/actionTypes'; const {isAuthenticated, username, errorMessage, loading} = initialAuthValues; export default function authenticationReducer(state = {isAuthenticated, username, errorMessage, loading} , action) { switch (action.type) { case `${types.LOGIN}_FULFILLED`: return { ...state, isAuthenticated: action.payload.data.authenticated, username: action.payload.data.userName, errorMessage: null }; case `${types.LOGIN}_REJECTED`: return { ...state, isAuthenticated: false, username: null, errorMessage: action.payload.message }; case `${types.LOGOUT}_FULFILLED`: return { ...state, isAuthenticated: false, username: null }; case `${types.GET_SESSION}_PENDING`: return { ...state, loading: true }; case `${types.GET_SESSION}_FULFILLED`: return { ...state, isAuthenticated: action.payload.data.authenticated || false, username: action.payload.data.userName, errorMessage: null, loading: false }; case `${types.GET_SESSION}_REJECTED`: return { ...state, isAuthenticated: false, username: null, debugError: action.payload, loading: false }; case types.ERROR_MESSAGE: return { ...state, errorMessage: action.message }; default: return state; } }
JavaScript
0
@@ -1,16 +1,15 @@ import -i nitialAu @@ -36,17 +36,16 @@ nstants/ -i nitialAu @@ -166,17 +166,16 @@ ding%7D = -i nitialAu
1782f9d0c0911627c3f4900497b4a94b9a9a954b
fix crash
lib/touch-events.js
lib/touch-events.js
'use babel'; import 'array.from'; import SubAtom from 'sub-atom'; import { isEnabled as autohideEnabled, show as showTreeView, hide as hideTreeView, } from './autohide-tree-view.js'; import { getConfig, } from './config.js'; import { getTreeViewEl, getContentWidth, isChildOf, } from './utils.js'; var onDidTouchSwipeLeft; var onDidTouchSwipeRight; export function consumeTouchSwipeLeftService(onDidTouchSwipeLeftService) { onDidTouchSwipeLeft = onDidTouchSwipeLeftService; if(getConfig('showOn').match('touch')) enable(); } export function consumeTouchSwipeRightService(onDidTouchSwipeRightService) { onDidTouchSwipeRight = onDidTouchSwipeRightService; if(getConfig('showOn').match('touch')) enable(); } var enabled = false; var disposables; export function enable() { if(enabled || !atom.packages.isPackageLoaded('atom-touch-events')) return; enabled = true; disposables = new SubAtom(); disposables.add(onDidTouchSwipeLeft(swipeChange, swipeEndLeft)); disposables.add(onDidTouchSwipeRight(swipeChange, swipeEndRight)); } export function disable() { if(!enabled) return; enabled = false; disposables.dispose(); disposables = null; } export function isEnabled() { return enabled; } var currentSwipeEvent = null; function shouldInitSwipe(event, source) { // false if autohide or touch events is disabled if(!autohideEnabled() || !getConfig('showOn').match('touch')) return false; var { pageX } = event.touches[0]; // always swipe when target is tree view if(!isChildOf(source, getTreeViewEl().parentNode)) { // check if in touch area if(getConfig('showOnRightSide', 'tree-view')) { if(pageX < window.innerWidth - getConfig('touchAreaSize')) return false; } else { if(pageX > getConfig('touchAreaSize')) return false; } } currentSwipeEvent = event; return true; } // triggered while swiping the tree view function swipeChange({ args: event, source, deltaX }) { // check if swipe should show the tree view if(!currentSwipeEvent && !shouldInitSwipe(event, source)) return; // calculate new tree view width if(getConfig('showOnRightSide', 'tree-view')) deltaX *= -1; var newWidth = getTreeViewEl().clientWidth + deltaX; newWidth = Math.min(getContentWidth(), Math.max(getConfig('minWidth'), newWidth)); // request the frame requestAnimationFrame(function frame() { getTreeViewEl().style.width = `${newWidth}px`; }); } // triggered after swipe left function swipeEndLeft() { if(!currentSwipeEvent) return; currentSwipeEvent = null; getConfig('showOnRightSide', 'tree-view') ? showTreeView() : hideTreeView(); } // triggered after swipe right function swipeEndRight() { if(!currentSwipeEvent) return; currentSwipeEvent = null; getConfig('showOnRightSide', 'tree-view') ? hideTreeView() : showTreeView(); }
JavaScript
0.000003
@@ -815,58 +815,52 @@ %7C%7C ! -atom.packages.isPackageLoaded('atom-touch-events') +onDidTouchSwipeLeft %7C%7C !onDidTouchSwipeRight ) re
0356784386bd9620c0dbde66dc985ffed854d0b8
Set correct content type
lib/support/store.js
lib/support/store.js
var AWS = require('aws-sdk'); var secrets = require('./../../conf/secrets/secrets'); var s3 = new AWS.S3({ params: { Bucket: 'best-ecosystem', Region: 'us-west-2', ACL: 'public-read' }, apiVersion: '2006-03-01', accessKeyId: secrets['aws_access_key_id'], secretAccessKey: secrets['aws_secret_access_key'] }); function getFile(path, cb) { s3.getObject({ Key: path }, cb); } function getData(path, cb) { getFile(path, function(err, result) { if (err || !result) { cb(err); } else if (result.Body) { cb(null, result.Body.toString()); } }); } function hasFile(path, cb) { getFile(path, function(err, result) { if (!err && result && result.Body) { cb(null, true); } else { cb(err, false); } }); } function listFiles(path, cb) { s3.listObjects({ Prefix: path }, cb); } function putFile(path, data, cb) { s3.putObject({ Key: path, Body: data }, cb); } module.exports = { getData: getData, getFile: getFile, hasFile: hasFile, listFiles: listFiles, putFile: putFile };
JavaScript
0.000995
@@ -1,12 +1,27 @@ +'use strict';%0A%0A var AWS = re @@ -38,16 +38,44 @@ -sdk');%0A +var path = require('path');%0A var secr @@ -391,16 +391,986 @@ '%5D%0A%7D);%0A%0A +// Mapping of extname to content type%0Avar typeMap = %7B%0A '.css': 'text/css',%0A '.eot': 'application/vnd.ms-fontobject',%0A '.gif': 'image/gif',%0A '.html': 'text/html',%0A '.htm': 'text/html',%0A '.ico': 'image/x-icon',%0A '.jpeg': 'image/jpeg',%0A '.jpg': 'image/jpeg',%0A '.js': 'application/javascript',%0A '.json': 'application/json',%0A '.markdown': 'text/x-markdown',%0A '.md': 'text/x-markdown',%0A '.otf': 'font/opentype',%0A '.png': 'image/png',%0A '.svg': 'image/svg+xml',%0A '.ttf': 'application/octet-stream',%0A '.txt': 'text/plain',%0A '.woff': 'application/x-font-woff',%0A '.woff2': 'application/font-woff2',%0A '.xhtml': 'text/html',%0A '.xml': 'application/xml'%0A%7D;%0A// Use this fallback if no content type found%0Avar fallback = 'application/octet-stream';%0A%0Afunction getContentType(filepath) %7B%0A var extname = path.extname(filepath.toLowerCase());%0A var found = typeMap%5Bextname%5D;%0A if (found) %7B%0A return found;%0A %7D%0A else %7B%0A return fallback;%0A %7D%0A%7D;%0A%0A function @@ -2052,16 +2052,16 @@ : path,%0A - @@ -2070,16 +2070,59 @@ dy: data +,%0A ContentType: getContentType(path) %0A %7D,
59573c6e889bf2bfc01a87ed21a32315ac26264a
Create a meaningful error from response.error.errors array
lib/transporters.js
lib/transporters.js
/** * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var request = require('request'), pkg = require('../package.json'); /** * Default transporter constructor. * Wraps request and callback functions. */ function DefaultTransporter() {} /** * Default user agent. */ DefaultTransporter.prototype.USER_AGENT = 'google-api-nodejs-client/' + pkg.version; /** * Configures request options before making a request. * @param {object} opts Options to configure. * @return {object} Configured options. */ DefaultTransporter.prototype.configure = function(opts) { // set transporter user agent opts.headers = opts.headers || {}; opts.headers['User-Agent'] = opts.headers['User-Agent'] ? opts.headers['User-Agent'] + ' ' + this.USER_AGENT : this.USER_AGENT; return opts; }; /** * Makes a request with given options and invokes callback. * @param {object} opts Options. * @param {Function=} opt_callback Optional callback. * @return {Request} Request object */ DefaultTransporter.prototype.request = function(opts, opt_callback) { opts = this.configure(opts); return request(opts.uri || opts.url, opts, this.wrapCallback_(opt_callback)); }; /** * Wraps the response callback. * @param {Function=} opt_callback Optional callback. * @return {Function} Wrapped callback function. * @private */ DefaultTransporter.prototype.wrapCallback_ = function(opt_callback) { return function(err, res, body) { if (err || !body) { return opt_callback && opt_callback(err, body, res); } // Only and only application/json responses should // be decoded back to JSON, but there are cases API back-ends // responds without proper content-type. try { body = JSON.parse(body); } catch (err) { /* no op */ } if (body && body.error) { if (typeof body.error === 'string') { err = new Error(body.error); err.code = res.statusCode; } else { err = new Error(body.error.message); err.code = body.error.code || res.statusCode; } body = null; } else if (res.statusCode >= 500) { // Consider all '500 responses' errors. err = new Error(body); err.code = res.statusCode; body = null; } if (opt_callback) { opt_callback(err, body, res); } }; }; /** * Exports DefaultTransporter. */ module.exports = DefaultTransporter;
JavaScript
0.999891
@@ -2475,24 +2475,313 @@ statusCode;%0A +%0A %7D else if (Array.isArray(body.error.errors)) %7B%0A err = new Error(body.error.errors.map(%0A function(err) %7B return err.message; %7D%0A ).join('%5Cn'));%0A err.code = body.error.errors%5B0%5D.code;%0A err.errors = body.error.errors;%0A%0A %7D else
2743bcee9e9ef7e932e2ad9323a17f484b749ea4
Fix tests
test/create-directory.js
test/create-directory.js
'use strict' var createDirectory = require('../lib/create-directory') var should = require('should') describe('directory » create', function () { describe('brand', function () { var brand = createDirectory(require('../lib/dir/brand.json')) it('prints name under detection', function () { const { data, output } = brand('chinook') should(data).be.equal('Chinook') should(output).be.equal('') }) it('undefined under non detection', function () { const { data, output } = brand('foobar') should(data).be.undefined() should(output).be.equal('foobar') }) }) })
JavaScript
0.000003
@@ -11,19 +11,89 @@ t'%0A%0A -var createD +const strmatch = require('str-match')()%0Aconst should = require('should')%0A%0Aconst d irec @@ -119,24 +119,46 @@ lib/ +dir/brand.json')%0Aconst create --d +D irectory ')%0Av @@ -157,39 +157,43 @@ tory -')%0Avar should = require('should + = require('../lib/create-directory ')%0A%0A @@ -279,11 +279,13 @@ -var +const bra @@ -309,40 +309,27 @@ ory( -require('../lib/dir/brand.json') +directory, strmatch )%0A%0A
029fb38cb23d3e3a8667d54c3af10af3686c9b47
Fix options for db
lib/syncDesignDoc.js
lib/syncDesignDoc.js
var couchdb = require('couchdb') , config = require('../config') , request = require("request"); var client = couchdb.createClient(config.port, config.host, { user: config.user, password: config.password }); var db = client.db(config.db); request.put('http://' + config.user + ":" + config.password + "@" + config.host + ":" + config.port + "/" + config.db, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("Database " + config.db + " created."); }else if(error){ console.log(error); }else{ console.log("Database " + config.db + " exists."); } }); var designDoc = { _id: '_design/' + config.db, language: 'javascript', views: { 'posts_by_date': { map: function(doc) { if (doc.type === 'post') { emit(doc.postedAt, doc); } }.toString() } } }; db.saveDoc(designDoc).then(function(resp) { console.log('updated design doc!'); }, function(err) { console.log('error updating design doc: '+require('util').inspect(err)); });
JavaScript
0.000008
@@ -99,50 +99,38 @@ );%0A%0A +%0A var -client = couchdb.createClient +options = %7B%7D;%0Aif (config. port @@ -129,21 +129,23 @@ fig. -port, +user && config. host @@ -144,21 +144,38 @@ fig. -host, %7B +password) %7B%0A options. user -: + = con @@ -186,18 +186,30 @@ user -, +;%0A options. password : co @@ -204,17 +204,18 @@ password -: + = config. @@ -222,18 +222,89 @@ password - %7D +;%0A%7D%0A%0Avar client = couchdb.createClient(config.port, config.host, options );%0Avar d
17359ab681048c58c954ed8330fcddef4725c005
set printWidth to 120 to reduce mangled text, readable html
src/vite/.prettierrc.js
src/vite/.prettierrc.js
module.exports = { printWidth: 80, tabWidth: 2, useTabs: false, semi: true, singleQuote: false, trailingComma: "es5", bracketSpacing: true, jsxBracketSameLine: false, arrowParens: "always", proseWrap: "never", htmlWhitespaceSensitivity: "strict", endOfLine: "lf", };
JavaScript
0.000001
@@ -30,9 +30,10 @@ th: -8 +12 0,%0A
b8706c3d84601135b94c5e494718d4a6e67e32dc
support pubmed search with keyword string
public/js/p3/widget/ExternalItemFormatter.js
public/js/p3/widget/ExternalItemFormatter.js
define([ "dojo/date/locale", "dojo/dom-construct", "dojo/dom-class", "dijit/form/Button", "../JobManager", "dijit/TitlePane", "dojo/request", "dojo/_base/lang" ], function(locale, domConstruct, domClass, Button, JobManager, TitlePane, xhr, lang){ var formatters = { "default": function(item, options){ options = options || {}; var table = domConstruct.create("table"); var tbody = domConstruct.create("tbody", {}, table); Object.keys(item).sort().forEach(function(key){ var tr = domConstruct.create("tr", {}, tbody); var tda = domConstruct.create("td", {innerHTML: key}, tr); var tdb = domConstruct.create("td", {innerHTML: item[key]}, tr); }, this); return table; }, "pubmed_data": function(item, options){ options = options || {}; var term; if(item.hasOwnProperty('feature_id')){ // feature var organism = item.genome_name.split(" ").slice(0, -1).join(" "); var opts = []; item.hasOwnProperty('product') ? opts.push(item.product) : {}; item.hasOwnProperty('patric_id') ? opts.push(item.patric_id) : {}; item.hasOwnProperty('gene') ? opts.push(item.gene) : {}; item.hasOwnProperty('refseq_locus_tag') ? opts.push(item.refseq_locus_tag) : {}; item.hasOwnProperty('protein_id') ? opts.push(item.protein_id) : {}; term = "(\"" + organism + "\") AND (" + opts.map(function(d){ return "\"" + d + "\""; }).join(" OR ") + ")"; } else if(item.hasOwnProperty('genome_name')){ term = item.genome_name; } else if(item.hasOwnProperty('taxon_name')){ term = item.taxon_name; }else{ return; } var eutilSearchURL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?usehistory=y&db=pubmed&term=" + term + "&retmode=json"; var div = domConstruct.create("div", {"class": "pubmed"}); var topLevelUl = domConstruct.create("ul", {}, div); xhr.get(eutilSearchURL, { headers: { accept: "application/json", 'X-Requested-With': null }, handleAs: "json" }).then(lang.hitch(this, function(pubmedList){ if(pubmedList.esearchresult.count > 0){ var pmids = pubmedList.esearchresult.idlist; var retmax = 5; var eutilSummaryURL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=" + pmids + "&retmax=" + retmax + "&retmode=json"; xhr.get(eutilSummaryURL, { headers: { accept: "application/json", 'X-Requested-With': null }, handleAs: "json" }).then(lang.hitch(this, function(pubmedSummary){ for(var i = 0; i < pubmedSummary.result.uids.length; i++){ var value = pubmedSummary.result.uids[i]; var listItem = domConstruct.create("li", {}, topLevelUl); domConstruct.create("div", {innerHTML: pubmedSummary.result[value].pubdate}, listItem); domConstruct.create("a", { href: 'https://www.ncbi.nlm.nih.gov/pubmed/' + value, target: '_blank', innerHTML: pubmedSummary.result[value].title }, listItem); var author; if(pubmedSummary.result[value].authors.length == 1){ author = pubmedSummary.result[value].authors[0].name; } else if(pubmedSummary.result[value].authors.length == 2){ author = pubmedSummary.result[value].authors[0].name + " and " + pubmedSummary.result[value].authors[1].name; } else{ author = pubmedSummary.result[value].authors[0].name + ' et al.' } domConstruct.create("div", {innerHTML: author}, listItem); domConstruct.create("div", {innerHTML: pubmedSummary.result[value].source}, listItem); } })); // add show more link domConstruct.create("a", {href: "https://www.ncbi.nlm.nih.gov/pubmed/?term=" + term, target:"_blank", innerHTML: "show more >>"}, div); } else{ domConstruct.create("li", {innerHTML: "No recent articles found."}, topLevelUl); } })); return div; } }; return function(item, type, options){ type = type || "default"; return formatters[type](item, options) } });
JavaScript
0
@@ -1591,22 +1591,57 @@ se%7B%0A%09%09%09%09 -return +// item is keyword string%0A%09%09%09%09term = item ;%0A%09%09%09%7D%0A%0A
ad814e2a08d48679820432aa95b84b0981171c70
update vimperator setting
common/vimperator/plugin/toggle-menu-toolbar.js
common/vimperator/plugin/toggle-menu-toolbar.js
commands.addUserCommand( ["toggleshowingmenutoolbar"], "Toggle the apperance of menu and toolbar", function() { if (options.get("gui").has("nonavigation")) { liberator.execute(":set gui='tabs,menu,navigation,addons,bookmarks'"); } else { liberator.execute(":set gui='tabs,nomenu,nonavigation,noaddons,nobookmarks'"); } } )
JavaScript
0
@@ -217,16 +217,18 @@ i='tabs, +no menu,nav
bf600b0526045aba8b8641401ecd35b02eaac939
fix lint issue
packages/babel-plugin-transform-react-jsx/src/index.js
packages/babel-plugin-transform-react-jsx/src/index.js
/* eslint max-len: 0 */ export default function ({ types: t }) { let JSX_ANNOTATION_REGEX = /\*?\s*@jsx\s+([^\s]+)/; let visitor = require("babel-helper-builder-react-jsx")({ pre(state) { let tagName = state.tagName; let args = state.args; if (t.react.isCompatTag(tagName)) { args.push(t.stringLiteral(tagName)); } else { args.push(state.tagExpr); } }, post(state, pass) { state.callee = pass.get("jsxIdentifier")(); } }); visitor.Program = function (path, state) { let { file } = state; let id = state.opts.pragma || "React.createElement"; for (let comment of (file.ast.comments: Array<Object>)) { let matches = JSX_ANNOTATION_REGEX.exec(comment.value); if (matches) { id = matches[1]; if (id === "React.DOM") { throw file.buildCodeFrameError(comment, "The @jsx React.DOM pragma has been deprecated as of React 0.12"); } else { break; } } } state.set( "jsxIdentifier", ()=> id.split(".").map((name) => t.identifier(name)).reduce( (object, property) => t.memberExpression(object, property) ) ); }; return { inherits: require("babel-plugin-syntax-jsx"), visitor }; }
JavaScript
0.000003
@@ -1052,16 +1052,17 @@ () + =%3E id.sp
b0dbb300db6849f8f6ce4aebbef325d4964d8ac1
check git repo by utils method now
lib/turbo-commit.js
lib/turbo-commit.js
#!/usr/bin/env node (function () { 'use strict'; var childProcess = require('child_process'), inquirer = require('inquirer'), configParser = require('../bin/config-parser'), messageHandler = require('../bin/message-handler'); require('colors'); init(); //SHOW TAG LIST FOR SELECTION function init() { //Exec git branch to check if exist .git files var checkRepoExistenceCommand = childProcess.exec('git branch'); checkRepoExistenceCommand.stderr.on('data', function (data) { messageHandler.showError(data); }); checkRepoExistenceCommand.on('close', function (code) { if (code === 0) { //0 means ok, 128 means error inquirer .prompt([ { type: 'list', name: 'tag', message: 'Select tag for your turbo-commit', choices: configParser.getTagsFormat() }]) .then(function (answers) { var tagTitle = answers.tag; showCommitPrompt(tagTitle); }); } }); } function showCommitPrompt(tagTitle) { var commitText, parseDesc; function onTitlePrompt() { onAskFor('title').then(function (commitTitle) { if (!commitTitle) { utils.showError('Title is mandatory'); return onTitlePrompt(); } //parse mandatory title for commit commitText = tagTitle + ' ' + commitTitle; //parse optional description fot the commit onAskFor('desc').then(function (commitDesc) { if (commitDesc) { parseDesc = '\n\n'; parseDesc += new Array(tagTitle.length).join(' '); parseDesc += ' - ' + commitDesc; commitText += parseDesc; } execCommit(commitText); }); }); } onTitlePrompt(); } function onAskFor(field) { var titleText = 'Type the commit title:', descText = 'Commit description (leave it empty for omit):'; return inquirer .prompt([ { type: 'input', name: field, message: field === 'desc' ? descText : titleText }]) .then(function (answers) { return answers[field]; }); } function execCommit(commitMessage) { childProcess.exec('git commit -m "' + commitMessage + '"', function (error) { if (error) { utils.showError('Nothing to commit, you need to do a `git add` before commit'); } }); } })();
JavaScript
0
@@ -200,30 +200,21 @@ -messageHandler +utils = requi @@ -228,24 +228,16 @@ bin/ -message-handler' +utils')( );%0A%0A @@ -276,365 +276,74 @@ ();%0A - //SHOW TAG LIST FOR SELECTION%0A function init() %7B%0A //Exec git branch to check if exist .git files%0A var checkRepoExistenceCommand = childProcess.exec('git branch');%0A%0A checkRepoExistenceCommand.stderr.on('data', function (data) %7B%0A messageHandler.showError(data);%0A %7D);%0A%0A checkRepoExistenceCommand.on('close', +%0A function init() %7B%0A utils.checkGitRepoExistence().then( fun @@ -353,80 +353,12 @@ on ( -code ) %7B%0A - if (code === 0) %7B //0 means ok, 128 means error%0A @@ -382,36 +382,32 @@ - - .prompt(%5B%0A @@ -416,34 +416,26 @@ - %7B%0A +%7B%0A @@ -480,28 +480,24 @@ - name: 'tag', @@ -513,36 +513,32 @@ - - message: 'Select @@ -590,20 +590,16 @@ - choices: @@ -644,36 +644,28 @@ - - %7D%5D)%0A - @@ -711,28 +711,24 @@ - - var tagTitle @@ -744,20 +744,16 @@ s.tag;%0A%0A - @@ -808,37 +808,88 @@ - %7D);%0A %7D +%7D);%0A %7D).catch( function (err) %7B%0A utils.showError(err); %0A
714042435fb95573390d580be9b93bca884be26a
encapsulate `isFinite`
packages/core-js/modules/es.number.to-exponential.js
packages/core-js/modules/es.number.to-exponential.js
'use strict'; var $ = require('../internals/export'); var global = require('../internals/global'); var uncurryThis = require('../internals/function-uncurry-this'); var toIntegerOrInfinity = require('../internals/to-integer-or-infinity'); var thisNumberValue = require('../internals/this-number-value'); var arraySlice = require('../internals/array-slice'); var $repeat = require('../internals/string-repeat'); var log10 = require('../internals/math-log10'); var fails = require('../internals/fails'); var RangeError = global.RangeError; var String = global.String; var abs = Math.abs; var floor = Math.floor; var pow = Math.pow; var round = Math.round; var un$ToExponential = uncurryThis(1.0.toExponential); var repeat = uncurryThis($repeat); // Edge 17- var ROUNDS_PROPERLY = un$ToExponential(-6.9e-11, 4) === '-6.9000e-11' // IE11- && Edge 14- && un$ToExponential(1.255, 2) === '1.25e+0'; // FF86-, enable after increasing maximum number of fraction digits in the implementation to 100 // && nativeToExponential.call(25, 0) === '3e+1'; // IE8- var THROWS_ON_INFINITY_FRACTION = fails(function () { un$ToExponential(1, Infinity); }) && fails(function () { un$ToExponential(1, -Infinity); }); // Safari <11 && FF <50 var PROPER_NON_FINITE_THIS_CHECK = !fails(function () { un$ToExponential(Infinity, Infinity); }) && !fails(function () { un$ToExponential(NaN, Infinity); }); var FORCED = !ROUNDS_PROPERLY || !THROWS_ON_INFINITY_FRACTION || !PROPER_NON_FINITE_THIS_CHECK; // `Number.prototype.toExponential` method // https://tc39.es/ecma262/#sec-number.prototype.toexponential $({ target: 'Number', proto: true, forced: FORCED }, { toExponential: function toExponential(fractionDigits) { var x = thisNumberValue(this); if (fractionDigits === undefined) return un$ToExponential(x); var f = toIntegerOrInfinity(fractionDigits); if (!isFinite(x)) return String(x); // TODO: ES2018 increased the maximum number of fraction digits to 100, need to improve the implementation if (f < 0 || f > 20) throw RangeError('Incorrect fraction digits'); if (ROUNDS_PROPERLY) return un$ToExponential(x, f); var s = ''; var m = ''; var e = 0; var c = ''; var d = ''; if (x < 0) { s = '-'; x = -x; } if (x === 0) { e = 0; m = repeat('0', f + 1); } else { // this block is based on https://gist.github.com/SheetJSDev/1100ad56b9f856c95299ed0e068eea08 // TODO: improve accuracy with big fraction digits var l = log10(x); e = floor(l); var n = 0; var w = pow(10, e - f); n = round(x / w); if (2 * x >= (2 * n + 1) * w) { n += 1; } if (n >= pow(10, f + 1)) { n /= 10; e += 1; } m = String(n); } if (f !== 0) { m = arraySlice(m, 0, 1) + '.' + arraySlice(m, 1); } if (e === 0) { c = '+'; d = '0'; } else { c = e > 0 ? '+' : '-'; d = String(abs(e)); } m += 'e' + c + d; return s + m; } });
JavaScript
0.999939
@@ -559,16 +559,48 @@ String;%0A +var isFinite = global.isFinite;%0A var abs
1f520da91e08d94f338649a8e2e9755660038f66
change users publication to publish children
server/users/publications.js
server/users/publications.js
Meteor.publishComposite("users", { find: function () { var user = Meteor.users.findOne({_id: this.userId}); if (!user) { return null; } if (!_.contains(user.roles, "admin")) { return Meteor.users.find({_id: this.userId}); } return Meteor.users.find({}); }, children: [ { find: function (user) { if (user.groups) { return Groups.find({ name: {$in: user.groups} }); } } } ] });
JavaScript
0
@@ -64,11 +64,13 @@ -var +const use @@ -183,17 +183,16 @@ if ( -! _.contai @@ -256,21 +256,60 @@ s.find(%7B -_id: +%7D);%0A %7D%0A let familyUsersIds = %5B this.use @@ -303,34 +303,33 @@ s = %5Bthis.userId -%7D) +%5D ;%0A %7D%0A @@ -314,33 +314,88 @@ serId%5D;%0A -%7D +findChildren(familyUsersIds, Meteor.users, this.userId); %0A return @@ -405,32 +405,58 @@ eor.users.find(%7B +_id: %7B$in: familyUsersIds%7D %7D);%0A %7D,%0A c @@ -709,12 +709,328 @@ %7D%0A %5D%0A%7D);%0A +%0Afunction findChildren (familyUsersIds, users, parentUserId) %7B%0A const children = users.find(%7B%22profile.parentUserId%22: parentUserId%7D);%0A children && children.forEach(child =%3E %7B%0A const childId = child._id;%0A familyUsersIds.push(childId);%0A findChildren(familyUsersIds, users, childId);%0A %7D);%0A%7D
dcf8ef0086f475f80c7e94737ec637c8a627be79
update tests
lib/template.test.js
lib/template.test.js
'use strict'; var expect = require('chai').expect, sinon = require('sinon'), template = require('./template'), embed = require('./embed'); describe('Template embedding:', function () { var fakeTemplateWithoutData = 'Fake T3mpl4te', fakeTemplateData = {thing: 'stuff!'}, fakeMergedDefaults = {thing: 'stuff!', otherThing: 'more stuff!'}, mock; beforeEach(function () { mock = sinon.mock(embed); }); afterEach(function () { mock.restore(); }); describe('standalone:', function () { it('Handles missing name by returning emptystring', function () { var result = template.embed(); expect(result).to.equal(''); }); it('Renders template with empty data', function () { mock.expects('render').withArgs('jfklda', {}); template.embed(undefined, 'jfklda', undefined); mock.verify(); }); it('Return data in template when piped from calling template', function () { mock.expects('render').withArgs('withData', fakeTemplateData); template.embed(fakeTemplateData, 'withData', {}); mock.verify(); }); it('Return data in template when given from extraData parameter', function () { mock.expects('render').withArgs('withData', fakeTemplateData); template.embed({}, 'withData', fakeTemplateData); mock.verify(); }); it('Data piped from parent has higher priority than extra parameters', function () { mock.expects('render').withArgs('withData', fakeTemplateData); template.embed(fakeTemplateData, 'withData', { thing: 'defaults'}); mock.verify(); }); }); describe('nunjucks filter:', function () { var nunjucks = require('nunjucks'), filter = template.embed, fakeTemplateWithData = 'Fake T3mpl4te {{ thing }}', MockLoader, env; before(function () { MockLoader = nunjucks.Loader.extend({ init: function () {}, async: false, getSource: function (name) { if (name.indexOf('withData') !== -1) { return {src: fakeTemplateWithData}; } else { return {src: fakeTemplateWithoutData}; } } }); //NOTE: Nunjucks is REALLY slow when starting up, so to prevent everyone having to wait for it whenever they run // tests, we'll only be testing using a single copy. Just a warning. nunjucks.configure('views', { watch: false }); env = new nunjucks.Environment(new MockLoader()); }); it('data passed from parent', function () { var template = 'start {{ {thing: "stuff!"} | embed("withData") }}'; mock.expects('render').withArgs('withData', fakeTemplateData); env.addFilter('embed', filter); env.renderString(template); mock.verify(); }); it('empty passed from parent and data passed as default', function () { var template = 'start {{ {} | embed("withData", {thing: "stuff!"}) }}'; mock.expects('render').withArgs('withData', fakeTemplateData); env.addFilter('embed', filter); env.renderString(template); mock.verify(); }); it('data from parent wins', function () { var template = 'start {{ {thing: "stuff!"} | embed("withData", {thing: "not shown"}) }}'; mock.expects('render').withArgs('withData', fakeTemplateData); env.addFilter('embed', filter); env.renderString(template); mock.verify(); }); it('using extraData', function () { var template = 'start {{ {thing: "stuff!"} | embed("withData", {otherThing: "more stuff!"}) }}'; mock.expects('render').withArgs('withData', fakeMergedDefaults); env.addFilter('embed', filter); env.renderString(template); mock.verify(); }); }); describe('jade function:', function () { var jade = require('jade'), locals = { embed: template.embed }; beforeEach(function () { mock = sinon.mock(embed); }); afterEach(function () { mock.restore(); }); it('data passed from parent', function () { var template = 'start #{embed({thing: "stuff!"}, "withData")}'; mock.expects('render').withArgs('withData', fakeTemplateData); jade.render(template, locals); mock.verify(); }); it('empty passed from parent and data passed as default', function () { var template = 'start #{embed({}, "withData", {thing: "stuff!"})}'; mock.expects('render').withArgs('withData', fakeTemplateData); jade.render(template, locals); mock.verify(); }); it('data from parent wins', function () { var template = 'start #{embed({thing: "stuff!"}, "withData", {thing: "not shown"})}'; mock.expects('render').withArgs('withData', fakeTemplateData); jade.render(template, locals); mock.verify(); }); it('using extraData', function () { var template = 'start #{embed({thing: "stuff!"}, "withData", {otherThing: "more stuff!"})}'; mock.expects('render').withArgs('withData', fakeMergedDefaults); jade.render(template, locals); mock.verify(); }); }) });
JavaScript
0.000001
@@ -2564,32 +2564,38 @@ ate = 'start %7B%7B +embed( %7Bthing: %22stuff!%22 @@ -2591,33 +2591,26 @@ g: %22stuff!%22%7D +, -%7C embed( %22withData%22) @@ -2688,46 +2688,8 @@ a);%0A - env.addFilter('embed', filter);%0A @@ -2707,32 +2707,51 @@ rString(template +, %7B embed: filter %7D );%0A mock.ve @@ -2877,20 +2877,19 @@ t %7B%7B - %7B%7D %7C embed( +%7B%7D, %22wit @@ -2994,46 +2994,8 @@ a);%0A - env.addFilter('embed', filter);%0A @@ -3013,32 +3013,51 @@ rString(template +, %7B embed: filter %7D );%0A mock.ve @@ -3142,32 +3142,38 @@ ate = 'start %7B%7B +embed( %7Bthing: %22stuff!%22 @@ -3169,33 +3169,26 @@ g: %22stuff!%22%7D +, -%7C embed( %22withData%22, @@ -3288,46 +3288,8 @@ a);%0A - env.addFilter('embed', filter);%0A @@ -3307,32 +3307,51 @@ rString(template +, %7B embed: filter %7D );%0A mock.ve @@ -3438,16 +3438,22 @@ tart %7B%7B +embed( %7Bthing: @@ -3465,17 +3465,10 @@ f!%22%7D +, -%7C embed( %22wit @@ -3585,46 +3585,8 @@ s);%0A - env.addFilter('embed', filter);%0A @@ -3612,16 +3612,35 @@ template +, %7B embed: filter %7D );%0A
e5cf80318c26e5a46b20a49af3332a8156660a7d
Add gittip:start Grunt task to make sure Gittip is running when we run Karma
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { gruntfile: { files: '<%= jshint.gruntfile %>', tasks: 'jshint:gruntfile' }, js: { files: '<%= jshint.js %>', tasks: ['jshint:js', 'karma:tests:run'] }, tests: { files: '<%= jshint.tests %>', tasks: ['jshint:tests', 'karma:tests:run'] } }, jshint: { gruntfile: 'Gruntfile.js', js: 'js/**/*.{js,json}', tests: 'jstests/**/*.js', options: { jshintrc: '.jshintrc', globals: { Gittip: true, _gttp: true, gttpURI: true, mixpanel: true, alert: true } } }, karma: { tests: { hostname: '0.0.0.0' }, singlerun: { singleRun: true }, options: { browsers: ['PhantomJS'], reporters: 'dots', frameworks: ['mocha', 'browserify'], urlRoot: '/karma/', proxies: { '/': 'http://127.0.0.1:8537/' }, files: [ 'www/assets/jquery-1.8.3.min.js', 'www/assets/%version/utils.js', 'jstests/**/test_*.js', ], browserify: { watch: true }, preprocessors: { 'jstests/**/*.js': ['browserify'] } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('default', ['test']); grunt.registerTask('test', ['jshint', 'karma:singlerun']); };
JavaScript
0.000001
@@ -1,8 +1,81 @@ +var http = require('http');%0Avar spawn = require('child_process').spawn;%0A%0A module.e @@ -2076,16 +2076,32 @@ jshint', + 'gittip:start', 'karma: @@ -2113,12 +2113,960 @@ erun'%5D); +%0A%0A grunt.registerTask('gittip:start', 'Start Gittip test server (if necessary)', function gittipStart() %7B%0A var done = this.async();%0A%0A http.get('http://127.0.0.1:8537/', function(res) %7B%0A grunt.log.writeln('Gittip seems to be running already. Doing nothing.');%0A done();%0A %7D)%0A .on('error', function(e) %7B%0A grunt.log.write('Starting Gittip server...');%0A%0A var started = false;%0A var gittip = spawn('make', %5B'run'%5D);%0A%0A gittip.stdout.setEncoding('utf8');%0A%0A gittip.stdout.on('data', function(data) %7B%0A if (!started && /Greetings, program! Welcome to port 8537%5C./.test(data)) %7B%0A started = true;%0A grunt.log.writeln('started.');%0A done();%0A %7D%0A %7D);%0A%0A process.on('exit', function() %7B%0A gittip.kill();%0A %7D);%0A %7D);%0A %7D); %0A%7D;%0A
03b64e99b7505ea6b69a6ab19c39feb38de9ba69
fix example
examples/websockets.js
examples/websockets.js
var BitfinexWS = require ('bitfinex-api-node').WS; var bws = new BitfinexWS(); bws.on('open', function () { bws.subscribeTrades('BTCUSD'); bws.subscribeOrderBook('BTCUSD'); bws.subscribeTicker('LTCBTC'); }); bws.on('trade', function (pair, trade) { console.log('Trade:', trade); }); bws.on('orderbook', function (pair, book) { console.log('Order book:', book); }); bws.on('ticker', function (pair, ticker) { console.log('Ticker:', ticker); }); bws.on('subscribed', function (data) { console.log('New subscription', data); }); bws.on('error', console.error);
JavaScript
0
@@ -43,11 +43,8 @@ de') -.WS ;%0A%0Av @@ -68,16 +68,19 @@ inexWS() +.ws ;%0A%0Abws.o
09e9e7337793c532e36b9a3bf74cfed9fde6e9e7
add common
test/specs/views/Stastistic/Statistic-test.js
test/specs/views/Stastistic/Statistic-test.js
import React from 'react' import { Statistic } from 'stardust' import faker from 'faker' describe('Statistic', () => { it('renders children', () => { const child = faker.hacker.phrase() deprecatedRender(<Statistic>{child}</Statistic>) .assertText(child) }) describe('Statistics', () => { it('renders children', () => { const child = faker.hacker.phrase() deprecatedRender(<Statistic.Statistics>{child}</Statistic.Statistics>) .assertText(child) }) }) describe('Label', () => { it('renders children', () => { const child = faker.hacker.phrase() deprecatedRender(<Statistic.Label>{child}</Statistic.Label>) .assertText(child) }) }) describe('Value', () => { it('renders children', () => { const child = faker.hacker.phrase() deprecatedRender(<Statistic.Value>{child}</Statistic.Value>) .assertText(child) }) }) })
JavaScript
0.999712
@@ -4,33 +4,61 @@ ort -React from 'react +Statistic from 'src/views/Statistic/Statistic '%0Aimport %7B S @@ -53,18 +53,16 @@ '%0Aimport - %7B Statist @@ -67,18 +67,21 @@ stic - %7D +Label from 's tard @@ -80,233 +80,231 @@ m 's -tardust'%0Aimport faker from 'faker'%0A%0Adescribe('Statistic', () =%3E %7B%0A it('renders children', () =%3E %7B%0A const child = faker.hacker.phrase()%0A deprecatedRender(%3CStatistic%3E%7Bchild%7D%3C/Statistic%3E)%0A .assertText(child)%0A %7D)%0A%0A +rc/views/Statistic/StatisticLabel'%0Aimport StatisticValue from 'src/views/Statistic/StatisticValue'%0Aimport StatisticStatistics from 'src/views/Statistic/StatisticStatistics'%0Aimport * as common from 'test/specs/commonTests'%0A%0A desc @@ -318,17 +318,16 @@ tatistic -s ', () =%3E @@ -335,107 +335,146 @@ %7B%0A - it('renders children', () =%3E %7B%0A const child = faker.hacker.phrase()%0A deprecatedRender(%3C +common.isConformant(Statistic)%0A common.hasUIClassName(StatisticStatistics)%0A common.rendersChildren(Statistic)%0A common.hasSubComponents( Stat @@ -470,33 +470,35 @@ onents(Statistic -. +, %5B Statistics%3E%7Bchil @@ -494,19 +494,15 @@ stic -s%3E%7Bchild%7D%3C/ +Label, Stat @@ -506,17 +506,23 @@ tatistic -. +Value, Statisti @@ -526,54 +526,25 @@ stic -s%3E)%0A .assertText(child)%0A %7D)%0A %7D)%0A%0A +Statistics%5D)%0A%7D)%0A%0A desc @@ -549,16 +549,25 @@ scribe(' +Statistic Label', @@ -580,192 +580,187 @@ %7B%0A - it(' +common.isConformant(Statistic)%0A common. renders - c +C hildren -', () =%3E %7B%0A const child = faker.hacker.phrase()%0A deprecatedRender(%3CStatistic.Label%3E%7Bchild%7D%3C/Statistic.Label%3E)%0A .assertText(child)%0A %7D)%0A +(Statistic)%0A%7D)%0A%0Adescribe('StatisticValue', () =%3E %7B%0A common.isConformant(Statistic)%0A common.rendersChildren(Statistic)%0A %7D)%0A%0A - desc @@ -765,21 +765,26 @@ scribe(' -Value +Statistics ', () =%3E @@ -792,187 +792,138 @@ %7B%0A - it('renders children', () =%3E %7B%0A const child = faker.hacker.phrase()%0A deprecatedRender(%3CStatistic.Value%3E%7Bchild%7D%3C/Statistic.Value%3E)%0A .assertText(child)%0A %7D)%0A %7D +common.isConformant(StatisticStatistics)%0A common.hasUIClassName(StatisticStatistics)%0A common.rendersChildren(StatisticStatistics )%0A%7D)
a8fd7fc03b3659449991b9242e51c9615b69994c
Fix JS unit tests
src/services/conversationsService.spec.js
src/services/conversationsService.spec.js
import mockAxios from '../__mocks__/axios' import { generateOcsUrl } from '@nextcloud/router' import { searchPossibleConversations } from './conversationsService' import { SHARE } from '../constants' describe('conversationsService', () => { afterEach(() => { // cleaning up the mess left behind the previous test mockAxios.reset() }) /** * @param {string} token The conversation to search in * @param {boolean} onlyUsers Whether or not to only search for users * @param {Array} expectedShareTypes The expected search types to look for */ function testSearchPossibleConversations(token, onlyUsers, expectedShareTypes) { searchPossibleConversations( { searchText: 'search-text', token, onlyUsers, }, { dummyOption: true, } ) expect(mockAxios.get).toHaveBeenCalledWith( generateOcsUrl('core/autocomplete/get'), { dummyOption: true, params: { itemId: token, itemType: 'call', search: 'search-text', shareTypes: expectedShareTypes, }, } ) } test('searchPossibleConversations with only users', () => { testSearchPossibleConversations( 'conversation-token', true, [ SHARE.TYPE.USER, ], ) }) test('searchPossibleConversations with other share types', () => { testSearchPossibleConversations( 'conversation-token', false, [ SHARE.TYPE.USER, SHARE.TYPE.GROUP, SHARE.TYPE.CIRCLE, SHARE.TYPE.EMAIL, ], ) }) test('searchPossibleConversations with other share types and a new token', () => { testSearchPossibleConversations( 'new', false, [ SHARE.TYPE.USER, SHARE.TYPE.GROUP, SHARE.TYPE.CIRCLE, ], ) }) })
JavaScript
0
@@ -87,16 +87,69 @@ router'%0A +import %7B loadState %7D from '@nextcloud/initial-state'%0A import %7B @@ -251,48 +251,364 @@ s'%0A%0A -describe('conversationsService', () =%3E %7B +jest.mock('@nextcloud/initial-state', () =%3E (%7B%0A%09loadState: jest.fn(),%0A%7D))%0A%0Adescribe('conversationsService', () =%3E %7B%0A%09let loadStateSettings%0A%0A%09beforeEach(() =%3E %7B%0A%09%09loadStateSettings = %7B%0A%09%09%09federation_enabled: false,%0A%09%09%7D%0A%0A%09%09loadState.mockImplementation((app, key) =%3E %7B%0A%09%09%09if (app === 'spreed') %7B%0A%09%09%09%09return loadStateSettings%5Bkey%5D%0A%09%09%09%7D%0A%09%09%09return null%0A%09%09%7D)%0A%09%7D)%0A %0A%09af
a0f48723c983fe2ce30ab335d43f1aebb0390dbd
task not found
packages/custom/icu/server/controllers/customData.js
packages/custom/icu/server/controllers/customData.js
exports.find = function(req, res, next) { if(req.locals.error) { return next(); } var query = req.acl.mongoQuery('Task'); var queryString = {}; Object.keys(req.query).forEach(function(key) { switch (key) { case 'uid': break; case 'type': queryString['custom.type'] = req.query.type; break; default: queryString[`custom.data.${key}`] = req.query[key]; break; } }); query.find(queryString) .exec(function(err, tasks) { if(err) { req.locals.error = { message: 'Can\'t get my tasks' }; } else { req.locals.result = tasks; } next(); }); }; exports.findByCustomId = function(req, res, next) { if(req.locals.error) { return next(); } var query = req.acl.mongoQuery('Task'); query.findOne({'custom.id': req.params.id}) .exec(function(err, tasks) { if(err) { req.locals.error = { message: 'Can\'t get my tasks' }; } else { req.locals.result = tasks; } next(); }); };
JavaScript
0.999999
@@ -873,33 +873,32 @@ nction(err, task -s ) %7B%0A if(err @@ -889,32 +889,41 @@ ) %7B%0A if(err + %7C%7C !task ) %7B%0A req. @@ -966,32 +966,32 @@ 'Can%5C't get -my +the task -s '%0A %7D; @@ -1030,33 +1030,32 @@ ls.result = task -s ;%0A %7D%0A
dd022ab2deac4df9d6825bd5bf498ec276ffef8e
Remove unnecessary slash
generators/app/templates/routes/users/index.js
generators/app/templates/routes/users/index.js
'use strict'; module.exports = function(app) { var path = require('path'); var ensureAuth = require(path.join(app.rootDir, '/lib/ensureAuth')); var logger = require(path.join(app.rootDir, '/lib/logger')); var User = require(path.join(app.rootDir, '/models')).User; var routeConfig = { GET: { '': [ ensureAuth , all ] , '/:userId': [ ensureAuth , byId ] } , POST: { '/': [ ensureAuth , create ] } , PUT: { '/:userId': [ ensureAuth , update ] } , DELETE: { '/:userId': [ ensureAuth , remove ] } }; return routeConfig; /** * Get A list of the Users * @return {object} body * @swagger * /users: * get: * operationId: listUsersV1 * summary: List Users * produces: * - application/json * tags: * - Users * security: * - Authorization: [] * responses: * 200: * description: Users get all * schema: * type: array * items: * $ref: '#/definitions/User' */ function *all() { var attributes = {}; try { var users = yield User .findAll ( attributes ); this.status = 200; this.body = users; } catch (e) { logger.error('Error: ', e.stack || e); this.status = 500; this.body = { error: true , msg: 'Error returning users' , develeoperMsg: e.message }; } return this.body; } /** * Create a new user * @return {object} body * @swagger * /users: * post: * operationId: createUsersV1 * summary: Creates a new User. * produces: * - application/json * tags: * - Users * security: * - Authorization: [] * parameters: * - name: User * in: body * required: true * schema: * $ref: '#/definitions/NewUser' * responses: * 200: * description: Creates a user * schema: * $ref: '#/definitions/User' */ function *create() { var body = this.request.body; body.level = 1; try { var res = yield User.create(body); this.status = 201; this.body = res; } catch (e) { this.status = 400; this.body = { error: true , msg: e.errors || 'Invalid Input' }; } return this.body; } /** * List a user by id * @return {object} body * @swagger * /users/{userId}: * get: * operationId: listUserByIdV1 * summary: List User by id * parameters: * - name: userId * in: path * type: integer * required: true * description: ID of user to fetch * tags: * - Users * responses: * 200: * description: Users by ID * schema: * $ref: '#/definitions/User' */ function *byId() { if (this.params.userId === 'me') { yield me(this); } else { try { var user = yield User.findById(this.params.userId); this.body = user; } catch (e) { switch (e.name) { case 'TypeError': this.status = 404; break; default: this.status = 500; this.body = { error: true , msg: e.message }; } } } return this.body; } /** * Update a user by id * @return {object} body * @swagger * /users/{userId}: * put: * operationId: updateUserV1 * summary: Update user by id * tags: * - Users * security: * - Authorization: [] * parameters: * - name: userId * in: path * type: integer * required: true * description: User ID * responses: * 200: * description: Update user by id * schema: * $ref: '#/definitions/User' */ function *update() { var body = this.request.body; try { var user = yield User.findById(this.params.userId); if (!user) { user = yield User.find({ where: {id: this.params.userId}, paranoid: false }); } for (let key in body) { if (body.hasOwnProperty(key) && key !== 'id') { user[key] = body[key]; } } if (user.deletedAt && user.isActive) { yield user.restore(); } yield user.save(); this.body = user; } catch (e) { logger.error('Error: ', e.stack); this.status = 500; this.body = { error: true , msg: e.errors || e.message }; } return this.body; } /** * Delete a user by id * @return {object} body * @swagger * /users/{userId}: * delete: * operationId: deleteUserV1 * summary: Remove User by id * tags: * - Users * parameters: * - name: userId * type: integer * in: path * required: true * description: User ID * security: * - Authorization: [] * responses: * 204: * description: Delete user by id */ function *remove() { try { var user = yield User.findById(this.params.userId); if (!user) { this.status = 404; return this.body; } user.isActive = false; yield user.save(); yield User .destroy ( { where: { id: this.params.userId } } ); this.status = 204; this.body = ''; } catch (e) { this.status = 500; this.body = { error: true , msg: e.errors || e.message }; } return this.body; } /** * Get the user * @param {object} that koa this reference * @return {object} body * @swagger * /users/me: * get: * operationId: getMeV1 * summary: Get the current logged in user information * tags: * - Users * security: * - Authorization: [] * responses: * 200: * description: User object * $ref: '#/definitions/User' * 401: * description: Not Authorized * $ref: '#/definitions/GeneralError' */ function *me(that) { var user = yield User.findById(that.auth.id); this.body = user; return this.body; } };
JavaScript
0.000162
@@ -426,17 +426,16 @@ %0A %7B ' -/ ':%0A
7a13b44f1e7381730ab91ce0a55db08dac560682
add modify_json task
Gruntfile.js
Gruntfile.js
const _URL__GRUNT_CONFIG_FILE = './config/grunt.json', _URL__NPM_MANIFEST_FILE = './package.json'; var _gruntRegisterTasks = require('grunt-register-tasks'), _loadGruntTasks = require('load-grunt-tasks'), _timeGrunt = require('time-grunt'); module.exports = function ( $grunt ) { var _$grunt__file = $grunt.file, _$grunt__file__readJSON = _$grunt__file.readJSON, _plugins = [ 'grunt-bump', 'grunt-contrib-*', 'grunt-easy-nodefy', 'grunt-exec', 'grunt-jsonlint', 'grunt-string-replace' ], _config = { 'bump': { 'options': { 'commit': true, 'commitFiles': [ '<%= cfg.PATH__ROOT %>/<%= cfg.GLOB__MANIFESTS %>' ], 'commitMessage': 'bump(version): %VERSION%', 'createTag': false, 'files': '<%= cfg.PATH__ROOT %>/<%= cfg.GLOB__MANIFESTS %>', 'push': true, 'pushTo': 'origin', 'updateConfigs': [ null, 'pkg' ] } }, 'cfg': _$grunt__file__readJSON( _URL__GRUNT_CONFIG_FILE ), 'clean': { 'dist': '<%= cfg.PATH__DIST %>' }, 'copy': { 'src': { 'cwd': '<%= cfg.PATH__SRC %>', 'dest': '<%= cfg.PATH__DIST__AMD %>', 'expand': true, 'src': '<%= cfg.GLOB__JS__RECURSIVE %>' } }, 'exec': { 'commit': 'git commit -m "release(v<%= pkg.version %>): distribute"', 'tag': 'git tag -a v<%= pkg.version %> -m "<%= grunt.option(\'tagMessage\') %>"' }, 'jsonlint': { 'config': '<%= cfg.PATH__CONFIG %>/<%= cfg.GLOB__JSON__RECURSIVE %>', 'manifests': '<%= cfg.PATH__ROOT %>/<%= cfg.GLOB__MANIFESTS %>' }, 'nodefy': { 'src': { 'cwd': '<%= cfg.PATH__SRC %>', 'dest': '<%= cfg.PATH__DIST__CJS %>', 'expand': true, 'src': '<%= cfg.GLOB__JS__RECURSIVE %>' } }, 'string-replace': { 'src': { 'files': [ { 'cwd': '<%= cfg.PATH__DIST %>', 'dest': '<%= cfg.PATH__DIST %>', 'expand': true, 'src': '<%= cfg.GLOB__INDEX_JS__RECURSIVE %>' } ], 'options': { 'replacements': [ { 'pattern': /<%= pkg\.version %>/g, 'replacement': '<%= pkg.version %>' } ] } } }, 'pkg': _$grunt__file__readJSON( _URL__NPM_MANIFEST_FILE ) }, _tasks = { 'build': [ 'default', 'clean', 'copy', 'nodefy', 'string-replace:src' ], 'default': [ 'jsonlint' ], }; _timeGrunt( $grunt ), $grunt.initConfig( _config ), _loadGruntTasks( $grunt, { pattern: _plugins, scope: 'devDependencies' } ), _gruntRegisterTasks( $grunt, _tasks ); };
JavaScript
0.000038
@@ -538,24 +538,55 @@ -jsonlint',%0A + 'grunt-modify-json',%0A 'g @@ -606,16 +606,16 @@ eplace'%0A - @@ -2077,32 +2077,462 @@ %0A %7D,%0A + 'modify_json': %7B%0A 'manifests': %7B%0A 'files': %7B%0A '%3C%25= cfg.PATH__ROOT %25%3E': '%3C%25= cfg.PATH__ROOT %25%3E/%3C%25= cfg.GLOB__MANIFESTS %25%3E'%0A %7D,%0A 'options': %7B%0A 'add': true,%0A 'fields': %7B%0A 'private': false%0A %7D%0A %7D%0A %7D%0A %7D,%0A 'nodef @@ -3746,12 +3746,8 @@ lace -:src '%0A @@ -3807,16 +3807,16 @@ onlint'%0A + @@ -3812,33 +3812,32 @@ t'%0A %5D -, %0A %7D;%0A%0A
a04a877bfe0248eba245a3b4207ba13042cd3b83
remove only-cr code
src/javascript/app/base/binary_loader.js
src/javascript/app/base/binary_loader.js
const BinaryPjax = require('./binary_pjax'); const pages_config = require('./binary_pages'); const Client = require('./client'); const GTM = require('./gtm'); const Header = require('./header'); const Login = require('./login'); const Page = require('./page'); const BinarySocket = require('./socket'); const BinarySocketGeneral = require('./socket_general'); const getElementById = require('../../_common/common_functions').getElementById; const localize = require('../../_common/localize').localize; const isStorageSupported = require('../../_common/storage').isStorageSupported; const urlFor = require('../../_common/url').urlFor; const applyToAllElements = require('../../_common/utility').applyToAllElements; const createElement = require('../../_common/utility').createElement; const BinaryLoader = (() => { let container; let active_script = null; const init = () => { if (!/\.html$/i.test(window.location.pathname)) { window.location.pathname += '.html'; return; } if (!isStorageSupported(localStorage) || !isStorageSupported(sessionStorage)) { Header.displayNotification(localize('[_1] requires your browser\'s web storage to be enabled in order to function properly. Please enable it or exit private browsing mode.', ['Binary.com']), true, 'STORAGE_NOT_SUPPORTED'); getElementById('btn_login').classList.add('button-disabled'); } Page.showNotificationOutdatedBrowser(); Client.init(); BinarySocket.init(BinarySocketGeneral.initOptions()); container = getElementById('content-holder'); container.addEventListener('binarypjax:before', beforeContentChange); container.addEventListener('binarypjax:after', afterContentChange); BinaryPjax.init(container, '#content'); }; const beforeContentChange = () => { if (active_script) { BinarySocket.removeOnDisconnect(); if (typeof active_script.onUnload === 'function') { active_script.onUnload(); } active_script = null; } }; const afterContentChange = (e) => { Page.onLoad(); GTM.pushDataLayer(); if (Client.isLoggedIn() && !Client.hasCostaricaAccount()) { applyToAllElements('.only-cr', (el) => { el.setVisibility(0); }); // Fix issue with tabs. if (/get_started_tabs=lookback/.test(window.location.href)) { BinaryPjax.load(urlFor('get-started')); } } const this_page = e.detail.getAttribute('data-page'); if (this_page in pages_config) { loadHandler(pages_config[this_page]); } else if (/\/get-started\//i.test(window.location.pathname)) { loadHandler(pages_config['get-started']); } }; const error_messages = { login : () => localize('Please [_1]log in[_2] or [_3]sign up[_2] to view this page.', [`<a href="${'javascript:;'}">`, '</a>', `<a href="${urlFor()}">`]), only_virtual: 'Sorry, this feature is available to virtual accounts only.', only_real : 'This feature is not relevant to virtual-money accounts.', }; const loadHandler = (config) => { active_script = config.module; if (config.is_authenticated) { if (!Client.isLoggedIn()) { displayMessage(error_messages.login()); } else { BinarySocket.wait('authorize') .then((response) => { if (response.error) { displayMessage(error_messages.login()); } else if (config.only_virtual && !Client.get('is_virtual')) { displayMessage(error_messages.only_virtual); } else if (config.only_real && Client.get('is_virtual')) { displayMessage(error_messages.only_real); } else { loadActiveScript(config); } }); } } else if (config.not_authenticated && Client.isLoggedIn()) { BinaryPjax.load(Client.defaultRedirectUrl(), true); } else { loadActiveScript(config); } BinarySocket.setOnDisconnect(active_script.onDisconnect); }; const loadActiveScript = (config) => { if (active_script && typeof active_script.onLoad === 'function') { // only pages that call formatMoney should wait for website_status if (config.needs_currency) { BinarySocket.wait('website_status').then(() => { active_script.onLoad(); }); } else { active_script.onLoad(); } } }; const displayMessage = (message) => { const content = container.querySelector('#content .container'); if (!content) { return; } const div_container = createElement('div', { class: 'logged_out_title_container', html: content.getElementsByTagName('h1')[0] }); const div_notice = createElement('p', { class: 'center-text notice-msg', html: localize(message) }); div_container.appendChild(div_notice); content.html(div_container); const link = content.getElementsByTagName('a')[0]; if (link) { link.addEventListener('click', () => { Login.redirectToLogin(); }); } }; return { init, }; })(); module.exports = BinaryLoader;
JavaScript
0.000423
@@ -2429,86 +2429,8 @@ ) %7B%0A - applyToAllElements('.only-cr', (el) =%3E %7B el.setVisibility(0); %7D);%0A
70806256aa1f92805dd675a8fd7c5057bb0cabcc
Add test to ensure selectionWraps can wrap from first to last item.
test/tests/SingleSelectionMixin.tests.js
test/tests/SingleSelectionMixin.tests.js
import * as symbols from '../../src/symbols.js'; import ReactiveMixin from '../../src/ReactiveMixin.js'; import SingleSelectionMixin from '../../src/SingleSelectionMixin.js'; class SingleSelectionTest extends ReactiveMixin(SingleSelectionMixin(HTMLElement)) { get defaultState() { return Object.assign({}, super.defaultState, { items: [] }); } get items() { return this.state.items; } } customElements.define('items-selection-test', SingleSelectionTest); describe("SingleSelectionMixin", () => { let container; before(() => { container = document.getElementById('container'); }); afterEach(() => { container.innerHTML = ''; }); it("has selectedIndex initially -1", () => { const fixture = document.createElement('items-selection-test'); assert.equal(fixture.state.selectedIndex, -1); }); it("can advance the selection to the next item", () => { const fixture = createSampleElement(); assert.equal(fixture.state.selectedIndex, -1); fixture.selectNext(); assert.equal(fixture.state.selectedIndex, 0); fixture.selectNext(); fixture.selectNext(); assert.equal(fixture.state.selectedIndex, 2); fixture.selectNext(); // Moving past last item should have no effect. assert.equal(fixture.state.selectedIndex, 2); }); it("can move the selection to the previous item", () => { const fixture = createSampleElement(); container.appendChild(fixture); fixture.selectPrevious(); assert.equal(fixture.state.selectedIndex, 2); // last item fixture.selectPrevious(); assert.equal(fixture.state.selectedIndex, 1); }); it("can wrap the selection from the last to the first item", () => { const fixture = createSampleElement(); fixture.selectionWraps = true; fixture.setState({ selectedIndex: 2 }); fixture.selectNext(); assert.equal(fixture.state.selectedIndex, 0); }); it("selects first item when selection is required and no item is currently selected", async () => { const fixture = createSampleElement(); assert.equal(fixture.state.selectedIndex, -1); await fixture.setState({ selectionRequired: true }); fixture.render(); assert.equal(fixture.state.selectedIndex, 0); }); it("selects nearest item when item in last place is removed", async () => { const fixture = createSampleElement(); const items = fixture.items.slice(); items.splice(2, 1); await fixture.setState({ items, selectedIndex: 2 }); fixture.render(); assert.equal(fixture.state.selectedIndex, 1); }); it("drops selection when the last item is removed", async () => { const fixture = createSampleElement(); await fixture.setState({ items: [], selectedIndex: 0 }); fixture.render(); assert.equal(fixture.state.selectedIndex, -1); }); it("sets canSelectNext/canSelectPrevious with no wrapping", () => { const fixture = createSampleElement(); assert(!fixture.selectionWraps); // No selection yet assert.equal(fixture.state.selectedIndex, -1); assert(fixture.canSelectNext); assert(fixture.canSelectPrevious); // Start of list fixture.selectFirst(); assert(fixture.canSelectNext); assert(!fixture.canSelectPrevious); // Middle of list fixture.selectNext(); assert(fixture.canSelectNext); assert(fixture.canSelectPrevious); // End of list fixture.selectLast(); assert(!fixture.canSelectNext); assert(fixture.canSelectPrevious); }); it("sets canSelectNext/canSelectPrevious with wrapping", () => { const fixture = createSampleElement(); fixture.selectionWraps = true; // Start of list fixture.selectFirst(); assert(fixture.canSelectNext); assert(fixture.canSelectPrevious); // End of list fixture.selectLast(); assert(fixture.canSelectNext); assert(fixture.canSelectPrevious); }); it("changing selection through (simulated) user interaction raises the selected-index-changed event", done => { const fixture = createSampleElement(); fixture.addEventListener('selected-index-changed', () => { done(); }); container.appendChild(fixture); fixture[symbols.raiseChangeEvents] = true; // Simulate user interaction fixture.selectedIndex = 1; fixture[symbols.raiseChangeEvents] = false; }); it("changing selection programmatically does not raise the selected-index-changed event", done => { const fixture = createSampleElement(); fixture.addEventListener('selected-index-changed', () => { assert.fail(null, null, 'selected-index-changed event should not have been raised in response to programmatic property change'); }); container.appendChild(fixture); fixture.selectedIndex = 1; // This should not trigger events. // Give event handler a chance to run (but it shouldn't). setTimeout(done); }); it("adds selected calculation to itemCalcs", () => { const fixture = createSampleElement(); const items = fixture.items; // Start of list fixture.selectFirst(); assert(fixture.itemCalcs(items[0], 0).selected); assert(!fixture.itemCalcs(items[1], 1).selected); assert(!fixture.itemCalcs(items[2], 2).selected); // End of list fixture.selectLast(); assert(!fixture.itemCalcs(items[0], 0).selected); assert(!fixture.itemCalcs(items[1], 1).selected); assert(fixture.itemCalcs(items[2], 2).selected); }); }); /** * @returns {SingleSelectionTest} */ function createSampleElement() { const fixture = document.createElement('items-selection-test'); // To keep this unit test collection focus on selection, and not on tracking // children as items, we just use a plain array of item objects instead. fixture.setState({ items: ['Zero', 'One', 'Two'] }); return fixture; }
JavaScript
0
@@ -1898,32 +1898,312 @@ dex, 0);%0A %7D);%0A%0A + it(%22can wrap the selection from the first to the last item%22, () =%3E %7B%0A const fixture = createSampleElement();%0A fixture.selectionWraps = true;%0A fixture.setState(%7B selectedIndex: 0 %7D);%0A fixture.selectPrevious();%0A assert.equal(fixture.state.selectedIndex, 2);%0A %7D);%0A%0A it(%22selects fi
b058efcc2979b3c96b4789f1b36aca367e5ed8b6
Call error_messages() error in function itself rather than passing it
src/javascript/app/base/binary_loader.js
src/javascript/app/base/binary_loader.js
const BinaryPjax = require('./binary_pjax'); const pages_config = require('./binary_pages'); const Client = require('./client'); const Header = require('./header'); const NetworkMonitor = require('./network_monitor'); const Page = require('./page'); const BinarySocket = require('./socket'); const ContentVisibility = require('../common/content_visibility'); const GTM = require('../../_common/base/gtm'); const Login = require('../../_common/base/login'); const getElementById = require('../../_common/common_functions').getElementById; const urlLang = require('../../_common/language').urlLang; const localizeForLang = require('../../_common/localize').forLang; const localize = require('../../_common/localize').localize; const ScrollToAnchor = require('../../_common/scroll_to_anchor'); const isStorageSupported = require('../../_common/storage').isStorageSupported; const ThirdPartyLinks = require('../../_common/third_party_links'); const urlFor = require('../../_common/url').urlFor; const createElement = require('../../_common/utility').createElement; const BinaryLoader = (() => { let container; let active_script = null; const init = () => { if (!/\.html$/i.test(window.location.pathname)) { window.location.pathname += '.html'; return; } if (!isStorageSupported(localStorage) || !isStorageSupported(sessionStorage)) { Header.displayNotification(localize('[_1] requires your browser\'s web storage to be enabled in order to function properly. Please enable it or exit private browsing mode.', 'Binary.com'), true, 'STORAGE_NOT_SUPPORTED'); getElementById('btn_login').classList.add('button-disabled'); } localizeForLang(urlLang()); Page.showNotificationOutdatedBrowser(); Client.init(); NetworkMonitor.init(); container = getElementById('content-holder'); container.addEventListener('binarypjax:before', beforeContentChange); container.addEventListener('binarypjax:after', afterContentChange); BinaryPjax.init(container, '#content'); ThirdPartyLinks.init(); }; const beforeContentChange = () => { if (active_script) { BinarySocket.removeOnDisconnect(); if (typeof active_script.onUnload === 'function') { active_script.onUnload(); } active_script = null; } ScrollToAnchor.cleanup(); }; const afterContentChange = (e) => { Page.onLoad(); GTM.pushDataLayer({ event: 'page_load' }); const this_page = e.detail.getAttribute('data-page'); if (this_page in pages_config) { loadHandler(pages_config[this_page]); } else if (/\/get-started\//i.test(window.location.pathname)) { loadHandler(pages_config['get-started']); } ContentVisibility.init(); ScrollToAnchor.init(); }; const error_messages = { login : () => localize('Please [_1]log in[_2] or [_3]sign up[_4] to view this page.', [`<a href="${'javascript:;'}">`, '</a>', `<a href="${urlFor('new-account')}">`, '</a>']), only_virtual : () => localize('Sorry, this feature is available to virtual accounts only.'), only_real : () => localize('This feature is not relevant to virtual-money accounts.'), not_authenticated: () => localize('This page is only available to logged out clients.'), }; const loadHandler = (config) => { active_script = config.module; if (config.is_authenticated) { if (!Client.isLoggedIn()) { displayMessage(error_messages.login()); } else { BinarySocket.wait('authorize') .then((response) => { if (response.error) { displayMessage(error_messages.login()); } else if (config.only_virtual && !Client.get('is_virtual')) { displayMessage(error_messages.only_virtual()); } else if (config.only_real && Client.get('is_virtual')) { displayMessage(error_messages.only_real()); } else { loadActiveScript(config); } }); } } else if (config.not_authenticated && Client.isLoggedIn()) { handleNotAuthenticated(error_messages.not_authenticated()); } else { loadActiveScript(config); } BinarySocket.setOnDisconnect(active_script.onDisconnect); }; const loadActiveScript = (config) => { if (active_script && typeof active_script.onLoad === 'function') { // only pages that call formatMoney should wait for website_status if (config.needs_currency) { BinarySocket.wait('website_status').then(() => { active_script.onLoad(); }); } else { active_script.onLoad(); } } }; const displayMessage = (localized_message) => { const content = container.querySelector('#content .container'); if (!content) { return; } const div_container = createElement('div', { class: 'logged_out_title_container', html: content.getElementsByTagName('h1')[0] }); const div_notice = createElement('p', { class: 'center-text notice-msg', html: localized_message }); div_container.appendChild(div_notice); content.html(div_container); const link = content.getElementsByTagName('a')[0]; if (link) { link.addEventListener('click', () => { Login.redirectToLogin(); }); } }; const handleNotAuthenticated = (localized_message) => { const content = container.querySelector('#content .container'); if (!content) { return; } const rowDiv = (element) => { const row_element = createElement('div', { class: 'gr-padding-10' }); row_element.appendChild(element); return row_element; }; const container_element = createElement('div', { class: 'center-text' }); const error_msg = createElement('div', { class: 'center-text notice-msg', text: localized_message }); const logout_cta = createElement('button'); const logout_span = createElement('span', { text: localize ('Sign out') }); logout_cta.addEventListener('click', () => { Client.doLogout({ logout: 1 }); }); logout_cta.appendChild(logout_span); container_element.appendChild(rowDiv(error_msg)); container_element.appendChild(rowDiv(logout_cta)); content.append(container_element); }; return { init, }; })(); module.exports = BinaryLoader;
JavaScript
0.000001
@@ -4670,42 +4670,8 @@ ted( -error_messages.not_authenticated() );%0A @@ -5997,33 +5997,16 @@ ated = ( -localized_message ) =%3E %7B%0A @@ -6510,33 +6510,50 @@ , text: -localized_message +error_messages.not_authenticated() %7D);%0A
b0addc41bb961ff76a53a0c382e3b0d192b79051
add test on graph state
test/unit/graph/controller/state-spec.js
test/unit/graph/controller/state-spec.js
const expect = require('chai').expect; const G6 = require('../../../../src'); const div = document.createElement('div'); div.id = 'state-controller'; document.body.appendChild(div); describe('graph state controller', () => { const graph = new G6.Graph({ container: div, width: 500, height: 500 }); const data = { nodes: [ { id: 'node1', x: 100, y: 100 }, { id: 'node2', x: 120, y: 80 }, { id: 'node3', x: 150, y: 150 } ], edges: [ { id: 'edge1', source: 'node1', target: 'node2' }, { id: 'edge2', source: 'node1', target: 'node3' } ] }; graph.read(data); it('set item state', done => { let graphCount = 0, itemCount = 0; graph.on('graphstatechange', () => { graphCount += 1; }); graph.on('beforeitemstatechange', () => { itemCount += 1; }); graph.setItemState('node1', 'selected', true); setTimeout(() => { expect(itemCount).to.equal(1); expect(graphCount).to.equal(1); expect(graph.get('states').selected).not.to.be.undefined; expect(graph.get('states').selected.length).to.equal(1); expect(graph.get('states').selected[0]).to.equal(graph.findById('node1')); graph.setItemState('node1', 'selected', false); graph.setItemState('node1', 'selected', true); graph.setItemState('node2', 'selected', true); graph.setItemState('node3', 'selected', true); setTimeout(() => { expect(itemCount).to.equal(5); expect(graphCount).to.equal(2); expect(graph.get('states').selected.length).to.equal(3); graph.setItemState('node1', 'selected', false); graph.setItemState('node2', 'selected', false); graph.setItemState('node3', 'selected', false); setTimeout(() => { expect(graph.get('states').selected.length).to.equal(0); done(); }, 50); }, 50); }, 50); }); it('state with behavior', done => { graph.removeEvent(); graph.addBehaviors('activate-relations', 'default'); let triggered = false; graph.emit('node:mouseenter', { item: graph.findById('node1') }); setTimeout(() => { graph.emit('node:mouseenter', { item: graph.findById('node2') }); triggered = true; }, 50); graph.on('graphstatechange', e => { if (!triggered) { expect(e.states.active).not.to.be.undefined; expect(e.states.active.length).to.equal(5); expect(e.states.inactive).not.to.be.undefined; expect(e.states.inactive.length).to.equal(0); } else { expect(e.states.active).not.to.be.undefined; expect(e.states.active.length).to.equal(3); expect(e.states.inactive).not.to.be.undefined; expect(e.states.inactive.length).to.equal(2); done(); } }); }); });
JavaScript
0.000008
@@ -1932,16 +1932,26 @@ ith -behavior +activate-relations ', d @@ -2714,32 +2714,32 @@ o.be.undefined;%0A - expect(e @@ -2768,32 +2768,873 @@ h).to.equal(2);%0A + graph.removeBehaviors('activate-relations', 'default');%0A done();%0A %7D%0A %7D);%0A %7D);%0A it('state with click-select', done =%3E %7B%0A graph.removeEvent();%0A graph.addBehaviors('click-select', 'default');%0A graph.emit('keydown', %7B keyCode: 17 %7D);%0A graph.emit('node:click', %7B item: graph.findById('node1') %7D);%0A graph.emit('node:click', %7B item: graph.findById('node2') %7D);%0A let finished = false;%0A setTimeout(() =%3E %7B%0A graph.emit('node:click', %7B item: graph.findById('node2') %7D);%0A finished = true;%0A %7D, 50);%0A graph.on('graphstatechange', e =%3E %7B%0A if (!finished) %7B%0A expect(e.states.selected).not.to.be.undefined;%0A expect(e.states.selected.length).to.equal(2);%0A %7D else %7B%0A expect(e.states.selected).not.to.be.undefined;%0A expect(e.states.selected.length).to.equal(1);%0A done();%0A
2d011a160fda77ac5da83352ce5dccfd98465f8a
Remove 'travelogue' dependency
hapi/data.js
hapi/data.js
'use strict'; var generatorData = { hapiDependencies: { 'catbox' : { moduleName: 'catbox', description: 'Multi-strategy object caching service' }, 'flod' : { moduleName: 'flod', description: 'A systematic toolchain for benchmarking and comparing Node.js web server ' + 'frameworks' }, 'joi' : { moduleName: 'joi', description: 'Object schema description language and validator for JavaScript objects' }, 'shot' : { moduleName: 'shot', description: 'Injects a fake HTTP request/response into a node HTTP server for simulating ' + 'server logic' }, 'travelogue' : { moduleName: 'travelogue', description: 'Passport.js integration for hapi' }, 'yar' : { moduleName: 'yar', description: 'A hapi session plugin and cookie jar' } }, extDependencies: { 'lodash' : { moduleName: 'lodash' }, 'moment' : { moduleName: 'moment' }, 'mongojs' : { moduleName: 'mongojs' }, 'q' : { moduleName: 'q' }, 'redis' : { moduleName: 'redis' }, 'request' : { moduleName: 'request' }, 'winston' : { moduleName: 'winston' }, 'xml2json': { moduleName: 'xml2json' } }, defaultConfig: { basicInfo: { name: '', description: '', version: '0.0.1', author: 'Capgemini Innovation', repo: '', license: '', pathPrefix: '', serverPort: 50000, quickInstall: false }, hapiDependencies: { hapiVersion: 'latest', hapiDepend: [ 'catbox', 'joi' ] }, extDependencies: { extDepend: [ 'lodash', 'request', 'q', 'redis', 'winston' ] } } }; module.exports = generatorData;
JavaScript
0.002068
@@ -52,16 +52,109 @@ cies: %7B%0A +%09%09'bell' : %7B%0A%09%09%09moduleName: 'bell',%0A%09%09%09description: 'Third-party login plugin for hapi'%0A%09%09%7D,%0A %09%09'catbo @@ -156,24 +156,24 @@ catbox' : %7B%0A - %09%09%09moduleNam @@ -397,16 +397,128 @@ s'%0A%09%09%7D,%0A +%09%09'hapi-auth-cookie' : %7B%0A%09%09%09moduleName: 'hapi-auth-cookie',%0A%09%09%09description: 'Cookie authentication plugin'%0A%09%09%7D,%0A %09%09'joi' @@ -767,24 +767,24 @@ ulating ' +%0A + %09%09%09'server l @@ -798,112 +798,8 @@ %09%7D,%0A -%09%09'travelogue' : %7B%0A%09%09%09moduleName: 'travelogue',%0A%09%09%09description: 'Passport.js integration for hapi'%0A%09%09%7D,%0A %09%09'y @@ -1733,8 +1733,9 @@ torData; +%0A
d914f68c73ee16c17f44c3c104077e2407f0169c
support dynamic nodes for Form component
src/components/Form.js
src/components/Form.js
var React = require('react/addons'); module.exports = React.createClass({ displayName: 'Form', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, type: React.PropTypes.oneOf(['horizontal', 'inline']) }, render() { var className = this.props.type ? ('Form--' + this.props.type) : null; return <form {...this.props} className={className} />; } });
JavaScript
0
@@ -1,12 +1,90 @@ +var blacklist = require('blacklist');%0Avar classnames = require('classnames');%0A var React = @@ -329,152 +329,335 @@ %7D,%0A%09 -render() %7B%0A%09%09var className = this.props.type ? ('Form--' + this.props.type) : null;%0A%09%09return %3Cform %7B...this.props%7D className=%7BclassName%7D /%3E +getDefaultProps () %7B%0A%09%09return %7B%0A%09%09%09component: 'form',%0A%09%09%09type: 'basic'%0A%09%09%7D;%0A%09%7D,%0A%09render() %7B%0A%09%09var props = blacklist(this.props, 'children', 'type');%0A%09%09props.className = classnames('Form', ('Form--' + this.props.type), this.props.className);%0A%09%09%0A%09%09return React.createElement(this.props.component, props, this.props.children) ;%0A%09%7D%0A%7D); %0A @@ -655,9 +655,8 @@ ;%0A%09%7D%0A%7D); -%0A
4f7cb7747d5796f2ebd4801f5b57a7d2afa2e5b5
update initiatives tests
analysis/test/js/spec/services/initiatives.js
analysis/test/js/spec/services/initiatives.js
'use strict'; describe('Service: Initiatives', function () { // instantiate service var Initiatives, $httpBackend, $rootScope; // load the service's module beforeEach(module('sumaAnalysis')); beforeEach(inject(function (_$rootScope_, _$httpBackend_, _initiatives_) { $rootScope = _$rootScope_; $httpBackend = _$httpBackend_; Initiatives = _initiatives_; })); it('should make an AJAX call', function (done) { $httpBackend.whenGET('lib/php/initiatives.php').respond([{}, {}]); Initiatives.get().then(function (result) { expect(result.length).to.equal(2); done(); }); $httpBackend.flush(); }); });
JavaScript
0
@@ -622,24 +622,380 @@ );%0A %7D);%0A%0A + $httpBackend.flush();%0A %7D);%0A%0A it('should respond with error message on failure', function (done) %7B%0A $httpBackend.whenGET('lib/php/initiatives.php').respond(500, %7Bmessage: 'Error'%7D);%0A%0A Initiatives.get().then(function (result) %7B%0A%0A %7D, function (result) %7B%0A expect(result).to.deep.equal(%7Bmessage: 'Error', code: 500%7D);%0A done();%0A %7D);%0A%0A $httpBac
99af2fd0963001d958b22b2536292c43cdb051f2
add hash for vendor chunks
.core/webpack/vendor.js
.core/webpack/vendor.js
const path = require('path'); const webpack = require('webpack'); module.exports = function(env) { return { entry: { react: [ 'react', 'react-dom', 'react-helmet', 'react-redux', 'react-router', 'react-router-redux', 'react-router-scroll', 'react-apollo', 'recompose', 'redux', ], utils: [ 'apollo-client', 'classnames', 'es6-promise', 'graphql-tag', 'immutability-helper', 'isomorphic-fetch', ], }, output: { filename: 'vendor-[name].js', path: path.join(process.cwd(), 'static', 'build'), library: '[name]_lib', }, plugins: [ new webpack.DllPlugin({ path: path.join(process.cwd(), 'static', 'build', 'vendor-[name]-manifest.json'), name: '[name]_lib', }), ], } }
JavaScript
0.000001
@@ -601,16 +601,23 @@ r-%5Bname%5D +-%5Bhash%5D .js',%0A @@ -834,16 +834,23 @@ manifest +-%5Bhash%5D .json'),
f6bb7aa8f04c5b8a27469d5e52b947f96f8acde0
add post data to setup for e2e tests
tests/cucumber/features/support/hooks.js
tests/cucumber/features/support/hooks.js
(function () { 'use strict'; module.exports = function () { this.Before(function () { this.server.call('addUsers'); }); }; })();
JavaScript
0
@@ -125,16 +125,51 @@ sers');%0A + this.server.call('addPost');%0A %7D);%0A
88ca152be79b78f6e94bdd2d89c10d45310bbea8
Add the ability to hash lists of strings #2027
src/util/hash.js
src/util/hash.js
let hashIterableInts = function( iterator, seed = 5381 ){ // djb2/string-hash let hash = seed; let entry; for( ;; ){ entry = iterator.next(); if( entry.done ){ break; } hash = (hash * 33) ^ entry.value; } return hash >>> 0; }; let hashString = function( str, seed ){ let entry = { value: 0, done: false }; let i = 0; let length = str.length; let iterator = { next(){ if( i < length ){ entry.value = str.charCodeAt(i++); } else { entry.done = true; } return entry; } }; return hashIterableInts( iterator, seed ); }; module.exports = { hashIterableInts, hashString };
JavaScript
0.000049
@@ -599,16 +599,342 @@ );%0A%7D;%0A%0A +let hashStrings = function()%7B%0A return hashStringsArray( arguments );%0A%7D;%0A%0Alet hashStringsArray = function( strs )%7B%0A let hash;%0A%0A for( let i = 0; i %3C strs.length; i++ )%7B%0A let str = strs%5Bi%5D;%0A%0A if( i === 0 )%7B%0A hash = hashString( str );%0A %7D else %7B%0A hash = hashString( str, hash );%0A %7D%0A %7D%0A%0A return hash;%0A%7D;%0A%0A module.e @@ -972,12 +972,43 @@ shString +, hashStrings, hashStringsArray %7D;%0A
645ea9ab57832b36a28cfa75103d4637ccbb878d
Update app.js
00-workspace/app.js
00-workspace/app.js
// SET UP THE MAP var mapProjection = new ol.proj.Projection({ code: 'EPSG:3857', extent: [-20037508, -20037508, 20037508, 20037508.34] }) var geoProjection = new ol.proj.Projection({ code: 'EPSG:4326', extent: [-180, -180, 180, 180] }) var map = new ol.Map({ layers:[ new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'https://api.mapbox.com/styles/v1/mapbox/outdoors-v10/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoid2lsbC1icmVpdGtyZXV0eiIsImEiOiItMTJGWEF3In0.HEvuRMMVxBVR5-oDYvudxw' }) }) ], target: 'map', view: new ol.View({ center: ol.proj.transform([-96, 39], geoProjection, mapProjection), zoom: 5 }) }); var app = { mapzenKey: 'mapzen-CpAANqF', activeSearch: 'from', typeAhead: function(e){ var el = e.target; var val = el.value; console.log(val); }, queryAutocomplete: throttle(function(){},150) } $('#search-from-input').on('keyup', {input:'from'}, app.typeAhead);
JavaScript
0.000002
@@ -878,18 +878,268 @@ unction( +text, callback)%7B%0A $.ajax(%7B%0A %09url: 'https://search.mapzen.com/vi/autocomplete?text=' + text + '@api_key=' + %09%09%09%09%09app.mapzenKey, %0A success: function(data, status, req)%7Bcallback(null, data)%7D, %0A error: function(req, status, err)%7Bcallback(err)%7D%0A %7D ) -%7B %7D,150)%0A%7D
88b43a857f3959550ee387008245f8c6fc799037
add autocomplete function
00-workspace/app.js
00-workspace/app.js
// SET UP THE MAP var mapProjection = new ol.proj.Projection({ code: 'EPSG:3857', extent: [-20037508, -20037508, 20037508, 20037508.34] }) var geoProjection = new ol.proj.Projection({ code: 'EPSG:4326', extent: [-180, -180, 180, 180] }) var map = new ol.Map({ layers:[ new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'https://api.mapbox.com/styles/v1/mapbox/outdoors-v10/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoid2lsbC1icmVpdGtyZXV0eiIsImEiOiItMTJGWEF3In0.HEvuRMMVxBVR5-oDYvudxw' }) }) ], target: 'map', view: new ol.View({ center: ol.proj.transform([-96, 39], geoProjection, mapProjection), zoom: 5 }) }); var app = { mapzenKey: 'mapzen-CpAANqF', activeSearch: 'from', typeAhead: function(e){ var el = e.target; var val = el.value; console.log(val); } }; $('#search-from-input').on('keyup', {input:'from'}, app.typeAhead);
JavaScript
0.000005
@@ -683,11 +683,8 @@ = %7B%0A - %0A @@ -713,16 +713,16 @@ ANqF', %0A + acti @@ -829,31 +829,455 @@ -console.log(val);%0A %7D +app.queryAutocomplete(val, function(err, data)%7B%0A %09console.log(data;%0A %7D%0A %7D,%0A %0A %09queryAutocomplete: throttle(function(text, callback)%7B%0A $.ajax(%7B%0A %09url: 'https://search.mapzen.com/v1/autocomplete?text=' + text + '&api_key=' + app.mapzenKey,%0A success: function(data, status, req)%7B%0A %09callback(null, data);%0A %7D,%0A error: function(req, status, err)%7B%0A %09callback(err)%0A %7D%0A %7D)%0A %7D, 150) %0A%7D;%0A
3f91980266c983a0920c94cf68b8100070937797
Fix colors in ProgressBoard
app/components/ProgressBoard/ProgressBoard.js
app/components/ProgressBoard/ProgressBoard.js
/* @flow */ import React, { Component } from 'react'; import { Text, View, StyleSheet, } from 'react-native'; import styles from './styles' function Tile(props: {num: string, winner: ?number}){ let backgroundColor: string = 'transparent' if(typeof props.winner === 'number'){ backgroundColor = ['red', 'blue'][props.winner] } return( <View style={StyleSheet.flatten([styles.scoreBoardNumberContainer,{backgroundColor: backgroundColor}])}> <Text style={styles.standingText}>{props.num}</Text> </View> ) } class ProgressBoard extends Component { render(){ return( <View style={styles.container}> <View style={styles.scoreBoardContainer}> <Tile num="1" winner={this.props.score[0]}/> <Tile num="2" winner={this.props.score[1]}/> <Tile num="3" winner={this.props.score[2]}/> <Tile num="4" winner={this.props.score[3]}/> <Tile num="5" winner={this.props.score[4]}/> </View> <View style={styles.scoreBoardContainer}> <Tile num="6" winner={this.props.score[5]}/> <Tile num="7" winner={this.props.score[6]}/> <Tile num="8" winner={this.props.score[7]}/> <Tile num="9" winner={this.props.score[8]}/> <Tile num="10" winner={this.props.score[9]}/> </View> <View style={styles.scoreBoardContainer}> <Tile num="11" winner={this.props.score[10]}/> <Tile num="12" winner={this.props.score[11]}/> <Tile num="13" winner={this.props.score[12]}/> <Tile num="14" winner={this.props.score[13]}/> <Tile num="15" winner={this.props.score[14]}/> </View> </View> ); } }; export default ProgressBoard
JavaScript
0.000001
@@ -309,19 +309,22 @@ = %5B' -red', 'blue +skyblue', 'red '%5D%5Bp
8259742e3d7c9a3b8c66b88910a4ca4c2a6a7f88
use isolate scope for metricPicker dir
app/directives/metric-picker/metric-picker.js
app/directives/metric-picker/metric-picker.js
angular.module(PKG.name + '.commons') .directive('myMetricPicker', function (MyDataSource) { var dSrc = new MyDataSource(); function MetricPickerCtrl ($scope) { var a = ['system', 'user']; $scope.available = { types: a, contexts: [], metrics: [] }; $scope.metric = { type: a[0], context: '', name: '' }; } return { restrict: 'E', require: 'ngModel', scope: true, templateUrl: 'metric-picker/metric-picker.html', controller: MetricPickerCtrl, link: function (scope, elem, attr, ngModel) { function fetchAhead () { var v = (scope.metric.context||'').replace(/\.$/, ''), u = ['/metrics', scope.metric.type, v].join('/'); dSrc.request( { _cdapNsPath: u + '?search=childContext' }, function (r) { scope.available.contexts = r.map(function (c) { return v ? v + '.' + c : c; }); } ); if(v) { // assigning the promise directly works // only because results are used as is. scope.available.metrics = dSrc.request( { _cdapNsPath: u + '/metrics' } ); } else { scope.available.metrics = []; } } var s = ngModel.$setTouched.bind(ngModel); elem.find('button').on('blur', s); elem.find('input').on('blur', s); scope.$watchCollection('metric', function (newVal, oldVal) { ngModel.$validate(); if(newVal.type !== oldVal.type) { scope.metric.context = ''; scope.metric.name = ''; fetchAhead(); return; } if(newVal.context !== oldVal.context) { scope.metric.name = ''; fetchAhead(); } if(newVal.context && newVal.name) { var m = [ '/metrics', newVal.type, ]; if(newVal.context) { m.push(newVal.context); } m.push(newVal.name); ngModel.$setViewValue(m.join('/')); } else { if(ngModel.$dirty) { ngModel.$setViewValue(null); } } }); fetchAhead(); } }; });
JavaScript
0
@@ -477,12 +477,10 @@ pe: -true +%7B%7D ,%0A%0A
c33b3048cb1b30d2babd9d5514f2d3c7c6d008ec
add logs
command-server.js
command-server.js
#!/usr/bin/env node /** * Created on 12/5/15. * @author rankun203 */ var express = require('express'); var bodyParser = require('body-parser'); var exec = require('child_process').exec; var log = require('log4js').getLogger('command-server'); var rawBody = require('./rawBody'); var commands = require('./commands'); var app = express(); app.use(rawBody); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({extended: false})); // parse application/json app.use(bodyParser.json()); // parse application/vnd.api+json as json app.use(bodyParser.json({type: 'application/vnd.api+json'})); // print all request info app.all('/o', function (req, res, next) { log.debug(req.url); log.debug(req.body); // populated! res.status(200).json({ code: 0, msg: 'success' }); }); // execute a command app.all('/c/:cid', function (req, res, next) { var cid = req.params.cid; var filteredCommands = commands.filter(function (command) { return command.id === cid }); // If there is no valid command if (filteredCommands.length === 0) { next(); } // extract command var command = filteredCommands[0]; // If there is a test, execute it if (command.test) { var testReg = new RegExp(command.test); var matches = testReg.test(req.rawBody); if (!matches) return res.json({ code: -2, msg: 'not match' }); } // execute log.debug('execute cmd: id=', command.id, 'command=', command.command); exec(command.command, function (error, stdout, stderr) { if (error) log.error('error', error); log.debug(stdout); log.debug(stderr); }); // notify the caller return res.status(200).json({ code: 0, msg: 'Executing...', command: command }); }); // 404 app.use(function (req, res, next) { res.status(404); return res.json({ code: -1, msg: '404' }); }); var port = 1394; var server = app.listen(port, function () { log.debug('Listening... :', port); });
JavaScript
0
@@ -925,16 +925,57 @@ s.cid;%0A%0A + log.debug('Incoming command: ', cid);%0A%0A var fi @@ -1361,16 +1361,68 @@ wBody);%0A + var msg = 'Not match';%0A%0A log.debug(msg);%0A if ( @@ -1480,19 +1480,11 @@ sg: -'not match' +msg %0A
efffabf76cdb52249cf07bc1b13b9971888ed33c
Disable cleaning build/ dir before building
metalsmith.js
metalsmith.js
const argv = require("yargs").argv; const Metalsmith = require("metalsmith"); const superstatic = require("superstatic").server; const watch = require("metalsmith-watch"); const metalsmith = new Metalsmith(__dirname); const server = superstatic({ port: 8000, cwd: __dirname, config: { public: "./build" } }); metalsmith.source("website") .use(argv.watch && watch({ log: _ => { } })) .build((err, files) => { if (err) { console.error(err); return; } if (!argv.serve) { return; } server.listen(e => { if (e) { console.error("Server error"); console.error(e); return; } console.log("Server started on port 8000"); }); });
JavaScript
0
@@ -356,16 +356,29 @@ ebsite%22) +.clean(false) %0A .us
d819ab6207d71bf01c4592b9b0e39e8dd1b25377
Clear income fields before setting them - otherwise we get 0.000 or 0.000.00
tests/nightwatch/specs/outgoings-page.js
tests/nightwatch/specs/outgoings-page.js
'use strict'; var util = require('util'); var common = require('../modules/common-functions'); var OUTGOINGS_QUESTIONS = require('../modules/constants').OUTGOINGS_QUESTIONS; module.exports = { 'Start page': common.startPage, 'Categories of law (Your problem)': common.selectDebtCategory, 'About you': function(client) { common.aboutPage(client); common.aboutPageSetAllToNo(client); client.submitForm('form'); }, 'Income': function(client) { client .waitForElementVisible('form[action="/income"]', 2000) .assert.urlContains('/income') .assert.containsText('h1', 'Your money coming in') .setValue('input[name="your_income-maintenance-per_interval_value"]', 0) .setValue('input[name="your_income-pension-per_interval_value"]', 0) .setValue('input[name="your_income-other_income-per_interval_value"]', 0) .submitForm('form') ; }, 'Outgoings': function(client) { client .waitForElementVisible('form[action="/outgoings"]', 2000) .assert.urlContains('/outgoings') .assert.containsText('h1', 'Your outgoings') ; }, 'Childcare fields': function(client) { client .assert.hidden('input[name="childcare-per_interval_value"]') .assert.hidden('input[name="childcare-interval_period"]') .back() .waitForElementPresent('form[action="/income"]', 2000) .back() .waitForElementPresent('form[action="/about"]', 2000) ; common.setYesNoFields(client, 'have_children', 1); client .setValue('input[name="num_children"]', 1) .submitForm('form') .waitForElementVisible('form[action="/benefits-tax-credits"]', 2000) ; common.setYesNoFields(client, 'other_benefits', 0); client .setValue('input[name="child_benefit-per_interval_value"]', 0) .setValue('input[name="child_tax_credit-per_interval_value"]', 0) .submitForm('form') .waitForElementVisible('form[action="/income"]', 2000) .setValue('input[name="your_income-maintenance-per_interval_value"]', 0) .setValue('input[name="your_income-pension-per_interval_value"]', 0) .setValue('input[name="your_income-other_income-per_interval_value"]', 0) .submitForm('form') .waitForElementVisible('form[action="/outgoings"]', 2000) .assert.visible('input[name="childcare-per_interval_value"]') .assert.visible('select[name="childcare-interval_period"]') ; }, 'Context-dependent text for partner': function(client) { client .assert.containsText('body', 'Money you pay your landlord') .assert.containsText('body', 'Money you pay to an ex-partner for their living costs') .assert.containsText('body', 'Money you pay per month towards your criminal legal aid') .assert.containsText('body', 'Money you pay for your child to be looked after while you work or study') .back() .waitForElementVisible('form[action="/income"]', 2000) .back() .waitForElementVisible('form[action="/benefits-tax-credits"]', 2000) .back() .waitForElementPresent('form[action="/about"]', 2000) ; common.setYesNoFields(client, 'have_partner', 1); common.setYesNoFields(client, 'in_dispute', 0); common.setYesNoFields(client, ['partner_is_employed', 'partner_is_self_employed'], 0); client .submitForm('form') .waitForElementPresent('form[action="/benefits-tax-credits"]', 2000) .submitForm('form') .waitForElementPresent('form[action="/income"]', 2000) .setValue('input[name="your_income-maintenance-per_interval_value"]', 0) .setValue('input[name="your_income-pension-per_interval_value"]', 0) .setValue('input[name="your_income-other_income-per_interval_value"]', 0) .setValue('input[name="partner_income-maintenance-per_interval_value"]', 0) .setValue('input[name="partner_income-pension-per_interval_value"]', 0) .setValue('input[name="partner_income-other_income-per_interval_value"]', 0) .submitForm('form') .waitForElementPresent('form[action="/outgoings"]', 2000) .assert.urlContains('/outgoings') .assert.containsText('h1', 'You and your partner’s outgoings') .assert.containsText('body', 'Money you and your partner pay your landlord') .assert.containsText('body', 'Money you and/or your partner pay to an ex-partner for their living costs') .assert.containsText('body', 'Money you and/or your partner pay per month towards your criminal legal aid') .assert.containsText('body', 'Money you and your partner pay for your child to be looked after while you work or study') ; }, 'Validation': function(client) { OUTGOINGS_QUESTIONS.forEach(function(item) { client.setValue(util.format('input[name=%s-per_interval_value]', item), '500'); common.submitAndCheckForFieldError(client, item + '-per_interval_value', 'Please select a time period from the drop down'); client.clearValue(util.format('input[name=%s-per_interval_value]', item)); common.setDropdownValue(client, item + '-interval_period', 'per_month'); common.submitAndCheckForFieldError(client, item + '-per_interval_value', 'Not a valid amount'); }); common.submitAndCheckForFieldError(client, 'income_contribution', 'Not a valid amount'); OUTGOINGS_QUESTIONS.forEach(function(item) { client.setValue(util.format('input[name=%s-per_interval_value]', item), '500'); }); client .setValue('input[name="income_contribution"]', 0) .submitForm('form') .waitForElementPresent('form[action="/call-me-back"]', 2000) .assert.urlContains('/result/eligible') ; client.end(); } };
JavaScript
0
@@ -1958,32 +1958,263 @@ ncome%22%5D', 2000)%0A + .clearValue('input%5Bname=%22your_income-maintenance-per_interval_value%22%5D')%0A .clearValue('input%5Bname=%22your_income-pension-per_interval_value%22%5D')%0A .clearValue('input%5Bname=%22your_income-other_income-per_interval_value%22%5D')%0A .setValue(
e36e90330b7aadf0c97c64bc6b764a8822ccfc60
test changing incoming text, what happens if not start dialog on disconnect
middleware.js
middleware.js
module.exports = { incoming: function (message, bot, builder, next) { console.log('conversations/state') console.log(global.conversations); console.log('************'); console.log('users'); console.log(global.users); console.log('agents'); console.log(global.agent); if (message.type === 'message') { // saves a ping from adding a user/agent // find out who is talking / add new convo if not found if (message.user.isStaff) { // move logic to an API for agents console.log('is staff'); var agentConversationId = message.address.conversation.id; var agentAddress = global.conversations[agentConversationId]; if (typeof agentAddress === 'undefined') { // agent not in state yet, add them ****This will happen for each conversation, not agent. global.agent.push(agentConversationId); global.conversations[agentConversationId] = { address: message.address }; } else if (agentAddress.userAddress) { var msg = new builder.Message() .address(agentAddress.userAddress) .text(message.text); bot.send(msg); } } // End Agent // Setting User state logic else { var userId = message.address.conversation.id; var thisUser = global.conversations[userId]; // Add a user not yet in state if (typeof thisUser === 'undefined') { console.log('got undefined'); global.conversations[userId] = { transcript: [message], address: message.address, status: 'Talking_To_Bot' }; } else { // get spread operator? global.conversations[userId].transcript.push(message); if (message.text === 'help' && thisUser.status === 'Talking_To_Bot') { // user initiated connect to agent global.conversations[message.address.conversation.id] = Object.assign({}, global.conversations[message.address.conversation.id], { 'status': 'Finding_Agent' }); global.users.push(message.address.conversation.id); } else if (message.text === 'done' && thisUser.status === 'Talking_To_Agent') { // deal with disconnecting agent as well delete thisUser.agentAddress; global.conversations[userId] = Object.assign({}, thisUser, { 'status': 'Talking_To_Bot' }); bot.beginDialog(message.address, '/'); } } switch (thisUser.status) { case 'Finding_Agent': var msg = new builder.Message() .address(message.address) .text('Please hold while I find an agent'); bot.send(msg); // finding agent and connecting the 2 if (global.agent.length >= 1) { var myAgent = global.conversations[global.agent[0]]; global.conversations[userId] = Object.assign({}, thisUser, { agentAddress: myAgent.address, 'status': 'Talking_To_Agent' }); global.conversations[myAgent.address.conversation.id] = Object.assign({}, myAgent, { userAddress: thisUser.address }); } break; case 'Talking_To_Agent': var msg = new builder.Message() .address(global.conversations[userId].agentAddress) .text(message.text); bot.send(msg); break; case 'Talking_To_Bot': message.text = 'talk to bot'; next(); break; default: break; } } } } }
JavaScript
0.000002
@@ -554,49 +554,8 @@ nts%0A - console.log('is staff');%0A @@ -617,32 +617,32 @@ onversation.id;%0A + @@ -1003,24 +1003,67 @@ .address %7D;%0A + message.text = 'test';%0A @@ -1642,58 +1642,8 @@ ) %7B%0A - console.log('got undefined');%0A @@ -2657,24 +2657,24 @@ To_Bot' %7D);%0A - @@ -2680,24 +2680,27 @@ + // bot.beginDi
e5d464f706d09a448c466be5a29c4e15473287ab
Align bottom sheet to center
app/hotels/src/map/singleHotel/BottomSheet.js
app/hotels/src/map/singleHotel/BottomSheet.js
// @flow import * as React from 'react'; import { View } from 'react-native'; import { Dimensions } from 'react-native'; import { BottomSheet as CommonBottomSheet, Device, type OnDimensionsChange, } from '@kiwicom/react-native-app-shared'; import { getWidth, openHeight, closedHeight } from '../bottomSheetDimensions'; type Props = {| children: React.Node, |}; type State = {| screenWidth: number, |}; export default class BottomSheet extends React.Component<Props, State> { isTablet: boolean; constructor(props: Props) { super(props); this.isTablet = Device.isTablet(); this.state = { screenWidth: Dimensions.get('screen').width, }; } componentDidMount = () => { Dimensions.addEventListener('change', this.onDimensionsChanged); }; componentWillUnmount = () => { Dimensions.removeEventListener('change', this.onDimensionsChanged); }; onDimensionsChanged = ({ screen: { width } }: OnDimensionsChange) => { this.setState({ screenWidth: width }); }; getWidth = () => getWidth(this.state.screenWidth, this.isTablet); render = () => { const { children } = this.props; return ( <View style={{ width: this.getWidth() }}> <CommonBottomSheet openHeight={openHeight} closedHeight={closedHeight}> {children} </CommonBottomSheet> </View> ); }; }
JavaScript
0
@@ -1195,16 +1195,37 @@ tWidth() +, alignSelf: 'center' %7D%7D%3E%0A
27cf9d443ffe422c698af405980847a22559925c
Add stuff to example embed
commands/embed.js
commands/embed.js
module.exports = { help: { name: 'embed', desc: 'Displays an example for rich embeds', usage: '<message>', aliases: [] }, exec: (client, msg, params) => { let embed = { color: 3447003, author: { name: client.user.username, icon_url: client.user.avatarURL // eslint-disable-line camelcase }, description: '\nThis is a test embed to showcase what they look like and what they can do.\n[Code here](https://github.com/vzwGrey/discord-selfbot/blob/master/commands/embed.js)', fields: [ { name: 'Fields', value: 'They can have different fields with small headlines.' }, { name: 'Masked links', value: 'You can put [masked](https://github.com/vzwGrey/discord-selfbot/blob/master/commands/embed.js) links inside of rich embeds.' }, { name: 'Markdown', value: 'You can put all the *usual* **__Markdown__** inside of them.' } ], timestamp: new Date(), footer: { icon_url: client.user.avatarURL, // eslint-disable-line camelcase text: '©vzwGrey' } }; msg.channel.sendMessage('', { embed }); } };
JavaScript
0
@@ -341,24 +341,115 @@ se%0A %7D,%0A + title: 'THIS IS A TITLE',%0A url: 'http://example.com', // The url for the title.%0A descri @@ -1084,16 +1084,494 @@ %7D -%0A %5D +,%0A %7B%0A name: 'Inline fields',%0A value: 'You can also have fields inline with eachother using the %60inline%60 property',%0A inline: true%0A %7D,%0A %7B%0A name: 'Images & thumbnails',%0A value: 'You can also embed images, and use little thumbnails!',%0A inline: true%0A %7D%0A %5D,%0A /* thumbnail: %7B%0A url: 'http://i.imgur.com/uaUxZtz.jpg'%0A %7D */%0A image: %7B%0A url: 'http://i.imgur.com/uaUxZtz.jpg'%0A %7D ,%0A
d68ba5cecd8809481ad305bd0fbcb118e6f87517
fix wite after end errors
lib/class/Connection.js
lib/class/Connection.js
const { BetterEvents } = require('better-events') const { StringDecoder } = require('string_decoder') /** * Class representing a connection to the daemon. * @class */ class Connection extends BetterEvents { /** * Create a new connection to the daemon. * @param {*} socket */ constructor(socket) { super() this.socket = socket this._message = '' const decoder = new StringDecoder() socket.on('data', async chunk => { this._message += decoder.write(chunk) this._parse() }) socket.once('end', async () => { this._message += decoder.end() this._parse() }) } /** * Parses this._message and emits the "message" event if one was received. */ _parse() { const i = this._message.indexOf('\n') if (i === -1) { return } const msg = this._message.substr(0, i) this._message = this._message.substr(i + 1) try { const obj = JSON.parse(msg) this.emit('message', obj) } catch (error) { this.emit('error', error) } this._parse() } /** * Writes a message to the socket. * @param {*} obj - The object to transmit. */ sendMessage(obj) { if (!obj.type) { throw new Error('Messages must have a type.') } this.socket.write(JSON.stringify(obj) + '\n') } get isDestroyed() { return this.socket.destroyed } } module.exports = Connection
JavaScript
0.000513
@@ -625,24 +625,84 @@ %7D)%0A %7D%0A%0A + get isDestroyed() %7B%0A return this.socket.destroyed%0A %7D%0A%0A /**%0A * P @@ -1167,16 +1167,71 @@ socket. + Returns true if the message was written to the socket. %0A * @p @@ -1269,16 +1269,40 @@ ansmit.%0A + * @returns %7Bboolean%7D%0A */%0A @@ -1408,113 +1408,123 @@ -this.socket.write(JSON.stringify(obj) + '%5Cn')%0A %7D%0A%0A get isDestroyed() %7B%0A return this.socket.destroyed +if (this.isDestroyed) %7B%0A return false%0A %7D%0A%0A this.socket.write(JSON.stringify(obj) + '%5Cn')%0A return true %0A %7D
c13a60937d7ead3f536d96a5aa2f7b830fe45a46
use captioned_title for outline
lib/converter-worker.js
lib/converter-worker.js
/* * Copyright (c) 2014 Thomas Kern * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /* * This file contains everything necessary to execute asciidoctor.js in a * a webworker thread. It is completely self-contained and contains copies * of opal.js and asciidoctor.js. * Currently, opal and asciidoctor are included manually, but we might create * this from its parts through a build process in the future. */ /*global Opal, importScripts, postMessage */ /*jshint -W079, -W098 */ // Webworkers do not have access to 'console', but Opal needs it. var console = { messages: [], log: function (m) { this.messages.push(m); }, info: function (m) { this.messages.push(m); }, warn: function (m) { this.messages.push(m); }, error: function (m) { this.messages.push(m); }, debug: function (m) { this.messages.push(m); }, clear: function() { this.messages = []; } }; // mapping for class names // in generated HTML var classNames = { stem: 'stemblock', admonition: 'admonitionblock', audio: 'audioblock', video: 'videoblock', colist: 'colist', dlist: function(style) { if (style === 'qanda') { return 'qlist'; } else if (style === 'horizontal') { return 'hdlist'; } else { return 'dlist'; } }, olist: 'olist', ulist: 'ulist', example: 'exampleblock', image: 'imageblock', listing: 'listingblock', literal: 'literalblock', open: function(style) { return (style === 'abstract')?'quoteblock':'openblock'; }, paragraph: 'paragraph', quote: 'quoteblock', table: 'tableblock', verse: 'verseblock' }; // onmessage is invoked by 'postMessage' on the worker var onmessage = function (e) { postMessage(convert(e.data)); }; // Actual conversion is done here function convert(data) { var startTime = new Date().getTime(); console.clear(); // communicate to Asciidoctor that the working directory is not the same as the preview file Opal.ENV['$[]=']("PWD", data.pwd); // options and attributes var opts = Opal.hash2(['base_dir', 'safe', 'doctype', 'sourcemap', 'attributes'], { 'base_dir': data.basedir, 'safe': data.safemode, 'doctype': data.doctype, 'sourcemap': true, // generate source map 'attributes': data.attributes }); var doc = Opal.Asciidoctor.$load(data.docText, opts); return { html: doc.$convert(), // convert! outline: outline(doc, opts), messages: console.messages, duration: new Date().getTime() - startTime }; } function outline(doc, opts) { var sectionInfo = []; var getBlockInfo = function(blocks) { var blockInfo = []; for (var i = 0; i < blocks.length && blocks[i].$node_name() != 'section'; i++) { var ln = blocks[i].$lineno(); // HACK: Line number of last block seems to be off by one if (i + 1 == blocks.length) { ln--; } blockInfo.push({ lineno: ln }); } return blockInfo; }; var fillSections = function self (level, sections) { level++; if (level > 5) { return; } for (var i = 0; i < sections.length; i++) { sectionInfo.push({ level: level, titleHtml: Opal.Asciidoctor.$convert(sections[i].title, opts), titleRaw: sections[i].title, lineno: sections[i].$lineno(), id: sections[i].$id(), blockInfo: getBlockInfo(sections[i].blocks) }); self(level, sections[i].$sections()); } }; fillSections(0, doc.$sections()); return { titleHtml: Opal.Asciidoctor.$convert(doc.$doctitle(), opts), titleRaw: doc.$doctitle(), sections: sectionInfo }; } // Import Opal and Asciidoctor.js importScripts('opal.js', 'asciidoctor.js');
JavaScript
0.000015
@@ -3487,21 +3487,16 @@ );%0A %0A - %0A var @@ -4521,32 +4521,34 @@ +// titleHtml: Opal. @@ -4616,19 +4616,16 @@ title -Raw : sectio @@ -4630,21 +4630,34 @@ ions%5Bi%5D. +$captioned_ title +() , %0A @@ -4920,24 +4920,29 @@ ections());%0A + %0A return %7B @@ -4946,24 +4946,26 @@ n %7B%0A +// titleHtml: O @@ -5030,11 +5030,8 @@ itle -Raw : do @@ -5042,16 +5042,62 @@ octitle( +Opal.hash2(%5B'sanitize'%5D, %7B 'sanitize': true %7D) ),%0A
17fafd162511586617dc5d123bea9b4a53f980d2
Update remind.js
chat-plugins/remind.js
chat-plugins/remind.js
exports.commands = { r: 'remind', remind: function (target, room, user) { if (!target) return; target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.sendReply("User " + this.targetUsername + " not found."); } if (!this.can('warn', targetUser, room)) return false; targetUser.popup("You have a tournament match to play. ");
JavaScript
0.000001
@@ -402,12 +402,18 @@ o play. %22);%0A +%09%7D%0A%7D;%0A
27265a1ea216147077297fd91b37bb1389c81a68
Remove unnecessary conditional
lib/define-assertion.js
lib/define-assertion.js
"use strict"; var slice = require("@sinonjs/commons").prototypes.array.slice; var assertArgNum = require("./assert-arg-num"); var interpolatePosArg = require("./interpolate-pos-arg"); var interpolateProperties = require("./interpolate-properties"); function createAssertion(referee, type, name, func, minArgs, messageValues) { var assertion = function() { var fullName = type + "." + name; var failed = false; if ( !assertArgNum( referee.fail, fullName, arguments, minArgs || func.length ) ) { return; } var args = slice(arguments, 0); var namedValues = {}; if (typeof messageValues === "function") { var replacedValues = messageValues.apply(this, args); if (typeof replacedValues === "object") { namedValues = replacedValues; } else { args = replacedValues; } } var ctx = { fail: function(msg) { failed = true; delete this.fail; var message = referee[type][name][msg] || msg; message = interpolatePosArg(message, args); message = interpolateProperties(referee, message, this); message = interpolateProperties(referee, message, namedValues); var operator = type + "." + name; var errorProperties = { operator: operator }; if (type === "assert") { if ( namedValues.hasOwnProperty("actual") && namedValues.hasOwnProperty("expected") ) { errorProperties.actual = namedValues.actual; errorProperties.expected = namedValues.expected; } } referee.fail("[" + operator + "] " + message, errorProperties); return false; } }; var result = func.apply(ctx, arguments); if (result instanceof Promise) { // Here we need to return the promise in order to tell test // runners that this is an asychronous assertion. // eslint complains about the return statement, because it is // not expected here, so let's ignore. // https://eslint.org/docs/rules/consistent-return /* eslint-disable-next-line consistent-return */ return result.then(function() { referee.pass(["pass", fullName].concat(args)); }); } if (!result && !failed) { // when a function returns false and hasn't already failed with a custom message, // fail with default message ctx.fail("message"); } if (!failed) { referee.pass(["pass", fullName].concat(args)); } }; return assertion; } // Internal helper. Not the most elegant of functions, but it takes // care of all the nitty-gritty of assertion functions: counting, // verifying parameter count, interpolating messages with actual // values and so on. function defineAssertion(referee, type, name, func, minArgs, messageValues) { referee[type][name] = function() { var assertion = createAssertion( referee, type, name, func, minArgs, messageValues ); return assertion.apply(null, arguments); }; } module.exports = defineAssertion;
JavaScript
0.000001
@@ -439,29 +439,16 @@ if ( -%0A !assertA @@ -457,153 +457,51 @@ Num( -%0A referee.fail,%0A fullName,%0A arguments,%0A minArgs %7C%7C func.length%0A )%0A +referee.fail, fullName, arguments, minArgs) ) %7B%0A
97c52066ddd01b03eb89093c6da93b1aaf2a9125
add deliveryOrderItem and deliveryOrderItemFulfillment in validator
src/validator.js
src/validator.js
module.exports = { auth: { account: require("./auth/account-validator"), profile: require("./auth/profile-validator"), role: require("./auth/role-validator") }, master: { product: require("./master/product-validator"), buyer: require("./master/buyer-validator"), supplier: require("./master/supplier-validator"), uom: require("./master/uom-validator"), unit: require("./master/unit-validator"), category: require("./master/category-validator"), currency: require("./master/currency-validator"), vat: require("./master/vat-validator"), budget: require('./master/budget-validator') }, purchasing: { purchaseOrder: require("./purchasing/purchase-order-validator"), purchaseOrderItem: require("./purchasing/purchase-order-item-validator"), purchaseOrderExternal: require("./purchasing/purchase-order-external-validator"), deliveryOrder: require("./purchasing/delivery-order-validator"), unitReceiptNote: require("./purchasing/unit-receipt-note-validator"), unitPaymentPriceCorrectionNote: require("./purchasing/unit-payment-price-correction-note-validator"), unitPaymentPriceCorrectionNoteItem: require("./purchasing/unit-payment-price-correction-note-item-validator"), UnitPaymentOrder: require("./purchasing/unit-payment-order-validator"), UnitPaymentOrderItem: require("./purchasing/unit-payment-order-item-validator"), purchaseRequest: require("./purchasing/purchase-request-validator"), purchaseRequestItem: require("./purchasing/purchase-request-item-validator") } };
JavaScript
0
@@ -672,17 +672,16 @@ dator%22), - %0A @@ -1165,32 +1165,235 @@ er-validator%22),%0A + deliveryOrderItem: require(%22./purchasing/delivery-order-item-validator%22),%0A deliveryOrderItemFulfillment: require(%22./purchasing/delivery-order-item-fulfillment-validator%22),%0A
26699023c91f3a07829bb9ce2f0081e23248ed07
Add units
src/constants/earth.js
src/constants/earth.js
// IERS numerical standards // (as per Technical Note No.36 Table 1.1) const earth = { a: 6378136.6, // Equatorial radius f: 0.003352819697896193, // Flattening invf: 298.25642, // Reciprocal flattening e: 0.08181930087617338, // Eccentricity e2: 0.006694397995865785, // Eccentricity squared J2: 1.0826359e-3, // Dynamical form factor ω: 7.29211514670698e-5, // Rotation rate M: 5.9721986e24, // Mass [kg] GM: 3.986004418e14, // Geocentric gravitational constant ε0: 23.439279444444445, // Obliquity of the ecliptic at J2000.0 θ0: 4.894961212823756 // Earth Rotation Angle (ERA) J2000.0 }; earth.grs80 = { GM: 3.986005e14, a: 6378137, J2: 1.08263e-3, ω: 7.292115e-5, f: 0.0033528106811836376, invf: 298.257222100882711243, e: 0.08181919104283185, e2: 0.006694380022903416 }; earth.wgs84 = { a: 6378137, f: 0.0033528106647474805, invf: 298.257223563, e: 0.08181919084262149, e2: 0.0066943799901413165 }; export default earth;
JavaScript
0.000001
@@ -120,16 +120,20 @@ l radius + %5Bm%5D %0A f: @@ -404,16 +404,26 @@ ion rate + %5Brad s-1%5D %0A M: @@ -510,16 +510,25 @@ constant + %5Bm3 s-2%5D %0A %CE%B50: @@ -587,16 +587,22 @@ J2000.0 + %5Bdeg%5D %0A %CE%B80: @@ -657,16 +657,22 @@ J2000.0 + %5Brad%5D %0A%7D;%0A%0Aear @@ -708,66 +708,189 @@ e14, -%0A a: 6378137,%0A J2: 1.08263e-3,%0A %CF%89: 7.292115e-5, + // Geocentric gravitational constant %5Bm3 s-2%5D%0A a: 6378137, // Equatorial radius %5Bm%5D%0A J2: 1.08263e-3, // Dynamical form factor%0A %CF%89: 7.292115e-5, // Rotation rate %5Brad s-1%5D %0A f @@ -916,16 +916,30 @@ 1836376, + // Flattening %0A invf: @@ -962,16 +962,41 @@ 2711243, + // Reciprocal flattening %0A e: @@ -1016,16 +1016,32 @@ 4283185, + // Eccentricity %0A e2: @@ -1061,16 +1061,40 @@ 22903416 + // Eccentricity squared %0A%7D;%0A%0Aear @@ -1122,16 +1122,41 @@ 6378137, + // Equatorial radius %5Bm%5D %0A f: @@ -1178,16 +1178,30 @@ 7474805, + // Flattening %0A invf: @@ -1215,16 +1215,41 @@ 7223563, + // Reciprocal flattening %0A e: @@ -1269,16 +1269,32 @@ 4262149, + // Eccentricity %0A e2: @@ -1315,16 +1315,40 @@ 01413165 + // Eccentricity squared %0A%7D;%0A%0Aexp
50cdfa075540a83d239ef3aa1fdbdcb71babf681
Update touchMe.js
common/touchMe.js
common/touchMe.js
function touchHandler(event) { console.info(event) if (event.touches.length > 1 || (event.type == "touchend" && event.touches.length > 0)){ return } var touches = event.targetTouches; var first = touches[0]; var type = ""; switch (event.type) { case "touchstart": type = "mousedown"; break; case "touchmove": type = "mousemove"; event.preventDefault(); break; case "touchend": type = "mouseup"; event.preventDefault(); break; default: type = "mouseup"; event.preventDefault(); break; } // initMouseEvent(type, canBubble, cancelable, view, clickCount, // screenX, screenY, clientX, clientY, ctrlKey, // altKey, shiftKey, metaKey, button, relatedTarget); var simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0 /*left*/ , null); first.target.dispatchEvent(simulatedEvent); } function touchMe_init() { document.addEventListener("touchstart", touchHandler, true); document.addEventListener("touchmove", touchHandler, true); document.addEventListener("touchend", touchHandler, true); document.addEventListener("touchcancel", touchHandler, true); } touchMe_init() // thanks, Mickey Shine!
JavaScript
0
@@ -82,66 +82,8 @@ %3E 1 - %7C%7C (event.type == %22touchend%22 && event.touches.length %3E 0) )%7B%0A
cbf1d2feb09f46f9b07fa23b2da37658886abe1b
Add specific handling for DOMExceptions
src/core/ChefWorker.js
src/core/ChefWorker.js
/** * Web Worker to handle communications between the front-end and the core. * * @author n1474335 [[email protected]] * @copyright Crown Copyright 2017 * @license Apache-2.0 */ import Chef from "./Chef"; import OperationConfig from "./config/OperationConfig.json"; import OpModules from "./config/modules/OpModules"; // Add ">" to the start of all log messages in the Chef Worker import loglevelMessagePrefix from "loglevel-message-prefix"; loglevelMessagePrefix(log, { prefixes: [], staticPrefixes: [">"], prefixFormat: "%p" }); // Set up Chef instance self.chef = new Chef(); self.OpModules = OpModules; self.OperationConfig = OperationConfig; self.inputNum = -1; // Tell the app that the worker has loaded and is ready to operate self.postMessage({ action: "workerLoaded", data: {} }); /** * Respond to message from parent thread. * * Messages should have the following format: * { * action: "bake" | "silentBake", * data: { * input: {string}, * recipeConfig: {[Object]}, * options: {Object}, * progress: {number}, * step: {boolean} * } | undefined * } */ self.addEventListener("message", function(e) { // Handle message const r = e.data; log.debug("ChefWorker receiving command '" + r.action + "'"); switch (r.action) { case "bake": bake(r.data); break; case "silentBake": silentBake(r.data); break; case "getDishAs": getDishAs(r.data); break; case "docURL": // Used to set the URL of the current document so that scripts can be // imported into an inline worker. self.docURL = r.data; break; case "highlight": calculateHighlights( r.data.recipeConfig, r.data.direction, r.data.pos ); break; case "setLogLevel": log.setLevel(r.data, false); break; default: break; } }); /** * Baking handler * * @param {Object} data */ async function bake(data) { // Ensure the relevant modules are loaded self.loadRequiredModules(data.recipeConfig); try { self.inputNum = parseInt(data.inputNum, 10); const response = await self.chef.bake( data.input, // The user's input data.recipeConfig, // The configuration of the recipe data.options, // Options set by the user data.progress, // The current position in the recipe data.step // Whether or not to take one step or execute the whole recipe ); self.postMessage({ action: "bakeComplete", data: Object.assign(response, { id: data.id, inputNum: data.inputNum, bakeId: data.bakeId, progress: response.progress }) }); } catch (err) { self.postMessage({ action: "bakeError", data: { error: err, id: data.id, inputNum: data.inputNum } }); } self.inputNum = -1; } /** * Silent baking handler */ function silentBake(data) { const duration = self.chef.silentBake(data.recipeConfig); self.postMessage({ action: "silentBakeComplete", data: duration }); } /** * Translates the dish to a given type. */ async function getDishAs(data) { const value = await self.chef.getDishAs(data.dish, data.type); self.postMessage({ action: "dishReturned", data: { value: value, id: data.id } }); } /** * Calculates highlight offsets if possible. * * @param {Object[]} recipeConfig * @param {string} direction * @param {Object} pos - The position object for the highlight. * @param {number} pos.start - The start offset. * @param {number} pos.end - The end offset. */ async function calculateHighlights(recipeConfig, direction, pos) { pos = await self.chef.calculateHighlights(recipeConfig, direction, pos); self.postMessage({ action: "highlightsCalculated", data: pos }); } /** * Checks that all required modules are loaded and loads them if not. * * @param {Object} recipeConfig */ self.loadRequiredModules = function(recipeConfig) { recipeConfig.forEach(op => { const module = self.OperationConfig[op.op].module; if (!OpModules.hasOwnProperty(module)) { log.info(`Loading ${module} module`); self.sendStatusMessage(`Loading ${module} module`); self.importScripts(`${self.docURL}/modules/${module}.js`); self.sendStatusMessage(""); } }); }; /** * Send status update to the app. * * @param {string} msg */ self.sendStatusMessage = function(msg) { self.postMessage({ action: "statusMessage", data: { message: msg, inputNum: self.inputNum || -1 } }); }; /** * Send an option value update to the app. * * @param {string} option * @param {*} value */ self.setOption = function(option, value) { self.postMessage({ action: "optionUpdate", data: { option: option, value: value } }); }; /** * Send register values back to the app. * * @param {number} opIndex * @param {number} numPrevRegisters * @param {string[]} registers */ self.setRegisters = function(opIndex, numPrevRegisters, registers) { self.postMessage({ action: "setRegisters", data: { opIndex: opIndex, numPrevRegisters: numPrevRegisters, registers: registers } }); };
JavaScript
0
@@ -3035,24 +3035,71 @@ tch (err) %7B%0A + if (err instanceof DOMException) %7B%0A self @@ -3105,32 +3105,36 @@ f.postMessage(%7B%0A + acti @@ -3150,16 +3150,20 @@ Error%22,%0A + @@ -3190,16 +3190,20 @@ + error: e @@ -3204,18 +3204,30 @@ ror: err -,%0A +.message,%0A @@ -3255,32 +3255,36 @@ + inputNum: data.i @@ -3307,18 +3307,25 @@ + -%7D%0A + %7D%0A %7D);%0A @@ -3316,28 +3316,291 @@ %0A + %7D);%0A + %7D else %7B%0A self.postMessage(%7B%0A action: %22bakeError%22,%0A data: %7B%0A error: err,%0A id: data.id,%0A inputNum: data.inputNum%0A %7D%0A %7D);%0A %7D%0A %7D%0A se
d433ca0dddbf989bff61225be06b11d40261f322
Make passing $CM_BUILDTYPE possible again. This fix was applied at DB level before but got lost during the sequalize transition.
add-build.js
add-build.js
var Troll = require('troll-opt').Troll; var models = require('./models/'); var buildInfo = (new Troll()).options(function(troll) { troll.banner('Adds a new build to the database.'); troll.opt('device', 'The device ID.', { type: 'string', required: true }); troll.opt('timestamp', 'The build\'s timestamp as "unixepoch" timestamp.', { type: 'integer', required: true }); troll.opt('md5sum', 'The build\'s md5sum.', { type: 'string', required: true }); troll.opt('filename', 'The resulting filename.', { type: 'string', required: true }); troll.opt('channel', 'The update-channel.', { type: 'string', required: true }); troll.opt('api_level', 'The SDK API-level of the ROM.', { type: 'integer', required: true }); troll.opt('subdirectory', 'The subdirectory from which the file can be downloaded.', { type: 'string' }); troll.opt('active', 'Marks the build as active (available for download) or not.', { type: 'boolean', required: true }); }); function createNewRomFor(device) { var deviceId = device.id; var newRom = models.Rom.build({ DeviceId: deviceId, timestamp: new Date(parseInt(buildInfo.timestamp)), md5sum: buildInfo.md5sum, filename: buildInfo.filename, updateChannel: buildInfo.channel, changelog: null, apiLevel: buildInfo.api_level, subdirectory: buildInfo.subdirectory, isActive: buildInfo.active }); newRom.save().complete(function(err) { if (err) { throw new Error('Could not add rom with parameters: ' + JSON.stringify(buildInfo) + '.\nError: ' + JSON.stringify(err)); } else { console.log('Successfully created new rom: ' + JSON.stringify(newRom)); } }); } models.sequelize.sync().complete(function(err) { if (err) { throw err; } else { models.Device.find({ where: { name: buildInfo.device } }).complete(function(err, device) { if (err) { throw err; } if (device) { createNewRomFor(device); } else { device = models.Device.build({ name: buildInfo.device }); device.save().complete(function(err) { if (err) { throw err; } console.log('Successfully created new device ' + JSON.stringify(device)); createNewRomFor(device); }); } }); } });
JavaScript
0
@@ -1007,16 +1007,227 @@ vice.id; +%0A%09var parsedUpdateChannel = new String(buildInfo.channel);%0A%0A%09if (parsedUpdateChannel.toUpperCase() == %22RC%22) %7B%0A%09%09parsedUpdateChannel = %22RC%22;%0A%09%7D else %7B%0A%09%09parsedUpdateChannel = parsedUpdateChannel.toLowerCase();%0A%09%7D %0A%0A%09var n @@ -1406,27 +1406,29 @@ hannel: -buildInfo.c +parsedUpdateC hannel,%0A
b6feec12ff74b2b9eebaeaee0708714729111cfe
Remove log
src/views/tab.js
src/views/tab.js
define(function() { var _ = codebox.require("hr/utils"); var $ = codebox.require("hr/dom"); var hr = codebox.require("hr/hr"); var dnd = codebox.require("utils/dragdrop"); var keyboard = codebox.require("utils/keyboard"); var menu = codebox.require("utils/menu"); var GridView = codebox.require("views/grid"); // Tab header var TabView = hr.List.Item.extend({ className: "component-tab", defaults: { title: "", tabid: "", close: true }, events: { "mousedown .close": "close", "dblclick": "open", "click .close": "close", "click": "open", }, states: { 'modified': "*", 'warning': "!", 'offline': "*", 'sync': "[-]", 'loading': "*" }, // Constructor initialize: function() { TabView.__super__.initialize.apply(this, arguments); var that = this; var $document = $(document); // Drop tabs to order this.dropArea = new dnd.DropArea({ view: this, dragType: this.model.manager.drag, handler: function(tab) { var i = that.list.collection.indexOf(that.model); var ib = that.list.collection.indexOf(tab); if (ib >= 0 && ib < i) { i = i - 1; } console.log("drop tab at position", i); that.model.manager.changeTabSection(tab, that.list.collection.sectionId, { at: i }); } }); this.model.manager.drag.enableDrag({ view: this, data: this.model, baseDropArea: this.list.dropArea, start: function() { that.open(); } }); // Context menu if (this.model.manager.options.tabMenu) { menu.add(this.$el, _.compact([ (this.model.manager.options.newTab ? { 'label': "New Tab", 'click': function() { that.model.manager.openDefault(); } } : null), (this.model.manager.options.newTab ? { 'type': "divider" } : null), { 'label': "Close", 'click': function() { that.close(); } }, { 'label': "Close Other Tabs", 'click': function() { that.closeOthers(); } }, { 'type': "divider" }, { 'label': "New Group", 'click': function() { that.model.splitSection(); } }, { 'type': "divider" }, { 'type': "menu", 'label': "Layout", 'items': _.map(that.model.manager.options.layouts, function(value, key) { return { 'label': key, 'click': function() { that.model.manager.setLayout(value); } } }) } ])); } return this; }, // Render the tab render: function() { this.$el.empty(); var inner = $("<div>", { "class": "inner" }).appendTo(this.$el); var title = $("<span>", { "class": "title", "html": this.model.get("title") }).appendTo(inner); var states = this.model.get("state", "").split(" "); _.each(states, function(state) { if (state && this.states[state]) { $("<span>", { "class": "state state-"+state, "text": this.states[state] }).prependTo(inner); } }, this); var icon = this.model.get("icon"); if (icon) { $("<i>", { "class": "icon octicon octicon-"+this.model.get("icon") }).prependTo(inner); } $("<a>", { "class": "close", "href": "#", "html": "&times;" }).prependTo(inner); this.$el.toggleClass("active", this.model.isActive()); return this.ready(); }, // Return true if is active isActive: function() { return this.$el.hasClass("active"); }, // (event) open open: function(e) { if (e != null) { e.preventDefault(); e.stopPropagation(); } this.model.active(); }, // (event) close close: function(e) { if (e != null) { e.preventDefault(); e.stopPropagation(); } this.model.close(); }, // (event) close others tabs closeOthers: function(e) { this.model.closeOthers(); } }); return TabView; });
JavaScript
0.000001
@@ -1528,68 +1528,8 @@ %7D%0A - console.log(%22drop tab at position%22, i);%0A
c5bb1f015ddd1472e6ddbf9f9e8cbf9452a88f42
fix compile-script: Don't filter out empty string commands.
compile-script.js
compile-script.js
'use strict'; let fs = require('fs'); let _ = require('lodash'); let Q = require('q'); let peg = require('pegjs'); let errorWithMetadata = require('./util/error-with-metadata'); let LowLevelScript = require('./low-level-script'); let parse = peg.buildParser ( fs.readFileSync ( __dirname + '/script-grammar.pegjs', { encoding: 'utf8', } ) ).parse; module.exports = function(source) { let script = new LowLevelScript(); let filterCount = 0; script.commands = parse(source).filter((command, i) => { let postFilterIndex = i - filterCount; if(typeof command !== 'object') { if(command === '') { ++filterCount; return false; } else { return true; } } let commandName = Object.keys(command)[0]; switch(commandName) { case 'label': script.labels[command.label] = postFilterIndex; ++filterCount; return false; case 'choice': if(command.choice.objectLiteral) { command.choice.code = command.choice.objectLiteral; } command.choice = new Function ( 'return (' + command.choice.code + ');' )(); if(Array.isArray(command.choice)) { command.choice.forEach(function(option) { option.fn = option.fn.bind(script); }); } else { command.choice = _.mapValues(command.choice, function(fn) { return fn.bind(script); }); } return true; default: return true; } }); return script; };
JavaScript
0.000001
@@ -583,85 +583,8 @@ ) %7B%0A -%09%09%09if(command === '') %7B%0A%09%09%09%09++filterCount;%0A%09%09%09%09return false;%0A%09%09%09%7D%0A%09%09%09else %7B%0A%09 %09%09%09r @@ -595,21 +595,16 @@ n true;%0A -%09%09%09%7D%0A %09%09%7D%0A%09%09le
4a3db2654d552ce8c0fa8f529b42efae8d383d91
refactor compile-script: Replace filter call with forEach call.
compile-script.js
compile-script.js
'use strict'; let fs = require('fs'); let _ = require('lodash'); let Q = require('q'); let peg = require('pegjs'); let errorWithMetadata = require('./util/error-with-metadata'); let LowLevelScript = require('./low-level-script'); let parse = peg.buildParser ( fs.readFileSync ( __dirname + '/script-grammar.pegjs', { encoding: 'utf8', } ) ).parse; module.exports = function(source) { let script = new LowLevelScript(); script.commands = parse(source).filter((command, i) => { if(typeof command !== 'object') { return true; } let commandName = Object.keys(command)[0]; switch(commandName) { case 'label': script.labels[command.label] = i; return true; case 'choice': if(command.choice.objectLiteral) { command.choice.code = command.choice.objectLiteral; } command.choice = new Function ( 'return (' + command.choice.code + ');' )(); if(Array.isArray(command.choice)) { command.choice.forEach(function(option) { option.fn = option.fn.bind(script); }); } else { command.choice = _.mapValues(command.choice, function(fn) { return fn.bind(script); }); } return true; default: return true; } }); return script; };
JavaScript
0
@@ -423,16 +423,31 @@ ipt();%0A%09 +let commands = script.c @@ -473,15 +473,27 @@ rce) -.filter +;%0A%09commands.forEach ((co @@ -543,16 +543,16 @@ ect') %7B%0A + %09%09%09retur @@ -548,29 +548,24 @@ %7B%0A%09%09%09return - true ;%0A%09%09%7D%0A%09%09let @@ -682,35 +682,29 @@ l%5D = i;%0A%09%09%09%09 -return true +break ;%0A%09%09%09case 'c @@ -1176,48 +1176,13 @@ %09%09%09%09 -return true;%0A%09%09%09default:%0A%09%09%09%09return true +break ;%0A%09%09
37e14841c9dbfea6a755ac042be4ec72426ebc4c
Put Queued project right after in process project
src/main/resources/js/boardcontroller.js
src/main/resources/js/boardcontroller.js
//controller and any services relating to the main boaard plugin.controller("BoardController", function ($scope, autoRefresh, $rootScope) { $scope.projectName = "CDPipeline"; $scope.results = autoRefresh.data; $rootScope.dataLoaded = false; }); //polls a REST endpoint every five seconds and automatically refreshes plugin.factory('autoRefresh', function ($http, $timeout, $rootScope) { var data = { resp: {}}; var poller = function() { $http.get('?type=json').then( function(r) { data.resp = r.data; $rootScope.dataLoaded = true; $timeout(poller, 5000); }); }; poller(); return { data: data }; }); // filter that puts element with key == null to the end of the list plugin.filter("emptyToEnd", function () { return function (array, key) { if(!angular.isArray(array)) return; var present = array.filter(function (item) { return item[key]; }); var empty = array.filter(function (item) { return !item[key] }); return present.concat(empty); }; }); // filter that puts in progress projects to the top plugin.filter("progressToFront", function () { return function (array, key) { if(!angular.isArray(array)) return; var inProgress = array.filter(function (item) { return item[key]["cdpipelineState"] == "CD_IN_PROGRESS"; }); var finished = array.filter(function (item) { return item[key]["cdpipelineState"] != "CD_IN_PROGRESS"; }); return inProgress.concat(finished); }; }); // The search button on the menu bar plugin.filter('searchFor', keywordSearch); // Helper method for the search button on the menu bar function keywordSearch(){ // All filters must return a function. The first parameter // is the data that is to be filtered, and the second is an // argument that may be passed with a colon (searchFor:searchString) return function(arr, searchString){ if(!searchString){ return arr; } var result = []; searchString = searchString.toLowerCase(); // Using the forEach helper method to loop through the array angular.forEach(arr, function(item){ if(item.projectName.toLowerCase().indexOf(searchString) !== -1 | item.planName.toLowerCase().indexOf(searchString) !== -1) { result.push(item); } for (i = 0; i < item.contributors.length; i++) { if (item.contributors[i].username.toLowerCase().indexOf(searchString) !== -1 | item.contributors[i].fullname.toLowerCase().indexOf(searchString) !== -1) { result.push(item) } } }); return result; }; } // Filter that deals with edge case of the pipeline // (when there's only one stage) plugin.filter('pipelineWidth', function(){ return function(input){ if(input > 1) { return (1 / (input - 1)); } else { return 0; } } });
JavaScript
0
@@ -1060,16 +1060,27 @@ rogress +and queued projects @@ -1337,32 +1337,157 @@ S%22;%0A %7D);%0A + var queued = array.filter(function (item) %7B%0A %09return item%5Bkey%5D%5B%22cdpipelineState%22%5D == %22CD_QUEUED%22;%0A %7D);%0A var fini @@ -1583,32 +1583,79 @@ %22CD_IN_PROGRESS%22 + && item%5Bkey%5D%5B%22cdpipelineState%22%5D != %22CD_QUEUED%22 ;%0A %7D);%0A%09%09 @@ -1679,16 +1679,31 @@ .concat( +queued).concat( finished
1c91d69ee72cac7f6c6f262eb1a1efb358e29b80
remove debug statement
src/client/component.js
src/client/component.js
const React = require('react'); const walkVars = require('./visitors/vars'); const walkNode = require('./visitors/node'); const utils = require('./utils'); require('__IDYLL_SYNTAX_HIGHLIGHT__'); let results = require('__IDYLL_AST__'); console.log(results); const transformRefs = (refs) => { const output = {}; const keys = ['scrollProgress', 'size', 'position']; Object.keys(refs).forEach((ref) => { const val = refs[ref]; keys.forEach((key) => { if (val === null || val === undefined) { return; } const results = utils.flattenObject(key, val[key]); Object.keys(results).forEach((result) => { output['_idyllRefs' + ref + result] = results[result]; }); }); }); return output; }; class InteractiveDocument extends React.PureComponent { constructor(props) { super(props); this.handleUpdateProps = this.handleUpdateProps.bind(this); // Walk the tree, creating the proper components for evererything. this.bindings = {}; this._idyllRefs = {}; this.derivedVars = {}; this.initialState = {}; results.map(walkVars(this)); this.state = this.initialState; this.getChildren = () => { return results.map(walkNode(this)); } } handleUpdateProps(nodeID) { return (props) => { if (this.bindings[nodeID]) { const newState = {}; Object.keys(props).forEach((propName) => { const val = props[propName]; if (this.bindings[nodeID][propName]) { newState[this.bindings[nodeID][propName]] = val; } }); this.setStateAndDerived(newState); } }; } setStateAndDerived(newState) { this.setState(newState); Object.keys(this.derivedVars).forEach((dv) => { this.derivedVars[dv].update(); }); } getDerivedVars() { let dvs = {}; Object.keys(this.derivedVars).forEach((dv) => { dvs[dv] = this.derivedVars[dv].value; }); return dvs; } componentDidMount() { Object.keys(this._idyllRefs).forEach((name) => { const ref = this._idyllRefs[name]; const rect = ref.domNode().getBoundingClientRect(); this._idyllRefs[name]._node = ref.domNode(); this._idyllRefs[name].size = { x: rect.width, y: rect.height }; this._idyllRefs[name].position = { top: rect.top, left: rect.left, right: rect.right, bottom: rect.bottom }; this._idyllRefs[name].absolutePosition = { top: rect.top + window.scrollY, left: rect.left + window.scrollX, right: rect.right + window.scrollX, bottom: rect.bottom + window.scrollY }; }); this.setState(transformRefs(this._idyllRefs)); window.addEventListener('scroll', (e) => { // calculate current position based on scroll position const body = document.body; const html = document.documentElement; const documentWidth = Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth ); const documentHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); const windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; const windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; const scrollX = window.scrollX; const scrollY = window.scrollY; const newRefs = {}; Object.keys(this._idyllRefs).forEach((ref) => { const { size, absolutePosition, _node } = this._idyllRefs[ref]; // 0 percent === top of the div is over the bottom of the window const minY = Math.max(0, absolutePosition.top - windowHeight); // 100 percent === bottom of div is at top of window const maxY = Math.min(documentHeight - windowHeight, absolutePosition.bottom); const minX = Math.max(0, absolutePosition.left - windowWidth); const maxX = Math.min(documentWidth - windowWidth, absolutePosition.right); const rect = _node.getBoundingClientRect(); newRefs[ref] = { scrollProgress: { x: minX === maxX ? 1 : Math.max(0, Math.min(1, (scrollX - minX) / (maxX - minX))), y: minY === maxY ? 1 : Math.max(0, Math.min(1, (scrollY - minY) / (maxY - minY))) }, position: { top: rect.top, left: rect.left, right: rect.right, bottom: rect.bottom } }; this._idyllRefs[ref] = Object.assign({}, this._idyllRefs[ref], newRefs[ref]); }); this.setState(transformRefs(newRefs)); }); } render() { return React.createElement('div', {className: 'idyll-root'}, this.getChildren()); } } module.exports = InteractiveDocument;
JavaScript
0.000517
@@ -232,30 +232,8 @@ _'); -%0Aconsole.log(results); %0A%0Aco