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
65d5b0ef50b1568f314d658811c576af6a0a8659
Rename define to defineComponent
lib/component.js
lib/component.js
/* Copyright 2013 Twitter, Inc. Licensed under The MIT License. http://opensource.org/licenses/MIT */ define( [ './advice', './utils', './compose', './base', './registry', './logger', './debug' ], function(advice, utils, compose, withBase, registry, withLogging, debug) { 'use strict'; var functionNameRegEx = /function (.*?)\s?\(/; var ignoredMixin = { withBase: true, withLogging: true }; // teardown for all instances of this constructor function teardownAll() { var componentInfo = registry.findComponentInfo(this); componentInfo && Object.keys(componentInfo.instances).forEach(function(k) { var info = componentInfo.instances[k]; // It's possible that a previous teardown caused another component to teardown, // so we can't assume that the instances object is as it was. if (info && info.instance) { info.instance.teardown(); } }); } function attachTo(selector/*, options args */) { // unpacking arguments by hand benchmarked faster var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) { args[i - 1] = arguments[i]; } if (!selector) { throw new Error('Component needs to be attachTo\'d a jQuery object, native node or selector string'); } var options = utils.merge.apply(utils, args); var componentInfo = registry.findComponentInfo(this); $(selector).each(function(i, node) { if (componentInfo && componentInfo.isAttachedTo(node)) { // already attached return; } (new this).initialize(node, options); }.bind(this)); } function prettyPrintMixins() { //could be called from constructor or constructor.prototype var mixedIn = this.mixedIn || this.prototype.mixedIn || []; return mixedIn.map(function(mixin) { if (mixin.name == null) { // function name property not supported by this browser, use regex var m = mixin.toString().match(functionNameRegEx); return (m && m[1]) ? m[1] : ''; } return (!ignoredMixin[mixin.name] ? mixin.name : ''); }).filter(Boolean).join(', '); }; // define the constructor for a custom component type // takes an unlimited number of mixin functions as arguments // typical api call with 3 mixins: define(timeline, withTweetCapability, withScrollCapability); function define(/*mixins*/) { // unpacking arguments by hand benchmarked faster var l = arguments.length; var mixins = new Array(l); for (var i = 0; i < l; i++) { mixins[i] = arguments[i]; } var Component = function() {}; Component.toString = Component.prototype.toString = prettyPrintMixins; if (debug.enabled) { Component.describe = Component.prototype.describe = Component.toString(); } // 'options' is optional hash to be merged with 'defaults' in the component definition Component.attachTo = attachTo; // enables extension of existing "base" Components Component.mixin = function() { var newComponent = define(); //TODO: fix pretty print var newPrototype = Object.create(Component.prototype); newPrototype.mixedIn = [].concat(Component.prototype.mixedIn); newPrototype.defaults = utils.merge(Component.prototype.defaults); newPrototype.attrDef = Component.prototype.attrDef; compose.mixin(newPrototype, arguments); newComponent.prototype = newPrototype; newComponent.prototype.constructor = newComponent; return newComponent; }; Component.teardownAll = teardownAll; // prepend common mixins to supplied list, then mixin all flavors if (debug.enabled) { mixins.unshift(withLogging); } mixins.unshift(withBase, advice.withAdvice, registry.withRegistration); compose.mixin(Component.prototype, mixins); return Component; } define.teardownAll = function() { registry.components.slice().forEach(function(c) { c.component.teardownAll(); }); registry.reset(); }; return define; } );
JavaScript
0
@@ -2445,16 +2445,25 @@ : define +Component (timelin @@ -2528,16 +2528,25 @@ n define +Component (/*mixin @@ -3242,16 +3242,25 @@ = define +Component (); //TO @@ -4099,16 +4099,25 @@ define +Component .teardow @@ -4265,24 +4265,24 @@ ();%0A %7D;%0A%0A - return d @@ -4286,16 +4286,25 @@ n define +Component ;%0A %7D%0A);
ef5ecfcf3e8c6154060257a35eb853042a489951
Fix build
lib/composite.js
lib/composite.js
'use strict'; module.exports = function (style) { var styleIDs = [], sourceIDs = []; for (var id in style.sources) { var source = style.sources[id]; if (source.type !== "vector") continue; var match = /^mapbox:\/\/(.*)/.exec(source.url); if (!match) continue; styleIDs.push(id); sourceIDs.push(match[1]); } if (styleIDs.length < 2) return style; styleIDs.forEach(function (id) { delete style.sources[id]; }); var compositeID = sourceIDs.join(","); style.sources[compositeID] = { "type": "vector", "url": "mapbox://" + id }; style.layers.forEach(function (layer) { if (styleIDs.indexOf(layer.source) >= 0) { layer.source = compositeID; } }); return style; };
JavaScript
0.000001
@@ -664,18 +664,27 @@ x://%22 + -id +compositeID %0A %7D;%0A
a277c9551c3e9edec5e9929f24f8215e1c15ea09
Remove date from logs
server/log.js
server/log.js
/** * Add a message to the logs * @param {string} type * @param {any} infos */ function log(type, infos) { var msg = new Date().toISOString() + "\t" + type; if (infos) msg += "\t" + JSON.stringify(infos); console.log(msg); } module.exports.log = log;
JavaScript
0
@@ -119,42 +119,8 @@ sg = - new Date().toISOString() + %22%5Ct%22 + typ
7ec574a11532d8f81397ed0715cb4bb13fc00609
fix check on cdn record on db
src/belt.js
src/belt.js
const request = require('request'); const config = require('./config'); const db = require('./db'); const { promisify } = require('util'); const reqAsync = promisify(request); const path = require('path'); const debug = require('./debug'); const REGEX_RAW_GIST_URL = /^https?:\/\/gist\.githubusercontent\.com\/(.+?\/[0-9a-f]+\/raw\/(?:[0-9a-f]+\/)?.+\..+)$/i; const CDN_URL = 'https://cdn.staticaly.com/gist'; const GIT_API_URL = 'https://api.github.com/'; const REGISTRY_URL = 'https://registry.npmjs.org/'; const GEO_IP = 'http://freegeoip.net/json/'; const pkgApi = async (repo, pkg) => { try { const res = await reqAsync(`https://umdfied-cdn.herokuapp.com/standalone/${repo}`); if (res.statusCode === 200 && res.body) { const cdnlink = await createGist(pkg, res.body); return cdnlink; } return false; } catch (e) { console.error(e.stack || e.message) return false; } }; const validatePackage = async (pkg, ver) => { try { let payload = false; const isOrg = /^@/.test(pkg); pkg = encodeURIComponent(pkg); if (!isOrg) { ver = !ver ? 'latest' : ver; const res = await reqAsync(`${REGISTRY_URL + pkg}/${ver}`); const body = JSON.parse(res.body); if (res.statusCode === 200 && body) { payload = { name: body.name, version: body.version }; } }else{ if(ver && !/^v/.test(ver) && ver !== 'latest') { ver = `v${ver}` }else if (ver && ver === 'latest') { ver = '' } const res = await reqAsync(`${REGISTRY_URL + pkg}/${ver}`); const body = JSON.parse(res.body); if (res.statusCode === 200 && body) { payload = { name: body.name, version: ver ? body.version: body['dist-tags'].latest }; } } return payload; } catch (e) { console.error(e.stack || e.message) return false; } }; const createGist = async (pkg, content) => { try { const data = { 'description': `Umdfied build of ${pkg}`, 'public': true, 'files': {} }; pkg = pkg.replace(/@/,'').replace(/\//,'-') const fname = `${pkg}.min.js`; data.files[fname] = { content }; const reqOpts = { method: 'POST', url: '/gists', headers: { 'Authorization': `token ${config.GIT_TOKEN}`, 'User-Agent': 'Umdfied-App' }, baseUrl: GIT_API_URL, json: true, body: data }; const res = await reqAsync(reqOpts); const body = res.body; debug(body, 'createGist'); let cdnurl = body.files[fname].raw_url.replace(REGEX_RAW_GIST_URL, `${CDN_URL}/$1`); return cdnurl; } catch (e) { console.log(e); } }; const getCountry = async ip => { try { const res = await reqAsync({ url: GEO_IP + ip, json: true }); const country = res.body.country_name; if (country) { return country; } return 'anonymous'; } catch (e) { return 'anonymous'; } }; const normalizeIp = ip => ip.replace(/^::ffff:/i, ''); const updateCdn = function(cdnurl) { return cdnurl.replace(/(cdn\.rawgit\.com|gistcdn\.githack\.com)/, 'cdn.staticaly.com/gist') } exports.umdfied = async (pkg, ver, ip) => { try { ip = normalizeIp(ip); const usrCountry = await getCountry(ip); debug(usrCountry, 'usrCountry'); await db.saveUsrInfo({ ip, country: usrCountry }); console.log('Checking DB', 'db'); const repoInfo = await validatePackage(pkg, ver); if (!repoInfo) { return false; } let fromDb = await db.getPkg(repoInfo.name, repoInfo.version); if (fromDb && fromDb.cdn.includes('rawgit.com')) { fromDb = await db.updatePkg(repoInfo.name, repoInfo.version, updateCdn(fromDb.cdn)); } if (fromDb) { return { gitCdn: fromDb.cdn, semver: fromDb.version }; } const repo = `${encodeURIComponent(repoInfo.name)}@${repoInfo.version}`; console.log(repo, 'repo'); const gitCdn = await pkgApi(repo, pkg); console.log(gitCdn, 'gitCdn'); if (!gitCdn) { return false; } await db.savePkg(repoInfo.name, repoInfo.version, gitCdn); return { gitCdn, semver: repoInfo.version }; } catch (e) { console.error(`${e.message}\n${e.stack}`, 'umdfied Error'); return false; } };
JavaScript
0
@@ -3537,16 +3537,17 @@ omDb && +( fromDb.c @@ -3570,16 +3570,55 @@ git.com' + %7C%7C fromDb.cdn.includes('githack.com')) )) %7B%0A
d50fed59d0a2b9069676d67d6635412e60b8c2de
update jshint config reference
task.js
task.js
'use strict'; /* ============================================================ *\ SCRIPTS JS / lint, concat and minify scripts \* ============================================================ */ // Gulp dependencies var concat = require('gulp-concat'); var gulpif = require('gulp-if') var path = require('path'); var sourcemaps = require('gulp-sourcemaps'); // Module dependencies var jshint = require('gulp-jshint'); var jsdoc = require('gulp-jsdoc'); var stylish = require('jshint-stylish'); var uglify = require('gulp-uglify'); module.exports = function(gulp, projectConfig, tasks) { /* -------------------- * CONFIGURATION * ---------------------*/ var TASK_NAME = 'scripts'; // Task Config var taskConfig = require(path.resolve(process.cwd(), projectConfig.dirs.config, 'task.' + TASK_NAME + '.js'))(projectConfig); /* -------------------- * MODULE TASKS * ---------------------*/ gulp.task(TASK_NAME, function () { return gulp.src(taskConfig.src) .pipe(gulpif(!projectConfig.isProd, sourcemaps.init())) // Default only .pipe(concat(taskConfig.bundle)) .pipe(gulpif(projectConfig.isProd, uglify())) // Production only .pipe(gulpif(!projectConfig.isProd, sourcemaps.write('.'))) // Default only .pipe(gulp.dest(projectConfig.paths.dest[TASK_NAME])); }); gulp.task(TASK_NAME + ':lint', function () { return gulp.src(taskConfig.src) .pipe(gulpif(!projectConfig.isProd, jshint(jshintConfig))) // Default only .pipe(gulpif(!projectConfig.isProd, jshint.reporter(stylish))) // Default only .pipe(gulp.dest(projectConfig.paths.dest[TASK_NAME])); }); gulp.task(TASK_NAME + ':docs', function () { return gulp.src(taskConfig.src) .pipe(gulpif(!projectConfig.isProd, jsdoc(taskConfig.docs))); // Default only }); /* -------------------- * WATCH TASKS * ---------------------*/ gulp.task('watch:' + TASK_NAME, function () { gulp.watch( taskConfig.watch, [TASK_NAME] ); }); /* ---------------------------- * CARTRIDGE TASK MANAGEMENT * -----------------------------*/ // Add the clean path for the generated scripts projectConfig.cleanPaths.push(projectConfig.paths.dest[TASK_NAME]); // Add the task to the default list tasks.default.push(TASK_NAME); // Add the task to the watch list tasks.watch.push('watch:' + TASK_NAME); }
JavaScript
0
@@ -1424,20 +1424,25 @@ int( +taskConfig. jshint -Config )))
7b758cacebcbcb16e223826b404b7195a9110146
Use var = function syntax
src/component.js
src/component.js
import { select, local } from "d3-selection"; var myLocal = local(), noop = function (){}; export default function (tagName, className){ var create = noop, render = noop, destroy = noop, selector = className ? "." + className : tagName; function myCreate(){ var my = myLocal.set(this, { selection: select(this), state: {}, render: noop }); create(my.selection, function setState(state){ Object.assign(my.state, state); my.render(); }); my.render = function (){ render(my.selection, my.props, my.state); }; } function myRender(props){ var my = myLocal.get(this); my.props = props; my.render(); } function myDestroy(props){ destroy(myLocal.get(this).state); } function component(selection, props){ var components = selection.selectAll(selector) .data(Array.isArray(props) ? props : [props]); components .enter().append(tagName) .attr("class", className) .each(myCreate) .merge(components) .each(myRender); components .exit() .each(myDestroy) .remove(); } component.render = function(_) { return (render = _, component); }; component.create = function(_) { return (create = _, component); }; component.destroy = function(_) { return (destroy = _, component); }; return component; };
JavaScript
0.005055
@@ -39,17 +39,16 @@ ction%22;%0A -%0A var myLo @@ -209,60 +209,18 @@ -selector = className ? %22.%22 + className : tagName;%0A%0A +myCreate = fun @@ -229,24 +229,16 @@ ion -myCreate ()%7B%0A var @@ -229,24 +229,28 @@ ion ()%7B%0A + var my = myL @@ -272,16 +272,20 @@ %7B%0A + selectio @@ -301,16 +301,20 @@ (this),%0A + st @@ -324,24 +324,28 @@ : %7B%7D,%0A + render: noop @@ -345,16 +345,20 @@ r: noop%0A + %7D);%0A @@ -361,16 +361,20 @@ %7D);%0A + create(m @@ -418,16 +418,20 @@ %7B%0A + Object.a @@ -456,24 +456,28 @@ ate);%0A + my.render(); @@ -477,24 +477,28 @@ nder();%0A + %7D);%0A my.r @@ -485,24 +485,28 @@ %7D);%0A + my.rende @@ -524,24 +524,28 @@ n ()%7B%0A + render(my.se @@ -582,26 +582,29 @@ -%7D;%0A %7D%0A%0A function + %7D;%0A %7D,%0A myR @@ -608,16 +608,28 @@ myRender + = function (props)%7B @@ -629,24 +629,28 @@ props)%7B%0A + var my = myL @@ -665,16 +665,20 @@ (this);%0A + my.p @@ -691,16 +691,20 @@ props;%0A + my.r @@ -718,31 +718,42 @@ ;%0A -%7D%0A%0A function myDestroy + %7D,%0A myDestroy = function (pro @@ -757,24 +757,28 @@ props)%7B%0A + destroy(myLo @@ -805,31 +805,98 @@ ;%0A -%7D%0A%0A function component + %7D,%0A selector = className ? %22.%22 + className : tagName,%0A component = function (sel @@ -907,24 +907,28 @@ on, props)%7B%0A + var comp @@ -972,16 +972,20 @@ )%0A + .data(Ar @@ -1023,16 +1023,20 @@ rops%5D);%0A + comp @@ -1048,16 +1048,20 @@ s%0A + .enter() @@ -1073,24 +1073,28 @@ nd(tagName)%0A + .att @@ -1115,32 +1115,36 @@ ssName)%0A + .each(myCreate)%0A @@ -1149,16 +1149,20 @@ )%0A + .merge(c @@ -1172,32 +1172,36 @@ onents)%0A + .each(myRender); @@ -1201,24 +1201,28 @@ ender);%0A + components%0A @@ -1216,24 +1216,28 @@ components%0A + .exit( @@ -1238,32 +1238,36 @@ .exit()%0A + .each(myDestroy) @@ -1275,16 +1275,20 @@ + .remove( @@ -1296,10 +1296,14 @@ ;%0A -%7D%0A + %7D; %0A c @@ -1431,32 +1431,32 @@ component); %7D;%0A + component.dest @@ -1511,17 +1511,16 @@ nt); %7D;%0A -%0A return
17c0501bfb8a702df832a034c257934c74befd0f
remove console log
src/directory.js
src/directory.js
var Log = require('./log.js') var config = require('../configs/config.json') var fs = require('fs') var Path = require('path') function Directory () { var self = this this.dir = {} this.fileInfo = {} this.loadFileInfo() setInterval(function () { self.updateDownloads() }, 30000) } Directory.prototype.list = function (dir) { if (this.dir[dir] == null) { this.dir[dir] = this.getDir(dir) } else { var s = fs.statSync(Path.join(config.directory.path, dir)) if (this.dir[dir].mtime < s.mtime) { this.dir[dir] = this.getDir(dir) } } return { 'totalSize': this.dir[dir].totalSize, 'files': this.dir[dir].files, 'infos': this.fileInfo } } Directory.prototype.getDir = function (dir) { var self = this var list = {} var totalSize = 0 var files = fs.readdirSync(Path.join(config.directory.path, dir)) if (files.length > 0) { files.forEach(function (file) { var stats = self.getInfo(Path.join(config.directory.path, dir, file)) list[file] = stats totalSize += stats.size }) } var s = fs.statSync(Path.join(config.directory.path, dir)) return { 'mtime': s.mtime, 'totalSize': totalSize, 'files': list } } Directory.prototype.getInfo = function (file) { var stats = fs.statSync(file) var sfile = {} if (stats.isFile()) { sfile = stats } else { stats.size = sizeRecursif(file) sfile = stats } sfile.isfile = stats.isFile() sfile.isdir = stats.isDirectory() return sfile } Directory.prototype.setDownloading = function (file) { var self = this setTimeout(function () { self.fileInfo[file] = self.fileInfo[file] ? self.fileInfo[file] : {} self.fileInfo[file].downloading = self.fileInfo[file].downloading ? {date: new Date(), count: self.fileInfo[file].downloading.count + 1} : {date: new Date(), count: 1} }, 1) } Directory.prototype.finishDownloading = function (file) { var self = this setTimeout(function () { self.fileInfo[file].downloading = self.fileInfo[file].downloading ? {date: self.fileInfo[file].downloading.date, count: self.fileInfo[file].downloading.count - 1} : {date: new Date(), count: 0} if (self.fileInfo[file].downloading.count >= 0) { delete self.fileInfo[file].downloading } }, 1) } Directory.prototype.updateDownloads = function () { var self = this setTimeout(function () { var curDate = new Date() for (var key in self.downloading) { // if downloading for more than 1 hour remove if (curDate - self.fileInfo[key].downloading.date > 3600000) { delete self.fileInfo[key].downloading } } }, 1) } Directory.prototype.isDownloading = function (file) { file = file[0] === '/' ? file.substring(1) : file return this.fileInfo[file] && this.fileInfo[file].downloading ? true : false } Directory.prototype.remove = function (file) { if (this.isDownloading(file)) return -1 setTimeout(function () { fs.stat(Path.join(config.directory.path, file), function (err, stats) { if (err) Log.print(err) if (stats) { if (stats.isDirectory()) { removeRecursif(Path.join(config.directory.path, file)) } else { fs.unlink(Path.join(config.directory.path, file), function (err) { if (err) Log.print(err) }) } } }) }, 1) } Directory.prototype.rename = function (path, oldname, newname) { if (this.isDownloading(path + oldname)) return -1 setTimeout(function () { fs.rename(Path.join(config.directory.path, path, oldname), Path.join(config.directory.path, path, newname), function (err) { if (err) Log.print(err) }) }, 1) } Directory.prototype.mkdir = function (path, name) { setTimeout(function () { fs.mkdir(Path.join(config.directory.path, path, name), function (err) { if (err) Log.print(err) }) }, 1) } Directory.prototype.mv = function (path, file, folder) { if (this.isDownloading(Path.join(path, file))) return -1 setTimeout(function () { fs.rename(Path.join(config.directory.path, path, file), Path.join(config.directory.path, path, folder, file), function (err) { if (err) Log.print(err) }) }, 1) } Directory.prototype.setOwner = function(file, user){ var self = this setTimeout(function () { file = file[0] == '/' ? file.slice(1) : file self.fileInfo[file] = self.fileInfo[file] ? self.fileInfo[file] : {} if(self.fileInfo[file].owner == null){ self.fileInfo[file].owner = user } self.saveFileInfo() },1) } Directory.prototype.loadFileInfo = function(){ var self = this setTimeout(function(){ fs.readFile('configs/fileInfo.json', function(err, data) { if (err){ console.log(err) self.fileInfo = {} self.saveFileInfo() } else { self.fileInfo = JSON.parse(data) } console.log(self.fileInfo) }) },1) } Directory.prototype.saveFileInfo = function(){ var self = this setTimeout(function(){ fs.writeFile('configs/fileInfo.json', JSON.stringify(self.fileInfo), function(err) { if (err) console.log(err) }) },1) } function removeRecursif (path) { setTimeout(function () { if (fs.existsSync(path)) { fs.readdirSync(path).forEach(function (file, index) { var curPath = Path.join(path, file) if (fs.lstatSync(curPath).isDirectory()) { // recurse removeRecursif(curPath) } else { // delete file fs.unlinkSync(curPath) } }) fs.rmdirSync(path) } }, 1) } function sizeRecursif (path) { var size = 0 if (fs.existsSync(path)) { fs.readdirSync(path).forEach(function (file, index) { var curPath = Path.join(path, file) if (fs.lstatSync(curPath).isDirectory()) { // recurse size += sizeRecursif(curPath) } else { // read size size += fs.statSync(curPath).size } }) return size } } module.exports = new Directory()
JavaScript
0.000003
@@ -4876,41 +4876,8 @@ %7D%0A - console.log(self.fileInfo)%0A
245dd2202da868fc97ed8f49db1cf4015b6e61a8
Fix windows checker...
web/isWindows.js
web/isWindows.js
const os = require('os'); var isWindows = ( os.platform() == 'win32' // true evenon 64 bit archs || os.release().substr('Microsoft') > -1 // bash on Windows 10 scenario ); module.exports = isWindows;
JavaScript
0
@@ -119,14 +119,15 @@ e(). -substr +indexOf ('Mi
1c8c5832527263aaf3cfbe3cfda3696574a76e4c
remove autoscale: true
lib/generator.js
lib/generator.js
/** * Created by azu on 2014/09/28. * LICENSE : MIT */ "use strict"; var fs = require("fs"); var path = require("path"); var execSync = require("child_process").execSync; var dateFormat = require("dateformat"); var mustache = require("mustache"); const { createMarkdown } = require("safe-marked"); const convertMarkdown = createMarkdown(); function loadMarkdown(filePath) { var content = fs.readFileSync(path.resolve(process.cwd(), filePath), "utf-8") .replace("autoscale: true", ""); return convertMarkdown(content); } function getTitleMarkdown(filePath) { var getTitle = require("get-md-title"); var content = fs.readFileSync(path.resolve(process.cwd(), filePath), "utf-8"); return getTitle(content).text; } function getModifiedDate(filePath) { // today return new Date(); } // http://stackoverflow.com/questions/2390199/finding-the-date-time-a-file-was-first-added-to-a-git-repository function getCreateDate(filePath) { if (filePath == null) { return new Date(); } var log = execSync("git log --diff-filter=A --follow --format=%aD -1 -- '" + filePath + "'"); if (log == null || Buffer.isBuffer(log)) { return new Date(); } return new Date(log); } function generator(options) { var filePath = path.resolve(process.cwd(), options.markdown); var templateObject = { title: options.markdown ? getTitleMarkdown(filePath) : path.basename(options["pdfUrl"]), "slide-url": options["slideUrl"], "base-url": options["baseUrl"], "pdf-url": options["pdfUrl"], markdown: options.markdown ? loadMarkdown(options.markdown) : "", dateModified: dateFormat(getModifiedDate(filePath), "yyyy-mm-dd"), datePublished: dateFormat(getCreateDate(filePath), "yyyy-mm-dd") }; var template = fs.readFileSync(__dirname + "/../template/index.html", "utf-8"); return mustache.to_html(template, templateObject); } module.exports = generator;
JavaScript
0.999999
@@ -470,17 +470,21 @@ replace( -%22 +/%5E%5Cs* autoscal @@ -489,14 +489,16 @@ ale: - +%5Cs* true -%22 +/ , %22%22
1cdc5ece396a564836af1b7cfd39ed5e6cbc1217
mongify a complex object
test.js
test.js
var Mongify = require('./'); var Mongodb = require('mongodb'); var Lab = require('lab'); var Chai = require('chai'); Chai.should(); var it = Lab.test; Lab.experiment('mongify', function(){ it('should convert an ObjectID string to the Mongodb.ObjectID', function(done){ Mongify('523396be6a51026f63000001').should.eql(new Mongodb.ObjectID('523396be6a51026f63000001')); done(); }), it('should keep the string "a message" unchanged', function(done){ Mongify('a message').should.eql("a message"); done(); }), it('should keep a Mongo.ObjectID unchanged', function(done){ Mongify(new Mongodb.ObjectID('523396be6a51026f63000001')).should.eql(new Mongodb.ObjectID('523396be6a51026f63000001')); done(); }), it('should convert an object with an ISO date string to an object with Date', function(done){ var anObject = { content: { }, createdAt: '523396be6a51026f63000001' } Mongify(anObject).should.eql({ content: { }, createdAt: new Mongodb.ObjectID('523396be6a51026f63000001') }); done(); }), it('should return a different object then the one it was converting', function(done){ var anObject = { content: { }, createdAt: '523396be6a51026f63000009' } Mongify(anObject).should.not.equal(anObject); done(); }); });
JavaScript
0.999999
@@ -227,14 +227,27 @@ ing -to the +(24hex string) to a Mon @@ -766,18 +766,15 @@ th a -n ISO date + 24-hex str @@ -787,24 +787,16 @@ an -o +O bject - with Date +ID ', f @@ -845,33 +845,27 @@ nt: %7B %7D,%0A%09%09%09 -createdAt +_id : '523396be6 @@ -938,25 +938,19 @@ %7B %7D,%0A%09%09%09 -createdAt +_id : new Mo @@ -1145,95 +1145,753 @@ %0A%09%09%09 -createdAt: '523396be6a51026f63000009'%0A%09%09%7D%0A%09%09Mongify(anObject).should.not.equal(anObject +_id: '523396be6a51026f63000009'%0A%09%09%7D%0A%09%09Mongify(anObject).should.not.equal(anObject);%0A%0A%09%09done();%0A%09%7D),%0A%0A%09it('should convert an object with nested 24-hex strings to an object with ObjectIDs', function(done)%7B%0A%09%09var anObject = %7B%0A%09%09%09number: 3441,%0A%09%09%09_id: new Mongodb.ObjectID(),%0A%09%09%09content: %7B content_id: '523396be6a51026f63000009', i: %7Bam: %7Blosing: %7Bit_id: '523396be6a51026f63000009', yep: %22i am%22%7D%7D%7D%7D,%0A%09%09%09super_id: '523396be6a51026f63000009'%0A%09%09%7D%0A%09%09Mongify(anObject).should.eql(%7B%0A%09%09%09number: 3441,%0A%09%09%09_id: anObject._id,%0A%09%09%09content: %7B content_id: new Mongodb.ObjectID('523396be6a51026f63000009'), i: %7Bam: %7Blosing: %7Bit_id: new Mongodb.ObjectID('523396be6a51026f63000009'), yep: %22i am%22%7D%7D%7D%7D,%0A%09%09%09super_id: new Mongodb.ObjectID('523396be6a51026f63000009')%0A%09%09%7D );%0A%0A
d2ef1b3bdfc3cc24298c9634181e012274094e8b
fix lint warnings in lib/glob_test.js
lib/glob_test.js
lib/glob_test.js
// Apply glob function to path specified on command line. var glob = require('./glob'), fs = require('fs'); if (process.argv.length != 3) { console.log("Bad usage"); process.exit(1); } glob.glob(process.argv[2], fs, function(err, files) { if (err) { console.log(err); } else { files.forEach(function(file) { console.log(file); }); } });
JavaScript
0.000001
@@ -84,13 +84,13 @@ ob') -,%0A +;%0Avar fs @@ -133,16 +133,17 @@ ength != += 3) %7B%0A @@ -154,17 +154,17 @@ ole.log( -%22 +' Bad usag @@ -168,9 +168,9 @@ sage -%22 +' );%0A
ed54b295d3a7746b453cc3f6edba369ff5175678
Use knex.destroy promise in test
test.js
test.js
'use strict'; var Promise = require('bluebird'); Promise.longStackTraces(); var test = require('tape'); var session = require('express-session'); var KnexStore = require('./index.js')(session); var knexPg = require('knex')({ client: 'pg', connection: { host: '127.0.0.1', user: 'postgres', password: '', database: 'travis_ci_test' } }); var knexMysql = require('knex')({ client: 'mysql', connection: { host: '127.0.0.1', user: 'travis', password: '', database: 'travis_ci_test' } }); var stores = []; stores.push(new KnexStore({db: ':memory:', dir: 'dbs'})); stores.push(new KnexStore({ knex: knexPg })); stores.push(new KnexStore({ knex: knexMysql })) stores.forEach(function (store) { test('initial clear', function (t) { t.plan(3); store.clear(function(err, success) { t.error(err); store.length(function(err, len) { t.error(err, 'no error after clear'); t.equal(len, 0, 'empty after clear'); }); }) }) test('set then clear', function (t) { t.plan(4); store.set('1092348234', {cookie: {maxAge: 1000}, name: 'InsertThenClear'}) .then(function () { store.clear(function(err, cleared) { t.error(err); t.equal(1, cleared, 'cleared 1'); store.length(function(err, len) { t.error(err, 'no error after clear'); t.equal(len, 0, 'empty after clear'); }); }) }) }) test('double clear', function (t) { t.plan(4); store.clear() .then(function () { return store.clear() }) .then(function () { store.clear(function(err, cleared) { t.error(err); t.equal(0, cleared, 'cleared 0'); store.length(function(err, len) { t.notOk(err, 'no error after clear'); t.equal(len, 0, 'length'); }); }) }) }) test('destroy', function (t) { t.plan(4); store.set('555666777', {cookie: {maxAge: 1000}, name: 'Rob Dobilina'}, function(err, rows) { t.error(err); if (rows.rowCount && rows.rowCount > 1) { t.fail('Row count too large'); } store.destroy('555666777', function(err) { t.error(err); store.length(function(err, len) { t.error(err, 'error'); t.equal(len, 0); }); }); }); }) test('set', function (t) { store.set('1111222233334444', {cookie: {maxAge: 20000}, name: 'sample name'}, function(err, rows) { t.error(err); if (rows.rowCount) { t.equal(rows.rowCount, 1, 'row count'); } t.end(); }); }) test('retrieve', function (t) { t.plan(3); store.get('1111222233334444', function(err, session) { t.error(err); t.ok(session, 'session'); t.deepEqual(session,{cookie: {maxAge: 20000 }, name: 'sample name'}) }) }) test('unknown session', function (t) { t.plan(2); store.get('hope-and-change', function(err, rows) { t.error(err); t.equal(rows, undefined, 'unknown session is not undefined'); }) }) test('only one session should exist', function (t) { t.plan(2); store.length(function(err, len) { t.error(err); t.equal(len, 1); }); }) test('cleanup', function (t) { store.knex.destroy(); t.end(); oneDbDone(); }) }) var done = 0; function oneDbDone() { done++; if (done == stores.length) { process.exit(); } }
JavaScript
0
@@ -3034,142 +3034,29 @@ oy() -;%0A%09%09t.end();%0A%09%09oneDbDone();%0A%09%7D)%09%0A%7D)%0A%0Avar done = 0;%0Afunction oneDbDone() %7B%0A%09done++;%0A%09if (done == stores.length) %7B%0A%09%09process.exit();%0A%09%7D%0A%7D +.then(t.end);%0A%09%7D)%09%0A%7D)%0A %0A%0A%0A
9adac659db4be46095a13c49bf1fbf9210df29b0
fix type in test decription
test.js
test.js
'use strict'; var assert = require('assert'); var gutil = require('gulp-util'); var wpRev = require('./'); it('should ', function (cb) { var stream = wpRev(); stream.on('data', function (file) { assert.strictEqual(file.contents.toString(), 'unicorns'); }); stream.on('end', cb); stream.write(new gutil.File({ base: __dirname, path: __dirname + '/file.ext', contents: new Buffer('unicorns') })); stream.end(); });
JavaScript
0.000001
@@ -112,16 +112,30 @@ 'should +write unicorns ', funct
7c6fea993784c47a500cf9119d52a24090c3cdef
test if `.test` is attached before first `flip-tape` call
test.js
test.js
const tape = require('tape') const wrappedMethods = require('./methods') var tapeMock = (arg0, arg1, cb) => { cb = cb || arg1 || arg0 // `arg0` and `arg1` are optional in `tape` let res = cb(testObjectMock) return [arg0, arg1, res] } var testObjectMock = { end: function () {} } wrappedMethods.forEach(elem => { testObjectMock[elem] = function () { return arguments } }) global.flipTape = { tapeMock } const flippedTape = require('.') var arityToMethod = { 1: ['fail', 'pass', 'skip'], 2: ['ok', 'notOk', 'error'], 3: ['equal', 'notEqual', 'deepEqual', 'notDeepEqual', 'deepLooseEqual', 'notDeepLooseEqual', 'throws', 'doesNotThrow', 'comment'] } flippedTape(x => { tape('`String.prototype.test(cb)`', t => { t.plan(2) let cbArgument = null let cbMock = t => { cbArgument = t } let testOpts = {test: 123} let result = 'msg'.test(testOpts, cbMock) result[0] = result[0].toString() t.deepEqual(result, tapeMock('msg', testOpts, cbMock), '`tape` is attached to `String.prototype` as `test`') 'msg'.test(cbMock) t.deepEqual(cbArgument, testObjectMock, 'test object is passed on to cb') }) tape('`String.prototype.t(cb)`', t => { t.plan(1) let cbArgument = null let cbMock = t => { cbArgument = t } 'msg'.t(cbMock) t.deepEqual(cbArgument, testObjectMock, 'test object is passed on to cb') }) Object.keys(arityToMethod).forEach(arity => { arity = +arity arityToMethod[arity].forEach(method => { let args = callMethod(method, arity) tape('`String.prototype.' + method + '()`', t => { if (arity === 3) { t.equal(args[1].toString(), 'arg1', 'second argument is passed on') } if ([2, 3].includes(arity)) { t.equal(args[0].toString(), 'arg0', 'first argument is passed on') } t.equal(args[arity - 1].toString(), 'msg', 'message argument is passed on') t.end() }) }) }) }) function callMethod (method, arity) { if (arity === 3) return 'msg'[method]('arg0', 'arg1') if (arity === 2) return 'msg'[method]('arg0') return 'msg'[method]() }
JavaScript
0.000001
@@ -67,19 +67,19 @@ hods')%0A%0A -var +let tapeMoc @@ -234,19 +234,19 @@ res%5D%0A%7D%0A -var +let testObj @@ -404,20 +404,18 @@ eMock %7D%0A -cons +le t flippe @@ -440,248 +440,8 @@ ')%0A%0A -var arityToMethod = %7B%0A 1: %5B'fail', 'pass', 'skip'%5D,%0A 2: %5B'ok', 'notOk', 'error'%5D,%0A 3: %5B'equal', 'notEqual', 'deepEqual', 'notDeepEqual', 'deepLooseEqual', 'notDeepLooseEqual', 'throws', 'doesNotThrow', 'comment'%5D%0A%7D%0A%0AflippedTape(x =%3E %7B%0A tape @@ -471,34 +471,32 @@ t(cb)%60', t =%3E %7B%0A - t.plan(2)%0A @@ -491,18 +491,16 @@ plan(2)%0A - let cb @@ -507,34 +507,32 @@ Argument = null%0A - let cbMock = t @@ -555,18 +555,16 @@ = t %7D%0A%0A - let te @@ -584,18 +584,16 @@ t: 123%7D%0A - let re @@ -628,18 +628,16 @@ cbMock)%0A - result @@ -663,18 +663,16 @@ tring()%0A - t.deep @@ -722,16 +722,21 @@ ock), '%60 +flip- tape%60 is @@ -776,22 +776,48 @@ s %60test%60 + before the first call to it ')%0A%0A - 'msg'. @@ -821,34 +821,32 @@ g'.test(cbMock)%0A - t.deepEqual(cb @@ -901,28 +901,274 @@ on to cb')%0A +%7D)%0A%0AflippedTape(x =%3E %7B%0A var arityToMethod = %7B%0A 1: %5B'fail', 'pass', 'skip'%5D,%0A 2: %5B'ok', 'notOk', 'error'%5D,%0A 3: %5B'equal', 'notEqual', 'deepEqual', 'notDeepEqual', 'deepLooseEqual', 'notDeepLooseEqual', 'throws', 'doesNotThrow', 'comment'%5D%0A %7D -) %0A%0A tape('%60S
85ebb5de9e70ff90ace1d8df54b4a10ab683311c
Add test should clear listeners for bidirectional data binding
test.js
test.js
var expect = require("chai").expect var ChiasmLinks = require("./index"); var ChiasmComponent = require("chiasm-component"); var Chiasm = require("chiasm"); function SimpleComponent(){ return new ChiasmComponent({ x: 5 }); } function initChiasm(){ var chiasm = new Chiasm(); chiasm.plugins.simpleComponent = SimpleComponent; chiasm.plugins.links = ChiasmLinks; return chiasm; } describe("ChiasmLinks", function() { it("should implement unidirectional data binding", function (done) { var chiasm = initChiasm(); chiasm.setConfig({ a: { plugin: "simpleComponent", state: { x: 100 } }, b: { plugin: "simpleComponent" }, links: { plugin: "links", state: { bindings: ["a.x -> b.x"] } } }).then(function (){ chiasm.getComponent("b").then(function (b){ b.when("x", function (x){ if(x === 100){ // If we are here, then the change successfully propagated from a to b. done(); } }); }); }); }); it("should clear listeners for unidirectional data binding", function (done) { var chiasm = initChiasm(); chiasm.setConfig({ a: { plugin: "simpleComponent", state: { x: 100 } }, b: { plugin: "simpleComponent" }, links: { plugin: "links", state: { bindings: ["a.x -> b.x"] } } }).then(function (){ chiasm.getComponent("b").then(function (b){ b.when("x", function (x){ if(x === 100){ // If we are here, then the change successfully propagated from a to b. // Now we'll remove the bindings. chiasm.getComponent("links").then(function (links){ links.bindings = []; // At this point, the bindings listeners should be removed. // setTimeout is needed here to queue our code to run // AFTER the model.when handler for "bindings" has executed. setTimeout(function (){ // Make a change in a.x and make sure it doesn't propagate to b.x. chiasm.getComponent("a").then(function (a){ a.x = 500; setTimeout(function (){ expect(b.x).to.equal(100); done(); }, 0); }); }, 0); }); } }); }); }); }); it("should implement bidirectional data binding", function (done) { var chiasm = initChiasm(); chiasm.setConfig({ a: { plugin: "simpleComponent", state: { x: 100 } }, b: { plugin: "simpleComponent" }, links: { plugin: "links", state: { bindings: ["a.x <-> b.x"] } } }).then(function (){ chiasm.getComponent("b").then(function (b){ b.when("x", function (x){ if(x === 100){ // If we are here, then the change successfully propagated from a to b. // This change should propagate from b to a. b.x = 500; } }); }); chiasm.getComponent("a").then(function (a){ a.when("x", function (x){ if(x === 500){ // If we are here, then the change successfully propagated from b to a. done(); } }); }); }); }); });
JavaScript
0.000001
@@ -3525,13 +3525,1692 @@ );%0A %7D); +%0A%0A it(%22should clear listeners for bidirectional data binding%22, function (done) %7B%0A var chiasm = initChiasm();%0A chiasm.setConfig(%7B%0A a: %7B%0A plugin: %22simpleComponent%22,%0A state: %7B%0A x: 100%0A %7D%0A %7D,%0A b: %7B%0A plugin: %22simpleComponent%22%0A %7D,%0A links: %7B%0A plugin: %22links%22,%0A state: %7B%0A bindings: %5B%22a.x %3C-%3E b.x%22%5D%0A %7D%0A %7D%0A %7D).then(function ()%7B%0A chiasm.getComponent(%22b%22).then(function (b)%7B%0A b.when(%22x%22, function (x)%7B%0A if(x === 100)%7B%0A // If we are here, then the change successfully propagated from a to b.%0A%0A // Now we'll remove the bindings.%0A chiasm.getComponent(%22links%22).then(function (links)%7B%0A links.bindings = %5B%5D;%0A%0A // At this point, the bindings listeners should be removed.%0A // setTimeout is needed here to queue our code to run%0A // AFTER the model.when handler for %22bindings%22 has executed.%0A setTimeout(function ()%7B%0A%0A // Make a change in a.x and make sure it doesn't propagate to b.x.%0A chiasm.getComponent(%22a%22).then(function (a)%7B%0A a.x = 500;%0A setTimeout(function ()%7B%0A expect(b.x).to.equal(100);%0A%0A // Make a change in b.x and make sure it doesn't propagate to a.x.%0A b.x = 99;%0A setTimeout(function ()%7B%0A expect(a.x).to.equal(500);%0A done();%0A %7D, 0);%0A %7D, 0);%0A %7D);%0A %7D, 0);%0A %7D);%0A %7D%0A %7D);%0A %7D);%0A %7D);%0A %7D); %0A%7D);%0A
54793c88b722f8e1769c53200cec7198dd041a64
Fix test for unclosed tag
test.js
test.js
'use strict'; var assert = require('assert'); var gutil = require('gulp-util'); var jsxcs = require('./'); describe('gulp-jsxcs test suite:', function() { this.timeout(5000); it('check JS files', function (cb) { var stream = jsxcs(); var success = false; stream.on('data', function() {}); stream.on('end', function() { if (!success) { assert(false, 'Failed to raise expected style errors'); } cb(); }); stream.on('error', function (err) { if (/Illegal space before/.test(err) && /Multiple var declaration/.test(err) && /Invalid quote mark found/.test(err)) { success = true; } }); stream.write(new gutil.File({ base: __dirname, path: __dirname + '/fixture.js', contents: new Buffer('var x = 1,y = 2;') })); stream.write(new gutil.File({ base: __dirname, path: __dirname + '/fixture2.js', contents: new Buffer('var x = { a: 1 };') })); stream.write(new gutil.File({ base: __dirname, path: __dirname + '/fixture3.js', contents: new Buffer('var x = "foo";') })); stream.end(); }); it('check JS files using a preset', function (cb) { var stream = jsxcs({preset: 'google'}); var success = false; stream.on('data', function() {}); stream.on('end', function() { if (!success) { assert(false, 'Failed to raise expected style errors'); } cb(); }); stream.on('error', function (err) { if (/Missing line feed at file end/.test(err)) { success = true; } }); stream.write(new gutil.File({ base: __dirname, path: __dirname + '/fixture.js', contents: new Buffer('var x = 1,y = 2;') })); stream.end(); }); it('check JS files with JSX pragma and ignore transformed blocks', function (cb) { var stream = jsxcs({preset: 'google'}); var success = false; stream.on('data', function() {}); stream.on('end', function() { if (!success) { assert(false, 'Failed to raise expected style errors'); } cb(); }); stream.on('error', function (err) { if (/Invalid quote mark found/.test(err)) { console.error(err); assert(false, 'Identified error in JSX block'); } else if (/Illegal space before/.test(err) && /Multiple var declaration/.test(err)) { success = true; } }); stream.write(new gutil.File({ base: __dirname, path: __dirname + '/fixture.js', contents: new Buffer('/** @jsx React.DOM */\n' + 'var x = 1,y = 2;\n' + 'var elem = (\n' + ' <div className="test">\n' + ' test\n' + ' </div>\n' + ' );\n' + 'var x = { a: 1 };') })); stream.end(); }); it('check JSX files without JSX pragma and ignore transformed blocks', function (cb) { var stream = jsxcs(); var success = false; stream.on('data', function() {}); stream.on('end', function() { if (!success) { assert(false, 'Failed to raise expected style errors'); } cb(); }); stream.on('error', function (err) { if (/Invalid quote mark found/.test(err)) { console.error(err); assert(false, 'Identified error in JSX block'); } else if (/Illegal space before/.test(err) && /Multiple var declaration/.test(err)) { success = true; } }); stream.write(new gutil.File({ base: __dirname, path: __dirname + '/fixture.jsx', contents: new Buffer('var x = 1,y = 2;\n' + 'var elem = (\n' + ' <div className="test">\n' + ' test\n' + ' </div>\n' + ' );\n' + 'var x = { a: 1 };') })); stream.end(); }); it('check valid JS files', function (cb) { var stream = jsxcs(); stream.on('data', function () {}); stream.on('error', function (err) { assert(false); }); stream.on('end', cb); stream.write(new gutil.File({ path: __dirname + '/fixture.js', contents: new Buffer('var x = 1; var y = 2;') })); stream.end(); }); it('check and respect "excludeFiles" from config', function (cb) { var stream = jsxcs(); stream.on('data', function () {}); stream.on('error', function (err) { assert(!err, err); }); stream.on('end', cb); stream.write(new gutil.File({ base: __dirname, path: __dirname + '/excluded.js', contents: new Buffer('var x = { a: 1 };') })); stream.end(); }); it('check valid JS files with flow types', function (cb) { var stream = jsxcs(); stream.on('data', function () {}); stream.on('error', function (err) { assert(false); }); stream.on('end', cb); stream.write(new gutil.File({ path: __dirname + '/fixture.js', contents: new Buffer('function foo(x: string): string {\n return x;\n}') })); stream.end(); }); it('check valid file with JSX in last line', function(cb) { var stream = jsxcs({requireLineFeedAtFileEnd: true}); stream.on('data', function () {}); stream.on('error', function (err) { assert(false); }); stream.on('end', cb); stream.write(new gutil.File({ path: __dirname + '/fixture.js', contents: new Buffer('/** @jsx React.DOM */\n' + 'var x = (<div />);\n') })); stream.end(); }); it('check valid file with requireCapitalizedComments', function(cb) { var stream = jsxcs({requireCapitalizedComments: true}); stream.on('data', function () {}); stream.on('error', function (err) { assert(false); }); stream.on('end', cb); stream.write(new gutil.File({ path: __dirname + '/fixture.js', contents: new Buffer('/** @jsx React.DOM */\n' + 'var x = (<div />);\n' + '\n' + 'var y = 2;\n' + '\n' + 'var z = (<div />);\n') })); stream.end(); }); it('check JS files with parse error', function (cb) { var stream = jsxcs(); var success = false; stream.on('data', function() {}); stream.on('end', function() { if (!success) { assert(false, 'Failed to raise expected parse errors'); } cb(); }); stream.on('error', function (err) { if (/Expected corresponding XJS closing tag/.test(err)) { success = true; } }); stream.write(new gutil.File({ base: __dirname, path: __dirname + '/fixture.js', contents: new Buffer('/** @jsx React.DOM */\n' + 'var x = (<div></span>);\n') })); stream.end(); }); });
JavaScript
0.000001
@@ -7772,11 +7772,17 @@ ing +( XJS +%7CJSX) clo
d1937262e6806c5ab7e98588977601c4f33625e8
add messages to log
test.js
test.js
const fs = require('fs'); code = fs.readFileSync('contract.sol','utf8'); var solc = require('solc'); var output = solc.compile(code, 1); if (output.errors) { console.log(output.errors); return 1; } else { console.log(output); return 0; }
JavaScript
0.000001
@@ -181,16 +181,50 @@ rrors);%0A + console.log(%22Build succeeded.%22)%0A return @@ -259,16 +259,47 @@ utput);%0A + console.log(%22Build failed.%22)%0A return
2ce8124332fe827aa0b496355d9785850f28a3d4
Fix test
test.js
test.js
import test from 'ava'; import requireUncached from 'require-uncached'; import Brakes from 'brakes'; import register from 'prom-client/lib/register'; const origNow = Date.now; test.beforeEach(t => { t.context.module = requireUncached('./brakes-events'); Date.now = () => 1494222986972; register.clear(); }); test.after.always(() => { Date.now = origNow; register.clear(); }); test.serial('add metrics on new brakes', t => { const brake = new Brakes(() => Promise.resolve(), { name: 'some-name' }); t.true(register.getMetricsAsJSON().length === 0); t.context.module(brake); t.true(register.getMetricsAsJSON().length === 9); brake.destroy(); }); test.serial('listen to execution', async t => { const brake = new Brakes(() => Promise.resolve(), { name: 'some-name' }); t.context.module(brake); t.deepEqual(register.getMetricsAsJSON()[0].values, []); await brake.exec(); t.deepEqual(register.getMetricsAsJSON()[0].values, [ { value: 1, // eslint-disable-next-line camelcase labels: { breaker_name: 'some-name' }, timestamp: 1494222986972, }, ]); brake.destroy(); }); test.serial('record timings in seconds', async t => { Date.now = origNow; const brake = new Brakes( () => new Promise(resolve => setTimeout(resolve, 250)), { name: 'some-name' } ); t.context.module(brake); t.deepEqual(register.getMetricsAsJSON()[0].values, []); await brake.exec(); const durationSum = register.getMetricsAsJSON()[7].values[9].value; t.true(durationSum > 0.250 && durationSum < 0.275); brake.destroy(); }); test.serial('handle failure', async t => { const brake = new Brakes(() => Promise.reject(new Error('test')), { name: 'some-name', }); t.context.module(brake); t.deepEqual(register.getMetricsAsJSON()[0].values, []); try { await brake.exec(); } catch (e) { // ignored } const execs = register.getMetricsAsJSON()[0].values[0].value; const successes = register.getMetricsAsJSON()[1].values; const failures = register.getMetricsAsJSON()[2].values[0].value; const timeouts = register.getMetricsAsJSON()[3].values; t.true(execs === 1); t.true(successes.length === 0); t.true(failures === 1); t.true(timeouts.length === 0); brake.destroy(); }); test.serial('handle timeouts', async t => { const brake = new Brakes( () => new Promise(resolve => setTimeout(resolve, 250)), { name: 'some-name', timeout: 50 } ); t.context.module(brake); t.deepEqual(register.getMetricsAsJSON()[0].values, []); try { await brake.exec(); } catch (e) { // ignored } const execs = register.getMetricsAsJSON()[0].values[0].value; const successes = register.getMetricsAsJSON()[1].values; const failures = register.getMetricsAsJSON()[2].values; const timeouts = register.getMetricsAsJSON()[3].values[0].value; t.true(execs === 1); t.true(successes.length === 0); t.true(failures.length === 0); t.true(timeouts === 1); brake.destroy(); }); test.serial('return input', t => { const brake = new Brakes(() => Promise.resolve(), { name: 'some-name' }); t.true(t.context.module(brake) === brake); brake.destroy(); });
JavaScript
0.000004
@@ -1625,16 +1625,17 @@ ionSum %3E += 0.250 &
7ac5a1313aa17439e8d9cb2be82bbc14a1f22873
improve tests
test.js
test.js
"use strict"; var assert = require('assert'); var lib = require('./vcgencmd'); /* measureClock(clock) */ assert.throws(function() { lib.measureClock(); }, /incorrect/); assert.throws(function() { lib.measureClock('Core'); }, /incorrect/); assert(lib.measureClock('core') > 0); /* measureVolts(id) */ assert.throws(function() { lib.measureVolts('Core'); }, /incorrect/); assert(lib.measureVolts() > 0); assert(lib.measureVolts('core') > 0); /* measureTemp() */ assert(lib.measureTemp() > 0); /* codecEnabled(codec) */ assert.throws(function() { lib.codecEnabled(); }, /incorrect/); assert.throws(function() { lib.codecEnabled('h264'); }, /incorrect/); assert.equal(typeof lib.codecEnabled('H264'), 'boolean'); /* getConfig(config|int|str) */ assert.throws(function() { lib.getConfig(); }, /incorrect/); assert.throws(function() { lib.getConfig('test'); }, /incorrect/); assert.equal(typeof lib.getConfig('arm_freq'), 'number'); assert(Object.keys(lib.getConfig('int')).length > 0); /* getCamera() */ assert.equal(typeof lib.getCamera().supported, 'boolean'); assert.equal(typeof lib.getCamera().detected, 'boolean'); /* getMem(mem) */ assert.throws(function() { lib.getMem(); }, /incorrect/); assert.throws(function() { lib.getMem('test'); }, /incorrect/); assert.equal(typeof lib.getMem('arm'), 'number'); /* getLCDInfo() */ var lcdInfo = lib.getLCDInfo(); assert.equal(typeof lcdInfo.width, 'number'); assert(lcdInfo.width > 0); assert.equal(typeof lcdInfo.height, 'number'); assert(lcdInfo.height > 0); assert.equal(typeof lcdInfo.depth, 'number'); assert(lcdInfo.depth > 0);
JavaScript
0.000016
@@ -231,39 +231,48 @@ , /incorrect/);%0A -assert( +var coreClock = lib.measureClock @@ -271,32 +271,92 @@ ureClock('core') +;%0Aassert.equal(typeof coreClock, 'number');%0Aassert(coreClock %3E 0);%0A%0A/*%0A m @@ -445,23 +445,32 @@ rect/);%0A -assert( +var coreVolts = lib.meas @@ -478,17 +478,83 @@ reVolts( -) +'core');%0Aassert.equal(typeof coreVolts, 'number');%0Aassert(coreVolts %3E 0);%0Aa @@ -576,22 +576,16 @@ reVolts( -'core' ) %3E 0);%0A @@ -610,23 +610,27 @@ p()%0A */%0A -assert( +var temp = lib.meas @@ -638,16 +638,66 @@ reTemp() +;%0Aassert.equal(typeof temp, 'number');%0Aassert(temp %3E 0);%0A%0A @@ -1217,24 +1217,54 @@ amera()%0A */%0A +var camera = lib.getCamera();%0A assert.equal @@ -1271,31 +1271,22 @@ (typeof -lib.getC +c amera -() .support @@ -1321,31 +1321,22 @@ (typeof -lib.getC +c amera -() .detecte @@ -1500,55 +1500,96 @@ /);%0A -assert.equal(typeof lib.getMem('arm'), 'number' +var armMem = lib.getMem('arm');%0Aassert.equal(typeof armMem, 'number');%0Aassert(armMem %3E 0 );%0A%0A
706d6414fc85c82dd5b2c7b443fd6253cccd00bf
Add better logging from Tenon on errors.
test.js
test.js
var unirest = require('unirest'); var config = require('./config.json'); var jira = require('jira-api'); var Request = unirest.post(config.tenon.tenonInstanceDomain + '/api/index.php') .send({ key: config.tenon.apiKey, projectID: config.tenon.projectID, url: 'http://www.google.com' // In the real world you're going to want to pass each url in some other way }).end(function (response) { console.log('Status:'); console.log(response.body.status); console.log('Response ID:'); console.log(response.body.request.responseID); console.log('Total Issues: '); console.log(response.body.resultSummary.issues.totalIssues); console.log('Result URL:'); console.log(config.tenon.tenonInstanceDomain + '/history.php?responseID=' + response.body.request.responseID); if (response.body.status === 200) { var fullIssueDescription = config.jira.issueDescriptionPre + '\n' + 'Density: ' + response.body.resultSummary.density.allDensity + '\n' + 'Total Issues: ' + response.body.resultSummary.issues.totalIssues + '\n' + 'Level A Issues: ' + response.body.resultSummary.issuesByLevel.A.count + '\n' + 'Level AA Issues: ' + response.body.resultSummary.issuesByLevel.AA.count + '\n' + 'Level AAA Issues: ' + response.body.resultSummary.issuesByLevel.AAA.count + '\n' + 'More at: ' + config.tenon.tenonInstanceDomain + '/history.php?responseID=' + response.body.request.responseID + '\n'; var options = { config: { "username": config.jira.user, "password": config.jira.password, "host": config.jira.host }, data: { fields: { project: { key: config.jira.projectKey, }, summary: response.body.resultSummary.issues.totalIssues + ' ' + config.jira.issueSummaryPre + ' ' + response.body.request.url, description: fullIssueDescription, issuetype: { name: config.jira.issueType } } } }; jira.issue.post(options, function (response) { // in the real world you'll want to do something more interesting with the response. console.log(JSON.stringify(response, null, 4)); }); } });
JavaScript
0
@@ -395,25 +395,72 @@ response) %7B%0A + %0A + if (response.body.status === 200) %7B%0A%0A console. @@ -471,24 +471,26 @@ 'Status:');%0A + console. @@ -512,25 +512,33 @@ dy.status);%0A -%0A + %0A console. @@ -554,24 +554,26 @@ onse ID:');%0A + console. @@ -608,24 +608,26 @@ sponseID);%0A%0A + console. @@ -645,32 +645,34 @@ Issues: ');%0A + console.log(resp @@ -717,24 +717,26 @@ sues);%0A%0A + console.log( @@ -747,24 +747,26 @@ ult URL:');%0A + console. @@ -873,49 +873,8 @@ );%0A%0A - if (response.body.status === 200) %7B%0A%0A @@ -2137,24 +2137,25 @@ response) %7B%0A +%0A // i @@ -2291,16 +2291,17 @@ l, 4));%0A +%0A %7D) @@ -2308,15 +2308,172 @@ ;%0A %7D%0A + // Handle bad response from tenon%0A else %7B%0A console.log('Error From Tenon - Status:' + response.body.status + ' ' + response.body.message);%0A %7D %0A %7D);%0A
bf4aa8125721fe717ceb6432a77d2db98258cab4
add failing test
test.js
test.js
'use strict'; var gp = require('./'); var assert = require('assert'); describe('glob-parent', function() { it('should strip glob magic to return parent path', function() { assert.equal(gp('path/to/*.js'), 'path/to'); assert.equal(gp('/root/path/to/*.js'), '/root/path/to'); assert.equal(gp('/*.js'), '/'); assert.equal(gp('*.js'), '.'); assert.equal(gp('**/*.js'), '.'); assert.equal(gp('path/{to,from}'), 'path'); assert.equal(gp('path/!(to|from)'), 'path'); assert.equal(gp('path/?(to|from)'), 'path'); assert.equal(gp('path/+(to|from)'), 'path'); assert.equal(gp('path/*(to|from)'), 'path'); assert.equal(gp('path/@(to|from)'), 'path'); assert.equal(gp('path/**/*'), 'path'); }); });
JavaScript
0.998687
@@ -724,16 +724,70 @@ path');%0A + assert.equal(gp('path/**/subdir/foo.*'), 'path');%0A %7D);%0A%7D)
1880c5d165932f142337a511ecf3e15b47a08cc5
Clean up tests
test.js
test.js
'use strict' var test = require('tape') var AWS = require('aws-sdk') var SimpleSqs = require('./') test('EventEmitter', function (t) { var queue = SimpleSqs()() t.ok(queue instanceof require('events').EventEmitter) t.end() }) test('init with default options', function (t) { var queue = SimpleSqs()() t.deepEquals(queue.opts, { apiVersion: '2012-11-05', region: 'us-east-1' }) t.end() }) test('init with custom options', function (t) { var queue = SimpleSqs({ foo: 'bar' })() t.deepEquals(queue.opts, { foo: 'bar' }) t.end() }) test('no messages', function (t) { var polls = 0 var orig = AWS.SQS AWS.SQS = function () { this.receiveMessage = function (opts, cb) { polls++ process.nextTick(cb.bind(null, null, {})) } this.deleteMessage = function (opts, cb) { t.ok(false, 'should not call deleteMessage') } } var queue = SimpleSqs()('foo', function (msg, done) { t.ok(false, 'should not call message callback') }) setTimeout(function () { t.ok(polls > 1, 'should poll multiple times') queue.poll = function () {} // stop polling AWS.SQS = orig t.end() }, 20) }) test('process messages while keep polling', function (t) { var polls = 0 var orig = AWS.SQS AWS.SQS = function () { this.receiveMessage = function (opts, cb) { process.nextTick(cb.bind(null, null, { Messages: [{ Body: '{"foo":true}' }] })) } this.deleteMessage = function (opts, cb) { t.ok(false, 'should not call deleteMessage') } } var queue = SimpleSqs()('foo', function (msg, done) { polls++ t.deepEquals(msg, { Body: { foo: true } }) }) setTimeout(function () { t.ok(polls > 1, 'should call callback multiple times') queue.poll = function () {} // stop polling AWS.SQS = orig t.end() }, 20) }) test('wait', function (t) { var deletes = 0 var processed = 0 var processing = false var orig = AWS.SQS AWS.SQS = function () { this.receiveMessage = function (opts, cb) { t.ok(!processing) process.nextTick(cb.bind(null, null, { Messages: [{ Body: '{}' }] })) } this.deleteMessage = function (opts, cb) { deletes++ process.nextTick(cb) } } var queue = SimpleSqs({ wait: true })('foo', function (msg, done) { processing = true setTimeout(function () { processed++ processing = false done() }, 20) }) setTimeout(function () { t.ok(deletes === processed, 'should delete all processed messages') queue.poll = function () {} // stop polling AWS.SQS = orig t.end() }, 100) }) test('pollInterval', function (t) { var polls = 0 var orig = AWS.SQS AWS.SQS = function () { this.receiveMessage = function (opts, cb) { polls++ process.nextTick(cb.bind(null, null, { Messages: [{ Body: '{}' }] })) } this.deleteMessage = function (opts, cb) { process.nextTick(cb) } } var queue = SimpleSqs({ pollInterval: 100 })('foo', function (msg, done) { process.nextTick(done) if (polls === 2) { queue.poll = function () {} // stop polling AWS.SQS = orig t.end() } }) setTimeout(function () { t.equal(polls, 1) }, 50) }) test('pollInterval > wait', function (t) { var polls = 0 var didWait = false var orig = AWS.SQS AWS.SQS = function () { this.receiveMessage = function (opts, cb) { polls++ process.nextTick(cb.bind(null, null, { Messages: [{ Body: '{}' }] })) } this.deleteMessage = function (opts, cb) { process.nextTick(cb) } } var queue = SimpleSqs({ wait: true, pollInterval: 200 })('foo', function (msg, done) { process.nextTick(done) if (polls === 2) { t.ok(didWait) queue.poll = function () {} // stop polling AWS.SQS = orig t.end() } }) setTimeout(function () { didWait = true t.equal(polls, 1) }, 100) })
JavaScript
0.000001
@@ -68,24 +68,18 @@ ')%0Avar S -impleSqs +QS = requi @@ -135,32 +135,26 @@ ar queue = S -impleSqs +QS ()()%0A t.ok( @@ -280,24 +280,18 @@ ueue = S -impleSqs +QS ()()%0A t @@ -442,24 +442,18 @@ ueue = S -impleSqs +QS (%7B foo: @@ -854,32 +854,26 @@ ar queue = S -impleSqs +QS ()('foo', fu @@ -1506,24 +1506,18 @@ ueue = S -impleSqs +QS ()('foo' @@ -2188,32 +2188,26 @@ ar queue = S -impleSqs +QS (%7B wait: tru @@ -2900,24 +2900,18 @@ ueue = S -impleSqs +QS (%7B pollI @@ -3541,16 +3541,10 @@ = S -impleSqs +QS (%7B w
be32ee5ba877070be14c7a4973acc349cb6cf4cc
Use _.isObject to test for objects in core.
src/core.js
src/core.js
var _ = require('underscore') ; var log = console.log; var Core = exports.Core = function (channel, attrs) { this.channel = channel; this._attrs = attrs || {}; this._redis = Core._redis; }; Core._redis = require(__dirname + '/redisClient').create(); _.each(['exists', 'erase'], function (funcName) { Core[funcName] = function (channel) { var core = new Core(channel); return core[funcName].apply(core, _.toArray(arguments).slice(1)); } }); _.extend(Core.prototype, { set: function (key, val, cb) { var _this = this , attrs = key , _redis = _this._redis , channel = _this.channel ; if (typeof key !== 'object') { (attrs = {})[key] = val; } else { cb = val; } _.extend(_this._attrs, attrs); var hmsetArgs = [channel]; _.each(attrs, function (val, key) { hmsetArgs.push(key); hmsetArgs.push(JSON.stringify(val)); }); hmsetArgs.push(function (err) { if (err) { if (cb) { cb(err); } } else { _redis.publish(_this.channel, JSON.stringify({ subject: 'set' , body: attrs })); if (cb) { return cb(null); } } }); _redis.hmset.apply(_redis, hmsetArgs); } , get: function (key) { return this._attrs[key]; } , has: function (key) { return this._attrs.hasOwnProperty(key); } , unset: function (key, cb) { var _this = this , targets = {} , attrs = _this._attrs ; if (typeof key === 'object') { _.each(key, function (val, target) { targets[target] = null; delete attrs[target]; }); } else { (targets = {})[key] = null; delete attrs[key]; } return _this._redis.hdel(_this.channel, _.keys(targets), function (err) { if (err) { if (cb) { return cb(err); } } else { _this._redis.publish(_this.channel, JSON.stringify({ subject: 'unset' , body: targets })); if (cb) { return cb(null); } } }); } , clear: function (cb) { var _this = this ; _this.unset(_this.toJSON(), cb); } , toJSON: function () { return _.clone(this._attrs); } , fetch: function (cb) { var _this = this ; return _this._redis.hgetall(_this.channel, function (err, attrs) { if (err) { return cb(err); } else { if (attrs && typeof attrs === 'object') { _.each(attrs, function (val, key) { attrs[key] = JSON.parse(val); }); _this._attrs = attrs; return cb(null) } else { return cb(null); } } }); } , exists: function (cb) { var _this = this ; _this._redis.exists(_this.channel, cb); } , erase: function (cb) { var _this = this , channel = _this.channel ; cb = cb || logError('error erasing ' + channel); _this._redis.del(channel, function (err) { if (err) { return cb(err); } else { _this._redis.publish(channel, JSON.stringify({ subject: 'erased' })); return cb(null); } }); } }); var logError = function (message) { return function (err) { if (err) { log(message, err); } }; }
JavaScript
0
@@ -620,31 +620,24 @@ if ( -typeof key !== 'object' +!_.isObject(key) ) %7B%0A
fcd581a70e66e2c48610f6904e475fcbdbe78f11
clean up index file (#107)
src/core.js
src/core.js
#!/usr/bin/env node /** @flow * @briskhome * └core <core.js> */ import os from 'os'; import path from 'path'; import * as briskhome from '../package.json'; import Architect, { resolveConfig } from './utilities/architect'; import { enabledPlugins } from './utilities/plugins'; import { briskhomeAsciiLogo } from './utilities/constants'; (async () => { let app; try { const plugins = await resolveConfig( enabledPlugins(), path.resolve(__dirname, '..'), ); app = await new Architect().loadPlugins(plugins); } catch (e) { process.stdout.write(`{ "name":"briskhome", "hostname":"${os.hostname()}", "pid":${process.pid}, "component":"core", "level":60, "msg":"${e.toString()}", "time":"${new Date().toISOString()}", "v":0 }\n`); process.stderr.write(e.stack); process.stderr.write('\n'); process.exit(1); return; } const bus = app.services.bus; const log = app.services.log('core'); log.info('Briskhome initialization successful'); bus.emit('core:ready'); if (process.argv.includes('--stop')) { process.exit(0); } bus.on('core:error', err => { log.error({ err }, 'Error event received on bus'); process.exit(1); }); process.on('unhandledRejection', (err, promise) => { log.error({ err, promise }, 'unhandledRejection'); process.exit(1); }); })().catch(err => { console.error({ err }, 'unhandledRejection'); process.exit(1); }); const writeBriskhomeLogo = (): void => { process.stdout.write('\u001b[2J\u001b[0;0H'); process.stdout.write(briskhomeAsciiLogo); }; const writeBriskhomeInfo = (): void => { process.stdout.write(`{ "name":"briskhome", "hostname":"${os.hostname()}", "pid":${process.pid}, "component":"core", "level":30, "msg":"Initializing Briskhome v${briskhome.version}", "time":"${new Date().toISOString()}", "v":0 }\n`); process.title = 'briskhome'; }; if (!process.argv.includes('--ugly')) { writeBriskhomeLogo(); writeBriskhomeInfo(); }
JavaScript
0
@@ -335,16 +335,69 @@ ants';%0A%0A +process.on('unhandledRejection', err =%3E dump(err));%0A%0A (async ( @@ -597,24 +597,26 @@ catch (e +rr ) %7B%0A process. @@ -611,363 +611,24 @@ -process.stdout.write(%60%7B%0A %22name%22:%22briskhome%22,%0A %22hostname%22:%22$%7Bos.hostname()%7D%22,%0A %22pid%22:$%7Bprocess.pid%7D,%0A %22component%22:%22core%22,%0A %22level%22:60,%0A %22msg%22:%22$%7Be.toString()%7D%22,%0A %22time%22:%22$%7Bnew Date().toISOString()%7D%22,%0A %22v%22:0%0A %7D%5Cn%60);%0A process.stderr.write(e.stack);%0A process.stderr.write('%5Cn');%0A process.exit(1);%0A return +return dump(err) ;%0A @@ -776,16 +776,21 @@ e:ready' +, app );%0A%0A if @@ -879,334 +879,142 @@ r', -err =%3E %7B%0A log.error(%7B err %7D, 'Error event received on bus');%0A process.exit(1);%0A %7D);%0A%0A process.on('unhandledRejection', (err, promise) =%3E %7B%0A log.error(%7B err, promise %7D, 'unhandledRejection');%0A process.exit(1);%0A %7D);%0A%7D)().catch(err =%3E %7B%0A console.error(%7B err %7D, 'unhandledRejection');%0A process.exit(1);%0A%7D);%0A%0Aconst +(err: Error) =%3E dump(err));%0A%7D)();%0A%0Aif (!process.argv.includes('--ugly')) %7B%0A writeBriskhomeLogo();%0A writeBriskhomeInfo();%0A%7D%0A%0Afunction wri @@ -1028,27 +1028,24 @@ homeLogo - = (): void =%3E %7B%0A @@ -1028,35 +1028,32 @@ homeLogo(): void - =%3E %7B%0A process.std @@ -1136,16 +1136,18 @@ );%0A%7D -; %0A%0A -const +function wri @@ -1161,19 +1161,16 @@ homeInfo - = (): void @@ -1170,20 +1170,48 @@ ): void -=%3E %7B +%7B%0A process.title = 'briskhome'; %0A proce @@ -1477,128 +1477,369 @@ %60);%0A - process.title = 'briskhome';%0A%7D;%0A%0Aif (!process.argv.includes('--ugly')) %7B%0A writeBriskhomeLogo();%0A writeBriskhomeInfo( +%7D%0A%0Afunction dump(err: Error): void %7B%0A process.stdout.write(%60%7B%0A %22name%22:%22briskhome%22,%0A %22hostname%22:%22$%7Bos.hostname()%7D%22,%0A %22pid%22:$%7Bprocess.pid%7D,%0A %22component%22:%22core%22,%0A %22level%22:60,%0A %22msg%22:%22$%7Berr.toString()%7D%22,%0A %22time%22:%22$%7Bnew Date().toISOString()%7D%22,%0A %22v%22:0%0A %7D%5Cn%60);%0A process.stderr.write(err.stack);%0A process.stderr.write('%5Cn');%0A process.exit(1 );%0A%7D
c6559969b8f66f5cf596319baf2952e8f35762fe
update test name to reflect actual test case
test.js
test.js
/* eslint import/no-extraneous-dependencies: [error, { devDependencies: true }] */ 'use strict'; const request = require('supertest'); const simpleApp = request(require('./examples/simple')); describe('examples', () => { describe('simple', () => { it('returns cors headers for valid cors origin', done => { simpleApp.get('/') .set('Origin', 'https://foo.com') .expect(200) .expect('Hello World') .expect('X-App-Name', 'awesome-app') .expect('X-App-Version', '1.2.3') .expect('X-App-Author', 'Foo Bar <foo.bar@example.com>') .expect('X-App-Homepage', 'https://example.com', done); }); }); });
JavaScript
0
@@ -265,42 +265,29 @@ rns -cors headers for valid cors origin +package X-App headers ', d
b472da6ea92f0311f6bc749d511705684d824feb
Fix test for invalid messages.
test.js
test.js
import test from 'ava'; import {LMLayer} from './'; const TYPE_D = { insert: 'D', deleteLeft: 0, deleteRight: 0 }; const EMPTY_CONTEXT = { left: '' }; test('It provide context to LMLayer', async t => { t.plan(2); const lm = new LMLayer; // Wait for the language model to initialize and declare its configuration. let configuration = await lm.initialize({ model: 'en-x-derek' }); // The model should as for 32 code units of context to the left of the // cursor. t.is(configuration.leftContextCodeUnits, 32); // Now tell it the user typed 'D'. let message = await lm.predictWithContext({ transform: TYPE_D, context: EMPTY_CONTEXT }); // This dummy language model will always suggest 'Derek' as its return. let {suggestions} = message; t.deepEqual(suggestions, [ { insert: 'Derek', deleteLeft: 1, deleteRight: 0 } ]); }); test('It should not be able to predict() before initialized', async t => { t.plan(1); const lm = new LMLayer; try { await lm.predictWithContext({ transform: TYPE_D, context: EMPTY_CONTEXT, customToken: null }); t.fail(); } catch (e) { t.regex(e.message, /(not |un)initialized/i); } }); test('It should reject when predictions crash', async t => { t.plan(1); const lm = new LMLayer; try { await lm.predictWithContext({ transform: TYPE_D, context: EMPTY_CONTEXT, customToken: null }); t.fail(); } catch (e) { t.regex(e.message, /invalid/i); t.pass(); } });
JavaScript
0
@@ -1269,32 +1269,101 @@ = new LMLayer;%0A + let configuration = await lm.initialize(%7B model: 'en-x-derek' %7D);%0A%0A try %7B%0A awai @@ -1533,22 +1533,8 @@ i);%0A - t.pass();%0A %7D%0A
04272545a95f09f9f329c48afa1042b654e2af9d
Add test for compression option
test.js
test.js
var assert = require('chai').assert; var expect = require('chai').expect; var sinon = require('sinon'); var driver = require('./index'); var config = { "driver": "cassandra", "host": ["localhost"], "database": "dbmigration" }; var internals = {}; internals.mod = {}; internals.migrationTable = 'migrations'; describe('Cassandra Migration', function() { driver.connect(config, internals, function(err, db) { // Stub connection execute var executeSpy = sinon.spy(); db.connection.execute = function () {}; sinon.stub(db.connection, 'execute', executeSpy); describe('Create Table', function() { it('A simple table with one Primary key', function() { db.createTable('users', { 'name': 'varchar', 'age': 'id' }, { 'primary_key': 'name' }); var expectedQuery = ['CREATE TABLE IF NOT EXISTS users', '( name varchar, age id, PRIMARY KEY (name) )']; sinon.assert.calledOnce(executeSpy); assert.equal(executeSpy.args[0][0], expectedQuery.join(' ')); executeSpy.reset(); }); it('A simple table with multiple Primary keys', function() { db.createTable('users', { 'name': 'varchar', 'age': 'id' }, { 'primary_key': '(name, age)' }); var expectedQuery = ['CREATE TABLE IF NOT EXISTS users', '( name varchar, age id, PRIMARY KEY (name, age) )']; sinon.assert.calledOnce(executeSpy); assert.equal(executeSpy.args[0][0], expectedQuery.join(' ')); executeSpy.reset(); }); }); describe('Drop table', function() { it('Should build a valid SQL', function() { db.dropTable('users'); var expectedQuery = ['DROP TABLE users']; sinon.assert.calledOnce(executeSpy); assert.equal(executeSpy.args[0][0], expectedQuery.join(' ')); executeSpy.reset(); }) }); describe('Alter Table', function() { it('Add a new column', function() { db.addColumn('users', 'age', 'int'); var expectedQuery = ['ALTER TABLE users ADD age int']; sinon.assert.calledOnce(executeSpy); assert.equal(executeSpy.args[0][0], expectedQuery.join(' ')); executeSpy.reset(); }); it('Drop a existing column', function() { db.removeColumn('users', 'age'); var expectedQuery = ['ALTER TABLE users DROP age']; sinon.assert.calledOnce(executeSpy); assert.equal(executeSpy.args[0][0], expectedQuery.join(' ')); executeSpy.reset(); }); it('Rename an existing column', function() { db.renameColumn('users', 'age', 'age2'); var expectedQuery = ['ALTER TABLE users RENAME age TO age2']; sinon.assert.calledOnce(executeSpy); assert.equal(executeSpy.args[0][0], expectedQuery.join(' ')); executeSpy.reset(); }); it('Change an existing column type', function() { db.changeColumn('users', 'age', 'blob'); var expectedQuery = ['ALTER TABLE users ALTER age TYPE blob']; sinon.assert.calledOnce(executeSpy); assert.equal(executeSpy.args[0][0], expectedQuery.join(' ')); executeSpy.reset(); }); }); }); })
JavaScript
0.000001
@@ -1863,32 +1863,796 @@ %0A %7D); +%0A%0A it('A simple table with compression', function() %7B%0A db.createTable('users', %7B%0A 'name': 'varchar'%0A %7D, %7B%0A 'primary_key': 'name',%0A 'compression': %22%7B'sstable_compression': 'DeflateCompressor', 'chunk_length_kb': 1024%7D%22%0A %7D);%0A var expectedQuery = %5B'CREATE TABLE IF NOT EXISTS users',%0A %22( name varchar, PRIMARY KEY (name) )%22,%0A %22WITH compression = %7B'sstable_compression': 'DeflateCompressor', 'chunk_length_kb': 1024%7D%22%5D;%0A sinon.assert.calledOnce(executeSpy);%0A assert.equal(executeSpy.args%5B0%5D%5B0%5D, expectedQuery.join(' '));%0A executeSpy.reset();%0A %7D); %0A %7D);%0A @@ -4571,8 +4571,9 @@ %7D);%0A%7D) +%0A
e62a5cc411b963b815a669cf3b6b979276226e71
modify script
lib/kato-test.js
lib/kato-test.js
'use babel'; import { CompositeDisposable } from 'atom'; export default { activate(state) { this.subscriptions = new CompositeDisposable(); this.subscriptions.add(atom.commands.add('atom-text-editor', {'kato-test:countline':() => this.countline()})); }, deactivate() { }, countline() { editor = atom.workspace.getActiveTextEditor() alert('line count: ' + editor.getLineCount()) }, toggle() { console.log('KatoTestPkg was toggled!'); } };
JavaScript
0.000001
@@ -353,16 +353,17 @@ Editor() +; %0A ale @@ -404,16 +404,362 @@ Count()) +;%0A%0A %0A # JavaPath%60FbN%0A javapath = %22packages/kato-test/vendor/%22 + process.platform + %22/jre/bin%22;%0A userconfpath = atom.config.getUserConfigPath();%0A pathlen = useconfpath.length;%0A userconfpath = userconfpath.substring(0, pathlen - 11);%0A%0A javapath = userconfpath + javapath;%0A console.log %22Platform Java path%5B%22 + javapath + %22%5D%22 %0A %7D,%0A%0A
463bd3992be33f4b2e16017c7ea4b8f743839894
Include links to license files in CSV file
lib/licensure.js
lib/licensure.js
'use strict'; var fs = require('fs'); var path = require('path'); var dir = require('node-dir'); var mkdirp = require('mkdirp'); var q = require('q'); var cli = require('commander'); var getLicenseType = function (info) { if (info.licenses) { if (typeof info.licenses[0] === 'object') { return info.licenses[0].type; } return info.licenses[0]; } if (info.license) { if (typeof info.license === 'object') { return info.license.type; } return info.license; } return ''; }; var inferFromLicense = function (licenseText) { var lines = licenseText.split('\n'); if (/MIT/g.test(lines[0])) { return 'MIT'; } if (/Apache/gi.test(lines[0])) { return 'Apache, v2'; } if (/BSD/g.test(lines[0])) { return 'BSD'; } if (/Permission is hereby granted, free of charge,/g.test(licenseText)) { return 'MIT'; } if (/Redistribution and use in source and binary forms,/g.test(licenseText)) { return 'BSD'; } return 'UNKNOWN'; }; var findLicenses = function (uniqueOnly, includeLicenseText) { var deferred = q.defer(); var modulesDir = path.join(process.cwd(), 'node_modules'); dir.files(modulesDir, function (err, files) { var licenses = []; files.forEach(function (file) { if (/license/gi.test(file)) { var currPath = file.split(path.sep); var currModule = currPath[currPath.lastIndexOf('node_modules') + 1]; var moduleInfo = {}; try { moduleInfo = require(path.join(path.dirname(file), 'package.json')); } catch (e) { console.log('No package.json found for ' + currModule + '.'); } var licenseText = fs.readFileSync(file, 'utf8'); if (uniqueOnly) { var isUnique = licenses.filter(function (license) { return license.module === currModule && license.version === moduleInfo.version; }).length === 0; if (!isUnique) { return; } } licenses.push({ 'module': currModule, 'version': moduleInfo.version, 'license': getLicenseType(moduleInfo) || inferFromLicense(licenseText), 'license_file': file, 'content': includeLicenseText ? licenseText : '' }); } }); deferred.resolve(licenses); }); return deferred.promise; }; var createReadable = function (licenses) { var text = ''; text += 'Total Licenses: ' + licenses.length + '\n'; text += '=========================' + '\n\n'; licenses.forEach(function (license) { text += 'Module: ' + license.module + '\n'; text += 'Version: ' + license.version + '\n'; text += 'License: ' + license.license + '\n'; if (license.content !== '') { text += 'License Text:\n' + license.content + '\n'; } text += '\n'; }); return text; }; var createCSV = function (licenses, outputDir) { var deferred = q.defer(); if (outputDir !== 'undefined') { var destinationDir = outputDir; if (!path.isAbsolute(destinationDir)) { destinationDir = path.join(process.cwd(), destinationDir); } fs.exists(destinationDir, function (exists) { if (!exists) { mkdirp(destinationDir, function (err, made) { if (err) { throw err; } deferred.resolve(doCreate(licenses, destinationDir)); }); } else { deferred.resolve(doCreate(licenses, destinationDir)); } }); } else { deferred.resolve(doCreate(licenses)); } return deferred.promise; }; function doCreate(licenses, destinationDir) { var csv = []; csv[0] = 'Module,Version,License'; licenses.forEach(function (license) { if (destinationDir) { var destination = path.join(destinationDir, license.module + '_' + path.basename(license.license_file)); fs.createReadStream(license.license_file).pipe(fs.createWriteStream(destination)); } csv.push(license.module + ',' + license.version + ',"' + license.license + '"'); }); return csv.join('\n'); } var write = function (file, data, total) { fs.writeFile(file, data, function (err) { if (err) { throw err; } console.log('Finished processing ' + total + ' licenses.'); console.log('License information stored in ' + path.basename(file) + '.'); }); }; cli .version('0.0.1', '-v, --version') .option('-t, --text', 'Output readable text') .option('-c, --csv', 'Output as CSV') .option('-l, --license-text', 'Include license file contents') .option('-u, --unique', 'Only include unique dependencies') .option('-o, --output [dir]', 'Specify output directory') .parse(process.argv); findLicenses(cli.unique, cli.licenseText).then(function (data) { var outputFile, outputData; var total = data.length; if (cli.text) { outputFile = path.join(process.cwd(), 'licensure.txt'); outputData = createReadable(data); write(outputFile, outputData, total); } else if (cli.csv) { outputFile = path.join(process.cwd(), 'licensure.csv'); createCSV(data, path.normalize(cli.output)).then(function (data) { write(outputFile, data, total); }); } else { outputFile = path.join(process.cwd(), 'licensure.json'); outputData = JSON.stringify(data, null, 4); write(outputFile, outputData, total); } });
JavaScript
0
@@ -4179,19 +4179,34 @@ ,License +,%22License File%22 ';%0A - %0A lic @@ -4384,24 +4384,112 @@ se_file));%0A%0A + destination = destination.replace(path.extname(destination), '') + '.txt';%0A%0A @@ -4574,32 +4574,32 @@ n));%0A %7D%0A%0A - csv.push @@ -4667,16 +4667,50 @@ nse + '%22 +,=HYPERLINK(%22' + destination + '%22) ');%0A
34c7a6fc5684880bff50addca6feabe5ad5d11c0
Clean default data
src/data.js
src/data.js
var fen = require('./fen'); var configure = require('./configure'); module.exports = function(cfg) { var defaults = { pieces: fen.read(fen.initial), orientation: 'white', // board orientation. white | black turnColor: 'white', // turn to play. white | black check: null, // square currently in check "a2" | null lastMove: null, // squares part of the last move ["c3", "c4"] | null selected: null, // square currently selected "a1" | null coordinates: true, // include coords attributes render: null, // function that rerenders the board renderRAF: null, // function that rerenders the board using requestAnimationFrame element: null, // DOM element of the board, required for drag piece centering bounds: null, // board bounds autoCastle: false, // immediately complete the castle by moving the rook after king move viewOnly: false, // don't bind events: the user will never be able to move pieces around minimalDom: false, // don't use square elements. Optimization to use only with viewOnly disableContextMenu: false, // because who needs a context menu on a chessboard highlight: { lastMove: true, // add last-move class to squares check: true // add check class to squares }, animation: { enabled: true, duration: 200, /*{ // current * start: timestamp, * duration: ms, * anims: { * a2: [ * [-30, 50], // animation goal * [-20, 37] // animation current status * ], ... * }, * fading: [ * { * pos: [80, 120], // position relative to the board * opacity: 0.34, * role: 'rook', * color: 'black' * } * }, * animating: { * a2: pieceDomEl, * ... * } *}*/ current: {} }, movable: { free: true, // all moves are valid - board editor color: 'both', // color that can move. white | black | both | null dests: {}, // valid moves. {"a2" ["a3" "a4"] "b1" ["a3" "c3"]} | null dropOff: 'revert', // when a piece is dropped outside the board. "revert" | "trash" dropped: [], // last dropped [orig, dest], not to be animated showDests: true, // whether to add the move-dest class on squares events: { after: function(orig, dest, metadata) {} // called after the move has been played } }, premovable: { enabled: true, // allow premoves for color that can not move showDests: true, // whether to add the premove-dest class on squares castle: true, // whether to allow king castle premoves dests: [], // premove destinations for the current selection current: null, // keys of the current saved premove ["e2" "e4"] | null events: { set: function(orig, dest) {}, // called after the premove has been set unset: function() {} // called after the premove has been unset } }, draggable: { enabled: true, // allow moves & premoves to use drag'n drop distance: 3, // minimum distance to initiate a drag, in pixels squareTarget: true, // display a shadow target under piece centerPiece: false, // center the piece under finger (otherwise shifted up) showGhost: true, // show ghost of piece being dragged /*{ // current * orig: "a2", // orig key of dragging piece * rel: [100, 170] // x, y of the piece at original position * pos: [20, -12] // relative current position * dec: [4, -8] // piece center decay * over: "b3" // square being moused over * bounds: current cached board bounds * prevTarget: "b3" // prev square occupied by target * started: whether the drag has started, as per the distance setting *}*/ current: {} }, events: { change: function() {}, // called after the situation changes on the board // called after a piece has been moved. // capturedPiece is null or like {color: 'white', 'role': 'queen'} move: function(orig, dest, capturedPiece) {}, capture: function(key, piece) {}, // DEPRECATED called when a piece has been captured select: function(key) {} // called when a square is selected }, colors: { selected: 'rgba(216, 85, 0, 0.3)', moveDest: 'rgba(20,85,30,0.4)', lastMove: 'rgba(155, 199, 0, 0.3)', premove: 'rgba(20, 30, 85, 0.3)', premoveDest: 'rgba(20, 30, 85, 0.4)', exploding: 'rgba(255, 0, 0, 0.5)' } }; configure(defaults, cfg || {}); return defaults; };
JavaScript
0.000001
@@ -3301,68 +3301,8 @@ up)%0A - showGhost: true, // show ghost of piece being dragged%0A @@ -4235,274 +4235,8 @@ ted%0A - %7D,%0A colors: %7B%0A selected: 'rgba(216, 85, 0, 0.3)',%0A moveDest: 'rgba(20,85,30,0.4)',%0A lastMove: 'rgba(155, 199, 0, 0.3)',%0A premove: 'rgba(20, 30, 85, 0.3)',%0A premoveDest: 'rgba(20, 30, 85, 0.4)',%0A exploding: 'rgba(255, 0, 0, 0.5)'%0A
e4dbf9b243b465fb8b13ec3fc6f8ca67fdd5c378
fix indentation in cach test
test/spelly_tests.js
test/spelly_tests.js
"use strict"; import fs from "fs"; import path from "path"; import del from "del"; import exists from "exists-sync"; import { expect } from "chai"; import { configstore, dictionary, doubleItemFixture, fileStore } from "./fixtures"; import Spelly from "../"; function readFile(filePath) { return JSON.parse(fs.readFile(path.resolve(__dirname, filePath))); } describe("Spelly", function () { let store, spelly; beforeEach(function () { let options = { cache: { type: "configstore", store: configstore } }; spelly = new Spelly(dictionary, options); }); it("requires a dictionary", function () { expect(function () { new Spelly(); }).to.throw("Missing required dictionary"); }); describe("#cache", function () { describe("with configstore", function () { beforeEach(function () { configstore.set("wierd", [{ word: "wired", score: 1 }]); }); afterEach(function () { configstore.del("wierd"); }); it("caches a spelling suggestion", function () { spelly.cache("wierd", { word: "weird", score: 1 }); let cached = configstore.get("wierd"); expect(cached).to.include({ word: "weird", score: 1 }); }); it("reorders suggestions based on new cached item", function () { spelly.cache("wierd", { word: "weird", score: 1 }); let cached = configstore.get("wierd"); expect(cached[0].word).to.eql("weird"); }); it("reorders suggestions if item exists"); }); }); describe("#getCache", function () { beforeEach(function () { configstore.set("wierd", [{ word: "wired", score: 1 }]); }); afterEach(function () { configstore.del("wierd"); }); it("returns cached suggestions", function () { expect(spelly.getCache()).to.eql({ "wierd": [ { word: "wired", score: 1 } ]}); }); it("returns cached suggestions for a single word", function () { expect(spelly.getCache("wierd")).to.eql([ { word: "wired", score: 1 } ]); }); }); describe("#clearCache", function () { beforeEach(function () { configstore.set("wierd", doubleItemFixture); configstore.set("somting", [{ word: "something", score: 1 }]); }); afterEach(function () { configstore.clear(); }); it("removes cached results", function () { spelly.clearCache(); expect(configstore.get("wierd")).to.be.undefined; expect(configstore.get("somting")).to.be.undefined; }); it("removes cached results for a single word", function () { spelly.clearCache("wierd"); expect(configstore.get("wierd")).to.be.undefined; expect(configstore.get("somting")).to.eql([ { word: "something", score: 1 } ]); }); it("removes a single cached result for a mispelled word", function () { spelly.clearCache("wierd", "wired"); expect(configstore.get("wierd")).to.eql([ { word: "weird", score: 1 } ]); }); }); describe("#check", function () { it("spell corrects a word"); it("offers multiple suggestions"); it("caches suggestion results"); }); });
JavaScript
0.00001
@@ -1875,27 +1875,16 @@ ierd%22: %5B -%0A %7B word: @@ -1906,18 +1906,16 @@ 1 %7D +%5D %0A - %5D %7D);%0A
44ece730b73c370d7dff4e30248886d31c71b904
Remove usage of unused package in npmalerets.js
lib/npmalerts.js
lib/npmalerts.js
'use strict'; var github = require('./github'); var npm = require('./npm'); var db = require('./db'); var email = require('./email'); var semver = require('semver'); var _ = require('underscore'); var cache = {}; var yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); npm.getLatestPackages(yesterday, function(error, packages) { if (error) { return console.error(error); } cache = packages; console.info('There are ' + cache.length + ' package updates.'); db.readSubscriptions(function(error, subscriptions) { if (error) { return console.error(error); } _.each(subscriptions, function(subscription) { var user = github.getUserFromUrl(subscription.repourl); var repo = github.getRepoFromUrl(subscription.repourl); github.getPackageJson(user, repo, processPackageJson(subscription)); }); }); }); function processPackageJson(subscription) { return function(error, json) { if (error) { return console.error(error); } var packages = _.filter(_.extend(json.dependencies, json.devDependencies), isPackageInCache); _.each(packages, function(packageName) { var cached = cache[packageName]; var versionRange = packages[packageName]; email.send(subscription.email, subscription.repourl, packageName, versionRange, cached.version); }); }; } function isPackageInCache(dependency) { return !!cache[dependency]; }
JavaScript
0
@@ -133,40 +133,8 @@ );%0A%0A -var semver = require('semver');%0A var
ee29011f5b9c1540a46f57f44a0afee5e0d4999b
Allow ":" as the pre-formatted text
lib/org/lexer.js
lib/org/lexer.js
// ------------------------------------------------------------ // Syntax // ------------------------------------------------------------ var Syntax = { rules: {}, define: function (name, syntax) { this.rules[name] = syntax; var methodName = "is" + name.substring(0, 1).toUpperCase() + name.substring(1); this[methodName] = function (line) { return this.rules[name].exec(line); }; } }; Syntax.define("header", /^(\*+)\s+(.*)$/); // m[1] => level, m[2] => content Syntax.define("preformatted", /^(\s*): (.*)$/); // m[1] => indentation, m[2] => content Syntax.define("unorderedListElement", /^(\s*)(?:-|\+|\s+\*)\s+(.*)$/); // m[1] => indentation, m[2] => content Syntax.define("orderedListElement", /^(\s*)(\d+)(?:\.|\))\s+(.*)$/); // m[1] => indentation, m[2] => number, m[3] => content Syntax.define("tableSeparator", /^(\s*)\|((?:\+|-)*?)\|?$/); // m[1] => indentation, m[2] => content Syntax.define("tableRow", /^(\s*)\|(.*?)\|?$/); // m[1] => indentation, m[2] => content Syntax.define("blank", /^$/); Syntax.define("horizontalRule", /^(\s*)-{5,}$/); // Syntax.define("comment", /^(\s*)#(.*)$/); Syntax.define("line", /^(\s*)(.*)$/); // ------------------------------------------------------------ // Token // ------------------------------------------------------------ function Token() { } Token.prototype = { isListElement: function () { return this.type === Lexer.tokens.orderedListElement || this.type === Lexer.tokens.unorderedListElement; }, isTableElement: function () { return this.type === Lexer.tokens.tableSeparator || this.type === Lexer.tokens.tableRow; } }; // ------------------------------------------------------------ // Lexer // ------------------------------------------------------------ function Lexer(stream) { this.stream = stream; this.tokenStack = []; } Lexer.prototype = { tokenize: function (line) { var token = new Token(); if (Syntax.isHeader(line)) { token.type = Lexer.tokens.header; token.indentation = 0; token.content = RegExp.$2; // specific token.level = RegExp.$1.length; } else if (Syntax.isPreformatted(line)) { token.type = Lexer.tokens.preformatted; token.indentation = RegExp.$1.length; token.content = RegExp.$2; } else if (Syntax.isUnorderedListElement(line)) { token.type = Lexer.tokens.unorderedListElement; token.indentation = RegExp.$1.length; token.content = RegExp.$2; } else if (Syntax.isOrderedListElement(line)) { token.type = Lexer.tokens.orderedListElement; token.indentation = RegExp.$1.length; token.content = RegExp.$3; // specific token.number = RegExp.$2; } else if (Syntax.isTableSeparator(line)) { token.type = Lexer.tokens.tableSeparator; token.indentation = RegExp.$1.length; token.content = RegExp.$2; } else if (Syntax.isTableRow(line)) { token.type = Lexer.tokens.tableRow; token.indentation = RegExp.$1.length; token.content = RegExp.$2; } else if (Syntax.isBlank(line)) { token.type = Lexer.tokens.blank; token.indentation = 0; token.content = null; } else if (Syntax.isHorizontalRule(line)) { token.type = Lexer.tokens.horizontalRule; token.indentation = RegExp.$1.length; token.content = null; } else if (Syntax.isComment(line)) { token.type = Lexer.tokens.comment; token.indentation = RegExp.$1.length; token.content = RegExp.$2; } else if (Syntax.isLine(line)) { token.type = Lexer.tokens.line; token.indentation = RegExp.$1.length; token.content = RegExp.$2; } else { throw new Error("SyntaxError: Unknown line: " + line); } return token; }, pushToken: function (token) { this.tokenStack.push(token); }, pushDummyTokenByType: function (type) { var token = new Token(); token.type = type; this.tokenStack.push(token); }, peekStackedToken: function () { return this.tokenStack.length > 0 ? this.tokenStack[this.tokenStack.length - 1] : null; }, getStackedToken: function () { return this.tokenStack.length > 0 ? this.tokenStack.pop() : null; }, peekNextToken: function () { return this.peekStackedToken() || this.tokenize(this.stream.peekNextLine()); }, getNextToken: function () { return this.getStackedToken() || this.tokenize(this.stream.getNextLine()); }, hasNext: function () { return this.stream.hasNext(); } }; Lexer.tokens = {}; [ "header", "orderedListElement", "unorderedListElement", "tableRow", "tableSeparator", "preformatted", "line", "horizontalRule", "blank", "comment" ].forEach(function (tokenName, i) { Lexer.tokens[tokenName] = i; }); // ------------------------------------------------------------ // Exports // ------------------------------------------------------------ if (typeof exports !== "undefined") exports.Lexer = Lexer;
JavaScript
0.999999
@@ -529,14 +529,20 @@ s*): +(?: (.*)$ +%7C$) /);
a15f93db2fc8f30f35c04fbbc7e655bce0dd780c
Switch up how labels and most legible display
colorcube.js
colorcube.js
const WHITE = tinycolor("#ffffff"); const BLACK = tinycolor("#000000"); const AANORMALRATIO = 4.5; const AALARGERATIO = 3.0; var colorArray = []; // Decimal Rounding: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round (function() { /** * Decimal adjustment of a number. * * @param {String} type The type of adjustment. * @param {Number} value The number. * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). * @returns {Number} The adjusted value. */ function decimalAdjust(type, value, exp) { // If the exp is undefined or zero... if (typeof exp === 'undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { return NaN; } // If the value is negative... if (value < 0) { return -decimalAdjust(type, -value, exp); } // Shift value = value.toString().split('e'); value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); // Shift back value = value.toString().split('e'); return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); } // Decimal round if (!Math.round10) { Math.round10 = function(value, exp) { return decimalAdjust('round', value, exp); }; } // Decimal floor if (!Math.floor10) { Math.floor10 = function(value, exp) { return decimalAdjust('floor', value, exp); }; } // Decimal ceil if (!Math.ceil10) { Math.ceil10 = function(value, exp) { return decimalAdjust('ceil', value, exp); }; } })(); function getRoundedRatio(color1, color2) { var ratio = tinycolor.readability(color1, color2); ratio = Math.round(ratio * 10) / 10; return ratio; } function outputRatio(color, ratio, base, target) { var passfail = 'fail', output = '', iclass = 'times-circle', size = 'normal', difference = 0; if ( ratio >= (target + 0.5) ) { // It passes if the ratio is greater than our constant plus 0.5 for gamma correction passfail = 'pass'; iclass = 'check-circle'; } else if ( ratio <= (target + 0.5) && ratio > target ) { // It barely passes if the ratio is less than our constant plus 0.5 for gamma correction // AND greater than the constant. So, within 0.5. passfail = 'edge'; iclass = 'exclamation-triangle'; } if ( target == AALARGERATIO ) { size = 'large'; } difference = Math.round10( (ratio - target), -1 ); var output = `<div class="color-ratio__wrapper ${size} ${passfail}"> <div class="color-ratio__label">color over ${color}</div> <div class="color-ratio__swatch" style="color: ${color}; border-color: ${color}; background-color: ${base};">Aa</div> <span class="fa fa-${iclass}"></span> <span class="color-ratio__passfail" title="Color ratio ${ratio} minus target ratio ${target}"> <b>${passfail}</b>${difference} </span> </div>`; return output; } var button = document.querySelector('#brand-color--button'); button.onclick = function(e) { e.preventDefault(); var resultsBlock = document.getElementById('results-content'); var results = document.getElementById('results-output'); // if there are already results displayed, clear them if ( results.children.length > 1 ) { results.innerHTML = ''; } // Set the header row results.innerHTML = `<div class="results__row results__row__header"> <div class="results__col ratios__original">Original</div> <div class="results__col ratios__on-white">With white</div> <div class="results__col ratios__on-black">With black</div> <div class="results__col ratios__most-legible">Most legible from available</div> </div>`; // get the colors inputted by the user var stringInput = document.querySelector('#brand-color--field').value; // if there's no input, get outta here if ( stringInput == '' ) { return; } // turn it into an array colorArray = stringInput.split("\n"); for (var i = 0; i < colorArray.length; i++) { // get the color's contrast ratios var ratio_onwhite = getRoundedRatio(colorArray[i], WHITE), ratio_onblack = getRoundedRatio(colorArray[i], BLACK), most_legible = tinycolor.mostReadable(colorArray[i], colorArray), ratio_mostlegible = getRoundedRatio(most_legible, colorArray[i]); // outputRatio( {color & border color}, ratio, {background color}, {ratio to test against} ) results.innerHTML += `<div class="results__row"> <div class="results__col ratios__original"> <div class="original__label">${colorArray[i]}</div> <div class="original__swatch" style="background-color: ${colorArray[i]};"></div> </div> <div class="results__col ratios__on-white"> ${outputRatio(colorArray[i], ratio_onwhite, '#fff', AANORMALRATIO)} ${outputRatio(colorArray[i], ratio_onwhite, '#fff', AALARGERATIO)} </div> <div class="results__col ratios__on-black"> ${outputRatio(colorArray[i], ratio_onblack, '#000', AANORMALRATIO)} ${outputRatio(colorArray[i], ratio_onblack, '#000', AALARGERATIO)} </div> <div class="results__col ratios__most-legible"> ${outputRatio(most_legible, ratio_mostlegible, colorArray[i], AANORMALRATIO)} ${outputRatio(most_legible, ratio_mostlegible, colorArray[i], AALARGERATIO)} </div> </div>`; } // make the results content visible resultsBlock.style.display = 'block'; resultsBlock.style.visibility = 'visible'; // jump to the results window.location.href = '#results-content'; // clear the input field //document.querySelector('#brand-color--field').value = ''; }
JavaScript
0.000063
@@ -2741,21 +2741,20 @@ over $%7B -color +base %7D%3C/div%3E%0A @@ -2802,29 +2802,28 @@ e=%22color: $%7B -color +base %7D; border-co @@ -2829,21 +2829,20 @@ olor: $%7B -color +base %7D; backg @@ -2856,20 +2856,21 @@ olor: $%7B -base +color %7D;%22%3EAa%3C/
504f2f619f99e4ebfa9a310e35f106e4a23ac615
build different sources for autocomplete
tx_highered/static/tx_highered/js/autocomplete.js
tx_highered/static/tx_highered/js/autocomplete.js
(function($, Trie, exports){ "use strict"; var $elem = $(".q"); var autocomplete_trie = new Trie(); // jQuery UI autocomplete var autocomplete_institutions = function(data) { // Map intitution names to URIs var urisByName = {}; $.map(data, function(o) { urisByName[o.name] = o.uri; }); // Insert institutions to trie $.each(data, function(i, o) { autocomplete_trie.insert(o.name.toLowerCase(), o); }); // Initialize autocomplete $elem.autocomplete({ source: $.map(data, function(n) { return n.name; }), select: function(e, o) { var uri = urisByName[o.item.label]; if (typeof(uri) !== "undefined") { location.href = uri; } } }); }; // Patch jQuery autocomplete to filter using fuzzy matching $.ui.autocomplete.filter = function(array, term) { var results = autocomplete_trie.search(term); return $.map(results, function(r) { return r.data.name; }); }; // TODO camelCase exports.autocomplete_institutions = autocomplete_institutions; })(jQuery, Trie, window);
JavaScript
0
@@ -1,8 +1,42 @@ +// TODO cache using localStorage?%0A (functio @@ -68,24 +68,41 @@ strict%22;%0A%0A%0A +// configuration%0A var $elem = @@ -110,16 +110,49 @@ (%22.q%22);%0A +var $ctl = $('#view-map a.btn');%0A %0A%0Avar au @@ -180,16 +180,320 @@ Trie(); +%0Avar _data = %5B%5B%5D, %5B%5D, %5B%5D%5D;%0Avar activeIdx = 0;%0A%0A// prebuild data source%0Avar build_sources = function(data)%7B%0A var newdata = _data, inst;%0A for (var i = 0; i %3C data.length; i++)%7B%0A inst = data%5Bi%5D;%0A newdata%5B0%5D.push(inst.name);%0A newdata%5B1 + !inst.is_private%5D.push(inst.name);%0A %7D%0A return newdata;%0A%7D; %0A%0A// jQu @@ -561,16 +561,48 @@ data) %7B%0A + _data = build_sources(data);%0A%0A // Map @@ -912,51 +912,16 @@ ce: -$.map(data, function(n) %7B return n.name; %7D) +_data%5B0%5D ,%0A @@ -1080,16 +1080,361 @@ %0A %7D);%0A%0A + $elem.on(%22keydown%22, function(e)%7B%0A if (e.which == 9) %7B // TAB%0A activeIdx = (activeIdx + 1) %25 3;%0A $elem.autocomplete('option', 'source', _data%5BactiveIdx%5D);%0A $elem.autocomplete('search', $elem.val());%0A $ctl.eq(activeIdx).addClass('active').siblings('.active').removeClass('active');%0A e.preventDefault();%0A %7D%0A%0A %7D);%0A %7D;%0A%0A// P
72f840a801d9dbfed956155ffe5726e32a2ffabb
Remove unused method.
src/file.js
src/file.js
'use strict'; var nodeFs = require('fs'); var cache = {}; function File ($matcher, $transformer, file) { if (cache[file]) { return cache[file]; } cache[file] = this; this._matcher = $matcher; this._transformer = $transformer; this._file = file; } File.prototype = { get code () { return this._code || (this._code = nodeFs.readFileSync(this.path).toString()); }, get imports () { return this._imports || (this._imports = this._matcher(this.path, this.pre)); }, get path () { return this._file; }, get post () { return this._post || (this._post = this._transformer.transform('post', this.pre, { imports: this.imports, path: this.path })); }, get pre () { return this._pre || (this._pre = this._transformer.transform('pre', this.code, { path: this.path })); }, cached: function () { return cache[this.path]; }, expire: function () { delete cache[this.path]; delete this._code; delete this._imports; delete this._post; delete this._pre; return this; } }; module.exports = File;
JavaScript
0
@@ -846,67 +846,8 @@ %7D,%0A%0A - cached: function () %7B%0A return cache%5Bthis.path%5D;%0A %7D,%0A%0A ex
73f6f286cc448115c7aab36c78eb7bcb51b3cc5e
Fix spacing on input with no status
ui/src/data_explorer/components/RawQueryEditor.js
ui/src/data_explorer/components/RawQueryEditor.js
import React, {PropTypes} from 'react' import classNames from 'classnames' const ENTER = 13 const ESCAPE = 27 const RawQueryEditor = React.createClass({ propTypes: { query: PropTypes.shape({ rawText: PropTypes.string.isRequired, id: PropTypes.string.isRequired, }).isRequired, onUpdate: PropTypes.func.isRequired, }, getInitialState() { return { value: this.props.query.rawText, } }, componentWillReceiveProps(nextProps) { if (nextProps.query.rawText !== this.props.query.rawText) { this.setState({value: nextProps.query.rawText}) } }, handleKeyDown(e) { if (e.keyCode === ENTER) { e.preventDefault() this.handleUpdate() } else if (e.keyCode === ESCAPE) { this.setState({value: this.state.value}, () => { this.editor.blur() }) } }, handleChange() { this.setState({ value: this.editor.value, }) }, handleUpdate() { this.props.onUpdate(this.state.value) }, render() { const {query: {rawStatus}} = this.props const {value} = this.state return ( <div className="raw-text"> <textarea className="raw-text--field" onChange={this.handleChange} onKeyDown={this.handleKeyDown} onBlur={this.handleUpdate} ref={(editor) => this.editor = editor} value={value} placeholder="Enter a query..." autoComplete="off" spellCheck="false" /> {this.renderStatus(rawStatus)} </div> ) }, renderStatus(rawStatus) { if (!rawStatus) { return null } return ( <div className={classNames("raw-text--status", {"raw-text--error": rawStatus.error, "raw-text--success": rawStatus.success, "raw-text--warning": rawStatus.warn})}> <span className={classNames("icon", {stop: rawStatus.error, checkmark: rawStatus.success, "alert-triangle": rawStatus.warn})}></span> {rawStatus.error || rawStatus.warn || rawStatus.success} </div> ) }, }) export default RawQueryEditor
JavaScript
0.000005
@@ -1615,12 +1615,66 @@ urn -null +(%0A %3Cdiv className=%22raw-text--status%22%3E%3C/div%3E%0A ) %0A
3eaab99699d029a74a8f58ee50d11fd83c495910
修改moedls/ post.js 代码格式
models/post.js
models/post.js
/** * models/post.js */ var mongoose = require('mongoose'); var PostSchema = new mongoose.Schema({ // 链接 link: String, // 标题 title: { type: String, unique: true}, // 图片 titlePic: String, // 内容 content: String, // 描述 description: String, // 发布内容 pubDate: { type: Date, default: Date.now }, source: String, typeId: Number, }); module.exports = mongoose.model('Post', PostSchema);
JavaScript
0
@@ -138,16 +138,20 @@ title: %7B +%0A type: S @@ -156,16 +156,20 @@ String, +%0A unique: @@ -173,16 +173,19 @@ ue: true +%0A %7D,%0A //
ddfbb46654fb8108f6fba93bbb6eb8c4300049e4
update min values
default/main.js
default/main.js
//Load Roles var consts = require('consts'); var helper = require('helper'); var roleHarvester = require('role.harvester'); var roleBuilder = require('role.builder'); var roleUpgrader = require('role.upgrader'); var roleRepair = require('role.repair'); // How to activate safeMode: Game.spawns['Spawn1'].room.controller.activateSafeMode(); /*-------------------------*/ /* -----Spawn Config -----*/ /*-------------------------*/ // Get spawn list var spawnList = []; for (let i in Game.spawns) { spawnList.push(Game.spawns[i]); } // Variables that don't do loop var spawn = spawnList[0]; var bodyTypes = consts.BODY_TYPES; // Start body chosen with BODY_TPYES[0] should be the smallest var bodyChosen = consts.BODY_TYPES[0]; // Max creeps according to role var max_harvester = 3; var max_builder = 2; var max_upgrader = 2; var max_repair = 2; // Min creeps that should have according to role var min_harvester = 2; var min_builder = 2; var min_upgrader = 2; var min_repair = 2; // Creeps count var num_harvesters = 0; var num_builders = 0; var num_upgraders = 0; var num_repair = 0; // Get all creeps separated by role. for (var i in Game.creeps) { var creep = Game.creeps[i]; if (creep.memory.role == consts.ROLE_HARVESTER) { num_harvesters++; } if (creep.memory.role == consts.ROLE_BUILDER) { num_builders++; } if (creep.memory.role == consts.ROLE_UPGRADER) { num_upgraders++; } if (creep.memory.role == consts.ROLE_REPAIR) { num_repair++; } } /*-------------------------*/ /* -- End Spawn Config --*/ /*-------------------------*/ // Main Loop module.exports.loop = function () { deathCreeps(); spawnCreeps(); for(var indx in Game.creeps) { var creep = Game.creeps[indx]; if (creep.memory.role == consts.ROLE_HARVESTER) { roleHarvester.run(creep); } if (creep.memory.role == consts.ROLE_UPGRADER) { roleUpgrader.run(creep); } if (creep.memory.role == consts.ROLE_BUILDER) { roleBuilder.run(creep); } if (creep.memory.role == consts.ROLE_REPAIR) { roleRepair.run(creep); } } } function deathCreeps() { /* ----- Clear death creeps config -----*/ for (var name in Memory.creeps) { if (!Game.creeps[name]) { if (Memory.creeps[name].role == consts.ROLE_HARVESTER) { num_harvesters--; } else if (Memory.creeps[name].role == consts.ROLE_BUILDER) { num_builders--; } else if (Memory.creeps[name].role == consts.ROLE_UPGRADER) { num_upgraders--; } else if (Memory.creeps[name].role == consts.ROLE_REPAIR) { num_repair--; } delete Memory.creeps[name]; console.log('Clearing non-existing creep memory:', name); } } } function spawnCreeps() { /* ----- Spawn Config -----*/ console.log("Quantidade de harvester: " + num_harvesters + "/" + max_harvester); console.log("Quantidade de builders: " + num_builders + "/" + max_builder); console.log("Quantidade de upgrader: " + num_upgraders + "/" + max_upgrader); console.log("Quantidade de reparadores: " + num_repair + "/" + max_repair); // If all creeps have their max, add one more. if (num_harvesters >= max_harvester && num_builders >= max_builder && num_upgraders >= max_upgrader && num_repair >= max_repair) { max_harvester++; max_builder++; max_upgrader++; max_repair++; } // Define what body should use. for (let i = bodyTypes.length - 1; i >= 0; i--) { if (spawn.canCreateCreep(bodyTypes[i], null) == OK) { bodyChosen = bodyTypes[i]; break; } } // Check if have the min creep in each role. if (num_harvesters >= min_harvester || num_builders >= min_builder || num_upgraders >= min_builder || num_repair >= min_repair) { // Spawn a new harvester if (num_harvesters <= max_harvester) { if (spawn.canCreateCreep(bodyChosen, null) == OK) { num_harvesters = helper.createCreep(spawn, num_harvesters, bodyChosen, consts.ROLE_HARVESTER); } } // Spawn a new builder else if (num_builders <= max_builder) { if (spawn.canCreateCreep(bodyChosen, null) == OK) { num_builders = helper.createCreep(spawn, num_builders, bodyChosen, consts.ROLE_BUILDER); } } // Spawn a new upgrader else if (num_upgraders <= max_upgrader) { if (spawn.canCreateCreep(bodyChosen, null) == OK) { num_upgraders = helper.createCreep(spawn, num_upgraders, bodyChosen, consts.ROLE_UPGRADER); } } // Spawn a new repair else if (num_repair <= max_repair) { if (spawn.canCreateCreep(bodyChosen, null) == OK) { num_repair = helper.createCreep(spawn, num_repair, bodyChosen, consts.ROLE_REPAIR); } } } else if (num_harvesters < min_harvester) { if (spawn.canCreateCreep(bodyChosen, null) == OK) { num_harvesters = helper.createCreep(spawn, num_harvesters, bodyChosen, consts.ROLE_HARVESTER); } } else if (num_builders < min_builder) { if (spawn.canCreateCreep(bodyChosen, null) == OK) { num_builders = helper.createCreep(spawn, num_builders, bodyChosen, consts.ROLE_BUILDER); } } else if (num_upgraders < min_upgrader) { if (spawn.canCreateCreep(bodyChosen, null) == OK) { num_upgraders = helper.createCreep(spawn, num_upgraders, bodyChosen, consts.ROLE_UPGRADER); } } else if (num_repair < min_repair) { if (spawn.canCreateCreep(bodyChosen, null) == OK) { num_repair = helper.createCreep(spawn, num_repair, bodyChosen, consts.ROLE_REPAIR); } } /* -- End Spawn Config --*/ }
JavaScript
0.000001
@@ -954,25 +954,25 @@ _upgrader = -2 +1 ;%0Avar min_re @@ -974,25 +974,25 @@ in_repair = -2 +1 ;%0A%0A// Creeps
cf2ea7593a5e928099b3fc560734c7ad1de35b4e
Add auth
asciipic/web/js/term.js
asciipic/web/js/term.js
var TOKEN = null, RETRY_COUNT = 25, RETRY_DELAY = 60; function setSize() { let height = $("#term-row").height() - $("footer").height() - 100; $("#term").css("height", height); } function send_login(command, terminal){ // Send the login credentials var params = command.split(" "); request = $.ajax({ async: false, url: "/api/user/token", method: "POST", data: { "username": params[1], "password": params[2] } }); request.fail(function( jqXHR, textStatus ) { terminal.echo("Error: " + textStatus ); }); request.done(function(response){ if(response["meta"]["status"]){ if(response["content"]["token"]){ TOKEN = response["content"]["token"]; localStorage.setItem("TOKEN", TOKEN) terminal.echo("Token :" + TOKEN); }else{ terminal.echo(response["meta"]["verbose"]); } }else{ terminal.echo(response["meta"]["verbose"]); } }); } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } function wait_for_job(job_id, path, terminal){ // for for the jobs id // // @param job_id // If of the job to wait // // @param path // The API endpoint to query // // @param terminatl // Reference to the terminal var fail = false, done = false; for(var i = 0; i<= RETRY_COUNT; i++){ if(fail) { terminal.echo("Can't reach the API."); return null; } if(done) { console.log("Done waiting.") return null; } sleep(RETRY_DELAY); request = $.ajax({ async: false, url: path + "/" + job_id, method: "GET", headers: { "Authorization": TOKEN }, }); request.fail(function( jqXHR, textStatus ) { terminal.echo("Error: " + textStatus ); fail = true; }); request.done(function(response){ if(response["meta"]["status"]){ // need to wait for the job to finish var echo_id = response["meta"]["job_id"]; if(response["meta"]["job_status"] === "finished"){ terminal.echo(response["content"]); done = true; }else { console.log("Retry " + i); console.log(response); } }else{ terminal.echo(response["meta"]["verbose"]); fail = true; } }); } } function send_echo(command, terminal){ // Send the login credentials request = $.ajax({ async: false, url: "/api/echo", method: "POST", data: { "data": command }, headers: { "Authorization": TOKEN }, }); request.fail(function( jqXHR, textStatus ) { terminal.echo("Error: " + textStatus ); }); request.done(function(response){ if(response["meta"]["status"]){ // need to wait for the job to finish var job_id = response["meta"]["job_id"]; terminal.echo("Id :"+job_id); wait_for_job(job_id, "/api/echo", terminal) }else{ terminal.echo(response["meta"]["verbose"]); } }); } (function() { 'use strict'; jQuery(function($, undefined) { $('#term').terminal(function(command) { // Preserve theterminal let terminal = this; if(command.startsWith("login")){ send_login(command, terminal); }else if(command.startsWith("echo")){ send_echo(command, terminal) }else{ // aici parsam restul comenzilor } // end for login }, { greetings: 'AsciiPic Web CLI', prompt: 'asciipic ~$ ', resize: true, history: true, }); }); // Resize setSize(); $(window).resize(setSize); })();
JavaScript
0.000007
@@ -3513,16 +3513,540 @@ %7D);%0A%7D%0A%0A +function send_auth(command, terminal)%0A%7B%0A var params = command.split(%22 %22);%0A%0A request = $.ajax(%7B%0A async: false,%0A url: %22/api/user/account%22,%0A method: %22POST%22,%0A data: %7B%0A %22username%22: params%5B1%5D,%0A %22password%22: params%5B2%5D,%0A %22email%22: params%5B3%5D%0A %7D%0A %7D);%0A%0A request.fail(function( jqXHR, textStatus ) %7B%0A terminal.echo(%22Error: %22 + textStatus );%0A %7D);%0A%0A request.done(function(response)%7B%0A terminal.echo(response%5B%22meta%22%5D%5B%22verbose%22%5D);%0A %7D);%0A%0A%7D%0A%0A %0A(functi @@ -4413,16 +4413,112 @@ minal) %0A + %7Delse if(command.startsWith(%22auth%22))%7B%0A send_auth(command, terminal) %0A
1c7394ee0176b30fef84b25d441629375f51441d
add 'open in editor' option
app/src/tray-popup/components/projects/project.js
app/src/tray-popup/components/projects/project.js
import { remote, shell, clipboard } from 'electron'; import styled, { css } from 'styled-components'; import Button from '~/common/components/button'; const { Menu, MenuItem } = remote; const userHomePath = remote.app.getPath('home'); const cropOverflowedText = css` white-space: nowrap; text-overflow: ellipsis; overflow: hidden; `; const Actions = styled.div` visibility: hidden; `; const Action = styled(Button).attrs({ ghost: true })` font-size: 1.25rem; `; const Container = styled.div` padding: 0.5rem 0.75rem; display: flex; &:hover { ${Actions} { visibility: visible; } } `; const Avatar = styled.div` width: 30px; height: 30px; color: white; display: flex; align-items: center; justify-content: center; text-transform: uppercase; font-weight: 100; border-radius: 50%; `; const Details = styled.div` padding-left: 0.5rem; flex-direction: column; display: flex; min-width: 0; flex: 1; `; const Name = styled.h3` ${cropOverflowedText}; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; margin: 0; padding: 0; font-weight: normal; font-size: 1rem; `; const Path = styled.div` ${cropOverflowedText}; font-size: 0.75rem; color: #999; `; const showOptions = project => { Menu.buildFromTemplate([ { label: 'Reveal in Finder', click: () => shell.showItemInFolder(project.path), }, { label: 'Copy Path', click: () => clipboard.writeText(project.path), }, ]).popup(); }; const Project = props => ( <Container> <Avatar style={{ backgroundColor: props.color }}>{props.name[0]}</Avatar> <Details> <Name title={props.name}>{props.name}</Name> <Path title={props.path}>{props.path.replace(userHomePath, '~')}</Path> </Details> <Actions> <Action onClick={() => showOptions(props)}>🛠</Action> </Actions> </Container> ); export default Project;
JavaScript
0.000016
@@ -1,12 +1,37 @@ +import path from 'path';%0A import %7B rem @@ -1275,61 +1275,315 @@ nst -showOptions = project =%3E %7B%0A Menu.buildFromTemplate(%5B +fetchScripts = project =%3E %7B%0A // tbd%0A%7D;%0A%0Aconst showProjectMenu = project =%3E %7B%0A Menu.buildFromTemplate(%5B%0A %7B%0A label: 'Scripts',%0A submenu: %5B%5D,%0A %7D,%0A %7B type: 'separator' %7D,%0A %7B%0A label: 'Open in Editor',%0A click: () =%3E shell.openItem(path.join(project.path), 'package.json'),%0A %7D, %0A @@ -2121,15 +2121,19 @@ show -Options +ProjectMenu (pro
2041deac2d475f1f8104ad0520abf4b1f7ab1405
Fix localization issue, now get dictionary into l10n component
activities/EbookReader.activity/js/l10n.js
activities/EbookReader.activity/js/l10n.js
// Localization component var Localization = { template: '<div/>', data: function() { return { l10n: null, eventReceived: false } }, mounted: function() { var vm = this; if (vm.l10n == null) { require(["sugar-web/env", "webL10n"], function (env, webL10n) { env.getEnvironment(function(err, environment) { vm.l10n = webL10n; var defaultLanguage = (typeof chrome != 'undefined' && chrome.app && chrome.app.runtime) ? chrome.i18n.getUILanguage() : navigator.language; var language = environment.user ? environment.user.language : defaultLanguage; webL10n.language.code = language; window.addEventListener("localized", function() { if (!vm.eventReceived) { vm.$emit("localized"); vm.eventReceived = true; } }); }); }); } }, methods: { get: function(str) { return this.l10n.get(str); } } }
JavaScript
0
@@ -109,16 +109,37 @@ : null,%0A +%09%09%09dictionary: null,%0A %09%09%09event @@ -721,24 +721,67 @@ Received) %7B%0A +%09%09%09%09%09%09%09vm.dictionary = vm.l10n.dictionary;%0A %09%09%09%09%09%09%09vm.$e @@ -798,16 +798,16 @@ ized%22);%0A - %09%09%09%09%09%09%09v @@ -912,33 +912,173 @@ %0A%09%09%09 -return this.l10n.get(str) +if (!this.dictionary) %7B%0A%09%09%09%09return str;%0A%09%09%09%7D%0A%09%09%09var item = this.dictionary%5Bstr%5D;%0A%09%09%09if (!item %7C%7C !item.textContent) %7B%0A%09%09%09%09return str;%0A%09%09%09%7D%0A%09%09%09return item.textContent ;%0A%09%09
fcd2564ad060874c4f1a53122a15db8b796b0d72
Modify test cases
jasmine/spec/inverted-index-test.js
jasmine/spec/inverted-index-test.js
describe ("Check if class exists", function () { it ("checks that class is defined", function () { expect (InvertedIndex).toBeDefined(); } ); }); describe ("Read book data", function () { var index = new InvertedIndex(); it ("readFile method should not return empty JSON", function () { var jsonFile = index.readFile("books.json"); expect (jsonFile.length).toBeGreaterThan(0); expect (jsonFile).not.toBe([]); }); }); describe ("Populate index", function () { var index = new InvertedIndex(); index.createIndex("books.json"); it ("verifies that index is created once jsonFile is read", function () { expect (index.data).toBeDefined(); }); it ("verifies that index is correct", function () { expect (index.data.alice).toEqual([0]); expect (index.data.of).toEqual([0,1]); expect (index.data.lord).toEqual([1]); expect (index.data.wonderful).toBeUndefined(); }); }); describe ("Search index", function () { var index = new InvertedIndex(); index.createIndex("books.json"); it ("verifies that search returns correct result", function () { expect (index.searchIndex("alice wonderland")).toEqual([[0],[0]]); expect (index.searchIndex("lord ring of")).toEqual([[1],[1],[0,1]]); expect (index.searchIndex("imagination")).toEqual([0]); }); it("verifies searching an index returns array of indices of correct object", function() { expect (index.searchIndex("into")).toEqual([[0]]); expect (index.searchIndex("wizard")).toEqual([[1]]); expect (index.searchIndex("a")).toEqual([[0],[1]]); expect (index.searchIndex("of")).toEqual([[0],[1]]); expect (index.searchIndex("lord")).toEqual([[0],[1]]); expect (index.searchIndex("elf")).toEqual([[1]]); }); it("can handle varied number of search terms", function() { expect(index.searchIndex(['alice', 'in', 'wonderland'])).toEqual([[0],[0],[0]]); expect(index.searchIndex(['lord', 'of', 'the', 'rings'])).toEqual([[1],[0, 1],[1],[1]]); expect(index.searchIndex(['an', 'unusual', 'alliance', 'of', 'man'])).toEqual([[1],[1],[1],[0, 1],[1]]); }); it("ensures search can handle a varied number of arguments and strings with space characters", function() { expect(index.searchIndex('alice', 'alice in wonderland', 'in')).toEqual([[0],[0],[0],[0],[0]]); expect(index.searchIndex('lord', 'of', 'the', 'rings')).toEqual([[1],[0, 1],[1],[1]]); expect(index.searchIndex('an', 'unusual', 'alliance', 'of', 'man')).toEqual([[1],[1],[1],[0, 1],[1]]); }); it("ensures search can handle edge cases", function() { expect(index.searchIndex('alice', 'notAvailable', 'in')).toEqual([[0],[],[0]]); }); });
JavaScript
0.000187
@@ -1163,32 +1163,61 @@ ual(%5B%5B0%5D,%5B0%5D%5D);%0A + console.log(index.data);%0A expect (inde @@ -1308,19 +1308,11 @@ ex(%22 -imagination +the %22)). @@ -1316,25 +1316,25 @@ )).toEqual(%5B -0 +1 %5D);%0A %7D);%0A @@ -1574,35 +1574,34 @@ a%22)).toEqual(%5B%5B0 -%5D,%5B +, 1%5D%5D);%0A expect @@ -1630,35 +1630,34 @@ f%22)).toEqual(%5B%5B0 -%5D,%5B +, 1%5D%5D);%0A expect @@ -1695,20 +1695,16 @@ Equal(%5B%5B -0%5D,%5B 1%5D%5D);%0A @@ -2626,18 +2626,13 @@ ', ' -notAvailab +bicyc le',
b65fab8458dd6e7de6996279ae493d69ee46e249
add more test
jasmine/spec/inverted-index-test.js
jasmine/spec/inverted-index-test.js
/* eslint-disable no-unused-vars*/ /* eslint-disable no-undef*/ /* eslint-disable no-dupe-keys*/ /* eslint-disable no-multi-assign*/ const invertedIndex = new InvertedIndex(); const books = require('../books.json'); const empty = require('../emptyBook.json'); const invalid = require('../invalidBook.json'); const little = require('../littleBook.json'); describe('Inverted Index', () => { /** * Test suite to ensure the validateFile method returns an object of * the correct index mapping */ describe('Read book data', () => { it('Should ensure file content is actually a valid JSON array', () => { expect(InvertedIndex.validateFile(books)).toEqual(true); }); it('Should return false for invalid JSON file', () => { expect(InvertedIndex.validateFile(invalid)).toEqual(false); }); it('Should ensure that JSON array is not empty', () => { expect(InvertedIndex.validateFile(empty)).toEqual(false); }); }); /* * Populate Index Test Suite */ describe('Populate Index', () => { invertedIndex.createIndex('books.json', books); it('Should ensure that index is created once file has been read', () => { expect(invertedIndex.indices['books.json']).toBeDefined(); }); it('Should map the string keys to the correct objects', () => { expect(invertedIndex.indices['books.json'].terms.alice).toEqual([1]); expect(invertedIndex.indices['books.json'].terms.and).toEqual([1, 2]); expect(invertedIndex.indices['books.json'].terms.lord).toEqual([2]); expect(invertedIndex.indices['books.json'].terms.lord).not.toEqual([1]); expect(invertedIndex.indices['books.json'].terms.alice).not.toEqual([2]); }); invertedIndex.createIndex('littleBook.json', little); it('Should return correct indices of JSON file contents', () => { expect(invertedIndex.indices['littleBook.json'].terms).toEqual({ ali: [1], is: [1, 2], human: [1], deliver: [2], me: [2], this: [2], progress: [2] }); }); it('Should return an accurate index of json file content', () => { expect(invertedIndex.getIndex('littleBook.json').terms.is) .toEqual([1, 2]); }); }); /** * Test suite to ensure the getIndex method returns an object of * the correct index mapping */ describe('Get index', () => { it('Should return an object when value is found', () => { const indexedFile = invertedIndex.getIndex('books.json'); expect(typeof indexedFile === 'object').toBeTruthy(); }); it('Should contain valid indexed words and position', () => { expect(invertedIndex.getIndex('books.json').terms.alice).toEqual([1]); expect(invertedIndex.getIndex('books.json').terms.and).toEqual([1, 2]); expect(invertedIndex.getIndex('books.json').terms.lord).toEqual([2]); }); invertedIndex.createIndex('littleBook.json', little); it('Should return correct indices of JSON file contents', () => { expect(invertedIndex.getIndex('littleBook.json').terms).toEqual({ ali: [1], is: [1, 2], human: [1], deliver: [2], me: [2], this: [2], progress: [2] }); }); }); /** * Test suite to ensure the tokenizer method returns an object of * the correct index mapping */ describe('Tokenizer', () => { it('Should return an array when a string is passed', () => { expect(InvertedIndex.tokenizer('This is yemi')) .toEqual(['this', 'is', 'yemi']); }); it('Should return an array when an array is passed', () => { expect(InvertedIndex.tokenizer(['testing#%', 'for*%$', 'array#@%'])) .toEqual(['testing', 'for', 'array']); }); it('Should return an array for strings with special characters', () => { expect(InvertedIndex.tokenizer('$#@ this&#@ is*&% testing')) .toEqual(['this', 'is', 'testing']); }); it('Should return an array for strings with white spaces', () => { expect(InvertedIndex.tokenizer(' these are lots of spaces ')) .toEqual(['these', 'are', 'lots', 'of', 'spaces']); }); it('Should return an array for strings with uppercases', () => { expect(InvertedIndex.tokenizer(' theSe aRe lOtS oF cAsEs ')) .toEqual(['these', 'are', 'lots', 'of', 'cases']); }); }); /** * Test suite to ensure the searchIndex method returns an object of * the correct index mapping */ describe('Search Index', () => { invertedIndex.searchIndex('books.json', 'alice'); it('Should return correct result of the search term', () => { expect(invertedIndex.searchIndex('books.json', 'alice, a')[0]).toEqual({ terms: { alice: [1], a: [1, 2] }, count: 2, fileName: 'books.json' }); }); it('Should return correct index in an array search terms', () => { expect(invertedIndex.searchIndex('books.json', ['alice', 'a', 'hole', 'lord'])) .toEqual([{ terms: { alice: [1], hole: [1], a: [1, 2], lord: [2] }, count: 2, fileName: 'books.json' }]); }); it('Should ensure searchIndex handles varied search terms as arguments', () => { expect(invertedIndex .searchIndex('littleBook.json', 'is')) .toEqual([{ terms: { is: [1, 2], }, count: 2, fileName: 'littleBook.json' }]); expect(invertedIndex .searchIndex('littleBook.json', 'is', 'progress', 'this')) .toEqual([{ terms: { is: [1, 2], progress: [2], this: [2], }, count: 2, fileName: 'littleBook.json' }]); }); it('Should go through all indexed terms if fileName is not passed', () => { expect(invertedIndex.searchIndex(null, 'alice, ali')).toEqual([{ terms: { alice: [1] }, count: 2, fileName: 'books.json' }, { terms: { ali: [1] }, count: 2, fileName: 'littleBook.json' }]); }); }); });
JavaScript
0.000002
@@ -5634,16 +5634,23 @@ , 'this' +, 'ali' ))%0A @@ -5749,32 +5749,53 @@ this: %5B2%5D,%0A + ali: %5B1%5D%0A %7D,%0A
95ca82c22f2587afaf6c75759bd841c09554815b
Fix sizing of instruction row on project overview page
website/static/js/pages/project-dashboard-page.js
website/static/js/pages/project-dashboard-page.js
/** Initialization code for the project dashboard. */ var $ = require('jquery'); require('jquery-tagsinput'); var m = require('mithril'); var Fangorn = require('fangorn'); var LogFeed = require('../logFeed.js'); var pointers = require('../pointers.js'); var Comment = require('../comment.js'); var Raven = require('raven-js'); var NodeControl = require('../nodeControl.js'); var nodeApiUrl = window.contextVars.node.urls.api; // Initialize controller for "Add Links" modal new pointers.PointerManager('#addPointer', window.contextVars.node.title); // Listen for the nodeLoad event (prevents multiple requests for data) $('body').on('nodeLoad', function(event, data) { new LogFeed('#logScope', nodeApiUrl + 'log/'); // Initialize nodeControl new NodeControl('#projectScope', data); }); // Initialize comment pane w/ it's viewmodel var $comments = $('#comments'); if ($comments.length) { var userName = window.contextVars.currentUser.name; var canComment = window.contextVars.currentUser.canComment; var hasChildren = window.contextVars.node.hasChildren; Comment.init('#commentPane', userName, canComment, hasChildren); } $(document).ready(function() { // Treebeard Files view $.ajax({ url: nodeApiUrl + 'files/grid/' }) .done(function( data ) { var fangornOpts = { divID: 'treeGrid', filesData: data.data, uploads : true, showFilter : true, filterStyle : { 'float' : 'left', width : '100%'}, placement: 'dashboard', columnTitles : function(){ return [ { title: 'Name', width : '100%', sort : false, sortType : 'text' } ]; }, resolveRows : function(item){ if (item.parentID) { item.data.permissions = item.data.permissions || item.parent().data.permissions; if (item.data.kind === 'folder') { item.data.accept = item.data.accept || item.parent().data.accept; } } if(item.data.tmpID){ return [ { data : 'name', // Data field name folderIcons : true, filter : true, custom : function(){ return m('span.text-muted', 'Uploading ' + item.data.name + '...'); } } ]; } return [{ data: 'name', folderIcons: true, filter: true, custom: Fangorn.DefaultColumns._fangornTitleColumn }]; }, }; var filebrowser = new Fangorn(fangornOpts); }); // Tooltips $('[data-toggle="tooltip"]').tooltip(); // Tag input $('#node-tags').tagsInput({ width: "100%", interactive: window.contextVars.currentUser.canEdit, maxChars: 128, onAddTag: function(tag){ var url = window.contextVars.node.urls.api + "addtag/" + tag + "/"; var request = $.ajax({ url: url, type: "POST", contentType: "application/json" }); request.fail(function(xhr, textStatus, error) { Raven.captureMessage('Failed to add tag', { tag: tag, url: url, textStatus: textStatus, error: error }); }) }, onRemoveTag: function(tag){ var url = window.contextVars.node.urls.api + "removetag/" + tag + "/"; var request = $.ajax({ url: url, type: "POST", contentType: "application/json" }); request.fail(function(xhr, textStatus, error) { Raven.captureMessage('Failed to remove tag', { tag: tag, url: url, textStatus: textStatus, error: error }); }) } }); // Limit the maximum length that you can type when adding a tag $('#node-tags_tag').attr("maxlength", "128"); // Remove delete UI if not contributor if (!window.contextVars.currentUser.canEdit || window.contextVars.node.isRegistration) { $('a[title="Removing tag"]').remove(); $('span.tag span').each(function(idx, elm) { $(elm).text($(elm).text().replace(/\s*$/, '')) }); } if (window.contextVars.node.isRegistration && window.contextVars.node.tags.length === 0) { $('div.tags').remove(); } });
JavaScript
0.000001
@@ -1473,94 +1473,151 @@ -filterStyle : %7B 'float' : 'left', width : '100%25'%7D,%0A placement: 'dashboard', +placement: 'dashboard',%0A title : undefined,%0A filterFullWidth : true, // Make the filter span the entire row for this view %0A
e190634f526339ee97dcd62e8bc3ffa8417986c0
Fix typo in urlForFindBelongsTo adapter method
addon/-private/adapters/build-url-mixin.js
addon/-private/adapters/build-url-mixin.js
import Ember from 'ember'; var get = Ember.get; /** WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 ## Using BuildURLMixin To use url building, include the mixin when extending an adapter, and call `buildURL` where needed. The default behaviour is designed for RESTAdapter. ### Example ```javascript export default DS.Adapter.extend(BuildURLMixin, { findRecord: function(store, type, id, snapshot) { var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); return this.ajax(url, 'GET'); } }); ``` ### Attributes The `host` and `namespace` attributes will be used if defined, and are optional. @class BuildURLMixin @namespace DS */ export default Ember.Mixin.create({ /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. When called by RESTAdapter.findMany() the `id` and `snapshot` parameters will be arrays of ids and snapshots. @method buildURL @param {String} modelName @param {(String|Array|Object)} id single id or array of ids or query @param {(DS.Snapshot|Array)} snapshot single snapshot or array of snapshots @param {String} requestType @param {Object} query object of query parameters to send for query requests. @return {String} url */ buildURL(modelName, id, snapshot, requestType, query) { switch (requestType) { case 'findRecord': return this.urlForFindRecord(id, modelName, snapshot); case 'findAll': return this.urlForFindAll(modelName); case 'query': return this.urlForQuery(query, modelName); case 'queryRecord': return this.urlForQueryRecord(query, modelName); case 'findMany': return this.urlForFindMany(id, modelName, snapshot); case 'findHasMany': return this.urlForFindHasMany(id, modelName); case 'findBelongsTo': return this.urlForFindBelongsTo(id, modelName); case 'createRecord': return this.urlForCreateRecord(modelName, snapshot); case 'updateRecord': return this.urlForUpdateRecord(id, modelName, snapshot); case 'deleteRecord': return this.urlForDeleteRecord(id, modelName, snapshot); default: return this._buildURL(modelName, id); } }, /** @method _buildURL @private @param {String} modelName @param {String} id @return {String} url */ _buildURL(modelName, id) { var url = []; var host = get(this, 'host'); var prefix = this.urlPrefix(); var path; if (modelName) { path = this.pathForType(modelName); if (path) { url.push(path); } } if (id) { url.push(encodeURIComponent(id)); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url && url.charAt(0) !== '/') { url = '/' + url; } return url; }, /** * @method urlForFindRecord * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForFindRecord(id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** * @method urlForFindAll * @param {String} modelName * @return {String} url */ urlForFindAll(modelName) { return this._buildURL(modelName); }, /** * @method urlForQuery * @param {Object} query * @param {String} modelName * @return {String} url */ urlForQuery(query, modelName) { return this._buildURL(modelName); }, /** * @method urlForQueryRecord * @param {Object} query * @param {String} modelName * @return {String} url */ urlForQueryRecord(query, modelName) { return this._buildURL(modelName); }, /** * @method urlForFindMany * @param {Array} ids * @param {String} modelName * @param {Array} snapshots * @return {String} url */ urlForFindMany(ids, modelName, snapshots) { return this._buildURL(modelName); }, /** * @method urlForFindHasMany * @param {String} id * @param {String} modelName * @return {String} url */ urlForFindHasMany(id, modelName) { return this._buildURL(modelName, id); }, /** * @method urlForFindBelongTo * @param {String} id * @param {String} modelName * @return {String} url */ urlForFindBelongsTo(id, modelName) { return this._buildURL(modelName, id); }, /** * @method urlForCreateRecord * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForCreateRecord(modelName, snapshot) { return this._buildURL(modelName); }, /** * @method urlForUpdateRecord * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForUpdateRecord(id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** * @method urlForDeleteRecord * @param {String} id * @param {String} modelName * @param {DS.Snapshot} snapshot * @return {String} url */ urlForDeleteRecord(id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** @method urlPrefix @private @param {String} path @param {String} parentURL @return {String} urlPrefix */ urlPrefix(path, parentURL) { var host = get(this, 'host'); var namespace = get(this, 'namespace'); if (!host || host === '/') { host = ''; } if (path) { // Protocol relative url if (/^\/\//.test(path) || /http(s)?:\/\//.test(path)) { // Do nothing, the full host is already included. return path; // Absolute path } else if (path.charAt(0) === '/') { return `${host}${path}`; // Relative path } else { return `${parentURL}/${path}`; } } // No path provided var url = []; if (host) { url.push(host); } if (namespace) { url.push(namespace); } return url.join('/'); }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ pathForType: function(modelName) { var decamelized = Ember.String.decamelize(modelName); return Ember.String.pluralize(decamelized); } }); ``` @method pathForType @param {String} modelName @return {String} path **/ pathForType(modelName) { var camelized = Ember.String.camelize(modelName); return Ember.String.pluralize(camelized); } });
JavaScript
0.000008
@@ -4490,16 +4490,17 @@ ndBelong +s To%0A *
da936872de9beaf485814732c3ee1757103fef4a
Replace deep equality with regular in Cache
web/src/js/core/cache.js
web/src/js/core/cache.js
import equal from 'deep-equal'; export default class Cache { constructor(size) { this.size = size; this.cache = []; } put(key, value) { const existing = this.cache.findIndex(item => equal(item.key, key)); if (existing >= 0) { this.cache.splice(existing, 1); } this.cache.push({key, value}); if (this.cache.length > this.size) { const removeCount = this.cache.length - this.size; return this.cache.splice(0, removeCount); } else { return []; } } get(key) { const item = this.cache.find(item => equal(item.key, key)); return item ? item.value : null; } }
JavaScript
0
@@ -1,38 +1,4 @@ -import equal from 'deep-equal';%0A%0A%0A expo @@ -158,38 +158,32 @@ dex(item =%3E -equal( item.key , key));%0A @@ -166,31 +166,32 @@ =%3E item.key -, + == key) -) ;%0A if (ex @@ -531,22 +531,16 @@ =%3E -equal( item.key , ke @@ -539,15 +539,16 @@ .key -, + == key) -) ;%0A
219ab75b089a2601fbfabd02dcfb2409c312c9f3
Rename user in require
src/game.js
src/game.js
import {EventEmitter2 as EventEmitter } from "eventemitter2" const User = require(`${__dirname}/game/model/user.js`); const Status = require(`${__dirname}/game/model/Status.js`); const Equipment = require(`${__dirname}/game/model/Equipment.js`); const Weapon = require(`${__dirname}/game/model/Weapon.js`); const Parameter = require(`${__dirname}/game/model/Parameter.js`); const HitRate = require(`${__dirname}/game/model/HitRate.js`); const Spell = require(`${__dirname}/game/model/Spell.js`); const Effect = require(`${__dirname}/game/model/Effect.js`); const HitPoint = require(`${__dirname}/game/model/HitPoint.js`); const Critical = require(`${__dirname}/game/model/Critical.js`); const UserStates= require(`${__dirname}/game/state/User.js`); const MagicPoint = require(`${__dirname}/game/model/MagicPoint.js`); const STATUS_VALUES = require(`${__dirname}/game/constant/Status.js`); import Job from "./game/model/Job" import Feedback from "./game/model/effect/Feedback" import FeedbackResult from "./game/model/effect/FeedbackResult" class Game extends EventEmitter { constructor(minHitPoint, maxHitPoint, minMagicPoint, maxMagicPoint) { super(); this.users = []; this.minHitPoint = isNaN(minHitPoint) ? 0 : minHitPoint; this.minMagicPoint = isNaN(minMagicPoint) ? 0 : minMagicPoint; this.maxHitPoint = isNaN(maxHitPoint) ? Infinity : maxHitPoint; this.maxMagicPoint = isNaN(maxMagicPoint) ? Infinity : maxMagicPoint; }; setUsers(users) { this.users = users; } findUser(name) { const targets = this.users.filter((u) => u.name === name); return targets.length === 0 ? null : targets.pop(); }; } module.exports = { Game: Game, User: User, HitPoint: HitPoint, MagicPoint: MagicPoint, Status: Status, Equipment: Equipment, Weapon: Weapon, Parameter: Parameter, HitRate: HitRate, Critical: Critical, Spell: Spell, Effect: Effect, StatusValues: STATUS_VALUES, UserStates: UserStates, Job: Job, Feedback: Feedback, FeedbackResult: FeedbackResult }
JavaScript
0.000001
@@ -105,17 +105,17 @@ e/model/ -u +U ser.js%60)
2a196515cb032b0a0f21014270850c422798c87a
Update game dependencies
src/game.js
src/game.js
import {Loop, AssetLoader} from 'gamebox'; import Base from 'flockn/base'; import Graphics from 'flockn/graphics'; import Scene from 'flockn/scene'; import Color from 'flockn/types/color'; import Viewport from 'flockn/viewport'; import {addable, renderable, updateable, serializable} from 'flockn/mixins'; var root = window; // Game is the entry point for all games made with flockn. // Any number of `Scene` instances can be attached to a `Game` instance class Game extends Base { constructor(descriptor) { // Extend the `Base` class super('Game', descriptor); // `this.container` is a string, which is the id of the element. // If it's not given, it should create a new element. This should be handled by the renderer. this.container = null; // By default, the width and height of a `Game` instance will be as large as the inside of the browser window. this.width = root.innerWidth; this.height = root.innerHeight; this.color = new Color(255, 255, 255); this.assetLoader = new AssetLoader(); // Set the viewport object this.viewport = Viewport; // `this.activeScene` is set to `null` by default, but will change to the instance of the scene // once a scene will be shown this.activeScene = null; // A `Game` instance is the root element so the descriptor needs to be called directly, // because it won't be added to anywhere else this.call(); Graphics.trigger('initialize', this); // Mix in `renderable` and `updateable` renderable.call(this); updateable.call(this); // Bind the game loop to the `update` event Loop.on('update', (dt) => { // Deltatime should not be a millisecond value, but a second one. // It should be a value between 0 - 1 this.trigger('update', dt / 1000); }); // Bind the game loop to the `render` event Loop.on('render', () => { this.trigger('render'); }); // Add a `resize` event to each `Game` instance root.addEventListener('resize', () => { var newWidth = root.innerWidth; var newHeight = root.innerHeight; this.trigger('resize', newWidth, newHeight); // Trigger resize event for the current scene var currentScene = this.children.byName(this.activeScene); if (currentScene) { currentScene.trigger('resize', root.innerWidth, root.innerHeight); } }, false); // Add an `orientationchange` event to each `Game` instance root.addEventListener('orientationchange', () => { this.trigger('orientationchange'); }, false); } addScene() { // When adding a scene, the dimension of scenes should be // exactly as large as the `Game` instance itself this.queue.push(addable(Scene, this.children, function (child) { child.width = this.width; child.height = this.height; }).apply(this, arguments)); } showScene(name) { // TODO: Add transitions this.children.forEach(scene => scene.visible = false); // Set the `activeScene` property this.activeScene = this.children.byName(name); this.activeScene.visible = true; if (this.activeScene) { this.activeScene.trigger('resize', root.innerWidth, root.innerHeight); // Trigger the `show` event this.trigger('show', name, this.children[this.activeScene]); } } preload(assets) { this.assetLoader.assets = assets; return this.assetLoader; } run(name) { this.on('executed', () => { // Start the game loop Loop.run(); if (!name) { // If there's only no name, take the first scene if (this.children.length >= 1) { name = this.children.first().name; } } // Show the scene if a parameter has been specified this.showScene(name); }); } } serializable(Game); export default Game;
JavaScript
0
@@ -55,22 +55,17 @@ e from ' -flockn +. /base';%0A @@ -86,22 +86,17 @@ s from ' -flockn +. /graphic @@ -118,22 +118,17 @@ e from ' -flockn +. /scene'; @@ -147,22 +147,17 @@ r from ' -flockn +. /types/c @@ -185,22 +185,17 @@ t from ' -flockn +. /viewpor @@ -260,22 +260,17 @@ %7D from ' -flockn +. /mixins'
294542782eea95dfeb74d7a2b24b72edfe5b5b44
Fix logout not removing session from RP
src/webid-oidc.js
src/webid-oidc.js
// @flow /* global RequestInfo, Response */ import * as authorization from 'auth-header' import RelyingParty from '@solid/oidc-rp' import PoPToken from '@solid/oidc-rp/lib/PoPToken' import type { loginOptions } from './solid-auth-client' import { currentUrl, navigateTo, toUrlString } from './url-util' import type { webIdOidcSession } from './session' import type { AsyncStorage } from './storage' import { defaultStorage, getData, updateStorage } from './storage' export async function login( idp: string, options: loginOptions ): Promise<?null> { try { const rp = await getRegisteredRp(idp, options) await saveAppHashFragment(options.storage) return sendAuthRequest(rp, options) } catch (err) { console.warn('Error logging in with WebID-OIDC') console.error(err) return null } } export async function currentSession( storage: AsyncStorage = defaultStorage() ): Promise<?webIdOidcSession> { try { const rp = await getStoredRp(storage) if (!rp) { return null } const url = currentUrl() if (!/#(.*&)?access_token=/.test(url)) { return null } const storeData = await getData(storage) const session = await rp.validateResponse(url, storeData) if (!session) { return null } await restoreAppHashFragment(storage) return { ...session, webId: session.idClaims.sub, idp: session.issuer } } catch (err) { console.warn('Error finding a WebID-OIDC session') console.error(err) return null } } export async function logout(storage: AsyncStorage): Promise<void> { const rp = await getStoredRp(storage) if (rp) { try { rp.logout() } catch (err) { console.warn('Error logging out of the WebID-OIDC session') console.error(err) } } } export async function getRegisteredRp( idp: string, options: loginOptions ): Promise<RelyingParty> { // To reuse a possible previous RP, // it be for the same IDP and redirect URI let rp = await getStoredRp(options.storage) if ( !rp || rp.provider.url !== idp || !rp.registration.redirect_uris.includes(options.callbackUri) ) { // Register a new RP rp = await registerRp(idp, options) await storeRp(options.storage, idp, rp) } return rp } async function getStoredRp(storage: AsyncStorage): Promise<?RelyingParty> { const data = await getData(storage) const { rpConfig } = data if (rpConfig) { rpConfig.store = storage return RelyingParty.from(rpConfig) } else { return null } } async function storeRp( storage: AsyncStorage, idp: string, rp: RelyingParty ): Promise<RelyingParty> { await updateStorage(storage, data => ({ ...data, rpConfig: rp })) return rp } function registerRp( idp: string, { storage, callbackUri }: loginOptions ): Promise<RelyingParty> { const responseType = 'id_token token' const registration = { issuer: idp, grant_types: ['implicit'], redirect_uris: [callbackUri], response_types: [responseType], scope: 'openid profile' } const options = { defaults: { authenticate: { redirect_uri: callbackUri, response_type: responseType } }, store: storage } return RelyingParty.register(idp, registration, options) } async function sendAuthRequest( rp: RelyingParty, { callbackUri, storage }: loginOptions ): Promise<void> { const data = await getData(storage) const url = await rp.createRequest({ redirect_uri: callbackUri }, data) await updateStorage(storage, () => data) return navigateTo(url) } async function saveAppHashFragment(store: AsyncStorage): Promise<void> { await updateStorage(store, data => ({ ...data, appHashFragment: window.location.hash })) } async function restoreAppHashFragment(store: AsyncStorage): Promise<void> { await updateStorage(store, data => { window.location.hash = data.appHashFragment delete data.appHashFragment return data }) } /** * Answers whether a HTTP response requires WebID-OIDC authentication. */ export function requiresAuth(resp: Response): boolean { if (resp.status !== 401) { return false } const wwwAuthHeader = resp.headers.get('www-authenticate') if (!wwwAuthHeader) { return false } const auth = authorization.parse(wwwAuthHeader) return ( auth.scheme === 'Bearer' && auth.params && auth.params.scope === 'openid webid' ) } /** * Fetches a resource, providing the WebID-OIDC ID Token as authentication. * Assumes that the resource has requested those tokens in a previous response. */ export async function fetchWithCredentials( session: webIdOidcSession, fetch: Function, input: RequestInfo, options?: RequestOptions ): Promise<Response> { const popToken = await PoPToken.issueFor(toUrlString(input), session) const authenticatedOptions = { ...options, credentials: 'include', headers: { ...(options && options.headers ? options.headers : {}), authorization: `Bearer ${popToken}` } } return fetch(input, authenticatedOptions) }
JavaScript
0.003176
@@ -33,16 +33,23 @@ Response +, fetch */%0Aimpo @@ -1670,19 +1670,273 @@ -rp.logout() +// First log out from the IDP%0A await rp.logout()%0A // Then, log out from the RP%0A try %7B%0A await fetch('/.well-known/solid/logout', %7B credentials: 'include' %7D)%0A %7D catch (e) %7B%0A // Ignore errors for when we are not on a Solid pod%0A %7D %0A
ee19311e25db20258aba68ff6e5fd2eb1277ae44
Add periodic table array constant
constants.js
constants.js
var BLOCK_FONT = "10px Verdana"; var DROP_DELAY = 600; var FAST_DROP = 100; var INPUT_DELAY = 200; var GRID_HEIGHT = 20; var GRID_WIDTH = 10; var BLOCK_WIDTH, BLOCK_HEIGHT; var BLOCK_SPACING_WIDTH, BLOCK_SPACING_HEIGHT; var TETRINIMO_TEMPLATES = { jBlock: ['xx', 'x ', 'x '], lBlock: ['xx', ' x', ' x'], square: ['xx', 'xx'], sBlock: ['x ', 'xx', ' x'], zBlock: [' x', 'xx', 'x '], line: ['x', 'x', 'x', 'x'], tBlock: ['xxx', ' x '] }; var processTetrinimos = function() { var tetraShape = new Object; for(var shape in TETRINIMO_TEMPLATES) { if( TETRINIMO_TEMPLATES.hasOwnProperty(shape)) { tetraShape[shape] = new Array; var currentShape = TETRINIMO_TEMPLATES[shape]; for(var row in currentShape) { for(var col in currentShape[row]) { if(currentShape[row][col] == 'x') { tetraShape[shape].push({x: parseInt(col, 10), y: parseInt(row, 10)}); } } } } } return tetraShape } var TETRINIMO_SHAPES = processTetrinimos(); var KEY_CODES = { 37: 'left', 38: 'up', 39: 'right', 40: 'down', 8: 'backspace' }
JavaScript
0.006812
@@ -1288,8 +1288,732 @@ pace'%0A%7D%0A +%0Avar PERIODIC_TABLE = %5B%0A %5B1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2%5D,%0A %5B3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 6, 7, 8, 9, 10%5D,%0A %5B11, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 14, 15, 16, 17, 18%5D,%0A %5B19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36%5D,%0A %5B37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54%5D,%0A %5B55, 56, 0, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86%5D,%0A %5B87, 88, 0, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118%5D,%0A %5B0, 0, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 0%5D,%0A %5B0, 0, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 0%5D%0A%5D;%0A
11e8bd1627b6b7668399b01943ace92abffa4380
Delete typo
src/wef.logger.js
src/wef.logger.js
/*! * Wef logger * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ /** * The wef plugins module. */ (function () { var textFormatter = function() { return this; }; textFormatter.prototype.format = function (messages, level, type) { var tmp = [], levelMarks = " ", levelText, typeText; tmp = Array.prototype.slice.call(messages, tmp); if (level) { levelText = levelMarks.slice(0, level); tmp.unshift(levelText); } if (type) { typeText = "[" + type + "]"; tmp.unshift(levelText); } return tmp; }; var logger = function() { return new logger.prototype.init(); }, active = true, level = 0; logger.prototype.constructor = logger; logger.prototype.level = 0; logger.prototype.version = "0.0.1"; logger.prototype.formatter = new textFormatter(); logger.prototype.init = function () { return this; }; logger.off = logger.prototype.off = function () { active = false; return this; }; logger.on = logger.prototype.on = function () { active = true; return this; }; logger.prototype.backend = window.console || {}; logger.prototype.backend.failSafe = function () { //silent }; logger.prototype.backend.failSafeGroup = function () { level++; }; logger.prototype.backend.failSafeGroupEnd = function () { level--; }; logger.prototype.backend.trace = window.console.trace || logger.prototype.backend.log; logger.prototype.backend.log = window.console.log || logger.prototype.backend.failSafe; logger.prototype.backend.debug = window.console.debug || logger.prototype.backend.log; logger.prototype.backend.info = window.console.info || logger.prototype.backend.log; logger.prototype.backend.error = window.console.error || logger.prototype.backend.log; logger.prototype.backend.warn = window.console.warn || logger.prototype.backend.log; logger.prototype.backend.group = window.console.group || logger.prototype.backend.failSafeGroup; logger.prototype.backend.groupCollapsed = window.console.groupCollapsed || window.console.group || logger.prototype.backend.failSafeGroup; logger.prototype.backend.groupEnd = window.console.groupEnd || logger.prototype.backend.failSafeGroupEnd; logger.prototype.init.prototype = logger.prototype; logger.prototype.init.prototype.debug = function (message) { if (!active) return this; this.backend.debug.apply(this.backend, this.formatter.format(arguments, level)); return this; }; logger.prototype.init.prototype.error = function (message) { if (!active) return this; this.backend.error.apply(this.backend, this.formatter.format(arguments, level)); return this; }; logger.prototype.init.prototype.info = function (message) { if (!active) return this; this.backend.info.apply(this.backend, this.formatter.format(arguments, level)); return this; }; logger.prototype.init.prototype.warn = function (message) { if (!active) return this; this.backend.warn.apply(this.backend, this.formatter.format(arguments, level)); return this; }; logger.prototype.init.prototype.log = function (message) { if (!active) return this; this.backend.log.apply(this.backend, this.formatter.format(arguments, level)); return this; }; logger.prototype.init.prototype.trace = function () { if (!active) return this; this.backend.trace.call(this.backend); return this; }; logger.prototype.init.prototype.group = function (message) { if (!active) return this; if (message) { this.log.apply(this, arguments); } this.backend.groupCollapsed.call(this.backend); return this; }; logger.prototype.init.prototype.groupEnd = function (message) { if (!active) return this; if (message) { this.log.apply(this, arguments); } this.backend.groupEnd.call(this.backend); return this; }; wef.fn.logger = logger; })();
JavaScript
0.000099
@@ -71,44 +71,8 @@ %0A */ -%0A%0A/**%0A * The wef plugins module.%0A */ %0A(fu
c3424de982fc23f973b080724845bd2bf4d7576d
Update client example.
example/client.js
example/client.js
/* * client sample */ // import Client class. var Client = require('hello-work').Client; // create client instance. var client = new Client(); // connect to server, with port and host parameter. clinet.connect(/* { host: 'localhost', port: 20000, }, */function (err) { // on('connect', function (err) { ... }) // error handling if (err) { // todo ... return; } // general sample. var add_task = client.do({ // return task. // ns: '/', // if namespace do not specific, default namespace '/' func: 'add', // function name. args: { // funciton arguments. a: 1, b: 2, }, }); // complete event. add_task.on('complete', function (res) { console.log('add complete : ' + res); }); // timeout sample. var sub_task = lient.do({ ns: '/ns1/', // namespace. func: 'sub', args: { a: 2, b: 2, }, timeout: 5000, }); // timeout event. sub_task.on('timeout', function (code) { // TODO: code : 1 -> network? 2 -> task do not finsh? console.log('sub timeout : ', code); }); // complete event. sub_task.on('complete', function (res) { console.log('sub complete : ' + res); }); // error sample. var mul_task = client.do({ func: 'mul', args: { a: 2, //b: 1, } }); // fail event. mul_task.on('fail', function (err) { console.log('mul fail : ' + err); }); // complete event. mul_task.on('complete', function (res) { console.log('mul complete : ' + res); }); // binary parameter sample. var image_buf = new Buffer(256 * 256); // image data. var image_proc_task = client.do({ func: 'process_image', args: { image: image_buf, } }); // complete event. image_proc_task.on('complete', function (res) { console.log('process_image : ' + res); }); }); // end of client.connect process.on('exit', function (code, signal) { // disconnect from server. client.disconnect(function (err) { // on('disconnect', function () { ... }); // error handling if (err) { // ... } console.log('disconnect'); }); });
JavaScript
0
@@ -403,23 +403,8 @@ e.%0A - var add_task = cli @@ -599,28 +599,45 @@ ,%0A %7D,%0A %7D -);%0A%0A +, function (job) %7B%0A // complet @@ -651,16 +651,13 @@ .%0A -add_task + job .on( @@ -677,32 +677,34 @@ unction (res) %7B%0A + console.log( @@ -721,32 +721,40 @@ ete : ' + res);%0A + %7D);%0A %7D);%0A%0A%0A // tim @@ -772,23 +772,9 @@ .%0A -var sub_task = +c lien @@ -889,28 +889,45 @@ t: 5000,%0A %7D -);%0A%0A +, function (job) %7B%0A // timeout @@ -932,32 +932,29 @@ ut event.%0A -sub_task + job .on('timeout @@ -1028,24 +1028,26 @@ finsh?%0A + console.log( @@ -1069,29 +1069,32 @@ ', code);%0A + + %7D);%0A -%0A + // complet @@ -1108,16 +1108,13 @@ .%0A -sub_task + job .on( @@ -1134,32 +1134,34 @@ unction (res) %7B%0A + console.log( @@ -1178,32 +1178,40 @@ ete : ' + res);%0A + %7D);%0A %7D);%0A%0A%0A // err @@ -1226,23 +1226,8 @@ e.%0A - var mul_task = cli @@ -1295,28 +1295,45 @@ 1,%0A %7D%0A %7D -);%0A%0A +, function (job) %7B%0A // fail ev @@ -1335,32 +1335,29 @@ il event.%0A -mul_task + job .on('fail', @@ -1369,24 +1369,26 @@ ion (err) %7B%0A + console. @@ -1413,23 +1413,26 @@ + err);%0A + %7D);%0A -%0A + // com @@ -1450,16 +1450,13 @@ .%0A -mul_task + job .on( @@ -1476,32 +1476,34 @@ unction (res) %7B%0A + console.log( @@ -1524,24 +1524,32 @@ : ' + res);%0A + %7D);%0A %7D);%0A%0A%0A // @@ -1635,30 +1635,8 @@ a.%0A - var image_proc_task = cli @@ -1716,20 +1716,37 @@ %7D%0A %7D -);%0A%0A +, function (job) %7B%0A // com @@ -1764,23 +1764,13 @@ .%0A -image_proc_task + job .on( @@ -1794,24 +1794,26 @@ ion (res) %7B%0A + console. @@ -1843,16 +1843,24 @@ + res);%0A + %7D);%0A %7D);%0A%0A%7D @@ -2089,19 +2089,38 @@ // -... +todo ...%0A return; %0A %7D%0A
01adbf595447260c37a45d0360a21277dfaa2750
Use card for image view
src/components/common/GifAddModal.js
src/components/common/GifAddModal.js
import React, { PropTypes } from 'react'; import * as _ from 'lodash'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import TextField from 'material-ui/TextField'; class GifAddModal extends React.Component { constructor(props) { super(props); this.handleNameChange = this.handleNameChange.bind(this); this.handleUrlChange = this.handleUrlChange.bind(this); this.handleAdd = this.handleAdd.bind(this); this.state = { name: '', url: props.url }; } componentWillReceiveProps(nextProps) { this.setState({ name: nextProps.name || '', url: nextProps.url || '', stillUrl: nextProps.stillUrl }); } handleNameChange(e) { this.setState({ name: e.target.value }); } handleUrlChange(e) { this.setState({ url: e.target.value }); } handleAdd() { if (!_.isEmpty(this.state.url) && !_.isEmpty(this.state.name)) { this.props.onSuccess( this.state.name, this.state.url, this.state.stillUrl ); } else { toastr.warning('Please provide a name and URL'); } } render() { const actions = [ <FlatButton label="Cancel" primary={true} onTouchTap={this.props.onCancel} style={{margin: 10}} />, <RaisedButton label="Add" primary={true} onTouchTap={this.handleAdd} style={{margin: 10}} /> ]; return ( <Dialog id="GifAddModal" title="Add Gif" actions={actions} modal={true} open={this.props.open} repositionOnUpdate={false} style={{ paddingTop: "15px" }} > <TextField hintText="Test Name" floatingLabelText="Name" fullWidth={true} autoComplete="off" onChange={this.handleNameChange} value={this.state.name} style={{marginBottom: 5}} /> <TextField hintText="http://media2.giphy.com/media/geozuBY5Y6cXm/giphy.gif" floatingLabelText="Url" fullWidth={true} autoComplete="off" onChange={this.handleUrlChange} value={this.state.url} style={{marginBottom: 5}} /> <img src={this.state.url} className="img-thumbnail center-block" role="presentation" /> </Dialog> ); } }; GifAddModal.propTypes = { open: PropTypes.bool.isRequired, name: PropTypes.string, url: PropTypes.string, stillUrl: PropTypes.string, onSuccess: PropTypes.func.isRequired, onCancel: PropTypes.func.isRequired, }; export default GifAddModal;
JavaScript
0
@@ -257,16 +257,66 @@ tField'; +%0Aimport %7BCard, CardMedia%7D from 'material-ui/Card'; %0A%0Aclass @@ -2903,93 +2903,174 @@ %3C -img src=%7Bthis.state.url%7D className=%22img-thumbnail center-block%22 role=%22presentation%22 / +Card%3E%0A %3CCardMedia%3E%0A %3Cimg src=%7Bthis.state.url%7D role=%22presentation%22 /%3E%0A %3C/CardMedia%3E%0A %3C/Card %3E%0A
a3fcd613c4ca424068d94488b5287eb3cde91212
mejora ajax modal
webroot/js/ajax_modal.js
webroot/js/ajax_modal.js
function mostrarModal( event ){ event.preventDefault(); console.info(event); console.info(event.target.href); $( "#ajaxModal .modal-body" ).load( event.target.href ); $( "#ajaxModal").modal("show"); return false; } $(function(){ $(document).on('click', '.ajax-modal', mostrarModal); $('#ajaxModal').on('hidden.bs.modal', function (e) { $( "#ajaxModal .modal-body" ).html(""); }); $('#loaderbar').hide(); var timeout; $( document ).ajaxComplete(function() { clearTimeout(timeout); $('#loaderbar').hide(); $('#loaderbar .progress-bar').css({'width': '100%'}); }); $( document ).ajaxStart(function() { $('#loaderbar').show(); var load = 0; timeout = setTimeout(function(){ console.info("incrementado loader %o", load); load = load + 10; $('#loaderbar .progress-bar').css({'width': load+'%'}); if ( load = 100 ) { load = 0; } }, 100); }); });
JavaScript
0.000001
@@ -61,70 +61,8 @@ ();%0A - %09%09%09console.info(event);%0A %09%09%09console.info(event.target.href);%0A %09%09%09 @@ -104,17 +104,24 @@ event. -t +currentT arget.hr @@ -734,59 +734,8 @@ ()%7B%0A -%09%09%09%09%09console.info(%22incrementado loader %25o%22, load);%0A %09%09%09%09
40d9941c8ee273bb331e9d093261e9bb08491b79
Implement getServerSnapshot
src/hook.js
src/hook.js
import { assoc, F, forEach, forEachObjIndexed, keys, identity, map, mergeRight, pathOr, reduce, } from 'ramda' import { combineTemplate, noMore } from 'baconjs' import { useContext, useCallback, useMemo, useEffect, useSyncExternalStore } from 'react' import Common from './utils/common-util' import BduxContext from './context' import { hooks } from './middleware' const getDispatch = pathOr( F, ['dispatcher', 'dispatchAction'] ) const getBindToDispatch = pathOr( identity, ['dispatcher', 'bindToDispatch'] ) const skipPropertiesDefault = map( property => property.skipDuplicates() ) const shallowEqual = (a, b) => { const keysA = keys(a) const keysB = keys(b) if (keysA.length !== keysB.length) { return false } for (let i = 0; i < keysA.length; i++) { const key = keysA[i] const valueA = a[key] const valueB = b[key] if (valueA !== valueB) { return false } } return true } const getPropertiesMemo = () => { let cached let prevBdux let prevProps let prevStores return (bdux, props, stores) => { if (!cached || prevBdux !== bdux || !shallowEqual(prevProps, props) || !shallowEqual(prevStores, stores)) { // cache the store properties. cached = map( store => store.getProperty({ ...props, bdux }), stores ) prevBdux = bdux prevProps = props prevStores = stores } return cached } } const removeProperties = props => map( store => store.removeProperty(props) ) const getSnapshotsMemo = (storeProperties) => { let cached = {} return () => { let initial = {} // forEach instead of combineTemplate to be synchronous. forEachObjIndexed( (property, name) => { property // todo: workaround baconjs v2 bug causing onValue to be not synchronous. .doAction(val => initial[name] = val) .onValue(() => noMore) }, storeProperties ) if (!shallowEqual(cached, initial)) { // cache the store snapshots. cached = initial } return cached } } const useCustomHooks = (props, params) => ( reduce( (acc, useHook) => { // run synchronously at the beginning of use fuction. // eslint-disable-next-line react-hooks/rules-of-hooks const ret = useHook(props, params) return ret ? mergeRight(acc, ret) : acc }, {}, hooks.get() ) ) export const useBdux = ( props, stores = {}, callbacks = [], skipProperties = skipPropertiesDefault, ) => { const bdux = useContext(BduxContext) const dispatch = getDispatch(bdux) const bindToDispatch = getBindToDispatch(bdux) const getProperties = useMemo(() => getPropertiesMemo(), []) const storeProperties = getProperties(bdux, props, stores) const getSnapshots = useMemo(() => getSnapshotsMemo(storeProperties), [storeProperties]) const state = useSyncExternalStore( useCallback((callback) => ( Common.isOnServer() // assuming only render once on server. ? undefined // subscribe to stores in browser. : combineTemplate(skipProperties(storeProperties)) .changes() .onValue(callback) ), [skipProperties, storeProperties]), // combine store snapshots. getSnapshots ) const unmount = () => { removeProperties({ ...props, bdux })(stores) } useEffect( () => { // trigger callback actions. const data = assoc('props', props, state) forEach(callback => dispatch(callback(data)), callbacks) // unsubscribe. return unmount }, // only on mount and unmount. // eslint-disable-next-line react-hooks/exhaustive-deps [] ) // assuming only render once on server. if (Common.isOnServer()) { // unmount afterward straight away. unmount() } const params = { dispatch, bindToDispatch, state, } return { ...useCustomHooks(props, params), ...params, } } export const createUseBdux = ( stores = {}, callbacks = [], skipDuplicates = skipPropertiesDefault, ) => props => ( useBdux(props, stores, callbacks, skipDuplicates) )
JavaScript
0.000001
@@ -3261,24 +3261,42 @@ snapshots.%0A + getSnapshots,%0A getSnaps
86fe7b492871773c83e718ff1486e7dc10ac1f75
add domain alias
modules/tld.js
modules/tld.js
var request = require( 'request' ); module.exports = { commands: { tld: { usage: [ 'tld' ], help: 'Checks whether a string is a top level domain', command: function ( bot, msg ) { request.get( 'https://data.iana.org/TLD/tlds-alpha-by-domain.txt', function ( e, r, b ) { var data = b.split( '\n' ); if ( data.indexOf( msg.args.tld.toUpperCase() ) !== -1 ) { bot.say( msg.to, msg.nick + ': ' + msg.args.tld + ' is a TLD' ); } else { bot.say( msg.to, msg.nick + ': ' + msg.args.tld + ' is not in IANA\'s list of TLDs' ); } } ); } } } };
JavaScript
0.000001
@@ -91,16 +91,42 @@ tld' %5D,%0A +%09%09%09aliases: %5B 'domain' %5D,%0A %09%09%09help:
12c34ef9c9ec840d4c0847b12fbf82235b04a5f9
update set link
src/components/header/views/index.js
src/components/header/views/index.js
define(['lazoView'], function (LazoView) { 'use strict'; return LazoView.extend({ events: { 'click .navbar-nav a': 'navigate' }, afterRender: function () { var self = this; this.setActiveLink(); }, navigate: function (e) { var self = this; this.$('.navbar-nav li').removeClass('active'); this.setActiveLink($(e.currentTarget).closest('li')); LAZO.app.on('navigate:application:begin', function () { self.setActiveLink($(e.currentTarget).closest('li')); }); }, setActiveLink: function ($el) { if (window.location.pathname !== '/') { $el = $el || this.$('.navbar-nav a[href*="' + window.location.pathname + '"]').closest('li'); $el.addClass('active'); } } }); });
JavaScript
0
@@ -339,68 +339,8 @@ s;%0A%0A - this.$('.navbar-nav li').removeClass('active');%0A @@ -603,24 +603,84 @@ ion ($el) %7B%0A + this.$('.navbar-nav li').removeClass('active');%0A
02a4439589d53e95457b24dd712941fda9d724f5
Remove junk
website/static/js/app.js
website/static/js/app.js
/** * app.js * Knockout models, ViewModels, and custom binders. */ //////////// // Models // //////////// /** * The project model. */ var Project = function(params) { var self = this; self._id = params._id; self.apiUrl = params.apiUrl; self.watchedCount = ko.observable(params.watchCount); self.userIsWatching = ko.observable(params.userIsWatching); // The button to display (e.g. "Watch" if not watching) self.watchButtonDisplay = ko.computed(function() { var text = self.userIsWatching() ? "Unwatch" : "Watch" var full = text + " " +self.watchedCount().toString(); return full; }); } var Log = function(params) { var self = this; self.action = params.action; self.date = params.date; self.nodeCategory = params.nodeCategory; self.nodeTitle = params.nodeTitle; self.contributor = params.contributor; self.contributors = params.contributors; self.nodeUrl = params.nodeUrl; self.userFullName = params.userFullName; self.apiKey = params.apiKey; self.params = params.params; // Extra log params self._actionTemplates = { project_created: "created " + self.nodeCategory + "<a href='" + self.nodeUrl + "'>" + self.nodeTitle + "</a>", node_created: "created " + self.nodeCategory + "<a href='" + self.nodeUrl + "'>" + self.nodeTitle + "</a>", wiki_updated: "updated wiki page <a href='" + self.nodeUrl + "wiki/" + self.params.page + "/'>" + self.params.page + "</a>", contributor_added: "" }; self.displayHTML = ko.computed(function() { var agent = self.userFullName ? self.userFullName : self.apiKey; var action = self._actionTemplates[self.action] || ""; return agent + " " + action; }); self.wikiUrl = ko.computed(function() { return self.nodeUrl + "wiki/" + self.params.page; }) } //////////////// // ViewModels // //////////////// var LogsViewModel = function(url) { var self = this; self.logs = ko.observableArray([]); // Get log data via AJAX var getUrl = ''; if (url) { getUrl = url; } else { getUrl = nodeToUseUrl() + "log/"; }; $.ajax({ url: getUrl, type: "get", dataType: "json", success: function(data){ var logs = data['logs']; var mappedLogs = $.map(logs, function(item) { return new Log({ "action": item.action, "date": item.date, "nodeCategory": item.category, "contributor": item.contributor, "contributors": item.contributors, "nodeUrl": item.node_url, "userFullName": item.user_fullname, "apiKey": item.api_key, "params": item.params, "nodeTitle": item.node_title }) }) self.logs(mappedLogs); } }) } /** * The project VM, scoped to the project page header. */ var ProjectViewModel = function() { var self = this; self.projects = ko.observableArray([{"watchButtonDisplay": ""}]); $.ajax({ url: nodeToUseUrl(), type: "get", contentType: "application/json", dataType: "json", success: function(data){ project = new Project({ "_id": data.node_id, "apiUrl": data.node_api_url, "watchCount": data.node_watched_count, "userIsWatching": data.user_is_watching, "logs": data.logs }); self.projects([project]); } }); /** * Toggle the watch status for this project. */ self.toggleWatch = function() { // Send POST request to node's watch API url and update the watch count $.ajax({ url: self.projects()[0].apiUrl + "togglewatch/", type: "POST", dataType: "json", data: JSON.stringify({}), contentType: "application/json", success: function(data, status, xhr) { // Update watch count in DOM self.projects()[0].userIsWatching(data['watched']); self.projects()[0].watchedCount(data['watchCount']); } }); }; } /** * The add contributor VM, scoped to the add contributor modal dialog. */ var AddContributorViewModel = function(initial) { var self = this; self.query = ko.observable(''); self.results = ko.observableArray(initial); self.selection = ko.observableArray([]); self.search = function() { $.getJSON( '/api/v1/user/search/', {query: self.query()}, function(result) { self.results(result); } ) }; self.addTips = function(elements, data) { elements.forEach(function(element) { $(element).find('.contrib-button').tooltip(); }); }; self.add = function(data, element) { self.selection.push(data); // Hack: Hide and refresh tooltips $('.tooltip').hide(); $('.contrib-button').tooltip(); }; self.remove = function(data, element) { self.selection.splice( self.selection.indexOf(data), 1 ); // Hack: Hide and refresh tooltips $('.tooltip').hide(); $('.contrib-button').tooltip(); }; self.selected = function(data) { for (var idx=0; idx < self.selection().length; idx++) { if (data.id == self.selection()[idx].id) return true; } return false; }; self.submit = function() { var user_ids = self.selection().map(function(elm) { return elm.id; }); $.ajax( nodeToUseUrl() + 'addcontributors/', { type: 'post', data: JSON.stringify({user_ids: user_ids}), contentType: 'application/json', dataType: 'json', success: function(response) { if (response.status === 'success') { window.location.reload(); } } } ) }; self.clear = function() { self.query(''); self.results([]); self.selection([]); }; }; ////////////////// // Data binders // //////////////////
JavaScript
0.00005
@@ -1098,938 +1098,8 @@ ams%0A - self._actionTemplates = %7B%0A project_created: %22created %22 + self.nodeCategory +%0A %22%3Ca href='%22 + self.nodeUrl + %22'%3E%22 +%0A self.nodeTitle +%0A %22%3C/a%3E%22,%0A node_created: %22created %22 + self.nodeCategory +%0A %22%3Ca href='%22 + self.nodeUrl + %22'%3E%22 +%0A self.nodeTitle +%0A %22%3C/a%3E%22,%0A wiki_updated: %22updated wiki page %3Ca href='%22 +%0A self.nodeUrl + %22wiki/%22 + self.params.page + %22/'%3E%22 +%0A self.params.page + %22%3C/a%3E%22,%0A contributor_added: %22%22%0A %7D;%0A%0A self.displayHTML = ko.computed(function() %7B%0A var agent = self.userFullName ? self.userFullName : self.apiKey;%0A var action = self._actionTemplates%5Bself.action%5D %7C%7C %22%22;%0A return agent + %22 %22 + action;%0A %7D);%0A%0A
5098510f96bbaf30074cf77efdee007c743c3e93
Update PushwooshAndroid.js
www/js/PushwooshAndroid.js
www/js/PushwooshAndroid.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ function registerPushwooshAndroid() { var pushNotification = window.plugins.pushNotification; //set push notifications handler document.addEventListener('push-notification', function(event) { var title = event.notification.title; var userData = event.notification.userdata; //dump custom data to the console if it exists if(typeof(userData) != "undefined") { console.warn('user data: ' + JSON.stringify(userData)); } //and show alert alert(title); //stopping geopushes //pushNotification.stopGeoPushes(); } ); //initialize Pushwoosh with projectid: "GOOGLE_PROJECT_ID", appid : "PUSHWOOSH_APP_ID". This will trigger all pending push notifications on start. pushNotification.onDeviceReady({ projectid: "344948053044 ", appid : "9A31C-C571D" }); //register for push notifications pushNotification.registerDevice( function(token) { alert(token); //callback when pushwoosh is ready onPushwooshAndroidInitialized(token); }, function(status) { alert("failed to register: " + status); console.warn(JSON.stringify(['failed to register ', status])); } ); } function onPushwooshAndroidInitialized(pushToken) { //output the token to the console console.warn('push token: ' + pushToken); var pushNotification = window.plugins.pushNotification; //if you need push token at a later time you can always get it from Pushwoosh plugin pushNotification.getPushToken( function(token) { console.warn('push token: ' + token); } ); //and HWID if you want to communicate with Pushwoosh API pushNotification.getPushwooshHWID( function(token) { console.warn('Pushwoosh HWID: ' + token); } ); pushNotification.getTags( function(tags) { console.warn('tags for the device: ' + JSON.stringify(tags)); }, function(error) { console.warn('get tags error: ' + JSON.stringify(error)); } ); //set multi notificaiton mode //pushNotification.setMultiNotificationMode(); //pushNotification.setEnableLED(true); //set single notification mode //pushNotification.setSingleNotificationMode(); //disable sound and vibration //pushNotification.setSoundType(1); //pushNotification.setVibrateType(1); pushNotification.setLightScreenOnNotification(false); //goal with count //pushNotification.sendGoalAchieved({goal:'purchase', count:3}); //goal with no count //pushNotification.sendGoalAchieved({goal:'registration'}); //setting list tags //pushNotification.setTags({"MyTag":["hello", "world"]}); //settings tags pushNotification.setTags({deviceName:"hello", deviceId:10}, function(status) { console.warn('setTags success'); }, function(status) { console.warn('setTags failed'); } ); //Pushwoosh Android specific method that cares for the battery //pushNotification.startGeoPushes(); }
JavaScript
0.000001
@@ -1600,17 +1600,16 @@ 48053044 - %22, appid
cd458965b088c32f540fd89a64f9e810cdd052fa
remove obsolete call to clearUndo
webui/task-management.js
webui/task-management.js
var task_desc; // A string describing the current task sessions.custom = {tasks: []}; var tasks_saved = {}; var tasks_solved = {}; var custom_rules = {}; var funnyUnicodeCharacters="☃⚛⚾♛♬☏⚒☸☀☮☘☭"; function saveTask() { if (task_desc) { tasks_saved[task_desc] = _.omit(graph.toJSON(), 'loading'); tasks_solved[task_desc] = graph.get('qed'); saveSession(); } } function saveSession() { localStorage["incredible-session"] = JSON.stringify({ saved: tasks_saved, solved: tasks_solved, custom: sessions.custom, rules: custom_rules }); } function loadSession() { if (localStorage["incredible-session"]) { var stored = JSON.parse(localStorage["incredible-session"]); tasks_saved = stored.saved || {}; tasks_solved = stored.solved || {}; sessions.custom = stored.custom || {tasks: []}; custom_rules = stored.rules || {}; } } function taskToDesc(logic, task) { return JSON.stringify([logic, task.assumptions, task.conclusions]); } function selectSessionTask(evt) { saveTask(); var session = sessions[$(evt.currentTarget).data('session')]; var thisTask = session.tasks[$(evt.currentTarget).data('task')]; task_desc = $(evt.currentTarget).data('desc'); selectLogic(session.logic, session["visible-rules"]); setupPrototypeElements(); loadTask(thisTask); if (tasks_saved[task_desc]) { graph.fromJSON(tasks_saved[task_desc]); } clearUndo(); // Start the animation at the end $("#taskdialog").hide("slide", {direction:"down"}, 800, function () { $("#taskbottombar").show("slide", {direction:"down"}, 100); }); } function taskToHTML(task) { d1 = $("<ul class='assumptions'>"); $.each(task.assumptions || [], function (i, el) { d1.append($("<li>").text(incredibleFormatTerm(el))); }); d2 = $("<ul class='conclusions'>"); $.each(task.conclusions || [], function (i, el) { d2.append($("<li>").text(incredibleFormatTerm(el))); }); return $("<div class='inferencerule'>").append(d1, $("<hr/>"), d2); } $(function () { $("#taskbottombar").on('click', function () { $("#taskbottombar").stop(); saveTask(); // to update session_saved showTaskSelection(); }); }); function setupTaskSelection() { $.each(sessions, function (i,session) { $("<h3>").text(i18n.t(session.name)).appendTo("#sessiontasks"); var container = $("<div>").addClass("tasklist").appendTo("#sessiontasks"); $.each(session.tasks, function (j,thisTask) { taskToHTML(thisTask) .addClass("sessiontask") .data({session: i, task: j, desc: taskToDesc(session.logic||'predicate', thisTask)}) .on('click', with_graph_loading(selectSessionTask)) .appendTo(container); }); }); $.each(sessions.custom.tasks, function (j,thisTask) { taskToHTML(thisTask) .addClass("sessiontask") .data({session: 'custom', task: j, desc: taskToDesc(sessions.custom.logic||'predicate', thisTask)}) .on('click', with_graph_loading(selectSessionTask)) .insertBefore("#customtask"); }); $("#customtask #addcustomtask").on('click', function (){ var thisTask = taskFromText($("#customtask textarea").val()); if (thisTask) { var j = sessions.custom.tasks.length; sessions.custom.tasks.push(thisTask); taskToHTML(thisTask) .addClass("sessiontask") .data({session: 'custom', task: j, desc: taskToDesc(sessions.custom.logic||'predicate', thisTask)}) .on('click', with_graph_loading(selectSessionTask)) .insertBefore("#customtask"); updateTaskSelectionInfo(); // A bit overhead re-doing all of them, but that’s ok, I hope saveSession(); } else { alert(i18n.t('task-parse-error')); } }); $("#addcustomblock").on('click', function (){ // Instead of reading the displayed rule, we simply re-calculate it. It // should be the same, if not, then that is a bug.. var proof = buildProof(graph, derivedRuleBlockSelector); var rule = incredibleNewRule(current_logic(), proof); if ($.isEmptyObject(proof.blocks) || typeof rule === 'string' || rule instanceof String || rule === null || rule === undefined) { alert('Could not produce a usable rule'); } else { if (!custom_rules[logicName]) { custom_rules[logicName] = []; } var n = custom_rules[logicName].length + 1; rule.id = "custom" + n; if (n<= funnyUnicodeCharacters.length) { rule.desc = {label: funnyUnicodeCharacters.substr(n-1,1)}; } custom_rules[logicName].push(rule); setupPrototypeElements(); selectNothing(); } }); } function taskFromText(text) { var lines = text.match(/[^\r\n]+/g); var task = {assumptions: [], conclusions: []}; var now = 'assumptions'; var ok = true; $.each(lines, function (i, l) { if (l.match(/^[–─–_-]+$/)){ now = 'conclusions'; } else { var prop = incredibleFormatTerm(l); if (prop) { task[now].push(l); } else { ok = false; } } }); if (ok && now == 'conclusions') { return task; } else { return; } } function updateTaskSelectionInfo() { var lookupmap = {}; $(".sessiontask").each(function (i,t) { var desc = $(t).data('desc'); lookupmap[desc] = lookupmap[desc]||[]; lookupmap[desc].push(t); }); $.each(tasks_saved, function (desc, proof) { $.each(lookupmap[desc]||[], function (i,t) { $(t).addClass('attempted'); }); }); $.each(tasks_solved, function (desc, qed) { $.each(lookupmap[desc]||[], function (i,t) { $(t).toggleClass('solved', qed); }); }); } function showTaskSelection() { updateTaskSelectionInfo(); $("#taskbottombar").hide("slide", {direction: "down"}, 100, function () { $("#taskdialog").show("slide", {direction:"down"}, 800, function () { $("#taskdialog").focus(); }); }); } $(function (){ $(window).on('unload', function () { saveTask(); saveSession(); }); });
JavaScript
0.000001
@@ -1406,23 +1406,8 @@ %7D%0A%0A - clearUndo();%0A //
44c5013ebe47c3d1e40b19e8c0d2c72fe4325494
Create database reference and add static methods to model.
examples/level.js
examples/level.js
'use strict'; const levelco = require('level-co'); const memdown = require('memdown'); const model = require('../'); var attributes = { username: 'me', email: 'me@gmail.com', password: 'mepass' }; const properties = Object.keys(attributes); const User = model.createMolde('User', properties);
JavaScript
0
@@ -110,16 +110,124 @@ ('../'); +%0Aconst db = levelco.deferred(%0A 'db',%0A %7B%0A db: function (l) %7B%0A return new (memdown)(l);%0A %7D%0A %7D%0A); %0A%0Avar at @@ -381,11 +381,11 @@ teMo -l de +l ('Us @@ -402,9 +402,138 @@ rties);%0A +const access = %7B%0A get: function *() %7B yield null; %7D,%0A put: function *() %7B yield null; %7D,%0A del: function *() %7B yield null; %7D%0A%7D; %0A
6caba56f5e4f083cc2e884e79159c8c792507740
Update youtube.js
res/js/front/youtube.js
res/js/front/youtube.js
function startVideoProgress() { if (!videoPaused) { actionTimers.clear(); videoProgress(); } else { actionTimers.clear(); videoProgress(); actionTimers.pause(); } } var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // **BREAKTHROUGH THE GREATER!** var player; function onYouTubeIframeAPIReady() { player = new YT.Player('youtube', { events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange, 'onError': onError } }); console.log("Debug: Player loaded"); } function onPlayerStateChange(event) { switch(event.data) { //unstarted case -1: console.log("unstarted"); break; //ending case 0: console.log("ending"); sendStation("playerending"); loopVideo(); break; //playing case 1: console.log("playing"); videoFunctions.play(); startVideoProgress(); break; //paused case 2: console.log("paused"); videoFunctions.pause(); break; //buffering case 3: console.log("buffering"); //this is here because video errors cause a 'paused' event //the same occurs when scrolling quickly through a playlist //don't move the videoFunctions.play() stuff here because this is NOT triggered on un-pausing //the 'buffering' event is never triggered on paused/pausing videos so this does not conflict with other things videoPaused = false; break; //cued case 5: console.log("cued"); startVideoProgress(); break; } } function onPlayerReady(event) { console.log("Debug: onPlayerReady"); startVideoProgress(); getPlaylist(); makeSortable(); videoPreviews(); } function onError(event) { console.log(videoPaused); videoErrorIds.push(videos[videoIteration][2]); $("tr:nth-child(" + videoIteration + ")").addClass("videoError"); forwardVideo(); } //need to initialize per 6/2017 YT backend change $("#youtube").attr("src", "https://www.youtube.com/embed/?enablejsapi=1");
JavaScript
0
@@ -1,16 +1,593 @@ +/**%0A Copyright 2018 LNFWebsite%0A Licensed under the Apache License, Version 2.0 (the %22License%22);%0A you may not use this file except in compliance with the License.%0A You may obtain a copy of the License at%0A http://www.apache.org/licenses/LICENSE-2.0%0A Unless required by applicable law or agreed to in writing, software%0A distributed under the License is distributed on an %22AS IS%22 BASIS,%0A WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A See the License for the specific language governing permissions and%0A limitations under the License.%0A**/%0A%0A function startVi
55ef1b604466e68bf395ca2ca4ef943269348c5a
fix some scope issues in js command
commands/js.js
commands/js.js
var config = require("../config.js"); var post = require("../flowdock.js").post; var dbConnect = require("../utility.js").dbConnect; var when = require("../when.js"); var commands = require("../commands.js"); var sandbox = new (require("sandbox"))(); var shortcircuit = false; module.exports = { description: "js {name}({params}) [\\n {code}]: create/run custom js code\n\t\t\t\t\t(see: 'js help')", pattern: /^js\s+(?:(help|list|shortcircuit|delete\s+(\S+))|(?:(\S+)\s*\(([^\n\r]*)\)\s*(?:[\n\r]+([\s\S]+))?))$/i, priority: -10, reply: function(match, context, callback) { dbConnect(function(db) { db.run("CREATE TABLE IF NOT EXISTS js" + "(name TEXT, params TEXT, code TEXT, deleted INTEGER)", function(error) { if (error) { console.error("Error creating js table in database: " + JSON.stringify(error)); } else if (match[2]) { // delete function var name = match[2]; deleteFunction(name, function() { if (this.changes) post("Deleted js function '" + name + "'.", context, callback); else post("No js function '" + name + "', nothing deleted.", context, callback); }); } else if (match[1]) { if (match[1] == "list") { // list functions db.all("SELECT * FROM js WHERE deleted = 0", function(error, rows) { if (error) { console.error("Error retrieving js functions from db: " + JSON.stringify(error)); } else if (rows.length) { var result = ["List of all user-defined js functions:" + when.noTrigger]; rows.forEach(function(r) { result.push(r.name + "(" + r.params + ")"); }); post(result.join("\n\t"), context, callback); } else post("No js functions to display.", context, callback); }); } else if (match[1] == "shortcircuit") { shortcircuit = true; } else { // help post(["User-defined javascript functions!\n", "Define a function:", "\tjs {name}({param, param, ...}) \\n {code}", "Call a function:", "\tjs {name}({arg, arg, ...})", "Delete a function:", "\tjs delete {name}", "List all functions:", "\tjs list", "Stop a spammy function in it's tracks:", "\tjs shortcircuit", "Inside the {code} block of a function definition, access is provided to the following:", "\tfunction post(\"{message text}\") {\n\t\t/* post a message */\n\t}", "\tfunction command(\"{command text}\") {\n\t\t/* call a " + config.botName + " command */\n\t}", "\tvar context = {\n\t\t/* the flowdock context of the function call */\n\t};", ].join("\n"), context, callback); } } else if (match[5]) { // define function var name = match[3]; var params = match[4]; var code = match[5]; deleteFunction(name, function() { db.run("INSERT INTO js VALUES (?, ?, ?, 0)", name, params, code, function(error) { if (error) { console.error("Error updating js table: " + JSON.stringify(error)); } else post("Thanks for the new function.", context, callback); }); }); } else { // call function var name = match[3]; var args = match[4]; db.get("SELECT * FROM js WHERE deleted = 0 AND name = ?", name, function(error, row) { if (error) { console.error("Error reading js table: " + JSON.stringify(error)); } else if (row) { var commandFlag = "<EXECUTE_BOT_COMMAND>"; sandbox.run("var post = print, context = " + JSON.stringify(context) + ", command = function(s) { print(\"" + commandFlag + "\" + s); }; (function(" + row.params + "){" + row.code + "})(" + args + ")", function(output) { var l = output.console.length, i = 0;; if (l) { var jsOut = function() { if (i < l) { var value = output.console[i++]; if (shortcircuit) { shortcircuit = false; post("Shortcircuited js function '" + name + "'.", context); } else { if (String(value).indexOf(commandFlag) == 0) { commands.execute(value.slice(commandFlag.length).trim(), context, jsOut); } else post(value, context, jsOut); } } else if (callback) callback(); }; jsOut(); } else if (callback) callback(); }); } else post("There is no js function '" + name + "'.", context, callback); }); } }); }); } }; function deleteFunction(name, callback) { db.run("UPDATE js SET deleted = 1 WHERE deleted = 0 AND name = ?", name, function(error) { if (error) { console.error("Error deleting js function '" + name + "': " + JSON.stringify(error)); } else callback(); }); }
JavaScript
0.000001
@@ -718,24 +718,343 @@ on(error) %7B%0A +%09%09%09%09%0A%09%09%09%09function deleteFunction(name, callback) %7B%0A%09%09%09%09%09db.run(%22UPDATE js SET deleted = 1 WHERE deleted = 0 AND name = ?%22, name, function(error) %7B%0A%09%09%09%09%09%09if (error) %7B%0A%09%09%09%09%09%09%09console.error(%22Error deleting js function '%22 + name + %22': %22 + JSON.stringify(error));%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09else callback.call(this);%0A%09%09%09%09%09%7D);%0A%09%09%09%09%7D%0A%09%09%09%09%0A %09%09%09%09if (erro @@ -4076,17 +4076,16 @@ , i = 0; -; %0A%09%09%09%09%09%09%09 @@ -4872,273 +4872,4 @@ %0A%7D;%0A -%0Afunction deleteFunction(name, callback) %7B%0A%09db.run(%22UPDATE js SET deleted = 1 WHERE deleted = 0 AND name = ?%22, name, function(error) %7B%0A%09%09if (error) %7B%0A%09%09%09console.error(%22Error deleting js function '%22 + name + %22': %22 + JSON.stringify(error));%0A%09%09%7D%0A%09%09else callback();%0A%09%7D);%0A%7D%0A
d40ae617025d0ff95ee3c326a6f9c5c36faa298f
Remove Back link
src/components/player/VideoPlayer.js
src/components/player/VideoPlayer.js
import React from 'react'; import { findDOMNode } from 'react-dom'; import {Link} from 'react-router'; import ReactPlayer from 'react-player'; import Duration from './Duration' import screenfull from 'screenfull'; class VideoPlayer extends React.Component { constructor(props, context){ super(props, context); this.router = context.router; this.sourceURL = props.location.query.src; this.state = { url:this.sourceURL, playing: true, volume: 0.8, played: 0, playbackRate: 1.0, loaded: 0, duration: 0, width : 480, height: 270 } this.playPause = this.playPause.bind(this); this.onClickFullScreen = this.onClickFullScreen.bind(this); this.onSeekMouseDown = this.onSeekMouseDown.bind(this); this.onSeekChange = this.onSeekChange.bind(this); this.onSeekMouseUp = this.onSeekMouseUp.bind(this); this.onProgress = this.onProgress.bind(this); this.onBackOneSec = this.onBackOneSec.bind(this); this.onFwdOneSec = this.onFwdOneSec.bind(this); this.onClickBackToPlayList = this.onClickBackToPlayList.bind(this); } playPause(){ this.setState({playing: !this.state.playing}) } onBackOneSec(){ let played = this.state.played; let duration = this.state.duration; let backOneSec = ((played * duration) - 1) / duration this.setState({played : backOneSec ? backOneSec : played }) this.player.seekTo(backOneSec ? backOneSec : played) } onFwdOneSec(){ let played = this.state.played; let duration = this.state.duration; let fwdOneSec = ((played * duration) + 1) / duration this.setState({played : fwdOneSec ? fwdOneSec : played }) this.player.seekTo(fwdOneSec ? fwdOneSec : played) } onSeekMouseDown(e){ this.setState({seeking: true}) } onSeekChange(e){ this.setState({played: parseFloat(e.target.value) }) } onSeekMouseUp(e){ this.setState({seeking: false}) this.player.seekTo(parseFloat(e.target.value)) } onProgress(state){ if (!this.state.seeking){ this.setState(state) } } onClickFullScreen(){ screenfull.request(findDOMNode(this.player)) } onClickBackToPlayList(){ this.props.router.push('/') } render(){ const { url, playing, volume, played, loaded, duration, playbackRate, width, height } = this.state; return ( <div> <h3>Video Player</h3> <p><Link to="/" >Back</Link></p> <ReactPlayer ref = {player => {this.player = player}} className="react-player" width={width} height={height} url={url} playing={playing} playbackRate = {playbackRate} volume = {volume} onReady = {()=>console.log('onReady')} onStart = {()=>console.log('onStart')} onPlay = {() => this.setState({playing: true})} onPause = {()=> this.setState({playing: false})} onBuffer = {()=>console.log('onBuffer')} onEnded = {()=> this.setState({playing:false})} onError = {e => console.log('onError', e)} onProgress = {this.onProgress} onDuration={duration => this.setState({duration})} /> <table> <tbody> <tr> <th></th> <td> <button onClick={this.playPause}>{playing ? 'Pause' : 'Play'}</button> <button onClick={this.onBackOneSec} >-1sec</button> <button onClick={this.onFwdOneSec} >+1sec</button> <button onClick={this.onClickFullScreen}>Fullscreen</button> <button onClick={this.onClickBackToPlayList}>Back to Play List</button> </td> </tr> <tr> <th></th> <td> <input type='range' min={0} max={1} step='any' value={played} onMouseDown={this.onSeekMouseDown} onChange={this.onSeekChange} onMouseUp={this.onSeekMouseUp} /> <Duration seconds={duration * played} />/<Duration seconds={duration * (1 - played)} /> </td> </tr> </tbody> </table> </div> ) } } export default VideoPlayer;
JavaScript
0
@@ -2712,16 +2712,19 @@ +%7B/* %3Cp%3E%3CLink @@ -2747,16 +2747,19 @@ ink%3E%3C/p%3E +*/%7D %0A
90b6dae2776a69c3623b6e11cc61601bac60857d
Fix being not able to use contextmenu after reload
src/init.js
src/init.js
// Entry point of the application var parser = require('./parser'); var Renderer = require('./renderer'); var Interpreter = require('./interpreter'); var Predictor = require('./predictor'); var Monitor = require('./monitor'); var ToolBox = require('./toolbox'); var Viewport = require('./viewport'); var ContextMenu = require('./contextmenu'); var Playback = require('./playback'); var interpreter; var renderer; var predictor; var monitor; var toolbox; var viewport; var contextmenu; var playback; var initialized = false; function repredict(initial) { // Clear all paths and reset if (!initial && renderer) { for (var y = 0; y < interpreter.map.height; ++y) { for (var x = 0; x < interpreter.map.width; ++x) { var tile = interpreter.map.get(x, y); var cacheTile = renderer.cacheMap.get(x, y); if (tile) { tile.directions = {}; tile.segments = {}; cacheTile.directions = {}; } } } } var predictQuota = interpreter.map.width * interpreter.map.height * 2; predictor = new Predictor(interpreter.map); for (var i = 0; i < predictQuota; ++i) { if (!predictor.next()) break; } if (!initial && renderer) renderer.redraw(); } function reset(initial) { if (!initial) { interpreter.reset(); renderer.reset(); } document.getElementById('codeForm-output').value = ''; playback.running = false; } function initialize() { if(initialized) { toolbox.renderer = renderer; viewport.renderer = renderer; playback.renderer = renderer; playback.interpreter = interpreter; return; } playback = new Playback(interpreter, renderer, function() { document.getElementById('codeForm-output').value += interpreter.shift(); document.getElementById('codeForm-debug').value = monitor.getStatus(); }, reset.bind(this, false)); toolbox = new ToolBox(renderer); contextmenu = new ContextMenu(document.getElementById('context-bg'), document.getElementById('context-push'), renderer); viewport = new Viewport(document.getElementById('viewport'), toolbox, renderer, contextmenu); viewport.checkCallback = function() { return !playback.running; }; viewport.clickCallback = repredict.bind(this, false); initialized = true; } window.onload = function() { document.getElementById('codeForm').onsubmit = function() { var code = document.getElementById('codeForm-code').value; interpreter = new Interpreter(code); monitor = new Monitor(interpreter); repredict(true); renderer = new Renderer(document.getElementById('canvas'), interpreter); initialize(); window.interpreter = interpreter; window.predictor = predictor; reset(true); // TODO implement input return false; }; document.getElementById('codeForm-export').onclick = function() { document.getElementById('codeForm-code').value = parser.encode( interpreter.map); }; /* document.getElementById('captureBtn').onclick = function() { renderer.canvases.dump(document.getElementById('capture')); }; */ };
JavaScript
0
@@ -1504,32 +1504,69 @@ rer = renderer;%0A + contextmenu.renderer = renderer;%0A playback.ren
03f9075fe5b526a59c874c8cd76f4f9dea8429f3
Fix scroll being at an awkward position when switching back from print-friendly
static/js/main.js
static/js/main.js
const renderer = new marked.Renderer(); const katexOpts = { throwOnError: false, errorColor: '#F44336', }; renderer.code = function(code) { try { const r = katex.renderToString(code, { displayMode: true, ...katexOpts, }); return `<blockquote class="katex-block">${r}</blockquote>`; } catch (e) { return `<blockquote class="katex-block">${e.message}</blockquote>`; } }; renderer.codespan = function(code) { try { return katex.renderToString(code, katexOpts); } catch (e) { return e.message; } }; const wrapper = document.getElementById('page-wrapper'); const preview = document.getElementById('preview'); const editor = ace.edit('editor'); editor.getSession().setUseSoftTabs(true); editor.getSession().setTabSize(2); editor.getSession().setUseWrapMode(true); editor.getSession().setMode("ace/mode/markdown"); function updateOutput() { const result = marked(editor.getValue(), { renderer: renderer, smartypants: true, }); preview.innerHTML = result; } editor.getSession().on('change', updateOutput); document.onkeydown = function(event) { if (event.keyCode === 77 && event.ctrlKey) { wrapper.classList.toggle('printable'); document.body.classList.toggle('printable'); event.preventDefault(); return false; } };
JavaScript
0
@@ -1235,24 +1235,51 @@ rintable');%0A + window.scrollTo(0, 0);%0A event.pr
885738a710579a8f556473e14828368307fee21e
fix templating bug
corehq/apps/accounting/static/accounting/js/pricing_table.js
corehq/apps/accounting/static/accounting/js/pricing_table.js
hqDefine('accounting/js/pricing_table', function () { var pricingTableModel = function (editions, current_edition, isRenewal) { 'use strict'; var self = {}; self.currentEdition = current_edition; self.isRenewal = isRenewal; self.editions = ko.observableArray(_.map(editions, function (edition) { return pricingTableEditionModel(edition, self.currentEdition); })); self.selected_edition = ko.observable(isRenewal ? current_edition : false); self.isSubmitVisible = ko.computed(function () { if (isRenewal){ return true; } return !! self.selected_edition() && !(self.selected_edition() === self.currentEdition); }); self.selectCurrentPlan = function () { self.selected_edition(self.currentEdition); }; self.form = undefined; self.openDowngradeModal = function(pricingTable, e) { var editionSlugs = _.map(self.editions(), function(e) { return e.slug(); }); self.form = $(e.currentTarget).closest("form"); if (editionSlugs.indexOf(self.selected_edition()) < editionSlugs.indexOf(self.currentEdition)) { var $modal = $("#modal-downgrade"); $modal.modal('show'); } else { self.form.submit(); } }; self.submitDowngrade = function(pricingTable, e) { var finish = function() { if (self.form) { self.form.submit(); } }; var $button = $(e.currentTarget); $button.disableButton(); $.ajax({ method: "POST", url: hqImport('hqwebapp/js/initial_page_data').reverse('email_on_downgrade'), data: { old_plan: self.currentEdition, new_plan: self.selected_edition(), note: $button.closest(".modal").find("textarea").val(), }, success: finish, error: finish, }); }; self.init = function () { $('.col-edition').click(function () { self.selected_edition($(this).data('edition')); }); }; return self; }; var pricingTableEditionModel = function (data, current_edition) { 'use strict'; var self = {}; self.slug = ko.observable(data[0]); self.name = ko.observable(data[1].name); self.description = ko.observable(data[1].description); self.currentEdition = ko.observable(data[0] === current_edition); self.notCurrentEdition = ko.computed(function (){ return !self.currentEdition(); }); self.col_css = ko.computed(function () { return 'col-edition col-edition-' + self.slug(); }); self.isCommunity = ko.computed(function () { return self.slug() === 'community'; }); self.isStandard = ko.computed(function () { return self.slug() === 'standard'; }); self.isPro = ko.computed(function () { return self.slug() === 'pro'; }); self.isAdvanced = ko.computed(function () { return self.slug() === 'advanced'; }); self.isEnterprise = ko.computed(function () { return self.slug() === 'enterprise'; }); return this; }; $(function () { var initial_page_data = hqImport('hqwebapp/js/initial_page_data').get, pricingTable = pricingTableModel( initial_page_data('editions'), initial_page_data('current_edition'), initial_page_data('is_renewal') ); // Applying bindings is a bit weird here, because we need logic in the modal, // but the only HTML ancestor the modal shares with the pricing table is <body>. $('#pricing-table').koApplyBindings(pricingTable); $('#modal-downgrade').koApplyBindings(pricingTable); pricingTable.init(); }()); });
JavaScript
0.000001
@@ -3491,20 +3491,20 @@ return -this +self ;%0A %7D;
530c9d8ebfdf9124227ccd550d3665378385905d
Fix QTable bottom (#1593)
src/components/table/table-bottom.js
src/components/table/table-bottom.js
import { QSelect } from '../select' import { QBtn } from '../btn' import { QIcon } from '../icon' export default { methods: { getBottom (h) { if (this.hideBottom) { return } if (this.nothingToDisplay) { const message = this.filter ? this.noResultsLabel || this.$q.i18n.table.noResults : (this.loading ? this.loadingLabel || this.$q.i18n.table.loading : this.noDataLabel || this.$q.i18n.table.noData) return h('div', { staticClass: 'q-table-bottom row items-center q-table-nodata' }, [ h(QIcon, {props: { name: this.$q.icon.table.warning }}), message ]) } const bottom = this.$scopedSlots.bottom return h('div', { staticClass: 'q-table-bottom row items-center' }, bottom ? [ bottom(this.marginalsProps) ] : this.getPaginationRow(h) ) }, getPaginationRow (h) { const { rowsPerPage } = this.computedPagination, paginationLabel = this.paginationLabel || this.$q.i18n.table.pagination, paginationSlot = this.$scopedSlots.pagination return [ h('div', { staticClass: 'col' }, [ this.hasSelectionMode && this.rowsSelectedNumber > 0 ? (this.selectedRowsLabel || this.$q.i18n.table.selectedRows)(this.rowsSelectedNumber) : '' ]), h('div', { staticClass: 'flex items-center' }, [ h('span', { staticClass: 'q-table-bottom-item' }, [ this.rowsPerPageLabel || this.$q.i18n.table.rowsPerPage ]), h(QSelect, { staticClass: 'inline q-table-bottom-item', props: { color: this.color, value: rowsPerPage, options: this.computedRowsPerPageOptions, dark: this.dark, hideUnderline: true }, on: { input: rowsPerPage => { this.setPagination({ page: 1, rowsPerPage }) } } }), paginationSlot ? paginationSlot(this.marginalsProps) : [ h('span', { staticClass: 'q-table-bottom-item' }, [ rowsPerPage ? paginationLabel(this.firstRowIndex + 1, Math.min(this.lastRowIndex, this.computedRowsNumber), this.computedRowsNumber) : paginationLabel(1, this.computedRowsNumber, this.computedRowsNumber) ]), h(QBtn, { props: { color: this.color, round: true, icon: this.$q.icon.table.prevPage, dense: true, flat: true, disable: this.isFirstPage }, on: { click: this.prevPage } }), h(QBtn, { props: { color: this.color, round: true, icon: this.$q.icon.table.nextPage, dense: true, flat: true, disable: this.isLastPage }, on: { click: this.nextPage } }) ] ]) ] } } }
JavaScript
0
@@ -1143,16 +1143,21 @@ ss: 'col +-auto ' %7D, %5B%0A @@ -1379,16 +1379,25 @@ Class: ' +col-auto flex ite @@ -1401,24 +1401,32 @@ items-center + no-wrap ' %7D, %5B%0A
96981e2ddd394d8c671c621f9ce594e3a3752c48
add forgotten googledrive
src/init.js
src/init.js
require('./i18n'); require('./syncedgetputdelete'); require('./eventhandling'); require('./util'); require('./wireclient'); require('./sync'); require('./modules'); require('./baseclient'); require('./caching'); require('./cachinglayer'); require('./dropbox'); require('./indexeddb'); require('./inmemorystorage'); require('./localstorage'); require('./baseclient/types'); require('./env'); require('./widget'); require('./view'); require('./access'); require('./assets'); require('./discover'); require('./authorize'); module.exports = require('./remotestorage');
JavaScript
0.000001
@@ -1,20 +1,65 @@ +module.exports = require('./remotestorage');%0A require('./i18n');%0Ar @@ -295,24 +295,50 @@ /dropbox');%0A +require('./googledrive');%0A require('./i @@ -556,24 +556,24 @@ discover');%0A + require('./a @@ -588,49 +588,4 @@ ');%0A -module.exports = require('./remotestorage');%0A
35c083122ef678d4db4b71ced4985c73ac072abe
Add function to automatically add/rm the coarse class
static/js/main.js
static/js/main.js
window.onload = function() { var container = document.querySelector('#toc'); if (container != null) { var toc = initTOC({ selector: 'h2, h3', scope: '.post', overwrite: false, prefix: 'toc' }); var heading = document.createElement("H2"); var heading_text = document.createTextNode("Table of Contents"); heading.appendChild(heading_text); container.appendChild(heading); container.appendChild(toc); } }
JavaScript
0
@@ -458,14 +458,472 @@ d(toc);%0A - %7D +%0A resize_toc(container);%0A %7D%0A%7D%0A%0Afunction resize_toc(container) %7B%0A var containerHeight = container.clientHeight;%0A%0A var resize = function() %7B%0A if (containerHeight %3E document.documentElement.clientHeight - 100) %7B%0A container.classList.add('coarse');%0A %7D else %7B%0A container.classList.remove('coarse');%0A %7D%0A %7D;%0A resize();%0A%0A var resizeId;%0A window.onresize = function() %7B%0A clearTimeout(resizeId);%0A resizeId = setTimeout(resize, 300);%0A %7D; %0A%7D%0A
96cf1b7952f1d64d5f2ba5d466b36681d6cb2953
Return polling
static/js/vole.js
static/js/vole.js
(function ($, Ember) { var cl = console.log.bind(console); var App = Ember.Application.create({ LOG_TRANSITIONS: true, rootElement: '#ember-container' }); window.App = App; //------------------------- // Store //------------------------- App.Store = DS.Store.extend({ revision: 12, adapter: DS.RESTAdapter }); DS.RESTAdapter.reopen({ namespace: 'api' }); //------------------------- // Models //------------------------- App.Post = DS.Model.extend({ title: DS.attr('string'), created: DS.attr('number'), userId: DS.attr('string'), userName: DS.attr('string'), userAvatar: DS.attr('string') }); App.User = DS.Model.extend({ name: DS.attr('string'), avatar: DS.attr('string'), isMyUser: DS.attr('boolean'), email: DS.attr('string') }); //------------------------- // Views //------------------------- App.PostsView = Ember.View.extend({ templateName: 'posts' }); //------------------------- // Controllers //------------------------- App.ApplicationController = Ember.Controller.extend({ needs: ['posts', 'users'] }); App.IndexController = Ember.Controller.extend({ needs: ['posts', 'users'], myUserBinding: 'controllers.users.myUser', newPostTitle: '', createNewPost: function() { var self = this; var myUser = this.get('controllers.users.myUser.firstObject.user'); var newPost = App.Post.createRecord({ user: myUser, title: this.get('newPostTitle') }); newPost.on('didCreate', function() { self.set('newPostTitle', ''); }); newPost.get('transaction').commit(); } }); App.ProfileController = Ember.Controller.extend({ needs: ['posts', 'users'], myUserBinding: 'controllers.users.myUser', filterByUserBinding: 'controllers.posts.filterByUser', newName: '', newEmail: '', // Helper to disable the button when the fields are not filled. createButtonDisabled: function() { return this.get('newName.length') === 0; }.property('newName'), createNew: function() { var self = this; var newUser = App.User.createRecord({ name: this.get('newName'), email: this.get('newEmail'), isMyUser: true }); newUser.on('didCreate', function() { self.set('myUser', App.User.filter(function(user) { return user.get('isMyUser') === true; })); self.set('filterByUser', self.get('myUser')); }); newUser.get('transaction').commit(); } }); App.UsersController = Ember.ArrayController.extend({ // This is set to a FilteredRecordArray by the router. Just use the // first object in the array. myUser: [] }); App.PostsController = Ember.ArrayController.extend({ filterByUser: [], sortProperties: ['created'], sortAscending: false, filteredPosts: function() { if (this.get('filterByUser.length') > 0) { var filterUserId = this.get('filterByUser.firstObject.id'); cl(filterUserId); if (filterUserId) { return this.get('arrangedContent').filterProperty('userId', filterUserId); } } return this.get('arrangedContent'); }.property('content.[]', 'filterByUser.[]') }); //------------------------- // Router //------------------------- App.Router.map(function() { this.resource('index', {path: '/'}); this.resource('profile', {path: '/profile'}); }); App.ApplicationRoute = Ember.Route.extend({ setupController: function(controller) { controller.set('controllers.posts.content', App.Post.find()); controller.set('controllers.users.myUser', App.User.find({'is_my_user': true})); var refreshUI = function() { App.Post.find(); //setTimeout(refreshUI, 1000); }; setTimeout(refreshUI, 5000); } }); App.IndexRoute = Ember.Route.extend({ setupController: function(controller) { var postsController = controller.get('controllers.posts'); postsController.set('filterByUser', []); } }); App.ProfileRoute = Ember.Route.extend({ setupController: function(controller) { var postsController = controller.get('controllers.posts'); var usersController = controller.get('controllers.users'); postsController.set('filterByUser', usersController.get('myUser')); } }); //------------------------- // Handlebars //------------------------- Ember.Handlebars.registerBoundHelper('nanoDate', function(value, options) { var escaped = Handlebars.Utils.escapeExpression(value); var ms = Math.round(escaped / Math.pow(10, 6)); return new Handlebars.SafeString(moment(ms).fromNow()); }); Ember.Handlebars.registerBoundHelper('enrich', function(value, options) { var escaped = Handlebars.Utils.escapeExpression(value); var rUrl = /\(?\b(?:(http|https|ftp):\/\/)+((?:www.)?[a-zA-Z0-9\-\.]+[\.][a-zA-Z]{2,4}|localhost(?=\/)|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?::(\d*))?(?=[\s\/,\.\)])([\/]{1}[^\s\?]*[\/]{1})*(?:\/?([^\s\n\?\[\]\{\}\#]*(?:(?=\.)){1}|[^\s\n\?\[\]\{\}\.\#]*)?([\.]{1}[^\s\?\#]*)?)?(?:\?{1}([^\s\n\#\[\]\(\)]*))?([\#][^\s\n]*)?\)?/ig; var matches = escaped.match(rUrl); if (matches) { var outer = $('<div />'); var link = $('<a />', { href : matches[0], target : '_blank' }); if (/\.(jpg|gif|png)$/.test(matches[0])) { link.html($('<img />', { src : matches[0] })); } else { link.text(matches[0]); } escaped = escaped.replace(matches[0], outer.append(link).html()); } return new Handlebars.SafeString(escaped); }); $('.time').moment({ frequency: 5000 }); })(jQuery, Ember);
JavaScript
0.000003
@@ -3812,18 +3812,16 @@ -// setTimeo
27122296fd14e3017045bf1981bdb7be92c0803c
Update tool.js
common/tool.js
common/tool.js
var bcrypt = require('bcrypt'); var moment = require('moment'); moment.locale('zh-cn'); // 使用中文 // 格式化时间 exports.formatDate = function (date, friendly) { date = moment(date); if (friendly) { return date.fromNow(); } else { return date.format('YYYY-MM-DD HH:mm'); } }; exports.validateAccount = function (str) { return (/^[a-zA-Z0-9\-_]+$/i).test(str); }; exports.bhash = function (str, callback) { bcrypt.hash(str, 10, callback); }; exports.bcompare = function (str, hash, callback) { bcrypt.compare(str, hash, callback); };
JavaScript
0.000001
@@ -413,24 +413,26 @@ llback) %7B%0A +// bcrypt.hash( @@ -509,16 +509,18 @@ ck) %7B%0A +// bcrypt.c
1f24f4303e453c1b19558ec47da86b2f833bc0c8
remove unused code
statusbar_test.js
statusbar_test.js
/*global describe it before after apf bar = */ "use client"; require(["lib/architect/architect", "lib/chai/chai"], function (architect, chai) { var expect = chai.expect; expect.setupArchitectTest([ { packagePath: "plugins/c9.core/c9", workspaceId: "ubuntu/ip-10-35-77-180", startdate: new Date(), debug: true, hosted: true, local: false, davPrefix: "/" }, "plugins/c9.core/ext", "plugins/c9.core/http-xhr", "plugins/c9.core/util", "plugins/c9.ide.ui/lib_apf", "plugins/c9.ide.ui/menus", { packagePath: "plugins/c9.core/settings", testing: true }, "plugins/c9.core/api.js", { packagePath: "plugins/c9.ide.ui/ui", staticPrefix: "plugins/c9.ide.ui" }, "plugins/c9.ide.editors/document", "plugins/c9.ide.editors/undomanager", { packagePath: "plugins/c9.ide.editors/editors", defaultEditor: "ace" }, "plugins/c9.ide.editors/editor", "plugins/c9.ide.editors/tabmanager", "plugins/c9.ide.ui/focus", "plugins/c9.ide.editors/pane", "plugins/c9.ide.editors/tab", "plugins/c9.ide.ace/ace", { packagePath: "plugins/c9.ide.ace.statusbar/statusbar", staticPrefix: "plugins/c9.ide.layout.classic" }, "plugins/c9.ide.keys/commands", "plugins/c9.fs/proc", "plugins/c9.vfs.client/vfs_client", "plugins/c9.vfs.client/endpoint", "plugins/c9.ide.auth/auth", "plugins/c9.fs/fs", { consumes: ["tabManager", "ace"], provides: [], setup: main } ], architect); function main(options, imports, register) { var tabs = imports.tabManager; var ace = imports.ace; function getTabHtml(tab) { return tab.pane.aml.getPage("editor::" + tab.editorType).$ext; } expect.html.setConstructor(function(tab) { if (typeof tab == "object") return tab.$ext; }); describe('statusbar', function() { before(function(done) { apf.config.setProperty("allow-select", false); apf.config.setProperty("allow-blur", false); bar.$ext.style.background = "rgba(220, 220, 220, 0.93)"; bar.$ext.style.position = "fixed"; bar.$ext.style.left = "20px"; bar.$ext.style.right = "20px"; bar.$ext.style.bottom = "20px"; bar.$ext.style.height = "33%"; document.body.style.marginBottom = "33%"; tabs.once("ready", function() { tabs.getPanes()[0].focus(); done(); }); }); describe("open", function() { this.timeout(10000); it('should open a pane with just an editor', function(done) { tabs.openFile("/file.txt", function(err, tab) { expect(!err); expect(tabs.getTabs()).length(1); // statusbar is added only after editor draw event // TODO make this api easier to use setTimeout(function() { var sb = tab.document.getSession().statusBar; var bar = sb.getElement("bar"); expect.html(bar, "rowcol").text("1:1"); tab.document.editor.ace.selectAll(); setTimeout(function() { expect.html(bar, "rowcol sel").text("2:1"); expect.html(bar, "sel").text("23 Bytes"); done(); }, 10); }); }); }); it('should handle multiple documents in the same pane', function(done) { tabs.openFile("/listing.json", function(err, tab) { expect(!err); expect(tabs.getTabs()).length(2); tab.activate(); setTimeout(function() { var sb = tab.document.getSession().statusBar; expect.html(sb.getElement("bar"), "caption").text("1:1"); done(); }, 10); }); }); }); describe("split(), pane.unload()", function() { it('should split a pane horizontally, making the existing pane the left one', function(done) { var pane = tabs.focussedTab.pane; var righttab = pane.hsplit(true); tabs.focussedTab.attachTo(righttab); setTimeout(function() { expect.html(pane.aml, "pane").text("2:1"); expect.html(righttab.aml, "righttab").text("1:1"); done(); }, 100); }); // it('should remove the left pane from a horizontal split', function(done) { // var pane = tabs.getPanes()[0]; // var tab = tabs.getPanes()[1].getTab(); // pane.unload(); // expect(tabs.getPanes()).length(1); // expect(tabs.getTabs()).length(2); // tabs.focusTab(tab); // done(); // }); }); // describe("Change Theme", function(){ // this.timeout(10000); // // it('should change a theme', function(done) { // var editor = tabs.focussedTab.editor; // ace.on("themeInit", function setTheme(){ // ace.off("theme.init", setTheme); // expect.html(getTabHtml(tabs.focussedTab).childNodes[1]).className("ace-monokai"); // editor.setOption("theme", "ace/theme/textmate"); // done(); // }); // editor.setOption("theme", "ace/theme/monokai"); // }); // }); // @todo test split api and menu if (!onload.remain) { after(function(done) { tabs.unload(); document.body.style.marginBottom = ""; done(); }); } }); onload && onload(); } });
JavaScript
0.000017
@@ -2326,149 +2326,8 @@ ) %7B%0A - apf.config.setProperty(%22allow-select%22, false);%0A apf.config.setProperty(%22allow-blur%22, false);%0A %0A
f903478696e2fb186cb343283f99d35e150ed1a5
fix build
cli/commands/build.js
cli/commands/build.js
'use strict'; const path = require('path'); const spawnSync = require('child_process').spawnSync; const rollup = require('rollup'); const babel = require('rollup-plugin-babel'); const nodeResolve = require('rollup-plugin-node-resolve'); const commonjs = require('rollup-plugin-commonjs'); const json = require('rollup-plugin-json'); const analyzer = require('rollup-analyzer'); const builtins = require('builtin-modules'); const rimraf = require('rimraf'); const createHandler = require('../lib/handler.js'); let cache; exports.command = 'build'; exports.desc = 'Compiles and transpiles source into a lambda-ready build'; exports.builder = { rollup: { config: true, describe: 'File for require([file]) that will provide options for rollup.rollup([options])', }, analyze: { boolean: true, describe: 'Analze the bundle and print the results', }, verbose: { boolean: true, alias: 'v', describe: 'Verbose output', } // 'copy-external': { // boolean: true, // describe: 'Externals that exist in node_modules should be copied to dist as-is', // }, }; function writePackageJson(target) { fs.writeFileSync(target, JSON.stringify({ description: 'This file is automatically generated by betty for unbundled dependencies.', dependencies: global.config.configuration.unbundled, }, null, 2)); } function npmInstall(target) { let node_modules = path.join(target, 'node_modules'); global.log.debug({ node_modules }, 'removing existing node_modules'); rimraf.sync(node_modules); global.log.debug({ cwd: target }, 'running npm install'); let res = spawnSync('npm install', [ '--production' ], { stdio: 'inherit', cwd: target, }); if (res.status !== 0) { global.log.warn({ code: res.status }, 'npm exited with non-zero'); global.log.trace(res, 'spawn sync response'); } else { global.log.debug('npm install success'); } } exports.handler = createHandler((argv, done) => { global.log.info('build started'); global.log.debug({ argv }, 'arguments'); let unbundledKeys = Object.keys(global.config.configuration.unbundled || {}); let defaultRollupOptions = { entry: path.join(process.cwd(), argv.source || 'src/main.js'), cache: cache, plugins: [ json({ exclude: 'node_modules/aws-sdk/**', }), nodeResolve({ jsnext: true, main: true, }), commonjs({ include: 'node_modules/**', exclude: 'node_modules/aws-sdk/**', }), babel({ exclude: 'node_modules/**', babelrc: false, presets: [ [ 'es2015', { modules: false } ] ], plugins: [ 'external-helpers' ], }), ], external: [].concat([ 'aws-sdk' ], builtins, unbundledKeys), }; let buildConfig = argv.rollup || defaultRollupOptions; global.log.debug({ rollup: buildConfig }, 'build config'); rollup.rollup(buildConfig).then(bundle => { cache = bundle; // build doesn't watch so this isn't used bundle.write({ format: 'cjs', sourceMap: true, dest: argv.main || 'dist/index.js', }); if (unbundledKeys.length) { let target = path.dirname(path.resolve(argv.main || 'dist/index.js')); writePackageJson(target); npmInstall(target); } global.log.info('build complete'); if (argv.analyze) { console.log('\n\n'); analyzer.formatted(bundle).then(console.log).catch(console.error); } done(null); }, done); });
JavaScript
0.000001
@@ -41,24 +41,59 @@ re('path');%0A +const fs = require('fs');%0A const spawnS @@ -1274,16 +1274,132 @@ rget) %7B%0A + let packageJson = path.join(target, 'package.json');%0A global.log.debug(%7B packageJson %7D, 'writing package.json');%0A fs.wri @@ -1409,22 +1409,27 @@ ileSync( -target +packageJson , JSON.s @@ -1772,16 +1772,26 @@ ules');%0A + try %7B%0A rimraf @@ -1811,16 +1811,87 @@ dules);%0A + %7D%0A catch (err) %7B%0A global.log.trace(%7B err %7D, 'rimraf error');%0A %7D%0A global @@ -1964,25 +1964,30 @@ awnSync('npm - +', %5B ' install', %5B @@ -1983,18 +1983,16 @@ nstall', - %5B '--prod @@ -2053,16 +2053,22 @@ target + + '/' ,%0A %7D);%0A @@ -3589,345 +3589,420 @@ -if (unbundledKeys.length) %7B%0A let target = path.dirname(path.resolve(argv.main %7C%7C 'dist/index.js'));%0A writePackageJson(target);%0A npmInstall(target);%0A %7D%0A global.log.info('build complete');%0A if (argv.analyze) %7B%0A console.log('%5Cn%5Cn');%0A analyzer.formatted(bundle).then(console.log).catch(console.error);%0A %7D +global.log.info('build complete');%0A if (argv.analyze) %7B%0A console.log('%5Cn%5Cn');%0A analyzer.formatted(bundle).then(console.log).catch(console.error);%0A %7D%0A%0A if (unbundledKeys.length) %7B%0A global.log.debug(%7B keys: unbundledKeys %7D, 'processing unbundled');%0A let target = path.dirname(path.resolve(argv.main %7C%7C 'dist/index.js'));%0A writePackageJson(target);%0A npmInstall(target);%0A %7D%0A %0A
08bdbf915156ccd3c25678300c1b1fe199075f21
disable socket.io debug and fix keycode/data messup
multiplayer.js
multiplayer.js
#!/usr/bin/env node var io = require('socket.io').listen(1338); var sys = require('sys'); var exec = require('child_process').exec; // how many seconds before RNG kicks in /* var rngTimerSeconds = 10; // wait until rngTimerSeconds from last player input var rngTimer; // repeats RNG keypresses var rngInterval; */ /* 1-med-low var highKeys = ['A']; var med = 0.50; var medKeys = ['Up', 'Down', 'Left', 'Right', 'B']; var low = 0.05; var lowKeys = ['Start', 'Select']; var choose = function(a) { return a[Math.floor(Math.random() * a.length)]; }; var setRngTimer = function() { clearInterval(rngInterval); rngTimer = setTimeout(function() { rngInterval = setInterval(function() { },) }, rngTimerSeconds * 1000); }; */ // safety first :> var getKey = function(data) { switch(data) { case 'Up': return '11'; case 'Down': return '116'; case 'Left': return '113'; case 'Right': return '114'; case 'A': return '61'; case 'B': return '56'; case 'Start': return '36'; case 'Select': return '22'; default: return; } }; var keyPress = function(keycode) { console.log("keyPress " + keycode); exec("xdo keypress -k " + getKey(keycode)); }; var keyRelease = function(keycode) { console.log("keyRelease " + keycode); exec("xdo keyrelease -k " + getKey(keycode)); }; io.sockets.on('connection', function(socket) { socket.on('keyPress', function(data) { keyPress(getKey(data)); }); socket.on('keyRelease', function(data) { keyRelease(getKey(data)); }); }); // serve a nice webpage on port 8000 var static = require('node-static'); var file = new static.Server('./static'); require('http').createServer(function(req, res) { req.addListener('end', function () { file.serve(req, res); }).resume(); }).listen(1337);
JavaScript
0
@@ -55,16 +55,32 @@ ten(1338 +, %7B log: false %7D );%0Avar s @@ -826,16 +826,17 @@ turn '11 +1 ';%0A%09%09cas @@ -1069,39 +1069,36 @@ ress = function( -keycode +data ) %7B%0A%09console.log @@ -1102,29 +1102,12 @@ log( -%22keyPress %22 + keycode +data );%0A%09 @@ -1131,39 +1131,36 @@ s -k %22 + getKey( -keycode +data ));%0A%7D;%0A%0Avar keyR @@ -1181,57 +1181,15 @@ ion( -keycode) %7B%0A%09console.log(%22keyRelease %22 + keycode); +data) %7B %0A%09ex @@ -1225,15 +1225,12 @@ Key( -keycode +data ));%0A @@ -1331,29 +1331,21 @@ eyPress( -getKey( data) -) ;%0A%09%7D);%0A%09 @@ -1398,29 +1398,21 @@ Release( -getKey( data) -) ;%0A%09%7D);%0A%7D
fa0e6f3348d4caf6f42a7ad1be1041345f32eba5
Fix nested function comma bug; closes #494
src/rules/function-comma-space-after/index.js
src/rules/function-comma-space-after/index.js
import valueParser from "postcss-value-parser" import { declarationValueIndexOffset, report, ruleMessages, styleSearch, validateOptions, whitespaceChecker, } from "../../utils" export const ruleName = "function-comma-space-after" export const messages = ruleMessages(ruleName, { expectedAfter: () => `Expected single space after ","`, rejectedAfter: () => `Unexpected whitespace after ","`, expectedAfterSingleLine: () => `Expected single space after "," in a single-line function`, rejectedAfterSingleLine: () => `Unexpected whitespace after "," in a single-line function`, }) export default function (expectation) { const checker = whitespaceChecker("space", expectation, messages) return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: expectation, possible: [ "always", "never", "always-single-line", "never-single-line", ], }) if (!validOptions) { return } functionCommaSpaceChecker({ root, result, locationChecker: checker.after, checkedRuleName: ruleName, }) } } export function functionCommaSpaceChecker({ locationChecker, root, result, checkedRuleName }) { root.walkDecls(decl => { const functionOffset = declarationValueIndexOffset(decl) const cssFunctions = valueParser(decl.value) .nodes .filter(node => node.type === "function") cssFunctions.forEach(cssFunction => { const cssFunctionString = valueParser.stringify(cssFunction) styleSearch({ source: cssFunctionString, target: "," }, match => { locationChecker({ source: cssFunctionString, index: match.startIndex, err: message => { report({ message, node: decl, index: functionOffset + cssFunction.sourceIndex + match.startIndex, result, ruleName: checkedRuleName, }) }, }) }) }) }) }
JavaScript
0.000024
@@ -1256,88 +1256,162 @@ -const functionOffset = declarationValueIndexOffset(decl)%0A%0A const cssFunctions +valueParser(decl.value).walk(valueNode =%3E %7B%0A if (valueNode.type !== %22function%22) %7B return %7D%0A%0A let functionArguments = (() =%3E %7B%0A let result = v @@ -1424,27 +1424,36 @@ rser -(decl. +.stringify( value +Node )%0A .nod @@ -1452,173 +1452,228 @@ -.nodes%0A .filter(node =%3E node.type === %22function%22)%0A%0A cssFunctions.forEach(cssFunction =%3E %7B%0A const cssFunctionString = valueParser.stringify(cssFunction + // Remove function name and opening paren%0A result = result.slice(valueNode.value.length + 1)%0A // Remove closing paren%0A result = result.slice(0, result.length - 1)%0A return result%0A %7D)( )%0A +%0A @@ -1687,16 +1687,24 @@ Search(%7B +%0A source: @@ -1708,47 +1708,105 @@ ce: -cssF +f unction -String, target: %22,%22 +Arguments,%0A target: %22,%22,%0A outsideFunctionalNotation: true,%0A %7D, +( match +) =%3E @@ -1855,25 +1855,25 @@ ce: -cssF +f unction -String +Arguments ,%0A @@ -1920,23 +1920,25 @@ err: +( message +) =%3E %7B%0A @@ -1951,146 +1951,259 @@ -report(%7B%0A message,%0A node: decl,%0A index: functionOffset + cssFunction.sourceIndex + match.startIndex +const index = declarationValueIndexOffset(decl) +%0A valueNode.value.length + 1 +%0A valueNode.sourceIndex +%0A match.startIndex%0A report(%7B%0A index,%0A message,%0A node: decl ,%0A
9df1c737ff249293d1c3e6b1b00745940d748ec4
Remove trailing zero from number
lib/elements/number-range.js
lib/elements/number-range.js
'use babel' import {CompositeDisposable, Emitter, Disposable} from 'atom' import {debounce, disposableEvent} from '../helpers' export default class NumberRange { constructor(match, textEditor) { this.subscriptions = null this.active = false this.element = NumberRange.getElement(match) this.element.addEventListener('click', _ => { textEditor.setCursorBufferPosition(match.marker.getBufferRange().start) }) this.element.addEventListener('mousedown', _ => { this.activate(_) }) let oldValue = parseFloat(match.text) let newValue = null this.applyDifference = debounce(function(difference) { newValue = (oldValue + (difference * oldValue)).toFixed(2) if (newValue.slice(-3) === '.00') { newValue = newValue.slice(0, -3) } textEditor.setTextInBufferRange(match.marker.getBufferRange(), newValue) }, 60) this.deactivate = function() { oldValue = parseFloat(newValue) if (this.subscriptions) { this.subscriptions.dispose() } this.active = false } } activate(e) { const initialPosition = e.screenX this.subscriptions = new CompositeDisposable() this.subscriptions.add(disposableEvent(document, 'mousemove', event => { this.applyDifference((event.screenX - initialPosition) / 200) })) this.subscriptions.add(disposableEvent(document, 'mouseup', _ => { this.deactivate() })) this.subscriptions.add(new Disposable(function() { this.subscriptions = null })) this.active = true } dispose() { this.deactivate() } static getElement(match) { const element = document.createElement('number-range') const leftPosition = '-' + (match.text.length * 8.25) + 'px' element.textContent = match.text element.style.left = leftPosition return element } }
JavaScript
0.000007
@@ -736,18 +736,105 @@ ce(- -3 +2 ) === ' -. 0 +0') %7B%0A newValue = newValue.slice(0, -3)%0A %7D else if (newValue.slice(-1) === ' 0') @@ -865,33 +865,33 @@ Value.slice(0, - -3 +1 )%0A %7D%0A
67cb93a4b582684144d5f2bd298653e471ebb6d2
Fix select control prop types
app/pages/search/controls/SelectControl.js
app/pages/search/controls/SelectControl.js
import React, { PropTypes } from 'react'; import ControlLabel from 'react-bootstrap/lib/ControlLabel'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import Select from 'react-select'; import isArray from 'lodash/isArray'; import { injectT } from 'i18n'; const getValue = (value, options) => { if (value) { if (isArray(value)) { return value.map(item => options.find(option => option.value === item)); } return options.find(option => option.value === value); } return null; }; function SelectControl({ id, isLoading, isMulti, label, onChange, options, t, value }) { return ( <div className="app-SelectControl"> <FormGroup controlId={id}> <ControlLabel>{label}</ControlLabel> {!isLoading && <Select className="app-Select" classNamePrefix="app-Select" isClearable isMulti={!!isMulti} isSearchable name={id} onChange={(selected, { action }) => { switch (action) { case 'clear': onChange('', action); break; default: onChange( !isMulti ? selected.value : selected.map(option => option.value), action ); break; } }} options={options} placeholder={t('common.select')} value={getValue(value, options)} />} </FormGroup> </div> ); } SelectControl.propTypes = { id: PropTypes.string.isRequired, isLoading: PropTypes.bool.isRequired, isMulti: PropTypes.bool, label: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, options: PropTypes.array.isRequired, t: PropTypes.func.isRequired, value: PropTypes.oneOfType(PropTypes.string, PropTypes.arrayOf(PropTypes.string)), }; export default injectT(SelectControl);
JavaScript
0.000001
@@ -1788,16 +1788,17 @@ eOfType( +%5B PropType @@ -1826,28 +1826,9 @@ rray -Of(PropTypes.string) +%5D ),%0A%7D
439e5609c18041ba4b42fb32d3dc26a6d1af8e74
Remove apikey parameter in submitApiData()
assets/js/_functions.js
assets/js/_functions.js
/* Function to check API key */ var checkApiKey = function(input, callback) { var apiKey = input; $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('X-AUTH', apiKey); } }); // Send request to check API key and also store the Xuid on success $.get('https://xboxapi.com/v2/accountXuid', function (data) { callback(data); // Return false }).fail(function() { callback(false); }); }; /* API call function */ var apiCall = function (apiKey, endpoint, cache, callback) { // Try to get the cached API results out of PouchDB retrieveDbData(endpoint, function(data){ timestampNow = $.now(); var dataExpiredCondition = (timestampNow - data.timestamp) / 1000, dataExpired = (dataExpiredCondition >= cache); // If no result or caching value exceeded => call API directly // Otherwise return cached API results out of PouchDB if (!data || dataExpired) { // Display caching status of cachable objects in PouchDB if (data && dataExpired) { console.log('[INFO] Cache expired for "' + endpoint + ': ' + dataExpiredCondition + ' ms > ' + cache); } console.log('[INFO] API call "' + endpoint + '" started'); // Execute retrieve function retrieveApiData(apiKey, endpoint, function(data) { // In case of server side API error, return false // Otherwise proceed to transfer the API results into local database if (!data) { console.log('[WARN] Couldn\'t finish API call "' + endpoint + '"!'); callback(false); } else { // Create new object to append a timestamp var jsonObject = {}; jsonObject.timestamp = timestampNow; jsonObject.jsonData = data; // Try to submit the data into the DB submitDbData(jsonObject, endpoint, function(submitData){ // Return false in case of error // Otherwise, send to callback if (!submitData) { callback(false); } else { callback(data); console.log('[INFO] API call "' + endpoint + '" finished'); } }); } }); } else { console.log('[INFO] DB call "' + endpoint + '" started'); // Retrieve cached data retrieveDbData(endpoint, function(data){ // Send callback callback(data.jsonData); console.log('[INFO] DB call "' + endpoint + '" finished'); }); } }); }; /* Retrieve direct API data function */ var retrieveApiData = function(apiKey, endpoint, callback) { // Prepare ajax request $.ajaxSetup({ beforeSend: function(xhr) { // Add X-AUTH header xhr.setRequestHeader('X-AUTH', apiKey); } }); // Fire GET $.get('https://xboxapi.com/v2'+endpoint, function (data) { callback(data); // In case of any error, return false }).fail(function() { callback(false); }); }; /* Retrieve DB data function */ var retrieveDbData = function (endpoint, callback) { // PouchDB init var pouchdb = new PouchDB(endpoint); // Try to get() pouchdb.get('jsonData', function(err, doc) { // In case of error, return false if (err) { if (err.status != 404) { console.log(err); } callback(false); } // If no error, send data to callback if (doc) { callback(doc); } }); }; /* Sumbit API data function */ var submitApiData = function (apikey, endpoint, content, callback) { // Test API key apikey = "ABC123"; // Prepare ajax request $.ajaxSetup({ beforeSend: function(xhr) { // Add X-AUTH header xhr.setRequestHeader('X-AUTH', apikey); } }); // Fire POST $.post('https://xboxapi.com/v2'+endpoint, content, function (data) { callback(data); console.log(data); // In case of any error, return false }).fail(function() { callback(false); }); }; /* Submit DB data function */ var submitDbData = function (input, endpoint, callback) { // PouchDB init var pouchdb = new PouchDB(endpoint); // Check for existing data pouchdb.get('jsonData', function(err, otherDoc) { // If no exisiting data, put() without revision // Otherwise put() with revision of outdated data if (!otherDoc) { // Try to put() the input object into PouchDB pouchdb.put(input, 'jsonData', function(err, response) { // In case of errors, return false if (err) { console.log(err); callback(false); } // If no errors, send response to callback if (response){ callback(response); } }); } else { // Try to put() the input object into PouchDB pouchdb.put(input, 'jsonData', otherDoc._rev, function(err, response) { // In case of errors, return false if (err) { console.log(err); callback(false); } // If no errors, send response to callback if (response){ callback(response); } }); } }); }; /* Function to open modal */ var renderModal = function(recipientsList, messagebody){ // Selector helpers var recipientsSelector = '.modal#composemessage select.chosen-recipients'; var messageSelector = '.modal#composemessage textarea#messagebody'; var modalSelector = '.modal#composemessage'; // If message body, prefill if (messagebody) { $(messageSelector).html(messagebody); } // Get our personal xUid out of settins DB retrieveDbData('settings', function(data){ if (data) { var myXuid = data.xuid; // Now get all friends out of PouchDB retrieveDbData('/' + myXuid + '/friends', function(data){ if (data) { // Variable initalization var friendsList = [], i = 0; // Store each friend in a object to parse easier $(data.jsonData).each(function(k,v){ var friendObject = {}; friendObject.id = i; friendObject.xuid = v.id; friendObject.gamertag = v.Gamertag; friendsList.push(friendObject); i++; }); // Add all friends to Chosen select $(friendsList).each(function(k,v){ $(recipientsSelector).append('<option value="' + v.xuid + '">' + v.gamertag + '</option>'); }); // Preselect the recipient $(recipientsList).each(function(k, v){ $(recipientsSelector + ' option[value="' + v.xuid + '"]').attr('selected',true); }); // Init the chosen select and show the modal $(recipientsSelector).chosen({ width:"100%" }); // Update in case chosen instance is already initiated $(recipientsSelector).trigger("chosen:updated"); submitApiData('/messages', {recipients: ['2535470525950774'], message: "test"}, function(callback){ $(modalSelector).modal('show'); return true; }); } }); } }); };
JavaScript
0
@@ -4009,16 +4009,8 @@ on ( -apikey, endp
54e9ed76a16b9bbfa7f787af0995d1f035d850ec
fix safari bug
public/app/services/ivleService.js
public/app/services/ivleService.js
"use strict"; angular.module("schoolines").factory("IVLEService", function($q, $http, $location, $cookies, $httpParamSerializer, $localStorage, Session) { var ivleService = {}; const ivle_api_key = "UY5RaT4yK3lgWflM47CJo"; /* Login Function */ ivleService.getLoginUrl = function() { var loginLink = "https://ivle.nus.edu.sg/api/login/?"; var urlPath = $location.absUrl(); var params = $httpParamSerializer({ apikey: ivle_api_key, url: urlPath }); return loginLink + params; } /* Create User */ ivleService.createUser = function(token) { return $http.post('/userManagement/createUser', { token: token }).then(function(res) { Session.userId = res.data.userId; $cookies.put("userId", res.data.userId); $localStorage.userId = res.data.userId; return res.data; }); } /* Get Modules */ ivleService.getModules = function(token) { console.log($localStorage.modules); if ($localStorage.modules != undefined && $localStorage.modules.length > 0) return $q.resolve(); else return $http.post('/userManagement/getModules', { token: token }).then( function successCallback(response) { $localStorage.modules = response.data; }, function errorCallback(response) { console.log("Encountered Error: ", response.statusText); }); } return ivleService; });
JavaScript
0.000001
@@ -183,13 +183,11 @@ -const +var ivl
8e178c57ffa420e5b0af794f4c688bfe04d46494
Support the insertion of 0
assets/js/btree-node.js
assets/js/btree-node.js
// constructor // don't call this directly, call BTree::createNode instead var BTreeNode = function(tree, keys, children, parent){ var newNode = Object.create(BTreeNode.prototype); newNode.tree = tree; newNode.keys = keys || []; newNode.children = children || []; // apparently fixed arrays are bad in JS newNode.parent = parent || null; return newNode; } // Traverse tree until we find correct node to insert this value // strict=true searches for node containing exact value BTreeNode.prototype.traverse = function(value, strict) { if (this.keys.indexOf(value) > -1) return this; else if (this.isLeaf()) { if (strict) return false; else return this; } else { // find the correct downward path for this value for(var i = 0; i < this.keys.length; i++){ if(value < this.keys[i]){ return this.children[i].traverse(value, strict); } } return this.children[this.keys.length].traverse(value, strict); } } BTreeNode.prototype.insert = function(value){ var int = parseInt(value) || 0; if ( int <= 0 || int > 1000000000000 ) { alert('Please enter a valid integer.'); return false; } // insert element this.keys.push(value); this.keys.sort(function(a,b){ // sort numbers ascending if(a > b) return 1; else if(a < b) return -1; else return 0; }) // if overflow, handle overflow (go up) if(this.keys.length === this.tree.order) { this.handleOverflow(); } else { // if not filled, start attaching children this.attachChildren(); } } BTreeNode.prototype.handleOverflow = function() { tree = this.tree; // find this node's median and split into 2 new nodes median = this.splitMedian(); // if no parent, create an empty one and set to root if(this.isRoot()) { tree.root = tree.createNode(); this.setParent(tree.root); } // if node is internal, unattach children and add to unattached_nodes if (this.isInternal()) this.unattachAllChildren(); // remove self from parent target = this.parent; this.unsetParent(); // Push median up to target, increment offset tree.current_leaf_offset += 1; target.insert(median); } // function to go down and reattach nodes BTreeNode.prototype.attachChildren = function() { var target = this; var offset = target.tree.current_leaf_offset-1; // get all nodes below the current node var target_nodes = target.tree.unattached_nodes[offset]; if (target_nodes && target_nodes.length > 0) { // first, put all existing nodes into target_nodes so they're ordered correctly target.unattachAllChildren(); // then, attach keys.length+1 children to this node for(var i=0; i<=target.keys.length; i++) { target.setChild(target_nodes[0]); target.tree.removeUnattached(target_nodes[0], offset); } // lower offset, and repeat for each one of the children tree.current_leaf_offset -= 1; target.children.forEach(function(child) { child.attachChildren(); }); // come back up so upper levels can process appropriately tree.current_leaf_offset +=1; } } // helper function to split node into 2 and return the median BTreeNode.prototype.splitMedian = function() { var median_index = parseInt(tree.order/2); var median = this.keys[median_index]; var leftKeys = this.keys.slice(0,median_index); var leftNode = tree.createNode(leftKeys); // no children or parent tree.addUnattached(leftNode, tree.current_leaf_offset); var rightKeys = this.keys.slice(median_index+1, this.keys.length); var rightNode = tree.createNode(rightKeys); tree.addUnattached(rightNode, tree.current_leaf_offset); return median; } BTreeNode.prototype.setChild = function(node) { if (node) { this.children.push(node) ; node.parent = this; } } BTreeNode.prototype.unattachAllChildren = function() { var length = this.children.length; for(var i=0; i<length; i++) { child = this.children[0]; child.unsetParent(); tree.addUnattached(child, tree.current_leaf_offset-1); } } BTreeNode.prototype.setParent = function(node) { node.setChild(this); } BTreeNode.prototype.unsetParent = function() { var node = this; if (node.parent) { node.parent.children.forEach(function(child, index){ if (child === node) node.parent.children.splice(index, 1); }); node.parent = null; } } BTreeNode.prototype.isRoot = function() { return this.parent === null; } BTreeNode.prototype.isLeaf = function() { return (!this.children) || this.children.length === 0; } BTreeNode.prototype.isInternal = function() { return !this.isLeaf() && !this.isRoot(); } // generate node json, used in BTree::toJSON BTreeNode.prototype.toJSON = function() { var json = {}; json.name = this.keys.toString(); if (!this.isRoot()) json.parent = this.parent.keys.toString(); if (!this.isLeaf()) { json.children = []; this.children.forEach(function(child, index){ json.children.push(child.toJSON()); }); } return json; }
JavaScript
0.000003
@@ -1036,22 +1036,18 @@ lue) - %7C%7C 0 ; +%0A %0A if ( int @@ -1046,16 +1046,33 @@ f ( -int %3C= 0 +typeof value !== %22number%22 %7C%7C
020085a6d5e107548da3884e77524df02bf235d6
Handle undefined options in hide().
util/jquery-animate.js
util/jquery-animate.js
/* Animate views */ var transitionend = 'transitionend oTransitionEnd webkitTransitionEnd'; $(document).on(transitionend, '.animate', function() { $(this).dequeue(); }); function transition($el) { // check if transition duration > 0, otherwise finish animation parseFloat($el.css('transition-duration')) || $el.dequeue(); // TODO set timeout or similar to prevent broken transitions from dequeuing } function enter() { $(this).addClass('animate enter').removeClass('hidden'); // force redraw this.offsetHeight; transition($(this).addClass('active').removeClass('leave')); } function leave(options) { options = options || {}; $(this).addClass('animate leave').addClass(options.className); // force redraw this.offsetHeight; transition($(this).addClass('active').removeClass('enter')); } // remove element when transition ends function remove(next) { $(this).removeClass('animate leave active').remove(); next(); } function hide(options) { options = options || {}; return function(next) { $(this).addClass('hidden').removeClass('visible').removeClass(options.className); next(); } } function setHeight(next) { $(this).css('height', this.scrollHeight); if(next) next(); } $.fn.extend({ toggle: function(options) { if(this.hasClass('hidden') || this.hasClass('leave')) this.show(options); else this.hide(options); }, enter: function(element, options) { options = options || {}; this.queue(function(next) { $(this).addClass(options.className); $(element)[options.method || 'append'](this); next(); }); if (options.animateHeight) this.queue(setHeight); return this.queue(enter).queue(function(next) { $(this).removeClass('animate enter active') .removeClass(options.className).css({ height: '' }); next(); }); }, leave: function(options) { return this.stop().queue([ leave.bind(this, options), remove ]); }, show: function(options) { $(this).removeClass('hidden').addClass('visible'); return this.enter(null, options); }, hide: function(options) { if(options.animateHeight) { setHeight.call(this[0]); // needed for some reason this.css('overflow'); } return this.stop().queue([ leave.bind(this, options), hide(options) ]); } });
JavaScript
0
@@ -2051,32 +2051,43 @@ ) %7B%0A%09%09if(options + && options .animateHeight)
b1dcf4848b130c041354b4ad1171ccaec0734a8b
Disable screen filter on blind mode
MapService/WebContent/js/screen_filter.js
MapService/WebContent/js/screen_filter.js
/******************************************************************************* * Copyright (c) 2014, 2017 IBM Corporation, Carnegie Mellon University and * others * * 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. ******************************************************************************/ window.$hulop || eval('var $hulop={};'); $hulop.screen_filter = function() { var history = [], last; var button, a; function onUpdateLocation(crd) { var start_timer = $hulop.config.SCREEN_FILTER_START_TIMER; var walk_speed = $hulop.config.SCREEN_FILTER_SPEED; if (!(start_timer && walk_speed && crd.provider == 'bleloc')) { return; } if (isPopupOpen()) { return; } $hulop.config.SCREEN_FILTER_NO_BUTTON == 'true' || button || showButton(); if (!use_filter()) { filter(); return; } var stop_timer = $hulop.config.SCREEN_FILTER_STOP_TIMER || (start_timer / 2); var visible = $('#screen_filter').size() > 0; var timer = visible ? stop_timer : start_timer; if (last) { crd.distance = Math.min($hulop.util.computeDistanceBetween([ crd.longitude, crd.latitude ], [ last.longitude, last.latitude ]), 8 * walk_speed * (crd.timestamp - last.timestamp) / 1000); } else { crd.distance = 0; } history.push(last = crd); var distance = 0 history = history.filter(function(data) { if (data.timestamp + timer * 1000 > crd.timestamp) { distance += data.distance; return true; } return false; }); var show = distance > walk_speed * timer; if (show != visible) { filter(show ? {} : null) } } function showButton() { var map = $hulop.map.getMap(); button = $('<div>', { 'class' : 'ol-unselectable ol-control TOP', 'css' : { 'z-index' : 10000 } }); a = $('<a>', { 'href' : '#', 'class' : 'ui-btn ui-mini ui-shadow ui-corner-all ui-btn-icon-top', 'css' : { 'margin' : '0px', 'width' : '22px' }, 'on' : { 'click' : function(e) { e.preventDefault(); e.target.blur(); a.toggleClass('ui-icon-forbidden'); a.toggleClass('ui-icon-alert'); localStorage.setItem('screen_filter', use_filter()); use_filter() || showPopup($m('DONT_LOOK_WHILE_WALKING'), 3 * 1000); } } }).appendTo(button); a.addClass(localStorage.getItem('screen_filter') == 'false' ? 'ui-icon-forbidden' : 'ui-icon-alert'); map.addControl(new ol.control.Control({ 'element' : button[0] })); showPopup($m('DONT_LOOK_WHILE_WALKING'), 10 * 1000); } function use_filter() { return a && a.hasClass('ui-icon-alert'); } function showPopup(text, timeout) { $('#popupText').text(text); $('#popupDialog').css({ 'z-index' : 10000 }); $('#popupDialog').popup('open'); timeout && setTimeout(function() { $('#popupDialog').popup('close'); }, timeout); } function isPopupOpen() { $('#popupDialog').parent().hasClass("ui-popup-active"); } function filter(options) { console.log([ 'filter', options ]); if (options) { var color = options.color || 'black'; var opacity = isNaN(options.opacity) ? 0.75 : options.opacity; var css = { 'position' : 'fixed', 'top' : '0px', 'left' : '0px', 'height' : '100%', 'width' : '100%', 'z-index' : 9999, 'background-color' : color, 'filter' : 'alpha(opacity=' + (opacity * 100) + ')', '-moz-opacity' : opacity, 'opacity' : opacity }; if ($('#screen_filter').size() == 0) { $('<div>', { 'id' : 'screen_filter', 'on' : { 'click' : function(event) { console.log([ 'click', event ]) filter(); } } }).appendTo($('body')); } $('#screen_filter').css(css); } else { $('#screen_filter').remove(); history = []; } } return { 'filter' : filter, 'onUpdateLocation' : onUpdateLocation } }();
JavaScript
0.000001
@@ -1469,24 +1469,122 @@ tion(crd) %7B%0A +%09%09if ($hulop.mobile && $hulop.mobile.getPreference('user_mode') == 'user_blind') %7B%0A%09%09%09return;%0A%09%09%7D%0A %09%09var start_
e727ef67f0fac305e73d6f529cb1fe9f9b6fe214
add maxAge parameter for token checking
lib/externalGradingSocket.js
lib/externalGradingSocket.js
const ERR = require('async-stacktrace'); const _ = require('lodash'); const config = require('./config'); const csrf = require('./csrf'); const question = require('./question'); const logger = require('./logger'); const socketServer = require('./socket-server'); const sqldb = require('./sqldb'); const sqlLoader = require('./sql-loader'); const sql = sqlLoader.loadSqlEquiv(__filename); module.exports = {}; // This module MUST be initialized after socket-server module.exports.init = function(callback) { this.namespace = socketServer.io.of('/external-grading'); this.namespace.on('connection', this.connection); callback(null); }; module.exports.connection = function(socket) { socket.on('init', (msg, callback) => { if (!ensureProps(msg, ['variant_id', 'variant_token'])) { return callback(null); } if (!checkToken(msg.variant_token, msg.variant_id)) { return callback(null); } socket.join(`variant-${msg.variant_id}`); module.exports.getVariantSubmissionsStatus(msg.variant_id, (err, submissions) => { if (ERR(err, (err) => logger.error(err))) return; callback({variant_id: msg.variant_id, submissions}); }); }); socket.on('getResults', (msg, callback) => { if (!ensureProps(msg, ['variant_id', 'variant_token', 'submission_id', 'url_prefix', 'question_context', 'csrf_token'])) { return callback(null); } if (!checkToken(msg.variant_token, msg.variant_id)) { return callback(null); } module.exports.renderPanelsForSubmission(msg.submission_id, msg.url_prefix, msg.question_context, msg.csrf_token, (err, panels) => { if (ERR(err, (err) => logger.error(err))) return; callback({ submission_id: msg.submission_id, submissionPanel: panels.submissionPanel, questionScorePanel: panels.questionScorePanel, assessmentScorePanel: panels.assessmentScorePanel, questionPanelFooter: panels.questionPanelFooter, }); }); }); }; module.exports.getVariantSubmissionsStatus = function(variant_id, callback) { const params = { variant_id, }; sqldb.query(sql.select_submissions_for_variant, params, (err, result) => { if (ERR(err, callback)) return; callback(null, result.rows); }); }; module.exports.gradingJobStatusUpdated = function(grading_job_id) { const params = { grading_job_id, }; sqldb.queryOneRow(sql.select_submission_for_grading_job, params, (err, result) => { if (ERR(err, (err) => logger.error(err))) return; const data = { variant_id: result.rows[0].variant_id, submissions: result.rows, }; this.namespace.to(`variant-${result.rows[0].variant_id}`).emit('change:status', data); }); }; module.exports.renderPanelsForSubmission = function(submission_id, urlPrefix, questionContext, csrfToken, callback) { question.renderPanelsForSubmission(submission_id, urlPrefix, questionContext, csrfToken, (err, results) => { if (ERR(err, callback)) return; callback(null, results); }); }; function ensureProps(data, props) { for (const prop of props) { if (!_.has(data, prop)) { logger.error(`socket.io external grader connected without ${prop}`); return false; } } return true; } function checkToken(token, variantId) { const data = { variantId, }; const ret = csrf.checkToken(token, data, config.secretKey, null); if (!ret) { logger.error(`CSRF token for variant ${variantId} failed validation.`); } return ret; }
JavaScript
0
@@ -3644,20 +3644,45 @@ retKey, -null +%7BmaxAge: 24 * 60 * 60 * 1000%7D );%0A i
d7f069d4cdb7fe551bd9d407a08d57d344a0a43a
Add rollbackSettings to effect dependencies list.
assets/js/components/settings/SettingsRenderer.js
assets/js/components/settings/SettingsRenderer.js
/** * Settings Renderer component. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { useEffect } from '@wordpress/element'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants'; const { useSelect, useDispatch } = Data; const NullComponent = () => null; export default function SettingsRenderer( { slug, isOpen, isEditing } ) { const storeName = `modules/${ slug }`; const isDoingSubmitChanges = useSelect( ( select ) => select( storeName )?.isDoingSubmitChanges?.() ); const haveSettingsChanged = useSelect( ( select ) => select( storeName )?.haveSettingsChanged?.() ); const module = useSelect( ( select ) => select( CORE_MODULES ).getModule( slug ) ); const SettingsEdit = module?.settingsEditComponent || NullComponent; const SettingsView = module?.settingsViewComponent || NullComponent; // Rollback any temporary selections to saved values if settings have changed and no longer editing. const { rollbackSettings } = useDispatch( storeName ) || {}; useEffect( () => { if ( rollbackSettings && haveSettingsChanged && ! isDoingSubmitChanges && ! isEditing ) { rollbackSettings(); } }, [ haveSettingsChanged, isDoingSubmitChanges, isEditing ] ); if ( ! isOpen ) { return null; } if ( isEditing ) { return <SettingsEdit />; } return <SettingsView />; }
JavaScript
0
@@ -1824,16 +1824,34 @@ %09%7D%0A%09%7D, %5B + rollbackSettings, haveSet
4e919dab110091f7ae7871a83462506be300e2f3
Add public option to webpack-dev-server
packages/client/webpack.config.js
packages/client/webpack.config.js
/* eslint-disable import/no-extraneous-dependencies */ const webpack = require('webpack'); const path = require('path'); const waitOn = require('wait-on'); const HardSourceWebpackPlugin = require('hard-source-webpack-plugin'); const MiniCSSExtractPlugin = require('mini-css-extract-plugin'); const ManifestPlugin = require('webpack-manifest-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const LoadablePlugin = require('@loadable/webpack-plugin'); const webpackPort = 3000; const buildConfig = require('./build.config'); const modulenameExtra = process.env.MODULENAME_EXTRA ? `${process.env.MODULENAME_EXTRA}|` : ''; const modulenameRegex = new RegExp(`node_modules(?![\\/](${modulenameExtra}@gqlapp)).*`); class WaitOnWebpackPlugin { constructor(waitOnUrl) { this.waitOnUrl = waitOnUrl; this.done = false; } apply(compiler) { compiler.hooks.afterEmit.tapAsync('WaitOnPlugin', (compilation, callback) => { if (!this.done) { console.log(`Waiting for backend at ${this.waitOnUrl}`); waitOn({ resources: [this.waitOnUrl] }, () => { console.log(`Backend at ${this.waitOnUrl} has started`); this.done = true; callback(); }); } else { callback(); } }); } } const config = { entry: { index: ['raf/polyfill', 'core-js/stable', 'regenerator-runtime/runtime', './src/index.ts'] }, name: 'web', module: { rules: [ { test: /\.mjs$/, include: /node_modules/, type: 'javascript/auto' }, { test: /\.(png|ico|jpg|gif|xml)$/, use: { loader: 'url-loader', options: { name: '[hash].[ext]', limit: 100000 } } }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: { loader: 'url-loader', options: { name: '[hash].[ext]', limit: 100000 } } }, { test: /\.(otf|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: { loader: 'file-loader', options: { name: '[hash].[ext]' } } }, { test: /\.css$/, use: [ process.env.NODE_ENV === 'production' ? { loader: MiniCSSExtractPlugin.loader } : { loader: 'style-loader' }, { loader: 'css-loader', options: { sourceMap: true, importLoaders: 1 } }, { loader: 'postcss-loader', options: { sourceMap: true } } ] }, { test: /\.scss$/, use: [ process.env.NODE_ENV === 'production' ? { loader: MiniCSSExtractPlugin.loader } : { loader: 'style-loader' }, { loader: 'css-loader', options: { sourceMap: true, importLoaders: 1 } }, { loader: 'postcss-loader', options: { sourceMap: true } }, { loader: 'sass-loader', options: { sourceMap: true } } ] }, { test: /\.less$/, use: [ process.env.NODE_ENV === 'production' ? { loader: MiniCSSExtractPlugin.loader } : { loader: 'style-loader' }, { loader: 'css-loader', options: { sourceMap: true, importLoaders: 1 } }, { loader: 'postcss-loader', options: { sourceMap: true } }, { loader: 'less-loader', options: { javascriptEnabled: true, sourceMap: true } } ] }, { test: /\.graphqls/, use: { loader: 'raw-loader' } }, { test: /\.(graphql|gql)$/, use: [{ loader: 'graphql-tag/loader' }] }, { test: /\.[jt]sx?$/, exclude: modulenameRegex, use: { loader: 'babel-loader', options: { babelrc: true, rootMode: 'upward-optional' } } }, { test: /locales/, use: { loader: '@alienfast/i18next-loader' } } ], unsafeCache: false }, resolve: { symlinks: false, cacheWithContext: false, unsafeCache: false, extensions: [ '.web.mjs', '.web.js', '.web.jsx', '.web.ts', '.web.tsx', '.mjs', '.js', '.jsx', '.ts', '.tsx', '.json' ] }, watchOptions: { ignored: /build/ }, output: { pathinfo: false, filename: '[name].[hash].js', chunkFilename: '[name].[chunkhash].js', path: path.join(__dirname, 'build'), publicPath: '/' }, devtool: process.env.NODE_ENV === 'production' ? '#nosources-source-map' : '#cheap-module-source-map', mode: process.env.NODE_ENV || 'development', performance: { hints: false }, plugins: (process.env.NODE_ENV !== 'production' ? [new webpack.HotModuleReplacementPlugin()].concat( typeof STORYBOOK_MODE === 'undefined' ? [new WaitOnWebpackPlugin('tcp:localhost:8080')] : [] ) : [ new MiniCSSExtractPlugin({ chunkFilename: '[name].[id].[chunkhash].css', filename: `[name].[chunkhash].css` }) ] ) .concat([ new CleanWebpackPlugin('build'), new webpack.DefinePlugin( Object.assign( ...Object.entries(buildConfig).map(([k, v]) => ({ [k]: typeof v !== 'string' ? v : `'${v.replace(/\\/g, '\\\\')}'` })) ) ), new ManifestPlugin({ fileName: 'assets.json' }), new HardSourceWebpackPlugin({ cacheDirectory: path.join(__dirname, `../../node_modules/.cache/hard-source-${path.basename(__dirname)}`) }), new HardSourceWebpackPlugin.ExcludeModulePlugin([ { test: /mini-css-extract-plugin[\\/]dist[\\/]loader/ } ]), new LoadablePlugin() ]) .concat( buildConfig.__SSR__ ? [] : [new HtmlWebpackPlugin({ template: './html-plugin-template.ejs', inject: true })] ), optimization: { splitChunks: { chunks: 'all' }, runtimeChunk: true }, node: { __dirname: true, __filename: true, fs: 'empty', net: 'empty', tls: 'empty' }, devServer: { host: '0.0.0.0', hot: true, publicPath: '/', headers: { 'Access-Control-Allow-Origin': '*' }, open: true, quiet: false, noInfo: true, historyApiFallback: true, port: webpackPort, writeToDisk: pathname => /(assets.json|loadable-stats.json)$/.test(pathname), ...(buildConfig.__SSR__ ? { proxy: { '!(/sockjs-node/**/*|/*.hot-update.{json,js})': { target: 'http://localhost:8080', logLevel: 'info', ws: true } } } : {}), disableHostCheck: true } }; module.exports = config;
JavaScript
0.000001
@@ -5775,24 +5775,64 @@ hot: true,%0A + public: %60localhost:$%7BwebpackPort%7D%60,%0A publicPa
cd3fa8076260111b22803a7c4c05b645f8eb1dc6
Fix bug where word-wrapping would not properly activate until window is resized
public/assets/default/js/thread.js
public/assets/default/js/thread.js
var posteditor; /** * Update the width of post-content elements. * A limit must be applied with Javascript so word-wrapping works. */ function updatePostWidth() { // Stop allowing wrapping in the middle of words $(".post .post-content").css("word-break", "inherit"); $(".post .post-content").css("width", "auto"); var postWidth = $(".post .post-content").width(); $(".post .post-content").css("width", postWidth + "px"); } $(document).ready(function(){ posteditor = new SimpleMDE({ element: $("#postreply-box")[0], // Autosave disabled temporarily because it keeps it's content even after submitting (Clearboard will use a custom AJAX submit function) /*autosave: { enabled: true, delay: 2000, unique_id: "thread-" + window.thread_id // save drafts based on thread id },*/ spellChecker: false, // Use remote server to process markdown preview, for best accuracy. previewRender: function(content, preview){ processMarkdown(content, false, function(data){ preview.innerHTML = data; }); return '<span style="color:#575757;font-weight:bold;">Loading, please wait...</span>'; } }); $("#postreply-submit").click(function() { // Submit post var req = $.post("/ajax/new_post", { _token: window.csrf_token, body: posteditor.value(), thread: window.thread_id }); req.done(function(data) { if (data.status) { // Successfully posted console.log("Successfully posted"); // Clear postreply field posteditor.value(""); // Render new post onto page $("#postreply").before(data.html); } else { // Unexpected response console.warn("Unexpected response when submitting post!"); alert("Oh noes! Something went wrong! :("); } }); req.fail(function() { console.warn("Request to submit post failed!"); alert("Oh noes! Something went wrong! :("); }); }); // Update post widths on window resize $(window).resize(updatePostWidth); });
JavaScript
0
@@ -266,15 +266,14 @@ %22, %22 -inherit +normal %22);%0A @@ -2305,12 +2305,64 @@ Width);%0A + updatePostWidth(); // initial post width update%0A %7D);%0A
00350d505a3dfc5ffdff1c81074f325387c0f1bf
cax ellipse position
packages/cax/cax/svg/ellipse.js
packages/cax/cax/svg/ellipse.js
import Ellipse from '../render/display/shape/ellipse' import { parseStyle } from './parse-style' import { transform } from './parse-transform' import { parseEvent } from './parse-event' export function ellipse(props, scope) { const options = Object.assign( { rx: 0, ry: 0, cx: 0, cy: 0 }, props ) const ellipse = new Ellipse( Number(options.rx) * 2, Number(options.ry) * 2, parseStyle(props) ) // ellipse.x = Number(options.cx) // ellipse.y = Number(options.cy) transform(props, ellipse, Number(options.cx), Number(options.cy)) parseEvent(props, ellipse, scope) return ellipse }
JavaScript
0.998976
@@ -563,34 +563,76 @@ ions.cx) -, Number(options.c + - Number(options.rx), Number(options.cy) - Number(options.r y))%0A pa
a08b36e0e1ffcb1b3ddc72c1b4888de93beb180c
Remove debugg statements
exporter/index.js
exporter/index.js
const express = require('express'); const puppeteer = require('puppeteer'); // eslint-disable-line const validate = require('express-validation'); const Joi = require('joi'); const bodyParser = require('body-parser'); const cors = require('cors'); const httpCommon = require('_http_common'); const _ = require('lodash'); const Sentry = require('@sentry/node'); const validation = { screenshot: { body: { format: Joi.string().valid(['png', 'pdf']), target: Joi.string() .uri() .required(), title: Joi.string(), selector: Joi.string().required(), }, }, }; let sentryClient; const sentryIsEnabled = () => sentryClient == null; console.log(process.env.SENTRY_DSN); console.log(process.env.SENTRY_RELEASE); console.log(process.env.SENTRY_ENVIRONMENT); console.log(process.env.SENTRY_SERVER_NAME); if (process.env.SENTRY_DSN == null && process.env.SENTRY_RELEASE == null && process.env.SENTRY_ENVIRONMENT == null && process.env.SENTRY_SERVER_NAME == null) { console.log('Sentry not configured'); } else { Sentry.init({ dsn: process.env.SENTRY_DSN, release: process.env.SENTRY_RELEASE, environment: process.env.SENTRY_ENVIRONMENT, serverName: process.env.SENTRY_SERVER_NAME, }); sentryClient = Sentry.getCurrentHub().getClient(); } const captureException = (error, runId = '') => { console.error(`Exception captured for run ID: ${runId} -`, error); if (sentryIsEnabled) Sentry.captureException(error); }; const configureScope = (contextData, callback) => { if (sentryIsEnabled) { Sentry.configureScope((scope) => { _.map(contextData, (value, key) => { scope.setExtra(key, value); }); callback(); }); } else { callback(); } }; const app = express(); let browser; let currentJobCount = 0; const MAX_CONCURRENT_JOBS = 5; app.use(bodyParser.json()); app.use(cors()); (async () => { try { browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'], }); console.log('Exporter started...'); app.listen(process.env.PORT || 3001, '0.0.0.0'); } catch (err) { captureException(err); } })(); function adaptTitle(title) { let r = ''; [...title].forEach((c) => { r += (httpCommon._checkInvalidHeaderChar(c) ? '' : c); // eslint-disable-line }); return r; } const takeScreenshot = (req, runId) => new Promise((resolve, reject) => { const { target, format, title, selector, clip, } = req.body; console.log('Starting run: ', runId, ' - ', target); configureScope({ target, format, title }, async () => { // Create a new incognito browser context. const context = await browser.createIncognitoBrowserContext(); const page = await context.newPage(); page.setDefaultNavigationTimeout(100000); page.on('pageerror', reject); page.on('error', reject); const token = req.header('access_token'); const locale = req.header('locale'); const dest = `${target}?access_token=${token}&locale=${locale}`; await page.goto(dest, { waitUntil: 'networkidle2', timeout: 0 }); const selectors = (selector || '').split(','); if (selectors.length) { await Promise.all(selectors.map(async (s) => { try { await page.waitFor(s); } catch (error) { captureException(error); reject(error); } })); } else { await page.waitFor(5000); } let screenshot; const screenshotOptions = { encoding: 'base64', format: 'A4', omitBackground: false, }; switch (format) { case 'png': { if (clip === undefined) { screenshotOptions.fullPage = true; } else { screenshotOptions.clip = clip; } screenshot = await page.screenshot(screenshotOptions); resolve(screenshot); break; } case 'pdf': { screenshot = await page.pdf({ format: 'A4', printBackground: true, }); const data = screenshot.toString('base64'); resolve(data); break; } // no default } await page.close(); await context.close(); }); }); const MAX_RETRIES = 2; const sendScreenshotResponse = ({ res, format, data, title, }) => { switch (format) { case 'png': { res.setHeader('Content-Length', data.length); res.setHeader('Content-Type', 'image/png'); res.setHeader( 'Content-Disposition', `attachment; filename=${adaptTitle(title)}.png` ); res.send(data); break; } case 'pdf': { res.setHeader('Content-Length', data.length); res.setHeader('Content-Type', 'application/pdf'); res.setHeader( 'Content-Disposition', `attachment; filename=${adaptTitle(title)}.pdf` ); res.send(data); break; } // no default } }; app.post('/screenshot', validate(validation.screenshot), async (req, res) => { if (currentJobCount > MAX_CONCURRENT_JOBS) { res.sendStatus(503); return; } const runId = _.uniqueId(); currentJobCount += 1; const { format, title } = req.body; let retryCount = 0; const tryTakeScreenshot = async () => { let data; try { data = await takeScreenshot(req, runId); } catch (error) { if (retryCount < MAX_RETRIES) { console.log('Duplicating/retrying run: ', runId); retryCount += 1; tryTakeScreenshot(); return; } console.log('Run failed: ', runId); res.status(500).send(error); currentJobCount -= 1; return; } currentJobCount -= 1; sendScreenshotResponse({ res, data, format, title, }); console.log('Done run: ', runId); }; tryTakeScreenshot(); }); function exitHandler(options, err) { if (browser) { browser.close(); } if (err) { captureException(err); } if (options.exit) { process.exit(err ? err.code : 0); } } process.on('exit', exitHandler); // do something when app is closing process.on('SIGINT', exitHandler); // catches ctrl+c event process.on('SIGUSR1', exitHandler); // catches "kill pid" (for example: nodemon restart) process.on('SIGUSR2', exitHandler); process.on('uncaughtException', exitHandler); // catches uncaught exceptions
JavaScript
0.000001
@@ -676,176 +676,8 @@ l;%0A%0A -console.log(process.env.SENTRY_DSN);%0Aconsole.log(process.env.SENTRY_RELEASE);%0Aconsole.log(process.env.SENTRY_ENVIRONMENT);%0Aconsole.log(process.env.SENTRY_SERVER_NAME);%0A if ( @@ -1129,16 +1129,51 @@ ient();%0A + console.log('Sentry initiated');%0A %7D%0A%0Aconst
f884d9bcf5a181210078326521770a7de0ed2e40
Change REST API呼び出し部分をmongooseに変更した
app/api/article/article.controller.js
app/api/article/article.controller.js
'use strict'; exports.findAll = function(req, res, next) { req.collections.articles.find({}, { sort: { _id: -1 } }).toArray((err, articles) => { if(err) return next(err); res.json({ articles: articles }); }); } exports.update = function(req, res, next) { req.collections.articles.findById(req.params.id, (err, article) => { if(err) return next(err); if(!article) return res.sendStatus(404); // 記事の公開フラグを変更する article.published = !article.published; req.collections.articles.updateById(req.params.id, { $set: article }, (err, count) => { if(err) return next(err); res.json({ article: article }); }); }); } exports.remove = function(req, res) { req.collections.articles.removeById(req.params.id, (err) => { res.sendStatus(204); }); }
JavaScript
0
@@ -8,16 +8,64 @@ rict';%0A%0A +var Article = require('../../models/article');%0A%0A exports. @@ -107,40 +107,23 @@ %7B%0A -req.collections.a +A rticle -s .find(%7B%7D , %7B%0A @@ -122,22 +122,20 @@ d(%7B%7D -, %7B +) %0A +. sort -: +( %7B%0A @@ -155,73 +155,50 @@ %7D +) %0A -%7D).toArray((err, articles) =%3E %7B%0A if(err) return next(err);%0A + .exec()%0A .then((articles) =%3E %7B%0A @@ -204,24 +204,26 @@ res.json(%7B%0A + articl @@ -235,24 +235,76 @@ rticles%0A + %7D);%0A %7D, (err) =%3E %7B%0A return next(err);%0A %7D);%0A %7D);%0A%7D%0A @@ -287,38 +287,32 @@ t(err);%0A %7D);%0A - %7D);%0A %7D%0A%0Aexports.updat @@ -346,34 +346,18 @@ ) %7B%0A +%0A -req.collections.a +A rticle -s .fin @@ -379,66 +379,56 @@ s.id -, (err, article) =%3E %7B%0A if(err) return next(err);%0A +)%0A .exec()%0A .then((article) =%3E %7B%0A if + (!ar @@ -462,16 +462,18 @@ s(404);%0A + // %E8%A8%98 @@ -485,24 +485,26 @@ %E3%83%A9%E3%82%B0%E3%82%92%E5%A4%89%E6%9B%B4%E3%81%99%E3%82%8B%0A + article.publ @@ -539,144 +539,100 @@ + + re -q.collections.articles.updateById(req.params.id, %7B%0A $set: article%0A %7D, (err, count) =%3E %7B%0A if(err) return next(err);%0A +turn article;%0A %7D)%0A .then((article) =%3E %7B%0A article.save().then(() =%3E %7B%0A + res. @@ -630,32 +630,34 @@ res.json(%7B%0A + article: @@ -665,16 +665,18 @@ article%0A + %7D) @@ -685,17 +685,64 @@ + %7D);%0A + -%7D); + %7D, (err) =%3E %7B%0A return next(err);%0A %7D);%0A %0A%7D%0A%0A @@ -779,49 +779,45 @@ res -) %7B%0A req.collections.articles.r +, next) %7B%0A Article.findByIdAndR emove -ById (req @@ -826,22 +826,41 @@ arams.id -, (err +)%0A .exec()%0A .then(( ) =%3E %7B%0A @@ -858,24 +858,26 @@ () =%3E %7B%0A + + res.sendStat @@ -885,16 +885,60 @@ s(204);%0A + %7D, (err) =%3E %7B%0A return next(err);%0A %7D);%0A%7D%0A
ce79ade7301f01f386e2a7bee530e471039a73ee
Use function.bind() where appropriate.
initialize.js
initialize.js
// This script should be run when the user logs in. // E.g. Trigger on "Welcome to Genesis". var Tasks = function () { var list = []; this.resume = function () { var fn = list.pop(); if (!fn) return false; fn.apply(null, arguments); return true; }; this.clear = function () { list = []; }; this.pushOne = function (task) { if (!task) return; list.push(task); } this.push = function (tasks) { tasks = tasks || []; while (tasks.length > 0) { this.pushOne(tasks.pop()); } }; }; var Commands = function (gwc) { var send = gwc.connection.send; var exec = function (cmd) { return function () { send(cmd); }; }; // Movement this.north = exec('north'); this.south = exec('south'); this.east = exec('east'); this.west = exec('west'); this.northeast = exec('northeast'); this.northwest = exec('northwest'); this.southeast = exec('southeast'); this.southwest = exec('southwest'); // Battle this.kill = function (target) { return exec('kill ' + target); }; }; var Player = function (gwc) { var tasks = new Tasks(); var cmds = new Commands(gwc); this.resume = tasks.resume; this.abort = tasks.clear; this.todo = tasks.push; this.move = { n: cmds.north, s: cmds.south, e: cmds.east, w: cmds.west, ne: cmds.northeast, nw: cmds.northwest, se: cmds.southeast, sw: cmds.southwest }; this.repeatedly = function (name, action) { var stop = 'stop ' + name; var repeatingAction = function (hint) { if (hint === stop) { // Don't execute the action this.resume(); // Continue to the next task without hints } else { this.todo([repeatingAction]); // Requeue this action action(); // Execute the action } }; return repeatingAction; }; this.moveAnd = function (action) { var move = this.move; var executeAfter = function (movement) { return function () { movement(); action(); }; }; return { here: action, n: executeAfter(move.n), s: executeAfter(move.s), e: executeAfter(move.e), w: executeAfter(move.w), ne: executeAfter(move.ne), nw: executeAfter(move.nw), se: executeAfter(move.se), sw: executeAfter(move.sw) }; }; this.kill = cmds.kill; this.hunt = function (target) { return this.moveAnd( this.repeatedly("killing " + target, this.kill(target)) ); }; }; window.me = new Player(gwc); console.log('Initialized');
JavaScript
0
@@ -576,20 +576,20 @@ %7B%0A var -send +conn = gwc.c @@ -601,21 +601,16 @@ tion -.send ;%0A var exec @@ -609,74 +609,24 @@ var -exec = function (cmd) %7B%0A return function () %7B send(cmd); %7D;%0A %7D +send = conn.send ;%0A%0A @@ -653,21 +653,32 @@ north = -exec( +send.bind(conn, 'north') @@ -694,21 +694,32 @@ south = -exec( +send.bind(conn, 'south') @@ -735,21 +735,32 @@ east = -exec( +send.bind(conn, 'east'); @@ -775,21 +775,32 @@ west = -exec( +send.bind(conn, 'west'); @@ -815,29 +815,40 @@ northeast = -exec( +send.bind(conn, 'northeast') @@ -868,21 +868,32 @@ hwest = -exec( +send.bind(conn, 'northwe @@ -913,29 +913,40 @@ southeast = -exec( +send.bind(conn, 'southeast') @@ -966,21 +966,32 @@ hwest = -exec( +send.bind(conn, 'southwe @@ -1054,13 +1054,24 @@ urn -exec( +send.bind(conn, 'kil @@ -1210,16 +1210,28 @@ s.resume +.bind(tasks) ;%0A this @@ -1250,16 +1250,28 @@ ks.clear +.bind(tasks) ;%0A this @@ -1288,16 +1288,28 @@ sks.push +.bind(tasks) ;%0A%0A thi @@ -2402,16 +2402,27 @@ mds.kill +.bind(cmds) ;%0A this
5e4a8756f307d2db10cfdea1ea1d5aa70d2ce460
Add constuctor params to FileUploadResult related to CB-2421
www/FileUploadResult.js
www/FileUploadResult.js
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /** * FileUploadResult * @constructor */ var FileUploadResult = function() { this.bytesSent = 0; this.responseCode = null; this.response = null; }; module.exports = FileUploadResult;
JavaScript
0
@@ -855,48 +855,75 @@ */%0A -var FileUploadResult = function() %7B%0A +module.exports = function FileUploadResult(size, code, content) %7B%0A%09 this @@ -939,15 +939,15 @@ t = -0;%0A +size;%0A%09 this @@ -966,18 +966,15 @@ e = -null;%0A +code;%0A%09 this @@ -989,49 +989,16 @@ e = -null;%0A%7D;%0A%0Amodule.exports = FileUploadResult;%0A +content;%0A %7D;
fddcaded3753be0b1d35c5c5276b00c5dd7f7eab
Fix missing function name
lib/frontend/rest-adaptor.js
lib/frontend/rest-adaptor.js
var defaultCommands = require('./default-commands/rest'); function createHandler(params) { params = params || {}; var connection = params.connection; var command = params.command; var requestBuilder = params.requestBuilder; if (!requestBuilder) throw new Error('no request builder for ' + command); return (function(request, response) { var message = requestBuilder(request); var timeout = message.timeout || null; connection.emitMessage( command, message, function(error, responseMessage) { if (error) { var body = responseMessage && responseMessage.body || null; response.contentType('application/json'); response.send(body, error); } else { var body = responseMessage.body; response.contentType('application/json'); response.send(body, 200); } }, { timeout: timeout } ); }); } exports.createHandler = createHandler; function getRegisterationMethod(method) { switch (method.toUpperCase()) { case 'GET': return 'get'; case 'PUT': return 'put'; case 'POST': return 'post'; case 'DELETE': return 'del'; default: throw new Error(method + ' is unsppported HTTP method!'); } } exports.findRegisterationMethod = findRegisterationMethod; exports.register = function(application, params) { params = params || {}; var connection = params.connection; if (!connection) throw new Error('Connection to the backend is required!'); var prefix = params.prefix || ''; prefix = prefix.replace(/\/$/, ''); var commandSets = [defaultCommands].concat(params.plugins || []); var unifiedCommandSets = {}; commandSets.forEach(function(commandSet) { if (typeof commandSets == 'string') commandSets = require(commandSets); Object.keys(commandSets).forEach(function(command) { var definition = commandSets[command]; unifiedCommandSets[command] = definition; }); }); Object.keys(unifiedCommandSets).forEach(function(command) { var definition = unifiedCommandSets[command]; var method = getRegisterationMethod(definition.method); application[method]( prefix + definition.path, createHandler({ connection: connection, command: command, requestBuilder: definition.requestBuilder }) ); }); }
JavaScript
0.999999
@@ -1264,20 +1264,19 @@ exports. -find +get Register @@ -1293,12 +1293,11 @@ d = -find +get Regi
0f0db4089dd9aadd22e3bfe5c5a9f2daa5f3fd34
Update wallpaper.js
www/wallpaper.js
www/wallpaper.js
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /** * This class contains information about the current wallpaper. */ function wallpaper() { } wallpaper.prototype.setImage = function(image, base64) { var successCallback = null; var errorCallback = null; var services = "wallpaper"; var dependentProperties = []; dependentProperties.push({ image }); dependentProperties.push({ base64 }); var action = "start"; //future actions new entries. Fixed. if (image) { cordova.exec(successCallback, errorCallback, services, action, dependentProperties); } }; wallpaper.install = function() { if (!window.plugins) { window.plugins = {}; } window.plugins.wallpaper = new wallpaper(); return window.plugins.wallpaper; }; cordova.addConstructor(wallpaper.install);
JavaScript
0
@@ -903,18 +903,16 @@ aper() %7B -%0A%0A %7D%0A%0Awallp @@ -960,17 +960,17 @@ base64) - +%0A %7B%0A%09var s @@ -1101,24 +1101,26 @@ erties.push( +%0A%09 %7B%0A%09%09image%0A%09%7D @@ -1120,41 +1120,9 @@ mage -%0A%09%7D);%0A%09dependentProperties.push(%7B +, %0A%09%09b @@ -1204,17 +1204,18 @@ (image) - +%0A%09 %7B%0A%09%09cord @@ -1332,17 +1332,17 @@ nction() - +%0A %7B%0A%09if (! @@ -1356,17 +1356,18 @@ plugins) - +%0A%09 %7B%0A%09%09wind
d173d46e9b5d7aeece8af6ecc0782a454ca23c51
Add logic to show and hid module based on voice command.
modules/trafficincidents/trafficincidents.js
modules/trafficincidents/trafficincidents.js
Module.register("trafficincidents", { defaults: { baseUrl: "http://www.mapquestapi.com/traffic/v2/incidents?key=", CK: "0MfvxPkvBhP7qwk0n7uNKAxVZzlSBXkQ", TL: "40.71", TR: "-73.999", BL: "40.69", BR: "-74.02" }, getHeader: function(){ return this.data.header //This is gonna be added in config.js file }, getTranslations: function(){ return false; }, start: function(){ Log.info("Starting module: " + this.name); moment.locale(config.language); this.fullDescription = null; // fullDesc this.incidents = []; this.sendSocketNotification("TRAFFIC_REQUEST"); this.loaded = false; }, getDom: function(){ var div = document.createElement("div") div.className = "traffic-display" var ol = document.createElement("ol"); for(i=0; i < this.incidents.length; i++){ var li = document.createElement("li"); li.className = "traffic-incident-" + i; li.innerHTML = this.incidents[i]; ol.appendChild(li); } div.appendChild(ol); return div; }, notificationReceived: function(notification){ if(notification === "traffic"){ this.sendSocketNotification("NEED_UPDATES", this.defaults) } }, socketNotificationReceived: function(notification, payload){ Log.log("This is for testing"); if(notification === "TRAFFIC_ALERTS"){ var parsedData = payload; for(i=0; i<3; i++){ this.incidents.push(parsedData["incidents"][i]["fullDesc"]) } this.updateDom(0); } }, });
JavaScript
0
@@ -190,18 +190,17 @@ : %22-73.9 -99 +7 %22,%0A B @@ -207,17 +207,17 @@ L: %2240.6 -9 +7 %22,%0A B @@ -1216,16 +1216,66 @@ efaults) +;%0A this.show();%0A %7Delse%7B%0A this.hide(); %0A %7D%0A @@ -1586,16 +1586,42 @@ Dom(0);%0A + this.incidents = %5B%5D%0A %7D%0A
35d7a3d13cbc5c60277609cf681e2d169c572c31
Add localStorage support for saving schema/data during reload
draft5/app/controllers/ValidatorController.js
draft5/app/controllers/ValidatorController.js
'use strict'; var app = angular.module('app', false); app.controller('validatorController', function ($scope, $http, $window) { var ajv = $window['ajv']; var validator = ajv({v5: true, verbose:true, allErrors:true}); var YAML = $window['YAML']; var self = this; this.reset = function() { self.document = ""; self.schema = ""; }; this.sample = function(ref) { console.debug('sample', ref); $http.get('samples/' + ref + '.document.json').success(function(data) { self.document = JSON.stringify(data, null, ' '); }); $http.get('samples/' + ref + '.schema.json').success(function(data) { self.schema = JSON.stringify(data, null, ' '); }); }; this.parseMarkup = function(thing) { try { return JSON.parse(thing); } catch (e) { console.log('not json, trying yaml'); return YAML.parse(thing); } }; this.reformatMarkup = function(thing) { try { return JSON.stringify(JSON.parse(thing), null, ' '); } catch (e) { return YAML.stringify(YAML.parse(thing), 4, 2); } }; this.formatDocument = function() { console.debug('formatDocument'); try { var documentObject = this.parseMarkup(self.document); this.document = this.reformatMarkup(self.document); } catch (e) { // *shrug* } }; this.formatSchema = function() { console.debug('formatSchema'); try { var schemaObject = this.parseMarkup(self.schema); this.schema = this.reformatMarkup(self.schema); } catch (e) { // *shrug* } }; this.validateDocument = function () { console.debug("document"); self.documentErrors = []; self.documentMessage = ""; // Parse as JSON try { self.documentObject = this.parseMarkup(self.document); // Do validation if (validator.validateSchema(this.schemaObject)) { if (validator.validate(this.schemaObject, this.documentObject)) { this.documentMessage = "Document conforms to the JSON schema."; } else { console.log(validator.errorsText(ajv.errors)); this.documentErrors = validator.errors; } } else { this.documentErrors = [{message: "Can't check data against an invalid schema."}] } } catch (e) { // Error parsing as JSON self.documentErrors = [{message: "Document is invalid JSON. Try http://jsonlint.com to fix it." }]; } console.log("validateDocument"); }; this.validateSchema = function () { console.debug("schema"); self.schemaErrors = []; self.schemaMessage = ""; // Parse as JSON try { self.schemaObject = this.parseMarkup(self.schema); // Do validation if (validator.validateSchema(this.schemaObject)) { this.schemaMessage = "Schema is a valid JSON schema."; } else { console.log(validator.errorsText(ajv.errors)); this.schemaErrors = validator.errors; } } catch (e) { // Error parsing as JSON self.schemaErrors = [{ message: "Schema is invalid JSON. Try http://jsonlint.com to fix it." }]; } }; // Document changes $scope.$watch(function () { return self.document; }, function (newValue, oldValue) { self.validateDocument(); }); // Schema changes $scope.$watch(function () { return self.schema; }, function (newValue, oldValue) { self.validateSchema(); self.validateDocument(); }); });
JavaScript
0
@@ -251,27 +251,215 @@ '%5D;%0A -%0A var self = this; + var ls = $window%5B'localStorage'%5D;%0A%0A var self = this;%0A %0A if (ls.getItem('data')) %7B%0A self.document = ls.getItem('data');%0A %7D%0A %0A if (ls.getItem('schema')) %7B%0A self.schema = ls.getItem('schema');%0A %7D %0A%0A @@ -530,16 +530,72 @@ a = %22%22;%0A + ls.removeItem(%22data%22);%0A ls.removeItem(%22schema%22);%0A %7D;%0A%0A @@ -3694,12 +3694,323 @@ %0A %7D);%0A%0A + // Save form data before reload%0A $window%5B'onbeforeunload'%5D = function () %7B%0A if (self.document) %7B%0A ls.setItem('data', self.document);%0A %7D else %7B%0A ls.removeItem(%22data%22);%0A %7D%0A if (self.schema) %7B%0A ls.setItem('schema', self.schema);%0A %7D else %7B%0A ls.removeItem(%22schema%22);%0A %7D%0A %7D;%0A %7D);%0A
3de6b5344c59c188822530a8ffee3ee6d9a01f3d
make link's href available
src/link.js
src/link.js
var utils = require('./utils'); var _ = require('lodash'); function Link(desc) { "use strict"; function has(key) { return key in desc; } function validate(key, type) { return _['is' + type].call(undefined, desc[key]); } if (!utils.isObjectLiteral(desc)) { throw new TypeError('Invalid parameter passed to Link constructor'); } if (!has('href')) { throw new ReferenceError('Missing "href" property to link description'); } this.templated = desc.templated === true; if (has('deprecation') && !validate('deprecation', 'Boolean') && !validate('deprecation', 'String')) { throw new TypeError('Invalid Link deprecation provided'); } this.deprecated = !!desc.deprecation; this.deprecationInfo = !desc.deprecation || _.isBoolean(desc.deprecation) ? null : desc.deprecation; ['type', 'name', 'profile', 'title', 'hreflang'].forEach(function (prop) { if (has(prop) && !validate(prop, 'String')) { throw new Error('Invalid link property "' + prop + '" provided.'); } this[prop] = desc[prop]; }.bind(this)); } module.exports = Link;
JavaScript
0.000001
@@ -499,21 +499,17 @@ = true;%0A - %0A +%0A %0A if (h @@ -855,16 +855,24 @@ 'title', + 'href', 'hrefla
c946d5178e88fdecffd0a72c12b11a342c75694f
allow encoding sortable values with identifiers hidden behind a null character - this comes at a 16% performance hit
naturalSort.js
naturalSort.js
/* * Natural Sort algorithm for Javascript * Version 0.3 * Author: Jim Palmer (based on chunking idea from Dave Koelle) * optimizations and safari fix by Mike Grier (mgrier.com) * Released under MIT license. */ function naturalSort(a, b){ // setup temp-scope variables for comparison evauluation var re = /(-?[0-9\.]+)/g, x = a.toString().toLowerCase() || '', y = b.toString().toLowerCase() || '', nC = String.fromCharCode(0), xN = x.replace( re, nC + '$1' + nC ).split(nC), yN = y.replace( re, nC + '$1' + nC ).split(nC), xD = (new Date(x)).getTime(), yD = xD ? (new Date(y)).getTime() : null; // natural sorting of dates if ( yD ) if ( xD < yD ) return -1; else if ( xD > yD ) return 1; // natural sorting through split numeric strings and default strings for( var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++ ) { oFxNcL = parseFloat(xN[cLoc]) || xN[cLoc]; oFyNcL = parseFloat(yN[cLoc]) || yN[cLoc]; if (oFxNcL < oFyNcL) return -1; else if (oFxNcL > oFyNcL) return 1; } return 0; }
JavaScript
0
@@ -335,16 +335,48 @@ %5D+)/g,%0D%0A +%09%09nC = String.fromCharCode(0),%0D%0A %09%09x = a. @@ -391,32 +391,45 @@ ().toLowerCase() +.split(nC)%5B0%5D %7C%7C '',%0D%0A%09%09y = b @@ -457,46 +457,27 @@ se() - %7C%7C '',%0D%0A%09%09nC = String.fromCharCode(0) +.split(nC)%5B0%5D %7C%7C '' ,%0D%0A%09
b288d0157362750fef6da577c3d45919e8f6cddc
fix nav global on mobile
assets/js/global-nav.js
assets/js/global-nav.js
/* ========================================================== * global-nav.js * Global Navigation syripts * * Author: Toni Fisler, toni@antistatique.net * Date: 2014-05-27 16:36:15 * * Copyright 2014 Federal Chancellery of Switzerland * Licensed under MIT ========================================================== */ (function($) { // Handle scroll to position nav as fixed var top = $('.nav-mobile').offset().top; $(window).scroll(function (event) { var y = $(this).scrollTop(); if (y >= top) { $('.nav-mobile').addClass('fixed'); } else { $('.nav-mobile').removeClass('fixed'); } }); }) (jQuery);
JavaScript
0
@@ -401,39 +401,11 @@ p = -$('.nav-mobile').offset().top;%0A +36; %0A%0A @@ -505,105 +505,307 @@ -$('.nav-mobile').addClass('fixed');%0A %7D%0A else %7B%0A $('.nav-mobile').removeClass('fixed'); +if (!$('.nav-mobile').hasClass('fixed')) %7B%0A $('.nav-mobile').addClass('fixed').after('%3Cdiv id=%22spacer%22 style=%22height:36px;%22%3E%3C/div%3E');%0A %7D%0A %7D%0A else %7B%0A if ($('.nav-mobile').hasClass('fixed')) %7B%0A $('.nav-mobile').removeClass('fixed');%0A $('#spacer').remove();%0A %7D %0A