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
1568efdf348a4a794b81846c5c283400f58a42bf
Update DefaultCrosswalkVersion to latest stable version (#3676)
usecase/usecase-cordova-android-tests/steps/DefaultCrosswalkVersion/step.js
usecase/usecase-cordova-android-tests/steps/DefaultCrosswalkVersion/step.js
var step = '<font class="fontSize">' +'<p>Purpose:</p>' +'<p>Verify the webview plugin should default to crosswalk latest stable version</p>' +'<p>Expected Result:</p>' +'<li>The crosswalk version is the same with the latest version in https://download.01.org/crosswalk/releases/crosswalk/android/maven2/org/xwalk/xwalk_core_library_beta/</li>' +'</font>';
JavaScript
0
@@ -377,13 +377,8 @@ rary -_beta /%3C/l
e07e500597c81fb35edbc7b2fed312cd10b3a4ed
Update reject calls to return
lib/Email.js
lib/Email.js
'use strict' const fs = require('fs') const path = require('path') const juice = require('juice') const Inky = require('inky').Inky const cheerio = require('cheerio') const nunjucks = require('nunjucks') const htmlMinify = require('html-minifier').minify const sass = require('node-sass') const htmlToText = require('html-to-text') const mailgun = require('mailgun-js') class Email { /** * @param {string} mailgunApiKey * @param {string} mailgunDomain */ constructor(mailgunApiKey, mailgunDomain) { this._mailgunApiKey = mailgunApiKey this._mailgunDomain = mailgunDomain } /** * Generates a fully built html email (as a string) and the plain text version with given template data * * no templateData param == marketing template output * * @param {string} templateName - which template to build * @param {object} templateData - data to pass to the template * @param {string} from - address to send from (optional) * @param {string} to - address to send to (optional) * @returns {Promise} */ build(templateName, templateData, from, to) { return this.getTemplate(templateName) .then(data => { // compile the template into a single document with templating engine templateData.dirname = `${__dirname}/../templates/` return this.compileTemplate(data, templateData) }) .then(this.compileInky) // compiles the inky html-like syntax into html for email clients .then(this.compileSass) // compile sass to css and add it to the document as a style tag .then(this.inlineCss) // inline the resulting css (but leave media queries in the style tag) .then(this.minifyHtml) // minify the resulting document .then(data => { // build the plain text version const textOutput = htmlToText.fromString(data, { wordWrap: 100, ignoreImage: true }) // return the html and text output return { html: data, text: textOutput } }) .then(data => { if (from && to) { return this.sendMail(from, to, templateData.subject, data.text, data.html) } return data }) } /** * Read a raw template * * @param {string} templateName - which template to build * @returns {Promise} */ getTemplate(templateName) { return new Promise((resolve, reject) => { fs.readFile(`${__dirname + '/../templates/' + templateName}.njk`, 'utf8', (error, data) => { if (error) { reject(error) } resolve(data) }) }) } /** * Compiles the template into a single document with a templating engine * * @param {string} htmlSource * @param {object} templateData * @returns {string} */ compileTemplate(htmlSource, templateData) { // if templateData, then use provided data // if no templateData, then output the variables return nunjucks.renderString(htmlSource, templateData) } /** * Compiles the inky html-like syntax into html ready for email clients * * @param {string} inkySource * @returns {string} */ compileInky(inkySource) { const i = new Inky({}) // null const html = cheerio.load(inkySource) const convertedHtml = i.releaseTheKraken(html) // The return value is a Cheerio object. Get the string value with .toString() return convertedHtml.toString() } /** * Compiles sass in `templates/scss/main.scss` to css * * @param {string} htmlSource - the html source to add the css to * @param {string} stylesheetPath - path to the sass stylesheet * @returns {Promise} */ compileSass(htmlSource, stylesheetPath = `${__dirname}/../templates/scss/main.scss`) { return new Promise((resolve, reject) => { const html = cheerio.load(htmlSource) let nodeModulesPath = (__dirname.includes('node_modules/revolutionuc-emails')) ? path.resolve(__dirname, '../../') : path.resolve(__dirname, '../') sass.render({ file: stylesheetPath, includePaths: [nodeModulesPath] }, (error, result) => { console.log(error); if (error) { reject(error) } // get the css as a string and add it to the cheerio document const css = result.css.toString() html('head').append(`<style type="text/css">${css}</style>`) resolve(html.html()) }) }) } /** * Inlines external css * * @param {string} htmlSource * @returns {string} */ inlineCss(htmlSource) { // TODO: change this to juice.juiceResources (https://github.com/Automattic/juice#methods) return juice(htmlSource, null) } /** * Minifies compiled html * * @param {string} htmlSource * @returns {string} */ minifyHtml(htmlSource) { // https://github.com/kangax/html-minifier#options-quick-reference const options = { minifyCSS: true, collapseWhitespace: true } return htmlMinify(htmlSource, options) } /** * Sends an email via mailgun * * @param {string} from * @param {string} to * @param {string} subject * @param {string} text * @param {string} html * @returns {string} */ sendMail(from, to, subject, text, html) { return new Promise((resolve, reject) => { const mg = mailgun({ apiKey: this._mailgunApiKey, domain: this._mailgunDomain }) const data = { from, to, subject, text, html } mg.messages().send(data, (error, body) => { if (error) { reject(error) } resolve(body) }) }) } } module.exports = Email
JavaScript
0
@@ -2521,32 +2521,49 @@ reject(error)%0A + return%0A %7D%0A%0A @@ -4147,32 +4147,49 @@ reject(error)%0A + return%0A %7D%0A%0A @@ -5524,32 +5524,49 @@ reject(error)%0A + return%0A %7D%0A%0A
6a0ad21b7ce4fda5d4b3e59127a2567afa234321
remove old code; basic structure
lib/Event.js
lib/Event.js
const EE = require('events'); module.exports = (event_name, args, scope) => { const obs = new EE(); const cache_key = 'l:' + event_name; // get cached module let cached_event = scope.cache.get(cache_key); if (cached_event) { process.nextTick(() => { obs.emit('ready', cached_event); }); return obs; } if (cached_event === null) { return obs; } scope.cache.set(cache_key, null); obs.link = (sequence) => {}, obs.onEnd = (node) => {}, obs.onError = (node) => {} return obs; }; /* exports.event = (loader, subject, ob:x ject) => { loader.emit('done', 'event') //console.log('#E instance:', subject); //console.log('event: ', object); var sequence = scope.events[event_id]; if (!instance.flow || !instance.flow[event]) { return sequence.emit('error', new Error('Flow.parse: Event "' + event + '" not found on instance "' + instance.name + '".')); } if (!instance.flow[event].d) { return sequence.emit('error', new Error('Flow.parse: No data handlers.')); } var parsedEvent = parseEvent(scope, instance, instance.flow[event].d); var count = 0; var check = function () { if (++count === parsedEvent.l.length) { parseSequence(scope, sequence, parsedEvent.s); } }; // set instance ref sequence.i = instance; // set end and error events sequence.e = instance.flow[event].e; sequence.r = instance.flow[event].r; if (parsedEvent.l.length > 0) { parsedEvent.l.forEach(function (instName) { Load(scope, sequence, instName, options, check); }); } else { parseSequence(scope, sequence, parsedEvent.s); } }; function parseEvent (scope, instance, config) { var instances = {}; var sequences = []; var pointer = 0; config.forEach(function (handler) { // resolve handler var path = handler; var args = {}; if (handler.constructor === Array) { path = handler[0]; args = handler[1] || {}; } let type = path.substr(0, 1); path = path.substr(1); // parse path let instance_name = instance.name; if (path.indexOf('/') > 0) { path = path.split('/', 2); instance_name = path[0]; path = path[1]; } if (!scope.instances[instance_name] || !scope.instances[instance_name].ready) { instances[instance_name] = 1; } switch (type) { // data handlers case ':': case '.': // create new section if current is a even/stream handler if (sequences[pointer] && sequences[pointer][0] > 0) { ++pointer; } sequences[pointer] = sequences[pointer] || [0, []]; sequences[pointer][1].push([instance_name, path, args, (type === '.')]); return; // stream handlers case '>': case '*': sequences.push([(type === '*' ? 1 : 2), [instance_name, path, args]]); ++pointer; return; } sequence.emit('error', new Error('Flow.parse: Invalid handler type:', type)); }); return { l: Object.keys(instances), s: sequences }; } */
JavaScript
0.018123
@@ -65,16 +65,22 @@ s, scope +, node ) =%3E %7B%0A%0A @@ -143,24 +143,334 @@ vent_name;%0A%0A + obs.link = (sequence) =%3E %7B%0A // if sequence is ready%0A // pipe to node._i (input)%0A return obs;%0A %7D;%0A obs.onEnd = (event) =%3E %7B%0A // emit args on node end%0A return obs;%0A %7D;%0A obs.onError = (event) =%3E %7B%0A // pipe node errors to event%0A return obs;%0A %7D;%0A%0A // get c @@ -781,2970 +781,19 @@ -obs.link = (sequence) =%3E %7B%7D,%0A obs.onEnd = (node) =%3E %7B%7D,%0A obs.onError = (node) =%3E %7B%7D%0A%0A return obs;%0A%7D;%0A/*%0Aexports.event = (loader, subject, ob:x%0Aject) =%3E %7B%0A loader.emit('done', 'event')%0A //console.log('#E instance:', subject);%0A //console.log('event: ', object);%0A var sequence = scope.events%5Bevent_id%5D;%0A%0A if (!instance.flow %7C%7C !instance.flow%5Bevent%5D) %7B%0A return sequence.emit('error', new Error('Flow.parse: Event %22' + event + '%22 not found on instance %22' + instance.name + '%22.'));%0A %7D%0A%0A if (!instance.flow%5Bevent%5D.d) %7B%0A return sequence.emit('error', new Error('Flow.parse: No data handlers.'));%0A %7D%0A%0A var parsedEvent = parseEvent(scope, instance, instance.flow%5Bevent%5D.d);%0A var count = 0;%0A var check = function () %7B%0A if (++count === parsedEvent.l.length) %7B%0A parseSequence(scope, sequence, parsedEvent.s);%0A %7D%0A %7D;%0A%0A // set instance ref%0A sequence.i = instance;%0A%0A // set end and error events%0A sequence.e = instance.flow%5Bevent%5D.e;%0A sequence.r = instance.flow%5Bevent%5D.r;%0A%0A if (parsedEvent.l.length %3E 0) %7B%0A parsedEvent.l.forEach(function (instName) %7B%0A Load(scope, sequence, instName, options, check);%0A %7D);%0A%0A %7D else %7B%0A parseSequence(scope, sequence, parsedEvent.s);%0A %7D%0A%7D;%0A%0Afunction parseEvent (scope, instance, config) %7B%0A%0A var instances = %7B%7D;%0A var sequences = %5B%5D;%0A var pointer = 0;%0A%0A config.forEach(function (handler) %7B%0A%0A // resolve handler%0A var path = handler;%0A var args = %7B%7D;%0A%0A if (handler.constructor === Array) %7B%0A path = handler%5B0%5D;%0A args = handler%5B1%5D %7C%7C %7B%7D;%0A %7D%0A%0A let type = path.substr(0, 1);%0A path = path.substr(1);%0A%0A // parse path%0A let instance_name = instance.name;%0A if (path.indexOf('/') %3E 0) %7B%0A path = path.split('/', 2);%0A instance_name = path%5B0%5D;%0A path = path%5B1%5D;%0A %7D%0A%0A if (!scope.instances%5Binstance_name%5D %7C%7C !scope.instances%5Binstance_name%5D.ready) %7B%0A instances%5Binstance_name%5D = 1;%0A %7D%0A%0A switch (type) %7B%0A%0A // data handlers%0A case ':':%0A case '.':%0A%0A // create new section if current is a even/stream handler%0A if (sequences%5Bpointer%5D && sequences%5Bpointer%5D%5B0%5D %3E 0) %7B%0A ++pointer;%0A %7D%0A%0A sequences%5Bpointer%5D = sequences%5Bpointer%5D %7C%7C %5B0, %5B%5D%5D;%0A sequences%5Bpointer%5D%5B1%5D.push(%5Binstance_name, path, args, (type === '.')%5D);%0A return;%0A%0A // stream handlers%0A case '%3E':%0A case '*':%0A%0A sequences.push(%5B(type === '*' ? 1 : 2), %5Binstance_name, path, args%5D%5D);%0A%0A ++pointer;%0A return;%0A %7D%0A%0A sequence.emit('error', new Error('Flow.parse: Invalid handler type:', type));%0A %7D);%0A%0A return %7B%0A l: Object.keys(instances),%0A s: sequences%0A %7D;%0A%7D%0A*/ +return obs;%0A%7D; %0A
8589c29901786002251bfca20f1488c10c3d88d4
Implement Graph#removeMatches
lib/Graph.js
lib/Graph.js
/** * The very fastest graph for heavy read operations, but uses three indexes * TripletGraph (fast, triple indexed) implements DataStore [NoInterfaceObject] interface Graph { readonly attribute unsigned long length; Graph add (in Triple triple); Graph remove (in Triple triple); Graph removeMatches (in any? subject, in any? predicate, in any? object); sequence<Triple> toArray (); boolean some (in TripleFilter callback); boolean every (in TripleFilter callback); Graph filter (in TripleFilter filter); void forEach (in TripleCallback callback); Graph match (in any? subject, in any? predicate, in any? object, in optional unsigned long limit); Graph merge (in Graph graph); Graph addAll (in Graph graph); readonly attribute sequence<TripleAction> actions; Graph addAction (in TripleAction action, in optional boolean run); }; */ var api = exports; /** * Read an RDF Collection and return it as an Array */ var rdfnil = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'; var rdffirst = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first'; var rdfrest = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest'; function insertIndex(i, a, b, c, t){ if(!i[a]) i[a] = {}; if(!i[a][b]) i[a][b] = {}; i[a][b][c] = t; } function deleteIndex(i, a, b, c){ if(i[a]&&i[a][b]&&i[a][b][c]){ delete(i[a][b][c]); if(!Object.keys(i[a][b]).length) delete(i[a][b]); if(!Object.keys(i[a]).length) delete(i[a]); } } api.Graph = api.TripletGraph = function TripletGraph(init){ this.clear(); Object.defineProperty(this, 'size', {get: function(){return self.length;}}); var self = this; if(init && init.forEach){ init.forEach(function(t){ self.add(t); }); } } api.TripletGraph.prototype.length = null; api.TripletGraph.prototype.graph = null; api.TripletGraph.prototype.importArray = function(a) { while( a.length > 0) { this.add(a.pop()) } }; api.TripletGraph.prototype.insertIndex = insertIndex; api.TripletGraph.prototype.deleteIndex = deleteIndex; api.TripletGraph.prototype.add = function(triple) { insertIndex(this.indexOPS, triple.object, triple.predicate, triple.subject, triple); insertIndex(this.indexPSO, triple.predicate, triple.subject, triple.object, triple); insertIndex(this.indexSOP, triple.subject, triple.object, triple.predicate, triple); this.length++; }; api.TripletGraph.prototype.addAll = function(g){ var g2 = this; g.forEach(function(s){ g2.add(s); }); }; api.TripletGraph.prototype.merge = function(g){ var gx = new api.TripletGraph; gx.addAll(this); gx.addAll(g); return gx; }; api.TripletGraph.prototype.remove = function(triple) { deleteIndex(this.indexOPS, triple.object, triple.predicate, triple.subject); deleteIndex(this.indexPSO, triple.predicate, triple.subject, triple.object); deleteIndex(this.indexSOP, triple.subject, triple.object, triple.predicate); this.length--; } api.TripletGraph.prototype.removeMatches = function(triple) { // TODO } api.TripletGraph.prototype.clear = function(){ this.indexSOP = {}; this.indexPSO = {}; this.indexOPS = {}; this.length = 0; } api.TripletGraph.prototype.import = function(s) { var _g1 = 0, _g = s.length; while(_g1 < _g) { var i = _g1++; this.add(s.get(i)) } }; api.TripletGraph.prototype.every = function every(filter) { return this.toArray().every(filter) }; api.TripletGraph.prototype.some = function some(filter) { return this.toArray().some(filter) }; api.TripletGraph.prototype.forEach = function forEach(callbck) { this.toArray().forEach(callbck) }; api.TripletGraph.prototype.apply = function apply(filter) { this.graph = this.toArray().filter(filter); this.length = this.graph.length; }; api.TripletGraph.prototype.toArray = function toArray() { return this.match(); }; api.TripletGraph.prototype.filter = function filter(cb){ return this.toArray().filter(cb) }; api.TripletGraph.prototype.getCollection = function getCollection(subject){ var collection=[], seen=[]; var first, rest=subject; while(rest && rest!=rdfnil){ first = this.match(rest, rdffirst).map(function(v){return v.object})[0]; if(first===undefined) throw new Error('Collection <'+rest+'> is incomplete'); if(seen.indexOf(rest)!==-1) throw new Error('Collection <'+rest+'> is circular'); seen.push(rest); collection.push(first); rest = this.match(rest, rdfrest).map(function(v){return v.object})[0]; } return collection; }; // FIXME this should return a Graph, not an Array // FIXME ensure that the RDFNode#equals semantics are met api.TripletGraph.prototype.match = function match(subject, predicate, object){ var triples = []; var pattern = {s:subject,p:predicate,o:object}; var patternIndexMap = [ {index:this.indexOPS, constants:["o", "p", "s"], variables:[]} , {index:this.indexPSO, constants:["p", "s"], variables:["o"]} , {index:this.indexSOP, constants:["s", "o"], variables:["p"]} , {index:this.indexSOP, constants:["s"], variables:["o", "p"]} , {index:this.indexOPS, constants:["o", "p"], variables:["s"]} , {index:this.indexPSO, constants:["p"], variables:["s", "o"]} , {index:this.indexOPS, constants:["o"], variables:["p", "s"]} , {index:this.indexPSO, constants:[], variables:["p", "s", "o"]} ]; var patternType = 0; if(!pattern.s) patternType |= 4; if(!pattern.p) patternType |= 2; if(!pattern.o) patternType |= 1; var index = patternIndexMap[patternType]; var data = index.index; index.constants.forEach(function(v){if(data) data=data[pattern[v]];}); if(!data) return []; (function go(data, c){ if(c) Object.keys(data).forEach(function(t){go(data[t], c-1);}); else triples.push(data); })(data, index.variables.length); return triples; };
JavaScript
0.000001
@@ -3056,26 +3056,104 @@ ion( -triple) %7B%0A%09// TODO +s, p, o) %7B%0A%09var graph = this;%0A%09this.match(s, p, o).forEach(function(t) %7B%0A%09%09graph.remove(t);%0A%09%7D); %0A%7D%0Aa
9dca882933d25ff8bf965626cdcbaa35417a9dd9
fix align error
lib/Style.js
lib/Style.js
var React = require('react'); var ReactNative = require('react-native'); var { StyleSheet, } = ReactNative; var Style = StyleSheet.create({ radioForm: { }, radioWrap: { flexDirection: 'row', alignItems: 'center', alignSelf: 'center', marginBottom: 5, }, radio: { justifyContent: 'center', alignItems: 'center', width: 30, height: 30, alignSelf: 'center', borderColor: '#2196f3', borderRadius: 30, }, radioLabel: { paddingLeft: 10, lineHeight: 20, }, radioNormal: { borderRadius: 10, }, radioActive: { width: 20, height: 20, backgroundColor: '#2196f3', }, labelWrapStyle: { flexDirection: 'row', alignItems: 'center', alignSelf: 'center' }, labelVerticalWrap: { flexDirection: 'column', paddingLeft: 10, }, labelVertical: { paddingLeft: 0, }, formHorizontal: { flexDirection: 'row', }, }); module.exports = Style;
JavaScript
0.00002
@@ -202,59 +202,8 @@ w',%0A - alignItems: 'center',%0A alignSelf: 'center',%0A
ff1e46db46ceb2cb2e76fd054a242a56f0d6e278
Add create table function
dbsdk2/index.js
dbsdk2/index.js
'user strict' const mysql = require('mysql'); const q = require('q'); const { getDbCredentials } = require('./config'); let createDatabase = (params) => { let defer = q.defer(); let connection = mysql.createConnection(getDbCredentials()); let query = mysql.format('CREATE DATABASE IF NOT EXISTS ??', [params.db.name]); connection.query(query, (error, results, fields) => { if(error) { defer.reject(error); } else { defer.resolve(results); // TODO Change this to an apt message } }); connection.end(); return defer.promise; } let listDatabases = () => { let defer = q.defer(); let connection = mysql.createConnection(getDbCredentials()); connection.connect(); let query = 'SHOW DATABASES'; connection.query(query, (error, results, fields) => { if(error) { defer.reject(error); } else { let databaseList = results.map(row => row.Database); defer.resolve(databaseList); } }); connection.end(); return defer.promise; } let deleteDatabase = (params) => { let defer = q.defer(); let connection = mysql.createConnection(getDbCredentials()); connection.connect(); let query = mysql.format('DROP DATABASE ??', [params.db.name]); connection.query(query, (error, results, fields) => { if(error) { defer.reject(error); } else { defer.resolve(results); // TODO Change this to an apt message } }); connection.end(); return defer.promise; }
JavaScript
0.000012
@@ -1610,28 +1610,1912 @@ return defer.promise;%0A%7D%0A +%0A// params object structure %5BWIP%5D%0A//%0A// %7B%0A// db : %7B%0A// name : '',%0A// %7D%0A//%0A// table : %7B%0A// name : '',%0A// fields : %5B%0A// %7B%0A// name : '',%0A// type : '',%0A// references : %7B%0A// table : '',%0A// field : ''%0A// %7D,%0A// isNullable : true,%0A// isPrimary : false,%0A// %7D,%0A//%0A// %7B%0A// name : '',%0A// type : '',%0A// references : %7B%0A// table : '',%0A// field : ''%0A// %7D,%0A// isNullable : true,%0A// isPrimary : false,%0A// %7D,%0A// %5D%0A// %7D%0A// %7D%0A%0Alet createTable = (params) =%3E %7B%0A let defer = q.defer();%0A%0A let connection = mysql.createConnection(getDbCredentials(params.db.name));%0A connection.connect();%0A%0A let query = '';%0A%0A params.table.fields.map((field, index) =%3E %7B%0A query = %5B%0A mysql.escapeId(field.name),%0A field.type,%0A field.isNullable ? ',' : 'NOT NULL ,',%0A query%0A %5D.join(' ');%0A%0A if(field.isPrimary) %7B%0A query += mysql.format('PRIMARY KEY (??)', field.name);%0A %7D%0A%0A if(field.references !== undefined) %7B%0A query += mysql.format(', FOREIGN KEY (??) REFERENCES ??(??)', %5Bfield.name, field.references.table, field.references.field%5D);%0A %7D%0A %7D);%0A%0A query = mysql.format('CREATE TABLE ?? (', params.table.name) + query + ')';%0A%0A connection.query(query, (error, results, fields) =%3E %7B%0A if(error) %7B%0A defer.reject(error);%0A %7D else %7B%0A defer.resolve(results); // TODO Change this to an apt message%0A %7D%0A %7D);%0A%0A connection.end();%0A%0A return defer.promise;%0A%7D%0A
30df6563a9479a7dbf01688290c52ca14d483c68
Fix match wrapping.
lib/beard.js
lib/beard.js
var iterator = 0; var exps = { 'statement': (/\{\s*([^}]+?)\s*\}/g), 'operators': (/\s+(and|or|eq|neq|not)\s+/g), 'if': (/^if\s+([^]*)$/), 'elseif': (/^else\s+if\s+([^]*)$/), 'else': (/^else$/), 'for': (/^for\s+([$A-Za-z_][0-9A-Za-z_]*)(?:\s*,\s*([$A-Za-z_][0-9A-Za-z_]*))?\s+in\s+(.*)$/), 'each': (/^each\s+([$A-Za-z_][0-9A-Za-z_]*)(?:\s*,\s*([$A-Za-z_][0-9A-Za-z_]*))?\s+in\s(.*)$/), 'end': (/^end$/), 'keep': (/^keep$/) } var operators = { and: ' && ', or: ' || ', eq: ' === ', neq: ' !== ', not: ' !' } var parse = { operators: function(_, op){ return operators[op]; }, if: function(_, state){ return 'if (' + state + ') {'; }, elseif: function(_, state){ return '} else if (' + state +') {'; }, else: function(){ return '} else {'; }, for: function(_, key, value, object){ if (!value) key = (value = key, 'iterator' + iterator++); return 'for (var ' + key + ' in ' + object + '){' + 'var ' + value + ' = ' + object + '[' + key +'];'; }, each: function(_, iter, value, array){ if (!value) iter = (value = iter, 'iterator' + iterator++); return 'for (var ' + iter + ' = 0, l = ' + array + '.length; ' + iter + ' < l; ' + iter + '++) {' + 'var ' + value + ' = ' + array + '[' + (iter) + '];'; }, end: function(){ return '}'; } } var keep = false; var parser = function(match, inner){ var prev = inner; switch (true){ case (match == 'keep'): keep = true; return ''; case (keep && match == 'end'): keep = false; return ''; case (keep): return match; } inner = inner.replace(exps.operators, parse.operators) .replace(exps.end, parse.end) .replace(exps.else, parse.else) .replace(exps.elseif, parse.elseif) .replace(exps.if, parse.if) .replace(exps.each, parse.each) .replace(exps.for, parse.for); return '";' + (inner == prev ? ' _buffer += ' : '') + inner.replace(/\t|\n|\r/, '') + '; _buffer += "'; } var compiler = function(str){ str = str.replace(new RegExp('\\\\', 'g'), '\\\\').replace(/"/g, '\\"'); var fn = ('var _buffer = ""; with (data){ _buffer += "' + str.replace(exps.statement, parser) + '"; return _buffer; }') .replace(/_buffer\s\+\=\s"";/, '') .replace(/(\{|\});/g, '$1') .replace('_buffer += "";', '') .replace(/\n/g, '\\n') .replace(/\t/g, '\\t') .replace(/\r/g, '\\r'); // create the function try { return new Function('data', fn); } catch(e) { throw new Error('Cant compile template:' + fn); } } Beard = { render: function(template, view){ return compiler(template)(view); } } module.exports = Beard;
JavaScript
0
@@ -1520,21 +1520,33 @@ %09return -match +'%7B' + match + '%7D' ;%0A%09%7D%0A%0A%09i
1419336ce71e522a6cb4b0cf58bc2b4917f94c8e
Fix error with more defensive programming
lib/block.js
lib/block.js
const Emoji = require('node-emoji') const emojiRegex = require('emoji-regex') const hljs = require('highlight.js') const util = require('./util') const emojiByShortcode = require('markdown-it-emoji/lib/data/full.json') const emojiByCharacter = util.reverseKeyValue(emojiByShortcode) const hashtagRegex = require('hashtag-regex') // The hashtag-regex module comes with a regex that auto-detects the number sign // characters, but markdown-it-hashtag wants to handle that by itself. This // function strips the # detection from the hashtag-regex output so that it // can be used with the markdown-it-hashtag module. Yay, plumbing! const getHashtagRegexCaptureGroup = () => { const string = hashtagRegex().toString() const start = string.indexOf('(') const end = string.lastIndexOf('/') return string.slice(start, end) } const defaults = { imageLink: ref => ref, toUrl: ref => ref, protocols: [] } const existingProtocols = ['http', 'https', 'ftp'] const additionalProtocols = ['dat'] let config = {} // init const md = require('markdown-it')({ breaks: true, linkify: true, typographer: true, highlight: function (str, lang) { if (lang && hljs.getLanguage(lang)) { try { return hljs.highlight(lang, str).value } catch (__) {} } return '' // use external default escaping } }) .use(require('markdown-it-hashtag'), { hashtagRegExp: getHashtagRegexCaptureGroup() }) .use(require('markdown-it-emoji'), { // default to emoji from markdown-it // seems like node-emoji has non-standard shortcode names defs: Object.assign({}, Emoji.emoji, emojiByShortcode), shortcuts: {} }) // hashtag md.renderer.rules.hashtag_open = function (tokens, idx) { var tagName = tokens[idx].content.toLowerCase() const url = config.toUrl('#' + tagName) return '<a href="' + url + '">' } // links var oldLinkOpenRender = md.renderer.rules.link_open || function (tokens, idx, options, env, self) { return self.renderToken(tokens, idx, options) } md.renderer.rules.link_open = (tokens, idx, options, env, self) => { const href = tokens[idx].attrs[0][1] if (href.indexOf('not-allowed-as-link') >= 0) { tokens[idx].attrs[0] = ['class', 'bad'] } else { let decoded try { decoded = decodeURI(href) } catch (e) { decoded = href } const result = config.toUrl(decoded) if (result) { // If result is truthy it's a link handled by to-url tokens[idx].attrs[0][1] = result } else { // Otherwise it's an external link, use `target="_blank"` tokens[idx].attrPush(['target', '_blank']) } } const oldLinkOpenRenderResult = oldLinkOpenRender(tokens, idx, options, env, self) return oldLinkOpenRenderResult// .replace('<a href="%25', '<a href="%') } const sigilRegExp = new RegExp(/^[a-zA-Z0-9+/=]{44}\.[a-z0-9]+/) // sigils const sigils = ['%', '&'] sigils.forEach(sigil => { md.linkify.add(sigil, { validate: function (text, pos, self) { var tail = text.slice(pos) if (!self.re.sigil) { self.re.sigil = sigilRegExp } if (self.re.sigil.test(tail)) { const match = tail.match(self.re.sigil)[0] const attempt = config.toUrl(sigil + match) if (attempt.length) { return match.length } } return 0 }, normalize: function (match) { match.text = util.formatSigilText(match.text) match.url = match.raw return match } }) }) // sigil @ and mention md.linkify.add('@', { validate: function (text, pos, self) { var tail = text.slice(pos) if (!self.re.sigil) { self.re.sigil = sigilRegExp } if (!self.re.mention) { self.re.mention = new RegExp( /^[A-Za-z0-9._\-+=/]*[A-Za-z0-9_\-+=/]/ ) } if (self.re.sigil.test(tail)) { return tail.match(self.re.sigil)[0].length } if (self.re.mention.test(tail)) { const match = tail.match(self.re.mention)[0] const attempt = config.toUrl('@' + match) if (attempt.length) { return match.length } } return 0 }, normalize: function (match) { match.url = match.raw if (sigilRegExp.test(match.raw)) { match.text = util.formatSigilText(match.text) } } }) // image md.renderer.rules.image = (tokens, idx) => { const token = tokens[idx] const text = token.attrs[0][1] const title = token.attrs[1][1] const alt = token.content const url = config.imageLink(text) const src = config.toUrl(text, true) const media = { src, alt, title } let properties = '' Object.keys(media).forEach(key => { const value = media[key] if (value.length) { properties += ` ${key}="${value}"` } }) if (alt.startsWith('audio:')) { return `<audio controls${properties}/>` } else if (alt.startsWith('video:')) { return `<video controls${properties}/>` } else { // XXX: do all images need to be wrapped in links? return `<a href="${url}"><img${properties}></a>` } } module.exports = (input, opts) => { // Ensure text is a string (or coerce to empty string) const text = '' + input || '' // Extend default config with custom options config = Object.assign({}, defaults, opts) // Handle additional protocols configured by options Object.values(config.protocols.concat(additionalProtocols)).forEach(protocol => { if (!existingProtocols.includes(protocol)) { existingProtocols.push(protocol) md.linkify.add(protocol + ':', 'http:') } }) const oldConfigToUrl = config.toUrl || ((x) => x) // Ensure emoji are always URI-encoded in URIs so that they never get the // config.emoji() function applied to them. if (config.emoji) { const regex = emojiRegex() config.toUrl = (x) => oldConfigToUrl(x).replace(regex, encodeURIComponent) } // Apply all plugins defined in this file let result = md.render(text) if (config.emoji) { // Replace emoji with `config.emoji()` output const regex = emojiRegex() result = result.replace(regex, config.emoji) } // Circumvent bug that adds extra bytes return util.removeBadBytes(result) }
JavaScript
0.000004
@@ -5789,60 +5789,196 @@ =%3E -oldConfigToUrl(x).replace(regex, encodeURIComponent) +%7B%0A const result = oldConfigToUrl(x)%0A if (typeof result === 'string') %7B%0A return result.replace(regex, encodeURIComponent)%0A %7D else %7B%0A return result%0A %7D%0A %7D %0A %7D
72bfb7c8212fba584ae587274bd4cf2c6f431d7f
Update minsoo.js
minsoo/minsoo.js
minsoo/minsoo.js
var count = document.getElementById("count"); var canvas = document.getElementById("canvas"); var dc = canvas.getContext("2d"); var ms = new Array(); var on_click = function(){ obj = { x : 320, y : 240, sx : Math.random() * 10, sy : Math.random() * 10, alpha : 255 } ms.push( obj ); } setInterval( function(){ dc.clearRect(0,0,640,480); for( var i in ms ){ var obj = ms[i]; dc.fillText( "민수천재야", obj.x,obj.y ); obj.x += obj.sx; obj.y += obj.sy; } dc.fill(); }, 33 );
JavaScript
0.000001
@@ -194,19 +194,19 @@ x : -32 +64 0, y : -2 4 +8 0,%0A @@ -231,16 +231,20 @@ m() * 10 + - 5 , sy : M @@ -351,14 +351,15 @@ 0,0, -640,48 +1280,96 0);%0A
137ee3b2b54913d4c8c7c5375fcf2356360d167a
add all available params http://docs.gurock.com/testrail-api2/reference-cases#get_cases
lib/cases.js
lib/cases.js
/* Cases http://docs.gurock.com/testrail-api2/reference-cases http://docs.gurock.com/testrail-api2/reference-cases-fields http://docs.gurock.com/testrail-api2/reference-cases-types */ //http://docs.gurock.com/testrail-api2/reference-cases#get_case TestRail.prototype.getCase = function(obj) { return this.get("get_case/" + obj.case_id); }; //http://docs.gurock.com/testrail-api2/reference-cases#get_cases TestRail.prototype.getCases = function(obj) { var path = "get_cases/" + obj.project_id; if (obj.suite_id) path += "&suite_id=" + obj.suite_id; if (obj.section_id) path += "&section_id=" + obj.section_id; return this.get(path); }; //http://docs.gurock.com/testrail-api2/reference-cases#add_case TestRail.prototype.addCase = function(obj) { return this.post("add_case/" + obj.section_id, obj); }; //http://docs.gurock.com/testrail-api2/reference-cases#update_case TestRail.prototype.updateCase = function(obj) { return this.post("update_case/" + obj.case_id, obj); }; //http://docs.gurock.com/testrail-api2/reference-cases#delete_case TestRail.prototype.deleteCase = function(obj) { return this.post("delete_case/" + obj.case_id); }; //http://docs.gurock.com/testrail-api2/reference-cases-fields TestRail.prototype.getCaseFields = function() { return this.get("get_case_fields"); }; //http://docs.gurock.com/testrail-api2/reference-cases-types TestRail.prototype.getCaseTypes = function() { return this.get("get_case_types"); };
JavaScript
0.000001
@@ -498,24 +498,25 @@ project_id;%0A +%0A if (obj. @@ -520,24 +520,30 @@ bj.suite_id) + path += %22&s @@ -547,24 +547,30 @@ %22&suite_id=%22 + + obj.suite @@ -597,16 +597,20 @@ tion_id) + path += @@ -624,16 +624,20 @@ ion_id=%22 + + obj.s @@ -643,24 +643,770 @@ section_id;%0A + if (obj.created_after) path += %22&created_after=%22 + obj.created_after;%0A if (obj.created_before) path += %22&created_before=%22 + obj.created_before;%0A if (obj.created_by) path += %22&created_by=%22 + obj.created_by;%0A if (obj.milestone_id) path += %22&milestone_id=%22 + obj.milestone_id;%0A if (obj.priority_id) path += %22&priority_id=%22 + obj.priority_id;%0A if (obj.template_id) path += %22&template_id=%22 + obj.template_id;%0A if (obj.type_id) path += %22&type_id=%22 + obj.type_id;%0A if (obj.updated_after) path += %22&updated_after=%22 + obj.updated_after;%0A if (obj.updated_before) path += %22&updated_before=%22 + obj.updated_before;%0A if (obj.updated_by) path += %22&updated_by=%22 + obj.updated_by;%0A%0A return t
497b9295177ba103e6726ba88b6f12e045f69f10
Comment for ApplicationAdapter
static/todoapp/app.js
static/todoapp/app.js
window.Todos = Ember.Application.create({}); Todos.ApplicationAdapter = DS.FixtureAdapter.extend();
JavaScript
0
@@ -37,16 +37,223 @@ ate(%7B%7D); +%0A%0A// Adapters are responsible for communicating with a source of data for your application.%0A// Typically this will be a web service API, but in this case we are using an adapter designed to load fixture data %0ATodos.A @@ -299,9 +299,8 @@ xtend(); -%0A
536b9ae3c49a00f1faa91fc062f64cc880a981b7
Remove more unused code
lib/haibu.js
lib/haibu.js
/* * haibu.js: Top level include for the haibu module * * (C) 2010, Nodejitsu Inc. * */ var fs = require('fs'), events = require('events'), path = require('path'), hookio = require('hook.io'); var haibu = module.exports = new events.EventEmitter(); // // Expose version through `pkginfo`. // require('pkginfo')(module, 'version'); haibu.log = require('cliff'); haibu.config = require('./haibu/core/config'); haibu.utils = require('./haibu/utils'); haibu.Spawner = require('./haibu/core/spawner').Spawner; haibu.repository = require('./haibu/repositories'); haibu.drone = require('./haibu/drone'); haibu.deploy = require('./haibu/core/deploy'); haibu.initialized = false; haibu.running = {}; haibu.plugins = {}; haibu.activePlugins = {}; // // function init (options, callback) // Initializes haibu directories and models // haibu.init = function (options, callback) { if (haibu.initialized) { return callback(); } haibu.config.load(options, function (err) { if (err) { return callback(err); } haibu.utils.initDirectories(function initialized() { haibu.initialized = true; callback(); }); }); }; // // ### function use (plugin) // #### @plugin {Object} Instance of a plugin from `haibu.plugins` // Adds the specified `plugin` to the set of active plugins used by haibu. // haibu.use = function (plugin) { var args = Array.prototype.slice.call(arguments), callback = typeof args[args.length - 1] === 'function' && args.pop(), options = args.length > 1 && args.pop(); if (!callback) { callback = function () {}; } if (haibu.activePlugins[plugin.name]) { return callback(); } haibu.activePlugins[plugin.name] = plugin; return plugin.init ? plugin.init(options, callback) : callback(); }; // // Define each of our plugins as a lazy loaded `require` statement // fs.readdirSync(__dirname + '/haibu/plugins').forEach(function (plugin) { plugin = plugin.replace('.js', ''); haibu.plugins.__defineGetter__(plugin, function () { return require('./haibu/plugins/' + plugin); }); });
JavaScript
0
@@ -115,40 +115,8 @@ '),%0A - events = require('events'),%0A @@ -147,14 +147,16 @@ -hookio +flatiron = r @@ -167,15 +167,16 @@ re(' -hook.io +flatiron ');%0A @@ -213,28 +213,160 @@ new -events.EventEmitter( +flatiron.App(%7B%0A directories: %7B%0A autostart: '#ROOT/autostart',%0A config: '#ROOT/config',%0A packages: '#ROOT/packages',%0A tmp: '#ROOT/tmp'%0A %7D%0A%7D );%0A%0A @@ -452,48 +452,8 @@ );%0A%0A -haibu.log = require('cliff');%0A haib @@ -461,27 +461,24 @@ .config - = require('. @@ -512,27 +512,24 @@ .utils - = require('. @@ -557,27 +557,24 @@ .Spawner - = require('. @@ -621,19 +621,16 @@ ository - = requir @@ -669,27 +669,24 @@ .drone - = require('. @@ -718,19 +718,16 @@ loy - - = requir @@ -756,37 +756,8 @@ ');%0A -haibu.initialized = false;%0A haib @@ -773,1407 +773,9 @@ - = %7B%7D; -%0Ahaibu.plugins = %7B%7D;%0Ahaibu.activePlugins = %7B%7D;%0A%0A//%0A// function init (options, callback)%0A// Initializes haibu directories and models%0A//%0Ahaibu.init = function (options, callback) %7B%0A if (haibu.initialized) %7B%0A return callback();%0A %7D%0A%0A haibu.config.load(options, function (err) %7B%0A if (err) %7B%0A return callback(err);%0A %7D%0A%0A haibu.utils.initDirectories(function initialized() %7B%0A haibu.initialized = true;%0A callback();%0A %7D);%0A %7D);%0A%7D;%0A%0A//%0A// ### function use (plugin)%0A// #### @plugin %7BObject%7D Instance of a plugin from %60haibu.plugins%60%0A// Adds the specified %60plugin%60 to the set of active plugins used by haibu.%0A//%0Ahaibu.use = function (plugin) %7B%0A var args = Array.prototype.slice.call(arguments),%0A callback = typeof args%5Bargs.length - 1%5D === 'function' && args.pop(),%0A options = args.length %3E 1 && args.pop();%0A%0A if (!callback) %7B%0A callback = function () %7B%7D;%0A %7D%0A%0A if (haibu.activePlugins%5Bplugin.name%5D) %7B%0A return callback();%0A %7D%0A%0A haibu.activePlugins%5Bplugin.name%5D = plugin;%0A%0A return plugin.init%0A ? plugin.init(options, callback)%0A : callback();%0A%7D;%0A%0A//%0A// Define each of our plugins as a lazy loaded %60require%60 statement%0A//%0Afs.readdirSync(__dirname + '/haibu/plugins').forEach(function (plugin) %7B%0A plugin = plugin.replace('.js', '');%0A haibu.plugins.__defineGetter__(plugin, function () %7B%0A return require('./haibu/plugins/' + plugin);%0A %7D);%0A%7D);%0A
ef675c190419fcb18c426484ba707dfddf9b866c
Add TODO related to the auto-request hook feature
lib/hooks.js
lib/hooks.js
'use strict' var http = require('http') var shimmer = require('shimmer') var asyncState = require('./async-state') module.exports = function (client) { shimmer({ logger: client.logger.error }) shimmer.massWrap(http.Server.prototype, ['on', 'addListener'], function (fn) { return function (event, listener) { if (event === 'request' && typeof listener === 'function') return fn.call(this, event, onRequest) else return fn.apply(this, arguments) function onRequest (req, res) { asyncState.req = req listener.apply(this, arguments) } } }) }
JavaScript
0
@@ -147,16 +147,237 @@ ient) %7B%0A + // TODO: This will actual just use the logger of the last client parsed in.%0A // In most use-cases this is a non-issue, but if someone tries to initiate%0A // multiple clients with different loggers, this will get weird%0A shimme @@ -411,16 +411,17 @@ rror %7D)%0A +%0A shimme
18f6a720b613e60bc4888e5e0ee31f2cf365a577
Update the adapter
lib/index.js
lib/index.js
const EngineParser = require("engine-parser") , EntrypointManager = require("engine-entrypoint-manager") , findValue = require("find-value") , setValue = require("set-value") , deffy = require("deffy") ; class FlowApi extends EngineParser { constructor (appPath, compositionCrud) { super(appPath, compositionCrud); this.entrypoint = new EntrypointManager(this); } // Entrypoints addEntrypoint (en, cb) { return this.entrypoint.add(en, cb); } removeEntrypoint (en, cb) { return this.entrypoint.remove(en, cb); } listEntrypoints (cb) { return this.entrypoint.list(cb); } updateEntrypoint (oldEn, newEn, cb) { return this.entrypoint.update(oldEn, newEn, cb); } getModuleComposition (moduleName, cb) { this.getModulePackage(moduleName, (err, data) => { if (err) { return cb(err); } cb(null, deffy(findValue(data, "composition"), {}), data); }); } _sanitizeListenerName (name) { return name.replace(/\./g, "\\."); } _setCompositionField (obj, field, data) { setValue(obj, field, data); return data; } _setInstanceField (instanceName, field, dataToSet, cb) { return this.readInstance(instanceName, (err, data) => { if (err) { return cb(err); } this._setCompositionField(data, field, dataToSet); this.updateInstance(instanceName, data, cb); }); } _setListenerField (instanceName, listenerName, data, field, cb) { listenerName = this._sanitizeListenerName(listenerName); return this._setInstanceField( instanceName , `flow.${listenerName}${field?'.':''}${field}` , data , cb ); } setListenerData (instanceName, listenerName, dataArr, cb) { return this._setListenerField(instanceName, listenerName, dataArr, "d", cb); } setErrorEvent (instanceName, listenerName, errEvent, cb) { return this._setListenerField(instanceName, listenerName, errEvent, "r", cb); } setEndEvent (instanceName, listenerName, endEvent, cb) { return this._setListenerField(instanceName, listenerName, endEvent, "e", cb); } setListener (instanceName, listenerName, listenerData, cb) { return this._setListenerField(instanceName, listenerName, listenerData, "", cb); } removeListener (instanceName, listenerName, cb) { return this._setListenerField(instanceName, listenerName, undefined, "", cb); } setInstanceStyles (instanceName, styles, cb) { styles = deffy(styles, []); this._setInstanceField(instanceName, "config.styles", styles, cb); } setInstanceMarkup (instanceName, markup, cb) { markup = deffy(markup, []); this._setInstanceField(instanceName, "config.markup", markup, cb); } setInstanceLoad (instanceName, load, cb) { load = deffy(load, []); this._setInstanceField(instanceName, "config.load", load, cb); } setInstanceRoles (instanceName, roles, cb) { roles = deffy(roles, {}); this._setInstanceField(instanceName, "config.roles", roles, cb); } setInstanceConfig (instanceName, config, cb) { config = deffy(config, {}); this._setInstanceField(instanceName, "config.config", config, cb); } } module.exports = FlowApi;
JavaScript
0.000001
@@ -277,73 +277,39 @@ r (a -ppPath, compositionCrud) %7B%0A super(appPath, compositionCrud +dapter) %7B%0A super(adapter );%0A
7ea593e20ec162b5c88caee9e9c1c0c112d0d82c
it's response_code not statuscode
lib/index.js
lib/index.js
var DD = require("node-dogstatsd").StatsD; module.exports = function (options) { var datadog = options.dogstatsd || new DD(); var stat = options.stat || "node.express.router"; var tags = options.tags || []; var response_code = options.response_code || false; return function (req, res, next) { if (!req._startTime) { req._startTime = new Date(); } var end = res.end; res.end = function (chunk, encoding) { res.end = end; res.end(chunk, encoding); if (!req.route || !req.route.path) { return; } var statTags = [ "route:" + req.route.path ].concat(tags); if (options.method) { statTags.push("method:" + req.method.toLowerCase()); } if (options.protocol && req.protocol) { statTags.push("protocol:" + req.protocol); } if (options.path !== false) { statTags.push("path:" + req.path); } if (statuscode) { statTags.push("response_code:" + req.statusCode); datadog.increment(stat + '.response_code.' + req.statusCode , 1, statTags); } datadog.histogram(stat + '.response_time', (new Date() - req._startTime), 1, statTags); }; next(); }; };
JavaScript
0.999884
@@ -864,22 +864,25 @@ %0A%09%09%09if ( -status +response_ code) %7B%0A
550cd0e54037a9a521cd192af839d0f89e900dac
Break on exception too
lib/index.js
lib/index.js
'use babel'; 'use strict'; const {EventEmitter} = require ('events'); const {Client} = require ('_debugger'); const {spawn} = require ('child_process'); const watt = require ('watt'); const escapeStringRegexp = require ('escape-string-regexp'); const path = require ('path'); const fs = require ('fs'); const Extractor = require ('./extractor.js'); class Wannabe extends EventEmitter { /** * Construct the Wannabe object. * * @param {string} script - Test script. */ constructor (script) { super (); this._frames = {}; this._script = script; this._client = new Client (); this._mocha = { kill: () => {} }; watt.wrapAll (this); } /** * Spawn mocha with the node debugger. * * @param {string|RegExp} regtest - Tests cases to grep. */ _spawn (pattern, next) { const regex = pattern instanceof RegExp ? pattern.toString ().replace (/^\/(.*)\/.?$/, '$1') : escapeStringRegexp (pattern); this._mocha = spawn ('node', [ '--debug', '--debug-brk', path.join (__dirname, './mocha.js'), this._script, regex ], { detached: false, stdio: ['ignore', 'ignore', 'pipe'] }); this._mocha.unref (); this._mocha.stderr.once ('data', () => next ()); this._mocha.on ('close', () => {}); this._mocha.on ('error', (err) => { console.error (err); }); } /** * Inspect the frame on the current breakpoint. * * It populates this._frames with the local variables. * The key of this._frames is the line number. * * NOTE: setBreakpoint is slow! */ * _inspect (next) { const {frames} = yield this._client.reqBacktrace (next); const line = `${frames[0].line}`; if (!this._frames[line]) { this._frames[line] = []; } const frame = { locals: [], arguments: [], returnValue: null }; frames[0].locals.forEach ((local) => { /* Local variables */ frame.locals.push ({ name: local.name, type: local.value.type, value: local.value.value }); }); frames[0].arguments.forEach ((argument) => { /* Arguments */ frame.arguments.push ({ name: argument.name, type: argument.value.type, value: argument.value.value }); }); /* Return value */ if (frames[0].returnValue && frames[0].returnValue.type !== 'undefined') { frame.returnValue = { type: frames[0].returnValue.type, value: frames[0].returnValue.value }; } this._frames[line].push (frame); } /** * Initialize the client connection. * * It waits on the first breakpoint because the child is executed with * the --debug-brk argument. * * @param {string|RegExp} regtest - Tests cases to grep. */ * init (pattern, next) { yield this._spawn (pattern, next); let first = true; this._client.on ('break', () => { if (first) { this.emit ('ready'); first = false; return; } this._inspect (() => this._client.reqContinue (() => {})); }); this._client.once ('connect', next.parallel ()); this._client.connect (5858); yield next.sync (); yield this.once ('ready', next); // wait for the first breakpoint (--debug-brk) } /** * Set one or more breakpoints according to the current script. * * @param {number[]} lines - Lines where put the breakpoints. */ * setBreakpoints (lines, next) { for (const line of lines) { this._client.setBreakpoint ({ type: 'script', target: this._script, line: line }, next.parallel ()); } yield next.sync (); } /** * Run Wannabe. * * When a new breakpoint is reached, the continue request is automatically * sent until that the child is terminated. * * @returns all frames. */ * run (next) { const promise = new Promise ((resolve) => { this._client.once ('error', (err) => { resolve (this._frames); }); this._client.once ('close', () => { resolve (this._frames); }); }); yield this._client.reqContinue (next); return yield promise; } dispose () { this._mocha.kill ('SIGINT'); } } const extract = watt (function * (script, data, extractor, next) { let file = null; if (data) { /* We must create a new script in the same location that {script}. * The reason is that we can not pass a buffer to mocha; only files * can be passed to the runner. */ file = path.join (script, `../.wannabe-${path.basename (script)}`); yield fs.writeFile (file, data, next); } else { file = script; } let _exThrown = false; let frames = null; const wannabe = new Wannabe (file); try { const {lines, pattern} = extractor (file); if (!lines.length) { return {}; } yield wannabe.init (pattern); yield wannabe.setBreakpoints (lines); frames = yield wannabe.run (); } catch (ex) { _exThrown = true; throw ex; } finally { wannabe.dispose (); if (data) { yield fs.unlink (file, next); } // FIXME: see watt bug: https://github.com/mappum/watt/issues/16 if (!_exThrown) { return frames; } } }); exports.byPattern = watt (function * (script, data, funcName, pattern, next) { return yield extract (script, data, (file) => { const lines = data ? Extractor.byFuncInData (data, funcName, pattern) : Extractor.byFuncInFile (file, funcName, pattern); return { lines, pattern } }, next); }); exports.byLine = watt (function * (script, data, funcName, line, next) { return yield extract (script, data, (file) => { return data ? Extractor.byLineInData (data, funcName, line) : Extractor.byLineInFile (file, funcName, line); }, next); });
JavaScript
0
@@ -3209,32 +3209,150 @@ %7B%7D));%0A %7D);%0A%0A + this._client.on ('exception', (ex) =%3E %7B%0A this._inspect (() =%3E this._client.reqContinue (() =%3E %7B%7D));%0A %7D);%0A%0A this._client @@ -3530,16 +3530,75 @@ ug-brk)%0A + yield this._client.reqSetExceptionBreak ('all', next);%0A %7D%0A%0A /
bd8eac80b27e15475a586d22ee8f69e9e42f9734
Handle exception
lib/index.js
lib/index.js
var PassThrough = require('stream').PassThrough; var Transform = require('./transform'); var util = require('util'); var PAYLOAD_SIZE = 1024 * 16; function PipeStream(options) { if (!(this instanceof PipeStream)) { return new PipeStream(options); } init(this); this._pipeError = (options && options.pipeError) !== false; this._options = util._extend({objectMode: true}, options); PassThrough.call(this, this._options); } util.inherits(PipeStream, PassThrough); var proto = PipeStream.prototype; var pipe = proto.pipe; proto.src = function(src, pipeOpts) { this._originalStream && this._originalStream.emit('src', src); src.pipe(this, pipeOpts).pipe(this._dest, this._dest.pipeOpts); return this; }; proto.pipe = function(dest, pipeOpts) { var self = this; self._originalStream && self._originalStream.emit('dest', dest); var pipes = self._heads.concat(self._pipes, self._tails); init(self); var passThrough = new PassThrough(this._options); pipe.call(self, passThrough); pipes.unshift(passThrough); dest.pipeOpts = pipeOpts; pipes.push(dest); pipeErrorToDest(self, true); function pipeErrorToDest(src, first) { var needPipeError = self._pipeError && src != dest && (first || (src.pipeOpts && src.pipeOpts.pipeError)) !== false; return needPipeError ? src.on('error', emitDestError) : src; } function emitDestError(err) { dest.emit('error', err); } self._pipeStream(pipes, 1, function(dest) { self.emit('_pipeEnd', dest); }, pipeErrorToDest); return dest; }; proto._pipeStream = function pipeStream(pipes, i, callback, pipeErrorToDest) { var self = this; var pipe = pipes[i]; var src = pipes[i - 1]; if (typeof pipe == 'function') { pipe(src, function(dest) { pipes[i] = pipeErrorToDest(dest); next(); }); } else if (src instanceof PipeStream) { src.once('_pipeEnd', next); src.pipe(pipeErrorToDest(pipe), pipe.pipeOpts); } else { src.pipe(pipeErrorToDest(pipe), pipe.pipeOpts); next(); } function next() { if (i + 1 == pipes.length) { callback(pipe); } else { self._pipeStream(pipes, ++i, callback, pipeErrorToDest); } } }; proto.add = function(pipe, pipeOpts) { pipe.pipeOpts = pipeOpts; this._pipes.push(pipe); return this; }; proto.insert = function(pipe, pipeOpts, index) { if (typeof pipeOpts == 'number') { var tmp = pipeOpts; pipeOpts = index; index = tmp; } pipe.pipeOpts = pipeOpts; typeof index == 'number' ? this._pipes.splice(index, 0, pipe) : this._pipes.push(pipe); return this; }; proto.addHead = function(pipe, pipeOpts) { pipe.pipeOpts = pipeOpts; this._heads.push(pipe); return this; }; proto.prepend = function(pipe, pipeOpts) { pipe.pipeOpts = pipeOpts; this._heads.unshift(pipe); return this; }; proto.addTail = function(pipe, pipeOpts) { pipe.pipeOpts = pipeOpts; this._tails.unshift(pipe); return this; }; proto.append = function(pipe, pipeOpts) { pipe.pipeOpts = pipeOpts; this._tails.push(pipe); return this; }; proto.dest = function(dest, pipeOpts) { dest.pipeOpts = pipeOpts; this._dest = dest; return dest; }; function init(pipeStream) { pipeStream._heads = []; pipeStream._pipes = []; pipeStream._tails = []; } PipeStream.Transform = Transform; PipeStream.wrap = function(stream, dest, options) { return new PipeStream(options).wrapStream(stream, dest, options); }; PipeStream.wrapSrc = function(stream, options) { return PipeStream.wrap(stream, false, options); }; PipeStream.wrapDest = function(stream, options) { return PipeStream.wrap(stream, true, options); }; var keys = Object.keys(proto); var getPayloadSize = function(opts) { var payloadSize = opts && opts.getPayloadSize; return payloadSize > 0 ? payloadSize : PAYLOAD_SIZE; }; proto.wrapStream = function(stream, dest, pipeOpts) { if (typeof pipeOpts == 'boolean' && typeof dest != 'boolean') { var tmp = pipeOpts; pipeOpts = dest; dest = tmp; } this._originalStream = stream; if (dest) { this.dest(stream, pipeOpts); } else { var self = this; var pipe = stream.pipe; var payloadSize = getPayloadSize(pipeOpts); var callbacks = []; var payload; var done; var end = function() { done = true; stream.pause(); stream.removeListener('data', handleData); stream.removeListener('end', end); callbacks.forEach(function(cb) { cb(payload); }); callbacks = []; }; var handleData = function(data) { payload = payload ? Buffer.concat([payload, data]) : data; if (payload.length >= payloadSize) { end(); } }; stream.getPayload = function(cb) { if (done) { return cb(payload); } if (!callbacks.length) { stream.on('data', handleData); stream.on('end', end); } callbacks.push(cb); }; stream.on('dest', function() { end(); payload && self.write(payload); pipe.call(stream, self, pipeOpts); }); } for (var i = 0, key; key = keys[i]; i++) { if (dest ? i != 'pipe' : i != 'src') { stream[key] = this[key].bind(this); } } return stream; }; module.exports = PipeStream;
JavaScript
0.001391
@@ -4240,16 +4240,29 @@ r done;%0A + var err;%0A var @@ -4268,32 +4268,33 @@ end = function( +e ) %7B%0A done = @@ -4300,16 +4300,31 @@ = true;%0A + err = e;%0A st @@ -4382,24 +4382,67 @@ andleData);%0A + stream.removeListener('error', end);%0A stream @@ -4516,24 +4516,29 @@ %0A cb( +err, payload);%0A @@ -4825,16 +4825,21 @@ turn cb( +err, payload) @@ -4875,24 +4875,24 @@ s.length) %7B%0A - stre @@ -4914,24 +4914,57 @@ andleData);%0A + stream.on('error', end);%0A stre
cba260b20c29cc8488cbb47a4b799acafa102c3e
Revert "Security Fix for Remote Code Execution - huntr.dev"
lib/index.js
lib/index.js
'use strict'; const crossSpawn = require('cross-spawn'); const detectStreamKind = require('./detect-stream-kind'); const path = require('path'); /** * Runs either npm or yarn in a child process, depending on whether current process was itself started via * `npm run` or `yarn run`. Passes all command line arguments down to the child process. * * @param {string[]} argv - The argument list to pass to npm/yarn. * @param {object|undefined} [options] Optional. * @param {stream.Readable|null|undefined} options.stdin - * A readable stream to send messages to stdin of child process. * If this is `null` or `undefined`, ignores it. * If this is `process.stdin`, inherits it. * Otherwise, makes a pipe. * Default is `null`. * @param {stream.Writable|null|undefined} options.stdout - * A writable stream to receive messages from stdout of child process. * If this is `null` or `undefined`, cannot send. * If this is `process.stdout`, inherits it. * Otherwise, makes a pipe. * Default is `null`. * @param {stream.Writable|null|undefined} options.stderr - * A writable stream to receive messages from stderr of child process. * If this is `null` or `undefined`, cannot send. * If this is `process.stderr`, inherits it. * Otherwise, makes a pipe. * Default is `null`. * @param {string} options.npmPath - * The path to npm/yarn. * Default is `process.env.npm_execpath` if set, `npm` otherwise. * @param {object} [options.env] - * Environment key-value pairs, replaces the default usage of process.env to spawn child process. * @returns {Promise} * A promise object which becomes fulfilled when npm/yarn child process is finished. */ module.exports = function yarpm(argv, options) { return new Promise((resolve, reject) => { options = options || {}; const stdinKind = detectStreamKind(options.stdin, process.stdin); const stdoutKind = detectStreamKind(options.stdout, process.stdout); const stderrKind = detectStreamKind(options.stderr, process.stderr); const spawnOptions = {stdio: [stdinKind, stdoutKind, stderrKind]}; if (options.env) { spawnOptions.env = options.env; } let execPath; let spawnArgs; if (!options.npmPath || path.extname(options.npmPath) === '.js') { const npmPath = options.npmPath || process.env.npm_execpath; execPath = npmPath ? process.execPath : 'npm'; spawnArgs = npmPath ? [npmPath].concat(argv) : argv; } else { execPath = options.npmPath; spawnArgs = argv; } let cp = crossSpawn(execPath.split(' ')[0],execPath.split(' ').slice(1), spawnArgs, spawnOptions); // Piping stdio. if (stdinKind === 'pipe') { options.stdin.pipe(cp.stdin) } if (stdoutKind === 'pipe') { cp.stdout.pipe(options.stdout, {end: false}); } if (stderrKind === 'pipe') { cp.stderr.pipe(options.stderr, {end: false}); } cp.on('error', err => { cp = null; reject(err); }); cp.on('close', code => { cp = null; resolve({spawnArgs, code}); }); }); };
JavaScript
0
@@ -2568,51 +2568,8 @@ Path -.split(' ')%5B0%5D,execPath.split(' ').slice(1) , sp
1ad35463c04960f238cca8c9dcb4e631aab5447f
Use key, not appGlobal when attaching to data.
lib/index.js
lib/index.js
var fs = require('fs'); var path = require('path'); var minimatch = require('minimatch'); var builder = require('./builder'); var store = {}; var lookupPackageData = function(attrs) { try { var parentRootDir = path.join(__dirname, '../../..'); var loadstar = require(path.join(parentRootDir, 'package')).loadstar; if (loadstar && loadstar.appDir) attrs.appDir = path.resolve(parentRootDir, loadstar.appDir); if (loadstar && loadstar.global) attrs.appGlobal = loadstar.global; } catch (e) { } }; var fetchData = function(key) { var attrs = store[key]; if (!attrs) { attrs = store[key] = { key: key, appDir: null, // Root of the application source tree appGlobal: key, // Global variable as string for defining the app. appList: {}, // List of files that make up the app buildList: {}, // List of files used to build up the app exported: {}, sources: {}, global: {}, defined: {}, transforms: {} }; lookupPackageData(attrs); attrs.global[attrs.appGlobal] = {}; } return attrs; }; var loadstar = function(key, filename, options) { var data = fetchData(key); // Dir we are requiring things from. var baseDir = path.dirname(filename); options = options || {}; if (options.appDir) data.appDir = path.resolve(baseDir, options.appDir); if (!data.appDir) data.appDir = baseDir; data.buildList[filename] = true; // Takes module and a fullpath (without extension), and adds it to the app root. // extendApp(mod, '/src/app/models/User') // eg: app.models.User = mod; var extendApp = function(mod, fullPath) { var relativeToAppDir = path.relative(data.appDir, fullPath); var segments = [data.appGlobal].concat(relativeToAppDir.split('/')); var root = data.global[data.appGlobal]; segments.slice(1, segments.length - 1).forEach(function(seg) { root[seg] = root[seg] || {}; root = root[seg]; }); var last = segments[segments.length - 1]; root[path.basename(last, path.extname(last))] = mod; return segments }; var requireAndAdd = function(requirePath, opts) { var fullPath = path.join(baseDir, requirePath); var mod = require(fullPath); opts.segments = opts.define && extendApp(mod, fullPath); addToApp(fullPath, opts); return mod; }; var addToApp = function(f, opts) { ext = opts.ext || '.js'; var filePath = f.slice(f.length - ext.length) === ext ? f : f+ext; if (!data.appList[filePath]) data.appList[filePath] = opts; }; // Split for dir; list dir; filter on glob; return list of matched files. var glob = function(requirePath) { var dir = path.dirname(requirePath); var filter = minimatch.filter(path.basename(requirePath), {matchBase: true}); return fs.readdirSync(path.join(baseDir, dir)).filter(filter).map(function(p) { return path.join(dir, p); }); }; // Public api. var api = { // Requires the file on both node and the browser, // and extends the global module tree with the result. define: function(requirePath, opts) { opts = opts || {}; opts.define = true; return this.require(requirePath, opts); }, require: function(requirePath, opts) { opts = opts || {}; if (typeof opts.define === 'undefined') opts.define = false; var paths = [requirePath]; if (requirePath.indexOf('*') === -1) { return requireAndAdd(requirePath, opts); } else { var files = glob(requirePath); return files.map(function(p) { return requireAndAdd(p, opts); }); }; }, browser: function(requirePath, opts) { opts = opts || {}; opts.browser = true; requirePath = requirePath[0] === '/' ? requirePath : path.join(baseDir, requirePath); addToApp(requirePath, opts); }, setTransform: function(key, fn) { data.transforms[key] = fn; }, installExpress: function(server, options) { options = options || {}; if (!options.rootDir) options.rootDir = baseDir; options.dev = true; options.prefix = '/dev'; var result = builder.make(data, options); server.use('/dev/', function(req, res) { res.type('application/javascript'); var loader = data.sources[req.path]; res.send(loader ? loader() : 404); }); if (options.app) { server.get(options.app, function(req, res) { res.type('application/javascript'); res.send(result); }); } }, make: function(options) { return builder.make(data, options); } }; api[data.appGlobal] = data.global[data.appGlobal]; return api; }; loadstar.fetchData = fetchData; loadstar.store = store; module.exports = loadstar;
JavaScript
0
@@ -1039,31 +1039,19 @@ .global%5B -attrs.appGlobal +key %5D = %7B%7D;%0A @@ -1787,30 +1787,19 @@ .global%5B -data.appGlobal +key %5D;%0A s @@ -4606,30 +4606,19 @@ %0A%0A api%5B -data.appGlobal +key %5D = data @@ -4625,30 +4625,19 @@ .global%5B -data.appGlobal +key %5D;%0A%0A re
ec53cc2938608b9599eaabf27f6316c3cc91d3e2
replace callbacks with EventEmitters
lib/index.js
lib/index.js
var q = require('q'), _ = require('lodash'), dnode = require('dnode'), net = require('net'), common = require('@screeps/common'), config = Object.assign(common.configManager.config, {storage: new EventEmitter()}), databaseMethods = require('./db'), pubsub = require('./pubsub'), queueMethods = require('./queue'); Object.assign(config.storage, { socketListener(socket) { var connectionDesc = `${socket.remoteAddress}:${socket.remotePort}`; console.log(`[${connectionDesc}] Incoming connection`); socket.on('error', error => console.log(`[${connectionDesc}] Connection error: ${error.message}`)); var pubsubConnection = pubsub.create(); var dnodeServer = dnode(_.extend({}, databaseMethods, queueMethods, pubsubConnection.methods)); socket.on('close', () => { pubsubConnection.close(); console.log(`[${connectionDesc}] Connection closed`); }); socket.pipe(dnodeServer).pipe(socket); } }); module.exports.start = function() { if (!process.env.STORAGE_PORT) { throw new Error('STORAGE_PORT environment variable is not set!'); } if (!process.env.DB_PATH) { throw new Error('DB_PATH environment variable is not set!'); } common.configManager.load(); config.storage.loadDb().then(() => { console.log(`Starting storage server`); var server = net.createServer(config.storage.socketListener); server.on('listening', () => { console.log('Storage listening on', process.env.STORAGE_PORT); if(process.send) { process.send('storageLaunched'); } }); server.listen(process.env.STORAGE_PORT, process.env.STORAGE_HOST || 'localhost'); }) .catch(error => console.error(error)); };
JavaScript
0.000017
@@ -94,24 +94,75 @@ ire('net'),%0A + EventEmitter = require('events').EventEmitter,%0A common =
776d1432eb54331a5d5d29860a26e97a28f8e155
Update index.js
lib/index.js
lib/index.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (superagent) { // don't patch if superagent was patched already if (superagent._patchedBySuperagentMocker) { return init; } superagent._patchedBySuperagentMocker = true; // Patch the end method to shallow the request and return the result var reqProto = superagent.Request.prototype; var oldEnd = reqProto.end; reqProto.end = function end(cb) { // do not use function arrow to access to this.url and this.method var route = routesMap[buildRouteKey(this.method, this.url)]; var reply = route && route.reply; if (reply) { var err = undefined; var res = undefined; if (reply.status >= 400) { err = { status: reply.status, response: reply.result }; } else { res = { status: reply.status, body: reply.result }; } try { cb && cb(err, res); } catch (e) { console.error('callback error', e.stack || e); var response = new superagent.Response({ res: { headers: {}, setEncoding: function setEncoding() {}, on: function on() {} }, req: { method: function method() {} }, xhr: { responseType: '', getAllResponseHeaders: function getAllResponseHeaders() { return 'a header'; }, getResponseHeader: function getResponseHeader() { return 'a header'; } } }); response.setStatusProperties(e.message); cb && cb(e, response); } /* TODO: delay: setTimeout(function() { try { cb && cb(null, current(state.request)); } catch (ex) { cb && cb(ex, null); } }, value(mock.responseDelay));*/ } else { oldEnd.call(this, cb); } }; return init; }; // TODO: unset var methodsMapping = { get: 'GET', post: 'POST', put: 'PUT', del: 'DELETE', patch: 'PATCH' }; var mock = {}; // The base url var baseUrl = undefined; // Routes registry var routesMap = {}; // The current (last defined) route var currentRoute = undefined; function buildRoute(method, url, reply) { return { method: method, url: baseUrl + url, reply: reply }; } function buildRouteKey(httpMethod, url) { return httpMethod + ' ' + url; } function addRoute(method, url) { var route = buildRoute(method, url); var routeKey = buildRouteKey(route.method, route.url); routesMap[routeKey] = route; currentRoute = route; return mock; // chaining } // TODO: mock.delay; // Sugar methods to add routes by http methods Object.keys(methodsMapping).forEach(function (method) { var httpMethod = methodsMapping[method]; mock[method] = addRoute.bind(null, httpMethod); }); // Reply function mock.reply = function (status, result) { if (!currentRoute) { throw new Error('Must call get, post, put, del or patch before reply'); } currentRoute.reply = { status: status, result: result }; return mock; // chaining }; mock.clear = function () { routesMap = {}; return mock; // chaining }; function init() { var requestBaseUrl = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; baseUrl = requestBaseUrl; // Set the baseUrl return mock; }
JavaScript
0.000002
@@ -793,30 +793,28 @@ %09%09%09%09%7D;%0A%09%09%09%7D -else %7B +%0A%09%09%09 %0A%09%09%09%09res = %7B @@ -871,25 +871,24 @@ t%0A%09%09%09%09%7D;%0A%09%09%09 -%7D %0A%0A%09%09%09try %7B%0A%09 @@ -3162,8 +3162,9 @@ mock;%0A%7D +%0A
af2cab3fce30277aca0f9776867e5ff9a81f2d3f
fix db.name for backwards compat
lib/index.js
lib/index.js
'use strict'; var utils = require('./pouch-utils'); var version = require('./version'); var ndj = require('ndjson'); var through = require('through2').obj; var pick = require('lodash.pick'); var toBufferStream = require('./to-buffer-stream'); var DEFAULT_BATCH_SIZE = 50; // params to the replicate() API that the user is allowed to specify var ALLOWED_PARAMS = [ 'batch_size', 'batches_limit', 'filter', 'doc_ids', 'query_params', 'since', 'view' ]; exports.adapters = {}; exports.adapters.writableStream = require('./writable-stream'); exports.plugin = require('pouch-stream'); exports.plugin.dump = utils.toPromise(function (writableStream, opts, callback) { var self = this; /* istanbul ignore else */ if (typeof opts === 'function') { callback = opts; opts = {}; } var PouchDB = self.constructor; var output = new PouchDB(self.name, { adapter: 'writableStream' }); output.setupStream(writableStream); var chain = self.info().then(function (info) { var header = { version: version, db_type: self.type(), start_time: new Date().toJSON(), db_info: info }; writableStream.write(JSON.stringify(header) + '\n'); opts = pick(opts, ALLOWED_PARAMS); if (!opts.batch_size) { opts.batch_size = DEFAULT_BATCH_SIZE; } return self.replicate.to(output, opts); }).then(function () { return output.close(); }).then(function () { callback(null, {ok: true}); }); /* istanbul ignore next */ function onErr(err) { callback(err); } chain.catch(onErr); }); exports.plugin.load = utils.toPromise(function (readableStream, opts, callback) { /* istanbul ignore else */ if (typeof opts === 'function') { callback = opts; opts = {}; } var batchSize; /* istanbul ignore if */ if ('batch_size' in opts) { batchSize = opts.batch_size; } else { batchSize = DEFAULT_BATCH_SIZE; } // We need this variable in order to call the callback only once. // The stream is not closed when the 'error' event is emitted. var error = null; var queue = []; readableStream .pipe(toBufferStream()) .pipe(ndj.parse()) .on('error', function (errorCatched) { error = errorCatched; }) .pipe(through(function (data, _, next) { if (!data.docs) { return next(); } // lets smooth it out data.docs.forEach(function (doc) { this.push(doc); }, this); next(); })) .pipe(through(function (doc, _, next) { queue.push(doc); if (queue.length >= batchSize) { this.push(queue); queue = []; } next(); }, function (next) { if (queue.length) { this.push(queue); } next(); })) .pipe(this.createWriteStream({new_edits: false})) .on('error', callback) .on('finish', function () { callback(error, {ok: true}); }); }); /* istanbul ignore next */ if (typeof window !== 'undefined' && window.PouchDB) { window.PouchDB.plugin(exports.plugin); window.PouchDB.adapter('writableStream', exports.adapters.writableStream); }
JavaScript
0.000003
@@ -834,16 +834,137 @@ uctor;%0A%0A + // db.name replaced db._db_name in pouch 6.0.0%0A /* istanbul ignore next */%0A var dbName = self.name %7C%7C self._db_name;%0A var ou @@ -982,22 +982,19 @@ PouchDB( -self.n +dbN ame, %7B%0A
b1a675c4b56d19287a833415eab27f4b354a96fe
use forEach
lib/index.js
lib/index.js
/* * biojs-io-snparser * https://github.com/jameshiew/biojs-io-snparser * * Copyright (c) 2015 James Hiew * Licensed under the MIT license. */ 'use strict' const csv = require('csv') /** @type {Map<string, object>} */ const dialects = new Map() dialects.set('23andMe-2015-07-22', { auto_parse: true, columns: [ 'rsid', 'chromosome', 'position', 'genotype' ], comment: '#', delimiter: '\t', quote: '' }) const SNP = { /** * Encapsulates a SNP. * * @param {Object} args * @param {Array<string>} args.alleles * @param {string} args.chromosome * @param {int} args.position * @param {string} args.referenceAssembly * @param {string} args.rsid * @param {string} args.strand */ init: function init (args) { this.alleles = args.alleles this.chromosome = args.chromosome this.referenceAssembly = args.referenceAssembly this.rsid = args.rsid this.position = args.position this.strand = args.strand return this } } /** * Parse raw data into SNP Javascript objects. * * @param {Object} options * @param {string} options.data - contents of the raw data set * @param {string} options.format - e.g. '23andMe-2015-07-22' * @return {Array<SNP>} */ module.exports.parse = function parse (options) { options = options || {} // validate arguments const dialect = dialects.get(options.format) if (!dialect) { throw new Error(`Unrecognised format specified: ${options.format}`) } // parse to SNP objects sychronously let snps = [] csv.parse(options.data, dialect, function onFinishedParsing (error, output) { if (error) { throw error } if (options.format === '23andMe-2015-07-22') { for (let rawSnp of output) { snps.push(Object.create(SNP).init({ alleles: rawSnp.genotype.split(''), chromosome: rawSnp.chromosome, position: rawSnp.position, referenceAssembly: 'GRCh37', rsid: rawSnp.rsid.match(/rs\d*/) ? rawSnp.rsid : undefined, strand: '+' })) } } }) return snps }
JavaScript
0.000002
@@ -1517,18 +1517,20 @@ ously%0A -le +cons t snps = @@ -1603,22 +1603,23 @@ (error, -output +rawSnps ) %7B%0A @@ -1716,33 +1716,59 @@ -for (le +rawSnps.forEach(function convertToSNPObjec t +( rawSnp - of output ) %7B%0A @@ -2105,24 +2105,25 @@ %7D))%0A %7D +) %0A %7D%0A %7D)%0A
739fa1573e59dee5c862ecf1f5e0dd71342ddfcc
Use the botstrap logger instead of console for logging
lib/index.js
lib/index.js
var math = require('mathjs'); var ERROR_RESPONSE = 'I can\'t calculate that!'; module.exports = function(argv, response) { var respBody = ERROR_RESPONSE; try { var expression = argv.slice(1).join(''); var result = math.eval(expression); if (typeof result === 'function') { console.error('Somehow got a function in a scalk eval'); } else { respBody = math.eval(expression).toString(); } } catch(e) { console.error(e); } response.end(respBody); }
JavaScript
0
@@ -115,16 +115,24 @@ response +, logger ) %7B%0A va @@ -297,31 +297,30 @@ n') %7B%0A -console +logger .error('Some @@ -454,15 +454,14 @@ -console +logger .err
2f6faf4a1411d24397eae9592611123c2036968e
using comparator
lib/index.js
lib/index.js
export default heapsort; const {floor} = Math; function heapsort(array, comparator=ascendantComparator) { const count = array.length; heapify(array); let end = count - 1; while (end > 0) { swapElems(array, end, 0); end = end - 1; siftDown(array, 0, end); } return array; } function ascendantComparator(a, b) { return a - b; } function heapify(array) { const count = array.length; let start = floor((count - 2) / 2); while (start >= 0) { siftDown(array, start, count - 1); start = start - 1; } } function siftDown(array, start, end) { let root = start; while (root * 2 + 1 <= end) { let child = root * 2 + 1; let swap = root; // comparison here if (array[swap] < array[child]) { swap = child; } if (child + 1 <= end && array[swap] < array[child + 1]) { swap = child + 1; } if (swap === root) { return; } swapElems(array, root, swap); root = swap; } } function swapElems(array, a, b) { const tmp = array[a]; array[a] = array[b]; array[b] = tmp; }
JavaScript
0.998776
@@ -145,16 +145,28 @@ fy(array +, comparator );%0A%0A%09let @@ -272,16 +272,28 @@ , 0, end +, comparator );%0A%09%7D%0A%0A%09 @@ -360,11 +360,32 @@ n a -- b +%3E b ? 1 : a %3C b ? -1 : 0 ;%0A%7D%0A @@ -407,16 +407,28 @@ fy(array +, comparator ) %7B%0A%09con @@ -546,16 +546,28 @@ ount - 1 +, comparator );%0A%09%09sta @@ -619,24 +619,36 @@ , start, end +, comparator ) %7B%0A%09let roo @@ -744,32 +744,22 @@ %0A%0A%09%09 -// +if ( compar -ison here%0A%09%09if +ator (arr @@ -758,34 +758,33 @@ ator(array%5Bswap%5D - %3C +, array%5Bchild%5D) %7B @@ -781,16 +781,24 @@ %5Bchild%5D) + === -1) %7B%0A%09%09%09sw @@ -840,16 +840,27 @@ end && +comparator( array%5Bsw @@ -862,18 +862,17 @@ ay%5Bswap%5D - %3C +, array%5Bc @@ -881,16 +881,21 @@ ld + 1%5D) + %3C 0) %7B%0A%09%09%09sw
63466ff2adfff5ad2fc984e28701dc5baea4d981
Update index.js
lib/index.js
lib/index.js
'use strict'; // Load modules const Stream = require('stream'); const Boom = require('boom'); const Cryptiles = require('cryptiles'); const Hoek = require('hoek'); const Joi = require('joi'); // Declare internals const internals = {}; internals.schema = Joi.object().keys({ key: Joi.string().optional(), size: Joi.number().optional(), autoGenerate: Joi.boolean().optional(), addToViewContext: Joi.boolean().optional(), cookieOptions: Joi.object().keys(null), headerName: Joi.string().optional(), restful: Joi.boolean().optional(), skip: Joi.func().optional(), logUnauthorized: Joi.boolean().optional() }); internals.defaults = { key: 'crumb', size: 43, // Equal to 256 bits autoGenerate: true, // If false, must call request.plugins.crumb.generate() manually before usage addToViewContext: true, // If response is a view, add crumb to context cookieOptions: { // Cookie options (i.e. hapi server.state) path: '/' }, headerName: 'X-CSRF-Token', // Specify the name of the custom CSRF header restful: false, // Set to true for custom header crumb validation. Disables payload/query validation skip: false // Set to a function which returns true when to skip crumb generation and validation, logUnauthorized: false // Set to true for crumb to write an event to the request log }; const register = (server, options) => { Joi.assert(options, internals.schema); const settings = Hoek.applyToDefaults(internals.defaults, options); const routeDefaults = { key: settings.key, restful: settings.restful, source: 'payload' }; server.state(settings.key, settings.cookieOptions); server.ext('onPostAuth', (request, h) => { const unauthorizedLogger = () => { if (settings.logUnauthorized) { request.log(['crumb', 'unauthorized'], 'validation failed'); } }; // If skip function enabled. Call it and if returns true, do not attempt to do anything with crumb. if (settings.skip && settings.skip(request, h)) { return h.continue; } // Validate incoming crumb if (typeof request.route.settings.plugins._crumb === 'undefined') { if (request.route.settings.plugins.crumb || !request.route.settings.plugins.hasOwnProperty('crumb') && settings.autoGenerate) { request.route.settings.plugins._crumb = Hoek.applyToDefaults(routeDefaults, request.route.settings.plugins.crumb || {}); } else { request.route.settings.plugins._crumb = false; } } // Set crumb cookie and calculate crumb if ((settings.autoGenerate || request.route.settings.plugins._crumb) && (request.route.settings.cors ? checkCORS(request) : true)) { generate(request, h); } // Validate crumb let routeIsRestful; if (request.route.settings.plugins._crumb && request.route.settings.plugins._crumb.restful !== undefined) { routeIsRestful = request.route.settings.plugins._crumb.restful; } if (routeIsRestful === false || !routeIsRestful && settings.restful === false) { if (request.method !== 'post' || !request.route.settings.plugins._crumb) { return h.continue; } const content = request[request.route.settings.plugins._crumb.source]; if (!content || content instanceof Stream) { unauthorizedLogger(); throw Boom.forbidden(); } if (content[request.route.settings.plugins._crumb.key] !== request.plugins.crumb) { unauthorizedLogger(); throw Boom.forbidden(); } // Remove crumb delete request[request.route.settings.plugins._crumb.source][request.route.settings.plugins._crumb.key]; } else { if (request.method !== 'post' && request.method !== 'put' && request.method !== 'patch' && request.method !== 'delete' || !request.route.settings.plugins._crumb) { return h.continue; } const header = request.headers[settings.headerName.toLowerCase()]; if (!header) { unauthorizedLogger(); throw Boom.forbidden(); } if (header !== request.plugins.crumb) { unauthorizedLogger(); throw Boom.forbidden(); } } return h.continue; }); server.ext('onPreResponse', (request, h) => { // Add to view context const response = request.response; if (settings.addToViewContext && request.plugins.crumb && request.route.settings.plugins._crumb && !response.isBoom && response.variety === 'view') { response.source.context = response.source.context || {}; response.source.context[request.route.settings.plugins._crumb.key] = request.plugins.crumb; } return h.continue; }); const checkCORS = function (request) { if (request.headers.origin) { return request.info.cors.isOriginMatch; } return true; }; const generate = function (request, h) { let crumb = request.state[settings.key]; if (!crumb) { crumb = Cryptiles.randomString(settings.size); h.state(settings.key, crumb, settings.cookieOptions); } request.plugins.crumb = crumb; return request.plugins.crumb; }; server.expose({ generate }); }; exports.plugin = { pkg: require('../package.json'), register };
JavaScript
0.000002
@@ -1257,25 +1257,25 @@ skip: false - +,
47b5698218b37b246f0c97f173abeb0062525d4f
Return this from customize for chaining.
lib/index.js
lib/index.js
/** * Copyright (c) Microsoft. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; function Snapshot(settings, environments) { var self = this; self.settings = {}; self.environments = {}; Object.keys(settings).forEach(function (key) { self.settings[key] = settings[key]; }); Object.keys(environments).forEach(function (key) { self.environments[key] = environments[key].snapshot(); }); } function Config(parent, defaultEnvVar, initialCustomizer) { var environments = { }; var settings = { }; var customizer = initialCustomizer; if (!defaultEnvVar) { defaultEnvVar = 'NODE_ENV'; } function config(envName) { if (!envName) { return config; } if (!environments[envName]) { environments[envName] = new Config(config, defaultEnvVar, customizer); } return environments[envName]; } config.configure = function (env, callback) { if (arguments.length === 1) { env(this); } else { callback(this(env)); } }; config.customize = function (newCustomizer) { newCustomizer(config); if (!customizer) { customizer = newCustomizer; } else { customizer = (function (oldCustomizer) { return function (c) { oldCustomizer(c); newCustomizer(c); }; }(customizer)); } Object.keys(environments).forEach(function (envName) { environments[envName].customize(newCustomizer); }); }; config.set = function (setting, value) { if (arguments.length === 2) { settings[setting] = function () { return value; }; } else { Object.keys(setting).forEach(function (key) { if (typeof setting[key] === 'function') { settings[key] = setting[key]; } else { settings[key] = function () { return setting[key]; }; } }); } return this; }; config.setFunc = function (setting, getter) { settings[setting] = getter; return this; }; config.get = function (setting) { var args = Array.prototype.slice.apply(arguments); var getter = this._getRaw(setting); if (!getter) { return undefined; } return getter.apply(this, args); }; config.has = function (setting) { return settings.hasOwnProperty(setting) || (!!parent && parent.has(setting)); }; config.snapshot = function () { return new Snapshot(settings, environments); }; config.restore = function (snapshot) { if (!(snapshot instanceof Snapshot)) { throw new Error('Invalid snapshot'); } settings = snapshot.settings; environments = {}; Object.keys(snapshot.environments).forEach(function (key) { config(key).restore(snapshot.environments[key]); }); }; config.tempConfig = function () { return new Config(this, defaultEnvVar, customizer); }; Object.defineProperties(config, { default: { get: function () { return config(process.env[defaultEnvVar]); }, enumerable: true }, environments: { get: function () { return Object.keys(environments); } }, settings: { get: function () { var s = {}; var allSettings = Object.keys(settings).concat(parent ? parent.settings : []); allSettings.forEach(function (setting) { s[setting] = 1; }); return Object.keys(s); } }, _getRaw: { value: function (setting) { if (!settings.hasOwnProperty(setting)) { if (parent) { return parent._getRaw(setting); } return undefined; } return settings[setting]; }, enumerable: false } }); if (customizer) { customizer(config); } return config; } function createConfig(options) { var defaultEnvVar = (options && options.defaultEnvVar) || null; var customizer = (options && options.customizer) || null; return new Config(null, defaultEnvVar, customizer); } exports.createConfig = createConfig;
JavaScript
0
@@ -1589,30 +1589,28 @@ wCustomizer( -config +this );%0A if (! @@ -1955,32 +1955,50 @@ omizer);%0A %7D); +%0A%0A return this; %0A %7D;%0A%0A config.
d8d55f3ef69007c500dec5f654b39b571209ad4e
Remove remaining cast methods & properties
lib/index.js
lib/index.js
import { Platform, AppRegistry, DeviceEventEmitter, NativeEventEmitter, NativeModules } from 'react-native'; import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource'; const { TrackPlayerModule: TrackPlayer } = NativeModules; function resolveAsset(uri) { if(!uri) return undefined; return resolveAssetSource(uri); } function resolveUrl(url) { if(!url) return undefined; return resolveAssetSource(url) || url; } function setupPlayer(options) { return TrackPlayer.setupPlayer(options || {}); } function updateOptions(data) { // Clone the object before modifying it, so we don't run into problems with immutable objects data = Object.assign({}, data); // Resolve the asset for each icon data.icon = resolveAsset(data.icon); data.playIcon = resolveAsset(data.playIcon); data.pauseIcon = resolveAsset(data.pauseIcon); data.stopIcon = resolveAsset(data.stopIcon); data.previousIcon = resolveAsset(data.previousIcon); data.nextIcon = resolveAsset(data.nextIcon); return TrackPlayer.updateOptions(data); } function add(tracks, insertBeforeId) { if(!Array.isArray(tracks)) { tracks = [tracks]; } for(let i = 0; i < tracks.length; i++) { // Clone the object before modifying it tracks[i] = Object.assign({}, tracks[i]); // Resolve the URLs tracks[i].url = resolveUrl(tracks[i].url); tracks[i].artwork = resolveUrl(tracks[i].artwork); // Cast ID's into strings tracks[i].id = `${tracks[i].id}` } return TrackPlayer.add(tracks, insertBeforeId); } function remove(tracks) { if(!Array.isArray(tracks)) { tracks = [tracks]; } return TrackPlayer.remove(tracks); } function warpEventResponse(handler, event, payload) { // transform into headlessTask format and return to handler const additionalKeys = payload || {}; handler({ type: event, ...additionalKeys }); } function registerEventHandler(handler) { const emitter = new NativeEventEmitter(TrackPlayer); const events = [ 'playback-state', 'playback-error', 'playback-queue-ended', 'playback-track-changed', 'remote-play', 'remote-pause', 'remote-stop', 'remote-next', 'remote-previous', 'remote-jump-forward', 'remote-jump-backward', ]; for (let i = 0; i < events.length; i++) { if (Platform.OS !== 'android') { emitter.addListener(events[i], warpEventResponse.bind(null, handler, events[i])); } else { DeviceEventEmitter.addListener(events[i], warpEventResponse.bind(null, handler, events[i])); } } if (Platform.OS === 'android') { AppRegistry.registerHeadlessTask('TrackPlayer', () => handler); } } // We'll declare each one of the constants and functions manually so IDEs can show a list of them // We should also add documentation here, but I'll leave this task to another day // States module.exports.STATE_NONE = TrackPlayer.STATE_NONE; module.exports.STATE_PLAYING = TrackPlayer.STATE_PLAYING; module.exports.STATE_PAUSED = TrackPlayer.STATE_PAUSED; module.exports.STATE_STOPPED = TrackPlayer.STATE_STOPPED; module.exports.STATE_BUFFERING = TrackPlayer.STATE_BUFFERING; // Capabilities module.exports.CAPABILITY_PLAY = TrackPlayer.CAPABILITY_PLAY; module.exports.CAPABILITY_PLAY_FROM_ID = TrackPlayer.CAPABILITY_PLAY_FROM_ID; module.exports.CAPABILITY_PLAY_FROM_SEARCH = TrackPlayer.CAPABILITY_PLAY_FROM_SEARCH; module.exports.CAPABILITY_PAUSE = TrackPlayer.CAPABILITY_PAUSE; module.exports.CAPABILITY_STOP = TrackPlayer.CAPABILITY_STOP; module.exports.CAPABILITY_SEEK_TO = TrackPlayer.CAPABILITY_SEEK_TO; module.exports.CAPABILITY_SKIP = TrackPlayer.CAPABILITY_SKIP; module.exports.CAPABILITY_SKIP_TO_NEXT = TrackPlayer.CAPABILITY_SKIP_TO_NEXT; module.exports.CAPABILITY_SKIP_TO_PREVIOUS = TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS; module.exports.CAPABILITY_JUMP_FORWARD = TrackPlayer.CAPABILITY_JUMP_FORWARD; module.exports.CAPABILITY_JUMP_BACKWARD = TrackPlayer.CAPABILITY_JUMP_BACKWARD; module.exports.CAPABILITY_SET_RATING = TrackPlayer.CAPABILITY_SET_RATING; // Pitch algorithms module.exports.PITCH_ALGORITHM_LINEAR = TrackPlayer.PITCH_ALGORITHM_LINEAR; module.exports.PITCH_ALGORITHM_MUSIC = TrackPlayer.PITCH_ALGORITHM_MUSIC; module.exports.PITCH_ALGORITHM_VOICE = TrackPlayer.PITCH_ALGORITHM_VOICE; // Rating Types module.exports.RATING_HEART = TrackPlayer.RATING_HEART; module.exports.RATING_THUMBS_UP_DOWN = TrackPlayer.RATING_THUMBS_UP_DOWN; module.exports.RATING_3_STARS = TrackPlayer.RATING_3_STARS; module.exports.RATING_4_STARS = TrackPlayer.RATING_4_STARS; module.exports.RATING_5_STARS = TrackPlayer.RATING_5_STARS; module.exports.RATING_PERCENTAGE = TrackPlayer.RATING_PERCENTAGE; // Cast States module.exports.CAST_NO_DEVICES_AVAILABLE = TrackPlayer.CAST_NO_DEVICES_AVAILABLE; module.exports.CAST_NOT_CONNECTED = TrackPlayer.CAST_NOT_CONNECTED; module.exports.CAST_CONNECTING = TrackPlayer.CAST_CONNECTING; module.exports.CAST_CONNECTED = TrackPlayer.CAST_CONNECTED; // General module.exports.setupPlayer = setupPlayer; module.exports.destroy = TrackPlayer.destroy; module.exports.updateOptions = updateOptions; module.exports.registerEventHandler = registerEventHandler; // Player Queue Commands module.exports.add = add; module.exports.remove = remove; module.exports.skip = TrackPlayer.skip; module.exports.getQueue = TrackPlayer.getQueue; module.exports.skipToNext = TrackPlayer.skipToNext; module.exports.skipToPrevious = TrackPlayer.skipToPrevious; module.exports.removeUpcomingTracks = TrackPlayer.removeUpcomingTracks; // Player Playback Commands module.exports.reset = TrackPlayer.reset; module.exports.play = TrackPlayer.play; module.exports.pause = TrackPlayer.pause; module.exports.stop = TrackPlayer.stop; module.exports.seekTo = TrackPlayer.seekTo; module.exports.setVolume = TrackPlayer.setVolume; module.exports.setRate = TrackPlayer.setRate; // Player Getters module.exports.getTrack = TrackPlayer.getTrack; module.exports.getCurrentTrack = TrackPlayer.getCurrentTrack; module.exports.getVolume = TrackPlayer.getVolume; module.exports.getDuration = TrackPlayer.getDuration; module.exports.getPosition = TrackPlayer.getPosition; module.exports.getBufferedPosition = TrackPlayer.getBufferedPosition; module.exports.getState = TrackPlayer.getState; module.exports.getRate = TrackPlayer.getRate; // Cast Getters module.exports.getCastState = TrackPlayer.getCastState; // Components module.exports.ProgressComponent = require('./ProgressComponent');
JavaScript
0
@@ -4838,296 +4838,8 @@ E;%0A%0A -// Cast States%0Amodule.exports.CAST_NO_DEVICES_AVAILABLE = TrackPlayer.CAST_NO_DEVICES_AVAILABLE;%0Amodule.exports.CAST_NOT_CONNECTED = TrackPlayer.CAST_NOT_CONNECTED;%0Amodule.exports.CAST_CONNECTING = TrackPlayer.CAST_CONNECTING;%0Amodule.exports.CAST_CONNECTED = TrackPlayer.CAST_CONNECTED;%0A%0A // G @@ -6184,81 +6184,8 @@ e;%0A%0A -// Cast Getters%0Amodule.exports.getCastState = TrackPlayer.getCastState;%0A%0A // C
b5aa3e5cf13f12eebfeeb95140d8f07f58de5cfa
Fix domain
lib/index.js
lib/index.js
'use strict'; var request = require('request'); var fs = require('fs'); var path = require('path'); var urls = require('./urls'); function kintone(domain, authorization) { var fullDomain = domain + '.cybozu.com'; function requestBase(link, data, callback) { var method = link.pop(); link.unshift(fullDomain, 'k', 'v1'); var options = { url: 'https://' + link.join('/') + '.json', method: method.toUpperCase(), headers: { 'Content-Type': 'application/json', 'X-Cybozu-Authorization': authorization, }, body: JSON.stringify(data) }; request(options, function(err, response, body) { callback(err, response, JSON.parse(body)); }); } for (var i = 0; i < urls.length; ++i) { var link = urls[i].split('/'); var head = kintone.prototype; while (link.length !== 0) { var key = link.shift(); if (!head.hasOwnProperty(key)) { head[key] = {}; } if (link.length !== 0) { head = head[key]; } else { head[key] = (function(linkStr) { return function(data, callback) { return requestBase(linkStr, data, callback); }; }(urls[i].split('/'))); } } } kintone.prototype.file.post = function(filename, callback) { var options = { url: 'https://' + fullDomain + '/k/v1/file.json', headers: { 'X-Cybozu-Authorization': authorization }, method: 'POST', formData: { file: { value: fs.createReadStream(filename), options: { filename: path.basename(filename), contentType: 'text/plain' } } } }; request(options, function(err, response, body) { callback(err, response, JSON.parse(body)); }); }; } module.exports = kintone;
JavaScript
0.000017
@@ -173,24 +173,48 @@ %7B%0A -var fullDomain = +if (!domain.match('cybozu%5C%5C.com')) %7B%0A dom @@ -218,16 +218,17 @@ domain + += '.cyboz @@ -234,16 +234,20 @@ zu.com'; +%0A %7D %0A%0A func @@ -334,21 +334,17 @@ unshift( -fullD +d omain, ' @@ -1371,13 +1371,9 @@ ' + -fullD +d omai
3cc2aa6efee9ed7818a78dcbb35eee5304c6b780
change this to print out all tags
lib/index.js
lib/index.js
// Load modules var Util = require('util'); var GoodReporter = require('good-reporter'); var Hoek = require('hoek'); var Moment = require('moment'); var SafeStringify = require('json-stringify-safe'); // Declare internals var internals = {}; module.exports = internals.GoodConsole = function (events, options) { Hoek.assert(this.constructor === internals.GoodConsole, 'GoodConsole must be created with new'); options = options || {}; var settings = Hoek.clone(options); GoodReporter.call(this, events, settings); }; Hoek.inherits(internals.GoodConsole, GoodReporter); internals.GoodConsole.timeString = function (timestamp) { var m = Moment.utc(timestamp); return m.format('YYMMDD/HHmmss.SSS'); }; internals.printEvent = function (event) { var timestring = internals.GoodConsole.timeString(event.timestamp); var data = event.data; if (typeof event.data === 'object' && event.data) { data = SafeStringify(event.data); } var output = timestring + ', ' + event.tags[0] + ', ' + data; console.log(output); }; internals.printRequest = function (event) { var query = event.query ? SafeStringify(event.query) : ''; var responsePayload = ''; var statusCode = ''; if (typeof event.responsePayload === 'object' && event.responsePayload) { responsePayload = 'response payload: ' + SafeStringify(event.responsePayload); } var methodColors = { get: 32, delete: 31, put: 36, post: 33 }; var color = methodColors[event.method] || 34; var method = '\x1b[1;' + color + 'm' + event.method + '\x1b[0m'; if (event.statusCode) { color = 32; if (event.statusCode >= 500) { color = 31; } else if (event.statusCode >= 400) { color = 33; } else if (event.statusCode >= 300) { color = 36; } statusCode = '\x1b[' + color + 'm' + event.statusCode + '\x1b[0m'; } internals.printEvent({ timestamp: event.timestamp, tags: ['request'], //instance, method, path, query, statusCode, responseTime, responsePayload data: Util.format('%s: %s %s %s %s (%sms) %s', event.instance, method, event.path, query, statusCode, event.responseTime, responsePayload) }); }; internals.GoodConsole.prototype._report = function (event, eventData) { if (event === 'ops') { internals.printEvent({ timestamp: eventData.timestamp, tags: ['ops'], data: 'memory: ' + Math.round(eventData.proc.mem.rss / (1024 * 1024)) + 'Mb, uptime (seconds): ' + eventData.proc.uptime + ', load: ' + eventData.os.load }); } else if (event === 'request') { internals.printRequest(eventData); } else if (event === 'error') { internals.printEvent({ timestamp: eventData.timestamp, tags: ['internalError'], data: 'message: ' + eventData.message + ' stack: ' + eventData.stack }); } else { internals.printEvent(eventData); } };
JavaScript
0.000022
@@ -1024,11 +1024,19 @@ tags -%5B0%5D +.toString() + '
0a712a9dc7b61e56eee6e1c25fc28b62c88c041b
Replace \r\n with \n
lib/index.js
lib/index.js
var Mehdown; if (typeof exports === 'object' && typeof require === 'function') { Mehdown = exports; } else { Mehdown = {}; } Mehdown.usernameRegExp = /(^|[^@\w])@(\w{1,15})\b/g; Mehdown.parse = function(text) { // Replace single newlines with <br /> tags: http://stackoverflow.com/questions/18011260/regex-to-match-single-new-line-regex-to-match-double-new-line text = text.replace(/(^|[^\r\n])\r\n(?!\r\n)/g, '$1<br />'); // Hashtags text = text.replace(/(^|[^#\w])#([a-z0-9_-]+)\b/gi, '$1' + Mehdown.hashtag('$2')); // Usernames text = text.replace(Mehdown.usernameRegExp, '$1' + Mehdown.username('$2')); return text; }; Mehdown.hashtag = function(hashtag) { return '<a href="https://mediocre.com/tags/' + hashtag + '">#' + hashtag + '</a>'; } Mehdown.username = function(username) { //return '<span class="vcard"><a href="https://mediocre.com/forums/users/' + username + '">@<span class="fn nickname">' + username + '</span></a>'; return '<a href="/brenner/users/' + username + '">@' + username + '</a>'; }
JavaScript
0.999999
@@ -370,16 +370,56 @@ ew-line%0A + text = text.replace(/%5Cr%5Cn/g, '%5Cn');%0A text @@ -445,23 +445,17 @@ %7C%5B%5E%5C -r%5C n%5D)%5C -r%5C n(?!%5C -r%5C n)/g
39ea95037158ed7a7670ac469c494adef6c0f3d7
Bump pngcrush version to 1.7.83
lib/index.js
lib/index.js
'use strict'; var BinWrapper = require('bin-wrapper'); var path = require('path'); var pkg = require('../package.json'); /** * Variables */ var BIN_VERSION = '1.7.82'; var BASE_URL = 'https://raw.githubusercontent.com/imagemin/pngcrush-bin/v' + pkg.version + '/vendor/'; /** * Initialize a new BinWrapper */ var bin = new BinWrapper({ progress: false }) .src(BASE_URL + 'osx/pngcrush', 'darwin') .src(BASE_URL + 'linux/pngcrush', 'linux') .src(BASE_URL + 'win/x64/pngcrush.exe', 'win32', 'x64') .src(BASE_URL + 'win/x86/pngcrush.exe', 'win32', 'x86') .dest(path.join(__dirname, '../vendor')) .use(process.platform === 'win32' ? 'pngcrush.exe' : 'pngcrush'); /** * Module exports */ module.exports = bin; module.exports.v = BIN_VERSION;
JavaScript
0
@@ -162,17 +162,17 @@ = '1.7.8 -2 +3 ';%0Avar B
89b82b20fd07375598f8912cbdd642ab10840626
lib/index.js
lib/index.js
'use strict'; var Q = require('q'); var sort = require('./sort.js'); var path = require('path'); var angularFilesort = function(emitter, logger, basePath, config) { config = typeof config === 'object' ? config : {}; var log = logger.create('karma-angular-filesort'); // Normalize whitelist paths against basePath config.whitelist = (config.whitelist || []).map(function (subPath) { return path.resolve(basePath, subPath); }); // The file list is sorted by intercepting the file_list_modified event as Vojta Jina describes here: // https://github.com/karma-runner/karma/issues/851#issuecomment-30290071 var originalEmit = emitter.emit; emitter.emit = function (event, promise) { if (event === 'file_list_modified') { originalEmit.call(emitter, event, Q.Promise(function (resolve) { promise.then(function (files) { // Only included files are sorted, as they're the ones loaded into the document files.included = sort(files.included, log, config); resolve(files); }); })); } else { originalEmit.apply(emitter, arguments); } }; }; angularFilesort.$inject = ['emitter', 'logger', 'config.basePath', 'config.angularFilesort']; module.exports = { 'framework:angular-filesort': ['factory', angularFilesort] };
JavaScript
0
@@ -675,23 +675,21 @@ (event, -promise +files ) %7B%0A%09%09if @@ -728,114 +728,8 @@ ) %7B%0A -%09%09%09originalEmit.call(emitter, event, Q.Promise(function (resolve) %7B%0A%09%09%09%09promise.then(function (files) %7B%0A%09%09 %09%09%09/ @@ -810,18 +810,16 @@ ment%0A%09%09%09 -%09%09 files.in @@ -869,38 +869,57 @@ %0A%09%09%09 -%09%09resolve(files);%0A%09%09%09%09%7D);%0A%09%09%09%7D +originalEmit.call(emitter, event, Q.resolve(files ));%0A
1ab465724cf65ca2668fe984b9bbbc743552e5a6
Improved date.since() output
lib/index.js
lib/index.js
/* Helper functions */ (function(helpers, global) { "use strict"; var is = (typeof require !== 'undefined') ? require('nor-is') : global && global.nor_is; if(!is) { throw new TypeError("nor-date requires nor-is"); } /* Get current time */ helpers.now = function() { return new Date(); }; /** Get time since `time` and `now` as a long human readable string */ helpers.longSince = function(time, now) { if(!time) { throw new TypeError("bad arguments"); } now = now || new Date(); var secs = Math.abs(Math.floor( (now.getTime()/1000) - (time.getTime()/1000) )); var mins = Math.floor(secs/60); var hours = Math.floor(mins/60); mins -= hours*60; secs -= hours*3600 + mins*60; var items = [ [hours, 'tuntia'], [mins, 'minuuttia'], [secs, 'sekuntia'] ]; items = items.filter(function(item) { return (item[0] !== 0) ? true : false; }).map(function(item) { return item.join(' '); }); items.push( (now.getTime() < time.getTime()) ? 'jäljellä' : 'sitten' ); return items.join(' '); }; /** Get time since `time` and `now` as a short human readable string */ helpers.since = function(time, now, labels) { if(!time) { throw new TypeError("bad arguments"); } function d(n) { return ((''+n).length === 1) ? '0'+n : n; } if(is.array(now)) { labels = now; now = undefined; } now = now || new Date(); if(!is.array(labels)) { labels = ['Jäljellä: ', 'Mennyt: ']; } if(labels.length < 2) { throw new TypeError("bad arguments: labels too few"); } var secs = Math.abs(Math.floor( (now.getTime()/1000) - (time.getTime()/1000) )); var mins = Math.floor(secs/60); var hours = Math.floor(mins/60); mins -= hours*60; secs -= hours*3600 + mins*60; var items = []; items.push( (now.getTime() < time.getTime()) ? (labels[0]) : (labels[1]) ); if(hours > 0) { items.push(hours, ':', d(mins), ':', d(secs) ); } else if(mins > 0) { items.push(mins, ':', d(secs)); } else if(secs > 0) { items.push(secs, ' s'); } return items.join(''); }; }( (typeof module === 'undefined') ? (this.nor_date = {}) : (module.exports={}) , this )); /* EOF */
JavaScript
0.999999
@@ -1377,21 +1377,19 @@ ll%C3%A4: - ', ' -Mennyt: +Loppui: '%5D;%0A @@ -1474,16 +1474,84 @@ w%22); %7D%0A%0A +%09var bid_active = (now.getTime() %3C time.getTime()) ? true : false;%0A%0A %09var sec @@ -1758,16 +1758,17 @@ s = %5B%5D;%0A +%0A %09items.p @@ -1777,38 +1777,18 @@ h( ( -now.getTime() %3C time.getTime() +bid_active ) ? @@ -1813,24 +1813,43 @@ els%5B1%5D) );%0A%0A +%09if(bid_active) %7B%0A%09 %09if(hours %3E @@ -1845,32 +1845,36 @@ if(hours %3E 0) %7B +%0A%09%09%09 items.push(hours @@ -1872,25 +1872,25 @@ ush(hours, ' -: +h ', d(mins), @@ -1890,17 +1890,19 @@ mins), ' -: +min ', d(sec @@ -1907,15 +1907,21 @@ ecs) - ); %7D%0A%09 +, 's' );%0A%09%09%7D else @@ -1927,33 +1927,36 @@ e if(mins %3E 0) %7B - +%0A%09%09%09 items.push(mins, @@ -1957,17 +1957,19 @@ (mins, ' -: +min ', d(sec @@ -1970,22 +1970,29 @@ d(secs) +, 's' ); -%7D %0A%09 +%09%7D else if( @@ -2002,17 +2002,20 @@ s %3E 0) %7B - +%0A%09%09%09 items.pu @@ -2028,14 +2028,165 @@ s, ' - s'); +s');%0A%09%09%7D%0A%09%7D else %7B%0A%09%09items.push( time.getDate() + '.' + (1+time.getMonth()) + '.' + time.getFullYear(), 'klo', time.getHours() + ':' + time.getMinutes() );%0A%09 %7D%0A%0A%09 @@ -2204,16 +2204,17 @@ s.join(' + ');%0A%7D;%0A%0A
aeecf1cd2c11de8dcdb9ecd64137a2ef2933052f
Use child_process.exec instead of spawn to execute jobs
lib/index.js
lib/index.js
var readline = require("readline"); var fs = require("fs"); var childProcess = require("child_process"); var CronJob = require("cron").CronJob; var parseCrontabRe = new RegExp(/^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)$/); function parseCrontab(line){ var matched = parseCrontabRe.exec(line); if (!matched) { throw Error("Failed to parse crontab line: " + line); } return { cronTime: [ matched[1], matched[2], matched[3], matched[4], matched[5], matched[6] ].join(" "), command: matched[7] } } exports.start = function(crontab, opts){ var exitOnFailure = Boolean(opts.exitOnFailure); var rl = readline.createInterface({ input: fs.createReadStream(crontab) }); rl.on("line", function(line){ if (line.match(/^#/)) { return; } var parsed = parseCrontab(line); var job = new CronJob({ cronTime: parsed.cronTime, onTick: function(){ var proc = childProcess.spawn(parsed.command, { shell: true, stdio: ["ignore", "pipe", "pipe"] }); proc.stdout.on('data', function(data){ console.log(parsed.command + " | stdout: " + data.toString().trim()); }); proc.stderr.on('data', function(data){ console.log(parsed.command + " | stderr: " + data.toString().trim()); }); proc.on('close', function(code){ console.log(parsed.command + " | exited with code " + code.toString()); if (exitOnFailure && code !== 0) { console.log("Aborting."); process.exit(code); } }); }, start: true }); console.dir(parsed); }); };
JavaScript
0
@@ -1054,31 +1054,13 @@ ess. -spawn(parsed.command, %7B +exec( %0A @@ -1080,19 +1080,22 @@ -shell: true +parsed.command ,%0A @@ -1116,283 +1116,145 @@ -stdio: %5B%22ignore%22, %22pipe%22, %22pipe%22%5D%0A %7D);%0A%0A proc.stdout.on('data', function(data)%7B%0A console.log(parsed.command + %22 %7C stdout: %22 + data.toString().trim());%0A %7D);%0A proc.stderr.on('data', function(data)%7B%0A +%7B%7D,%0A function(err, stdout, stderr)%7B%0A console.log(parsed.command + %22 %7C stdout: %22 + stdout);%0A @@ -1318,30 +1318,14 @@ %22 + -data.toString().trim() +stderr );%0A @@ -1330,37 +1330,32 @@ %0A - %7D);%0A @@ -1351,48 +1351,27 @@ - proc.on('close', function(code)%7B%0A +if (err) %7B%0A @@ -1472,16 +1472,28 @@ + + err. code.toS @@ -1526,43 +1526,131 @@ -if (exitOnFailure && code !== 0) %7B%0A + console.log(%22Aborting.%22);%0A process.exit(err.code);%0A %7D else %7B%0A @@ -1677,37 +1677,53 @@ console.log( -%22Aborting. +parsed.command + %22 %7C exited %22) -; %0A @@ -1739,27 +1739,9 @@ -process.exit(code); +%7D %0A @@ -1751,32 +1751,32 @@ %7D%0A + @@ -1767,33 +1767,32 @@ -%7D );%0A %7D
ea500cd547bc1ab34736a3ae7e22f67e2e5084e2
Update code comment
lib/index.js
lib/index.js
'use strict'; // MODULES // var pinf = require( 'const-pinf-float64' ); var ninf = require( 'const-ninf-float64' ); var abs = require( 'math-abs' ); var floor = require( 'math-floor' ); var rpad = require( 'utils-right-pad-string' ); var lpad = require( 'utils-left-pad-string' ); var repeat = require( 'utils-repeat-string' ); var div2 = require( './div2.js' ); var mult2 = require( './mult2.js' ); // CONSTANTS // var BIAS = 1023; // exponent bias => (2**11)/2 - 1 // BITS // /** * FUNCTION: bits( x ) * Returns a string giving the literal bit representation of a double-precision floating-point number. * * @param {Number} x - input value * @returns {String} bit representation */ function bits( x ) { var nbits; var sign; var str; var exp; var n; var f; var i; // Check for a negative value or negative zero... if ( x < 0 || 1/x === ninf ) { sign = '1'; } else { sign = '0'; } // Special case: +- infinity if ( x === pinf || x === ninf ) { // Based on IEEE754-1985... exp = repeat( '1', 11 ); // all 1s str = repeat( '0', 52 ); // all 0s return sign + exp + str; } // Special case: NaN if ( x !== x ) { // Based on IEEE754-1985... exp = repeat( '1', 11 ); // all 1s str = '1' + repeat( '0', 51 ); // can't be all 0s return sign + exp + str; } // Special case: +-0 if ( x === 0 ) { // Based on IEEE754-1985... exp = repeat( '0', 11 ); // all 0s str = repeat( '0', 52 ); // all 0s return sign + exp + str; } x = abs( x ); // Isolate the integer part (digits before the decimal): n = floor( x ); // Isolate the fractional part (digits after the decimal): f = x - n; // Convert the integer and fractional parts to bit strings: n = div2( n ); f = mult2( f ); // Determine the exponent needed to normalize the integer+fractional parts... if ( n ) { // Move the decimal `d` digits to the left: exp = n.length - 1; } else { // Find the first '1' bit... for ( i = 0; i < f.length; i++ ) { if ( f[ i ] === '1' ) { nbits = i + 1; break; } } // Move the decimal `d` digits to the right: exp = -nbits; } // Normalize the combined integer+fractional string... str = n + f; if ( exp < 0 ) { // Handle subnormals... if ( exp < -BIAS ) { // Cap the number of bits removed: nbits = BIAS - 1; } // Remove all leading zeros and the first '1' for normal values, and, for subnormals, remove at most BIAS-1 leading bits: str = str.substring( nbits ); } else { // Remove the leading '1' (implicit/hidden bit): str = str.substring( 1 ); } // Convert the exponent to a bit string: exp = div2( exp + BIAS ); exp = lpad( exp, 11, '0' ); // Fill in any trailing zeros and ensure we have only 52 fraction bits: str = rpad( str, 52, '0' ).substring( 0, 52 ); // Return a bit representation: return sign + exp + str; } // end FUNCTION bits() // EXPORTS // module.exports = bits;
JavaScript
0
@@ -918,17 +918,16 @@ case: +- - infinity
62efbd8c99719f5a4d715b3990a82c8ee54407c6
check if server is defined
lib/index.js
lib/index.js
var _ = require('lodash'), semver = require('semver'); exports.create = function (Arrow) { var min = '1.7.0'; if (semver.lt(Arrow.Version || '0.0.1', min)) { throw new Error('This connector requires at least version ' + min + ' of Arrow; please run `appc use latest`.'); } var Connector = Arrow.Connector, Capabilities = Connector.Capabilities; var server = Arrow.getGlobal(); /** * Register a custom api endpoint with the application * This should be done after the app registers all Models (inlucing customsearch Model) */ server.on('starting', function () { require('./api/searchQuery.js'); }); return Connector.extend({ filename: module.filename, capabilities: [ Capabilities.ConnectsToADataSource, Capabilities.ValidatesConfiguration, Capabilities.ContainsModels, // Capabilities.CanRetrieve ] }); };
JavaScript
0.000002
@@ -79,17 +79,16 @@ function - (Arrow) @@ -579,16 +579,38 @@ */%0A + if (server) %7B%0A serv @@ -639,14 +639,17 @@ tion - () %7B%0A + @@ -689,19 +689,29 @@ ');%0A + -%7D); + %7D);%0A %7D %0A%0A re
e1afde2721be170f0bfd6d5dc934ed567a91fd28
fix logging of error objects as meta-data
lib/index.js
lib/index.js
var util = require('util') var winston = require('winston') var Transport = winston.Transport var common = require('winston/lib/winston/common') var _dirname = require('path').dirname var LogseneJS = require('logsene-js') var flat = require('flat') var Logsene = function (options) { Transport.call(this, options) options = options || {} this.handleExceptions = options.handleExceptions this.exitOnError = options.exitOnError this.errorOutput = [] this.writeOutput = [] this.flatOptions = options.flatOptions || {safe: true, delimiter: '_'} this.json = options.json || false this.colorize = options.colorize || false this.prettyPrint = options.prettyPrint || false this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false this.label = options.label || null this.source = options.source || (process.mainModule ? null : _dirname(process.mainModule.filename)) || module.filename this.rewriter = options.rewriter || null if (this.json) { this.stringify = options.stringify || function (obj) { return JSON.stringify(obj, null, 2) } } this.logger = new LogseneJS(options.token, options.type || 'winston_logsene', options.url) var self = this this.logger.on('error', function (err) { self.emit('error', err) }) this.logger.on('log', function (data) { self.emit('logged', data) self.emit('flush', data) }) } // // Inherit from `winston.Transport`. // util.inherits(Logsene, winston.Transport) // // Expose the name of this Transport on the prototype // Logsene.prototype.name = 'Logsene' // // ### function log (level, msg, [meta], callback) // #### @level {string} Level at which to log the message. // #### @msg {string} Message to log // #### @meta {Object} **Optional** Additional metadata to attach // #### @callback {function} Continuation to respond to when complete. // Core logging method exposed to Winston. Metadata is optional. // Logsene.prototype.log = function (level, msg, meta, callback) { if (this.silent) { return callback(null, true) } if (meta && (!meta['source'])) { meta.source = this.source } if (this.rewriter){ meta = this.rewriter(level, msg, meta) } if (!msg && meta instanceof Error) { msg = meta.message + '\n' + meta.stack } var output = common.log({ colorize: this.colorize, json: this.json, level: level, message: msg, meta: meta, stringify: this.stringify, timestamp: this.timestamp, prettyPrint: this.prettyPrint, raw: this.raw, label: this.label }) this.logger.log(level, msg, flat(meta, this.flatOptions), callback) if (level === 'error' || level === 'debug') { this.errorOutput.push(output) } else { this.writeOutput.push(output) } } Logsene.prototype.clearLogs = function () { // not required ? } module.exports = Logsene module.exports.Logsene = Logsene
JavaScript
0.000036
@@ -335,16 +335,59 @@ s %7C%7C %7B%7D%0A + this.logsene_debug=options.logsene_debug%0A this.h @@ -2045,16 +2045,38 @@ back) %7B%0A + var metaData = meta%0A if (th @@ -2084,24 +2084,24 @@ s.silent) %7B%0A - return c @@ -2272,16 +2272,8 @@ if ( -!msg && meta @@ -2301,46 +2301,127 @@ -msg = meta.message + '%5Cn' + meta.stack +if (!msg) %7B%0A msg = meta.stack %7C%7C meta.message %0A %7D %0A metaData = %7Berror_stack: meta.stack %7C%7C meta.message%7D %0A %7D @@ -2549,16 +2549,20 @@ ta: meta +Data ,%0A st @@ -2601,16 +2601,30 @@ estamp: +new Date(), // this.tim @@ -2708,24 +2708,82 @@ .label%0A %7D)%0A + if (this.logsene_debug) %7B%0A console.log(output) %0A %7D%0A this.logge @@ -2809,16 +2809,20 @@ lat(meta +Data , this.f
7a5d54bd9039a7e94f608185ac4d53a9205b5e63
Fix service uuids
lib/nuimo.js
lib/nuimo.js
var noble = require('noble'); function Nuimo() { // Private members var handlers = undefined; var ledMatrix = undefined; // Public members this.createDataForLedMatrix = createDataForLedMatrix; this.init = init; this.writeToLEDs = writeToLEDs; this.SERVICES = { LED_MATRIX: 'f29b1523cb1940f3be5c7241ecb82fd1', USER_INPUT: 'f29b1525cb1940f3be5c7241ecb82fd2' }; this.CHARACTERISTICS = { BATTERY: '00002a1900001000800000805f9b34fb', DEVICE_INFO: '00002a2900001000800000805f9b34fb', LED_MATRIX: 'f29b1524cb1940f3be5c7241ecb82fd1', ROTATION: 'f29b1528cb1940f3be5c7241ecb82fd2', BUTTON_CLICK: 'f29b1529cb1940f3be5c7241ecb82fd2', SWIPE: 'f29b1527cb1940f3be5c7241ecb82fd2', FLY: 'f29b1526cb1940f3be5c7241ecb82fd2' }; this.EVENTS = { Connected: 'Connected', Disconnected: 'Disconnected' }; // Implementations: function writeToLEDs(data){ if(ledMatrix){ ledMatrix.write(data); } else { console.log("Can't writeToLEDs yet.") } }; function createDataForLedMatrix(data, brightness, duration){ if(arguments.length != 3){ throw 'createDataForLedMatrix requires three arguments'; } var strData = ''; if(data instanceof Array){ strData = data.join(''); } else { strData = data; } var tempArr = strData.split('').filter(x => x === '1' || x === '0'); if(strData.length != 81) throw 'data must be 81 bits'; if(brightness < 0 || brightness > 255) throw 'brightness must be between 0 and 255'; if(duration < 0 || duration > 255) throw 'duration must be between 0 and 255'; var output = []; while(tempArr.length > 0){ var temp = parseInt(tempArr.splice(0,8).reverse().join(''), 2); output.push(temp); } output.push(brightness); output.push(duration); return new Buffer(output); } function init(handlers){ handlers = handlers; noble.on('stateChange', state => { if (state === 'poweredOn') { noble.startScanning(['180F', '180A'], false); } else { noble.stopScanning(); } }); noble.on('discover', p => { p.connect(err => { if(err) return; if (handlers[this.EVENTS.Connected]){ handlers[this.EVENTS.Connected](p); } p.discoverServices([this.SERVICES.LED_MATRIX, this.SERVICES.USER_INPUT], (err, services) => { for(var service of services){ var nuimoChars = Object.keys(this.CHARACTERISTICS).map(prop => this.CHARACTERISTICS[prop]); service.discoverCharacteristics(nuimoChars, (err, characteristics) => { characteristics.forEach(c => { if(c.uuid == this.CHARACTERISTICS.LED_MATRIX){ ledMatrix = c; } if(handlers[c.uuid]){ if(c.properties.indexOf('notify') > -1){ c.on('read', (data, isNotification) => { handlers[c.uuid](this, data, c); }); c.notify(true); } else if (c.properties.indexOf('write') > -1){ handlers[c.uuid](this, c); } } }); }); } }); }); p.once('disconnect', () => { if (handlers[this.EVENTS.Disconnected]){ handlers[this.EVENTS.Disconnected](p); } noble.startScanning(['180F', '180A'], false); }); }); } } module.exports = Nuimo;
JavaScript
0.000007
@@ -2358,33 +2358,33 @@ anning(%5B'180 -F +f ', '180 -A +a '%5D, false);%0A @@ -4258,17 +4258,17 @@ '180 -F +f ', '180 -A +a '%5D,
6cc119d6ef52e7f2d109f9d7e7f5ccabccb3afa6
Create new file on enter and no selection
lib/panel.js
lib/panel.js
'use babel' import R from 'ramda' import Bacon from 'baconjs' import React from 'react-for-atom' import Path from 'path' import * as atoms from './atom-streams' import DisposableValues from './disposable-values' import PanelComponent from './react/panel' // Wrap the panel component, bridges between Atom context and the React panel component class Panel { constructor (project) { this._panelElement = document.createElement('div') this._atomPanel = atom.workspace.addTopPanel({item: this._panelElement}) const focusOnSearchStream = atoms.createCommandStream('atom-workspace', 'notational:focus-on-search') const togglePanelStream = atoms.createCommandStream('atom-workspace', 'notational:toggle-panel') const focusBus = new Bacon.Bus() focusBus.plug(Bacon.mergeAll( focusOnSearchStream, togglePanelStream, // Focus on search when panel changes visibility (to visible) atoms.createStream(this._atomPanel, 'onDidChangeVisible').filter(R.identity), // Focus on search when active editor gets focus (e.g. on click or other model cancels) atoms.createStream(atom.workspace, 'onDidChangeActivePaneItem').filter(item => item === this._previewEditor), )) const reactPanel = React.render( <PanelComponent focusStream={focusBus} bodyHeightStream={atoms.createConfigStream('notational.bodyHeight')} resultsProp={project.resultsProp} openProjectPathStream={project.openProjectPathStream} parsedprojectPathStream={project.parsedprojectPathStream} />, this._panelElement) project.queryBus.plug( Bacon.combineTemplate({ searchStr: reactPanel.searchProp, paginationOffset: reactPanel.paginationOffsetProp, paginationSize: reactPanel.paginationSizeProp }) .toEventStream() // using this instead of .changes() to trigger an initial query ) // Open either on open-stream event from panel, or if clicking inside the previewEditor const openFileStream = Bacon .fromEvent(atom.views.getView(atom.workspace), 'click') .filter(ev => ev.srcElement === atom.views.getView(this._previewEditor)) .merge(reactPanel.enterKeyStream) this.disposables = new DisposableValues( focusOnSearchStream.onValue(() => { this._atomPanel.show() }), togglePanelStream.onValue(() => { if (this._atomPanel.isVisible()) { this._atomPanel.hide() } else { this._atomPanel.show() } }), reactPanel.bodyHeightProp.debounce(500).onValue(h => atom.config.set('notational.bodyHeight', h)), // An item is selected; preview it after debounce (to avoid slugginess) reactPanel.selectedItemProp .debounce(50) .onValue(selectedItem => { if (selectedItem) { if (!this._previewEditor) { this._previewEditor = atom.workspace.buildTextEditor() this._previewEditor.getTitle = () => 'Notational Preview' this._previewEditor.onDidDestroy(() => this._previewEditor = null) this._previewEditor.buffer.isModified = R.always(false) const view = atom.views.getView(this._previewEditor) view.onfocus = function () { focusBus.push(null) } } atom.workspace.getActivePane().activateItem(this._previewEditor) this._previewEditor.setText(selectedItem.content) // For preview to behave like a real editor, for interop with other packages (e.g. quick-file-actions) this._previewEditor.getPath = R.always(Path.join(selectedItem.projectPath, selectedItem.relPath)) } else if (this._previewEditor) { this._previewEditor.destroy() } }), // Open-file stream trigger; open selected item reactPanel.selectedItemProp .sampledBy(openFileStream) .filter(R.is(Object)) .onValue(selectedItem => { atom.workspace.open(Path.join(selectedItem.projectPath, selectedItem.relPath)) }) ) } isVisible () { return this._atomPanel.isVisible() } show () { this._atomPanel.show() this._atomPanel.emitter.emit('did-change-visible', true) // force event, to trigger focusStream } dispose () { React.unmountComponentAtNode(this._panelElement) this._panelElement = null this._atomPanel.destroy() this._atomPanel = null this.disposables.dispose() this.disposables = null } } export default Panel
JavaScript
0
@@ -2020,18 +2020,16 @@ n%0A - .fromEve @@ -2076,18 +2076,16 @@ click')%0A - .f @@ -2155,18 +2155,16 @@ ditor))%0A - .m @@ -3828,107 +3828,167 @@ item -%0A reactPanel.selectedItemProp%0A .sampledBy(openFileStream)%0A .filter(R.is(Object)) + if any, or create a new file%0A Bacon.when(%0A %5BopenFileStream, reactPanel.selectedItemProp, reactPanel.searchProp%5D, (_, selectedItem, searchStr) =%3E %7B %0A @@ -3988,32 +3988,29 @@ %3E %7B%0A -.onValue + if (selectedIte @@ -4002,38 +4002,38 @@ if (selectedItem - =%3E +) %7B%0A + atom.w @@ -4109,24 +4109,139 @@ h))%0A + %7D else %7B%0A atom.workspace.open(%60$%7BsearchStr.trim()%7D.txt%60)%0A %7D%0A %7D%0A ).onValue(() =%3E %7B %7D)%0A )%0A %7D
ffe288fb1d63d0440415380d7dd3391234dc999d
Check in node.js environment before exporting
lib/poker.js
lib/poker.js
var POKER = { rankToString: ['', '', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'], suitToString: ['h', 'd', 'c', 's'], rankToInt: {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}, suitToInt: {'h': 0, 'd': 1, 'c': 2, 's': 3} }; (function (POKER, undefined) { 'use strict'; var privateBar = 'this is private'; POKER.foo = 'bar'; POKER.getBar = function() { return privateBar; }; })(POKER = POKER); POKER.Card = function(rank, suit) { this.getRank = function() {return rank}; this.getSuit = function() {return suit}; this.toString = function() { return POKER.rankToString[rank] + '' + POKER.suitToString[suit]; } }; // create Card object from string like 'As', 'Th' or '2c' POKER.cardFromString = function(cardVal) { return new POKER.Card( POKER.rankToInt[cardVal[0]], POKER.suitToInt[cardVal[1]] ); }; // create Hand object from array of Card objects POKER.Hand = function(cards) { this.numSameSuits = function() { var counters = [0, 0, 0, 0]; for (var idx = 0; idx < cards.length; idx += 1) { counters[cards[idx].getSuit()] += 1; }; return Math.max.apply(null, counters); }; // number of longest consecutive straight run this.numConnected = function() { var oRanks = this.getOrderedRanks(), run = max = 1, thisCardRank, prevCardRank; for (var idx = 1; idx < oRanks.length; idx += 1) { thisCardRank = oRanks[idx]; prevCardRank = oRanks[idx - 1]; if (thisCardRank !== prevCardRank + 1) { run = 1; } else { run = run + 1; max = run > max ? run : max; } } if (isLowStraight(oRanks)) { return 5; } return max; }; this.getOrderedRanks = function(desc) { var ranks = []; for (var idx = 0; idx < cards.length; idx += 1) { ranks.push(parseInt(cards[idx].getRank(), 10)); }; return sortIntArray(ranks, desc); // return ranks.sort(); }; // special case where A plays low for A to 5 straight function isLowStraight(oRanks) { var lowFourCards = oRanks.slice(0, 4); // if 2,3,4,5 and Ace in hand if (equivIntArrays(lowFourCards, [2,3,4,5]) && oRanks.indexOf(14) > -1) { return true; } return false; } // true if two int arrays identical function equivIntArrays(a, b) { if (a.length !== b.length) { return false; } for (var idx = 0; idx < a.length; idx += 1) { if (a[idx] !== b[idx]) { return false; } } return true; } // temp sort function, replace with array.sort function sortIntArray(array, desc) { var sorted = []; for (var idx = 0; idx < array.length; idx += 1) { var indexOfMax = getIndexOfMax(array); sorted.push(array[indexOfMax]); array[indexOfMax] = -1; } if (!desc) { sorted.reverse(); } return sorted; } function getIndexOfMax(array) { var max = 0, maxIndex = -1; for (var idx = 0; idx < array.length; idx += 1) { if (array[idx] > max) { max = array[idx]; maxIndex = idx; } }; return maxIndex; } this.numOfAKind = function() { return [0]; }; this.toString = function() { var str = ''; for (var idx = 0; idx < cards.length; idx += 1) { str += cards[idx].toString() + ' '; }; return str.slice(0, str.length - 1); } }; // create Hand object from string like 'As Ks Th 7c 4s' POKER.handFromString = function(handString) { var cardStrings = handString.split(' '), cards = []; for (var idx = 0; idx < cardStrings.length; idx += 1) { cards.push(POKER.cardFromString(cardStrings[idx])); }; return new POKER.Hand(cards); }; // a deck of Card objects POKER.Deck = function() {}; // compare an array of Hands and return the winner(s) POKER.compare = function(hands) {}; exports.POKER = POKER;
JavaScript
0
@@ -4367,16 +4367,114 @@ s) %7B%7D;%0A%0A +// if in Node.js environment export the POKER namespace%0Aif (typeof exports !== 'undefined') %7B%0A exports. @@ -4488,8 +4488,10 @@ POKER;%0A +%7D%0A
c4812b1d7f7164a5c23c1c723d564cfdac584680
Use path.resolve instead of string join
lib/praat.js
lib/praat.js
var info = require('./info'); var path = require('path'); var myPackageJson = require('../package.json'); var version = myPackageJson.praatVersion; module.exports = [__dirname, '..', 'node_modules', '.bin', info.praatRealExecName(info.getOsInfo(), version)].join(path.sep);
JavaScript
0.000099
@@ -162,9 +162,21 @@ s = -%5B +path.resolve( __di @@ -265,22 +265,7 @@ ion) -%5D.join(path.sep );%0A
d8885e00d0bbebbc5d7f165e47f441a86e3569a0
Include method in proxy logging
lib/proxy.js
lib/proxy.js
var _ = require('underscore'), config = require('./config'), cookieMonster = require('./cookieMonster').cookieMonster, cors = require('./cors'), http = require('http'), https = require('https'), url = require("url"); var fs = require('fs'); var servicePattern = /service=([^&]+)/; var methodPattern = /method=([^&]+)/; exports.proxy = function(secure) { // Mirror the services layer on this instance return function(req, res) { var forwarded = req.headers['x-forwarded-proto'] === 'https', port = secure || forwarded ? config.secureProxyPort : config.proxyPort, href = url.parse(req.url), options = { method: req.method, host: config.proxyServer, port: port, path: (href.pathname || "") + (href.search || ""), headers: _.defaults({ host: config.proxyServer + (port !== 80 && port !== 443 ? (':' + port) : ''), // Disabled chunking for OPTIONS. It appears this is an Akami bug as the response hangs // for chunked zero-length requests 'content-length': req.method === 'OPTIONS' ? 0 : undefined }, req.headers) }, len = 0; // Rewrite standalone requests as they don't use the /m prefix if (config.standalone) { options.path = options.path.replace(/^\/m/, ''); } var startTime = Date.now(); // Remap the host param to prevent funky redirects var originalHost = req.headers.host; if (config.logTrace && options.headers['accept-encoding']) delete options.headers['accept-encoding']; console.info("start proxy url:", req.url, "host:", options.host, "time:", startTime); var sourceReq = (secure || forwarded ? https : http).request(options, function(sourceRes) { var result = ''; sourceRes.on("data", function(chunk) { res.write(chunk); result += chunk; len += chunk.length; }); sourceRes.on("end", function() { console.info("proxied url", req.url, "length", len, "status", sourceRes.statusCode, "time:", Date.now()-startTime); res.end(); if (config.logTrace) { var service = options.path.match(servicePattern); if (service && service.length) service = service[1]; var method = options.path.match(methodPattern); if (method && method.length) method = method[1]; var fileName = 'service-' + (service || '') + '_method-' + (method || '') + '_' + new Date().getTime() + ".log"; var fd = fs.openSync((config.logTracePrefix || 'log') + "/" + fileName, "w"); fs.writeSync(fd, req.method + req.url + '\nRequest Headers: ' + JSON.stringify(options.headers) + '\n\nResult Headers: ' + JSON.stringify(sourceRes.headers) + '\n\n' + result); fs.closeSync(fd); } }); // Rewrite CORS for all cors.applyCORS(originalHost, req, sourceRes); cookieMonster(originalHost, sourceRes); // Make sure that we redirect and stay within this server if (sourceRes.statusCode === 302) { var redirect = url.parse(sourceRes.headers.location), host = originalHost.split(':')[0]; if (redirect.hostname === host || redirect.hostname === config.proxyServer) { redirect.hostname = host; redirect.port = (redirect.protocol === 'http:') ? config.forwardPort : config.securePort; redirect.host = redirect.hostname + ':' + redirect.port; sourceRes.headers.location = url.format(redirect); } } res.writeHead(sourceRes.statusCode, sourceRes.headers); }).on("error", function(e) { console.info("error", e); res.send(502); }); if (req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS') { req.on('data', function(chunk) { sourceReq.write(chunk); }); req.on('end', function() { sourceReq.end(); }); } else { sourceReq.end(); } }; };
JavaScript
0
@@ -1657,17 +1657,17 @@ le.info( -%22 +' start pr @@ -1674,17 +1674,17 @@ oxy url: -%22 +' , req.ur @@ -1690,15 +1690,38 @@ rl, -%22 +'method:', req.method, ' host: -%22 +' , op @@ -1732,23 +1732,23 @@ s.host, -%22 +' time: -%22 +' , startT
b98e1aca9a4674999ffc1a36bac14ee4b0fe99bf
Update razor.js
lib/razor.js
lib/razor.js
/*! * Razor * Copyright(c) 2012 David Murdoch <[email protected]> * MIT Licensed */ /** * Module dependencies. */ var Utils = require( "./utils" ), Proxy = require("node-proxy"), Parser = require( "./parser" ), Html = require( "./html" ), _ = require( "lodash" ), fs = require( "fs" ), nil = require( "nil" ); /** * Library version. */ exports.version = "0.1.1alpha4"; var parse = function ( str, options ) { // normalize newlines. str = str.replace( /\r\n|\r/g, "\n" ) // and backslashes .replace(/\\/g, "\\\\"); var parser = new Parser( str, options ), js = parser.parse(), out; out = [ "this.buffer=[];", "with(this){", js, "}", "return this.buffer.join('');" ]; return out.join( "\n" ); } /** * We can take an object and watch it for ALL JS access. * This mean if we look up a property on the current context without * using `this` we can determine if that property exists on the object. * Basically, we lie to the V8 runtime when it asks if the property exists: * we always say it does. * * You might think this has severe issues (and it might) but when V8 asks * *for* the actual property itself we give it the value `undefined` ... * exactly like `this.notDefinedProperty` does. * * Now our issue is that undefined.toString() === "undefined". To fix that * our overridden ToString method in html.js ALWAYS returns an empty string * when a property === `undefined`. * * @param {Object} obj The object we need to run through our proxy * @return {Object} The handler */ var handlerMaker = function(obj) { return { "hasOwn": function(name) { return true; //return Object.prototype.hasOwnProperty.call(obj, name); }, "get": function(receiver, name) { var val = obj[ name ]; if ( (val === undefined || val === null) && val !== nil.nil ) { val = nil.nil; } // not everything can be Proxied, like Streams and JSON. :-( // this means that the http `request` and response objects can't be proxied. else if ( ( (val.constructor == Object || Object.prototype.toString.call( val ) == "[object Object]") && val.toString() !== "[object JSON]") || val.constructor == Array ) { val = getProxy( val ); } return val; }, "set": function(receiver, name, val) { obj[name] = val; return true; }, /* fixes for(var name in obj) {}*/ "enumerate": function() { var result = []; for (var name in obj) { result.push(name); }; return result; }, }; }; var getProxy = function( obj ){ var prox = Proxy.create( handlerMaker( obj ), obj.constructor.prototype || Object.prototype ); // JSON doesn't work on Proxies, so we need to keep a reference to the original. Proxy.hidden( prox, "original", obj ); return prox; } // expose our Html functions to whoever is consuming us. exports.Html = Html; exports.compile = function( str, options ) { options = options || {}; var fnStr = parse( String( str || "" ), options ), client = options.client, fn; if ( client ){ fn = new Function( fnStr ); return fn; } var compiledFn = function( locals ) { var args = _.keys(locals), fn, razor = getProxy({}); args.push( fnStr ); fn = Function.apply( null, args ); razor.Model = locals; _.extend( razor, global, locals ); // expose our Html functions razor.Html = Html; // expose our JSON object razor.JSON = { "parse": JSON.parse, "stringify": function(object){ return JSON.stringify( Proxy.isProxy( object ) ? Proxy.hidden( object, "original" ) : object ); } } // add a RenderBody function razor.RenderBody = function (){ return locals && locals.body !== undefined ? Html.Raw( locals.body ) : ""; }; razor.console = console; return fn.apply( razor, _.values( locals ) ); }; compiledFn.fn = fnStr; return compiledFn; } /** * Render the given `str` of razor and invoke * the callback `fn(err, str)`. * * Options: * * - `cache` enable template caching * - `filename` filename required for `include` / `extends` and caching * * @param {String} str * @param {Object|Function} options or fn * @param {Function} fn * @api public */ exports.render = function(str, options, fn){ // swap args if (typeof options === 'function') { fn = options, options = {}; } // cache requires .filename if (options.cache && !options.filename) { return fn(new Error('the "filename" option is required for caching')); } try { var path = options.filename, tmpl = options.cache ? exports.cache[path] || (exports.cache[path] = exports.compile(str, options)) : exports.compile(str, options); fn(null, tmpl(options)); } catch (err) { fn(err); } }; /** * Render a Razor file at the given `path` and callback `fn(err, str)`. * * @param {String} path * @param {Object|Function} options or callback * @param {Function} fn * @api public */ exports.renderFile = function(path, options, fn){ var key = path + ':string'; if ( typeof options === "function" ) { fn = options; options = {}; } try { path = options.filename = path.replace("/", "\\"); var str = options.cache ? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8')) : fs.readFileSync(path, 'utf8'); exports.render(str, options, function( _, html ){ if ( options.layout ) { options.body = html; var path = options.layout; delete options.layout; exports.renderFile(path, options, function( _, html ){ fn( _, html ); }); } else { fn( _, html ); } }); } catch (err) { fn(err); } }; /** * Express support. */ exports.__express = exports.renderFile;
JavaScript
0.000001
@@ -295,19 +295,21 @@ ( %22fs%22 ) -, +; %0A%09 +// nil = re @@ -1806,27 +1806,8 @@ ull) - && val !== nil.nil ) %7B @@ -1822,13 +1822,10 @@ = n -il.ni +ul l;%0A%09 @@ -5584,8 +5584,9 @@ derFile; +%0A
be52e5ba78e704b56d0f5d4c27ca0c768d5e4fe0
Call onSend in case of errors
lib/reply.js
lib/reply.js
/* eslint-disable no-useless-return */ 'use strict' const pump = require('pump') const validation = require('./validation') const serialize = validation.serialize const statusCodes = require('http').STATUS_CODES const stringify = JSON.stringify const flatstr = require('flatstr') const fastseries = require('fastseries') const runHooks = fastseries() function Reply (req, res, store) { this.res = res this.store = store this._req = req this.sent = false this._serializer = null this._errored = false } /** * Instead of using directly res.end(), we are using setImmediate(…) * This because we have observed that with this technique we are faster at responding to the various requests, * since the setImmediate forwards the res.end at the end of the poll phase of libuv in the event loop. * So we can gather multiple requests and then handle all the replies in a different moment, * causing a general improvement of performances, ~+10%. */ Reply.prototype.send = function (payload) { if (this.sent) { this._req.log.warn(new Error('Reply already sent')) return } this.sent = true if (payload === undefined) { this.res.setHeader('Content-Length', '0') setImmediate(handleReplyEnd, this, '') return } if (payload && payload.isBoom) { this._req.log.error(payload) this.res.statusCode = payload.output.statusCode this.res.setHeader('Content-Type', 'application/json') this.headers(payload.output.headers) setImmediate( handleReplyEnd, this, stringify(payload.output.payload) ) return } if (payload instanceof Error) { handleError(this, payload) return } if (payload && typeof payload.then === 'function') { return payload.then(wrapReplySend(this)).catch(wrapReplySend(this)) } if (payload && payload._readableState) { if (!this.res.getHeader('Content-Type')) { this.res.setHeader('Content-Type', 'application/octet-stream') } return pump(payload, this.res, wrapPumpCallback(this)) } if (!this.res.getHeader('Content-Type') || this.res.getHeader('Content-Type') === 'application/json') { this.res.setHeader('Content-Type', 'application/json') // Here we are assuming that the custom serializer is a json serializer var str = this._serializer ? this._serializer(payload) : serialize(this.store, payload, this.res.statusCode) if (typeof str === 'string') { flatstr(str) } setImmediate(handleReplyEnd, this, str) return } // All the code below must have a 'content-type' setted if (this._serializer) { setImmediate(handleReplyEnd, this, this._serializer(payload)) return } setImmediate(handleReplyEnd, this, payload) return } Reply.prototype.header = function (key, value) { this.res.setHeader(key, value) return this } Reply.prototype.headers = function (headers) { var keys = Object.keys(headers) for (var i = 0; i < keys.length; i++) { this.header(keys[i], headers[keys[i]]) } return this } Reply.prototype.code = function (code) { this.res.statusCode = code return this } Reply.prototype.serializer = function (fn) { this._serializer = fn return this } Reply.prototype.type = function (type) { this.res.setHeader('Content-Type', type) return this } Reply.prototype.redirect = function (code, url) { if (typeof code === 'string') { url = code code = 302 } this.res.writeHead(code, { Location: url }) this.res.end() } function wrapPumpCallback (reply) { return function pumpCallback (err) { if (err) { reply._req.log.error(err) setImmediate(handleReplyEnd, reply, '') } } } function handleReplyEnd (reply, payload) { setImmediate( runHooks, new State(reply, payload), hookIterator, reply.store.onSend, onSendEnd ) } function onSendEnd (err) { if (err) { return handleError(this.reply, err) } if (!this.reply.res.getHeader('Content-Length')) { this.reply.res.setHeader('Content-Length', Buffer.byteLength(this.payload)) } this.reply.sent = true this.reply.res.end(this.payload) } function wrapReplyEnd (reply, payload) { if (!reply.res.getHeader('Content-Length')) { reply.res.setHeader('Content-Length', Buffer.byteLength(payload)) } reply.sent = true reply.res.end(payload) } function wrapReplySend (reply, payload) { return function send (payload) { // reset sent so that we can call it again reply.sent = false return reply.send(payload) } } function handleError (reply, err) { if (!reply.res.statusCode || reply.res.statusCode < 400) { reply.res.statusCode = 500 } reply._req.log.error({ res: reply.res, err }, err.message) const store = reply.store const errorHandler = store && store.errorHandler if (errorHandler && !reply._errored) { reply.sent = false reply._errored = true errorHandler(err, reply) return } reply.res.setHeader('Content-Type', 'application/json') setImmediate( wrapReplyEnd, reply, stringify(Object.assign({ error: statusCodes[reply.res.statusCode + ''], message: err.message, statusCode: reply.res.statusCode }, reply._extendServerError && reply._extendServerError(err))) ) return } function State (that, payload) { this.reply = that this.payload = payload } function hookIterator (fn, cb) { fn(this.reply._req, this.reply.res, cb) } function buildReply (R) { function _Reply (req, res, store) { this.res = res this.store = store this._req = req this.sent = false this._serializer = null } _Reply.prototype = new R() return _Reply } module.exports = Reply module.exports.buildReply = buildReply
JavaScript
0
@@ -4102,219 +4102,8 @@ %0A%7D%0A%0A -function wrapReplyEnd (reply, payload) %7B%0A if (!reply.res.getHeader('Content-Length')) %7B%0A reply.res.setHeader('Content-Length', Buffer.byteLength(payload))%0A %7D%0A reply.sent = true%0A reply.res.end(payload)%0A%7D%0A%0A func @@ -4136,24 +4136,24 @@ payload) %7B%0A + return fun @@ -4480,21 +4480,19 @@ age)%0A%0A -const +var store = @@ -4506,21 +4506,19 @@ store%0A -const +var errorHa @@ -4767,20 +4767,22 @@ te(%0A -wrap +handle ReplyEnd
135fbc903fa6cfce1062ad5b6337c24d556f075f
update properties, add history
models/device.js
models/device.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.Types.ObjectId; var checklist = require('./checklist').deviceChecklistSchema; var device = new Schema({ serialNo: { type: String, index: true, unique: true }, name: String, type: String, department: String, owner: String, details: ObjectId, checklist: checklist, checkedValue: { type: Number, default: 0, min: 0 }, totalValue: { type: Number, default: 0, min: 0 }, installToDevice: ObjectId, installToSlot: ObjectId, /** * 0: spare * 1: prepare to install * 1.5: prepare installation checklist * 2: approved to install * 3: installed */ status: { type: Number, default: 0, enum: [0, 1, 1.5, 2, 3] } }); var Device = mongoose.model('Device', device); module.exports = { Device: Device };
JavaScript
0
@@ -96,16 +96,66 @@ bjectId; +%0Avar addHistory = require('./history').addHistory; %0A%0Avar ch @@ -581,43 +581,201 @@ ce: -ObjectId,%0A installToSlot: ObjectId +%7B%0A serialNo: %7Btype: String, default: null%7D,%0A id: %7Btype: String, default: null%7D,%0A %7D,%0A installToSlot: %7B%0A name: %7Btype: String, default: null%7D,%0A id: %7Btype: String, default: null%7D,%0A %7D ,%0A @@ -986,16 +986,16 @@ , 2, 3%5D%0A - %7D%0A%7D);%0A @@ -995,16 +995,66 @@ %7D%0A%7D);%0A%0A +device.plugin(addHistory, %7B%0A watchAll: true%0A%7D);%0A%0A var Devi
ffa0c2b5bc9b2971cac1552be0e0af17d8c79231
add missing callback so will work with node-resque 3.0
lib/rider.js
lib/rider.js
var util = require("util"); var worker = require("node-resque").worker; var utils = require(__dirname + '/sections/utils.js'); var bus = require(__dirname + '/bus.js').bus; var rider = function(options, jobs){ worker.call(this, options, jobs); var busClassKey = this.busDefaults().busClassKey; this.jobs[busClassKey] = this.busJob(); this.bus = new bus(options, jobs); var busDefaults = this.busDefaults(); for(var i in busDefaults){ if(this.options[i] === undefined){ this.options[i] = busDefaults[i]; } } if(this.options.toDrive === true){ if(this.queues instanceof Array && this.queues.indexOf(this.options.incomingQueue) < 0){ this.queues.push( this.options.incomingQueue ); } } this.bus.connect(); var self = this; this.bus.on('error', function(error){ self.emit(error); }); }; util.inherits(rider, worker); rider.prototype.busDefaults = utils.defaults; rider.prototype.busJob = require(__dirname + '/sections/driver.js').busJob; exports.rider = rider;
JavaScript
0
@@ -760,16 +760,29 @@ connect( +function()%7B %7D );%0A var
d037921547985288fc111e9be6fe6c6d4c84fb77
Replace path.sep with "/"
lib/route.js
lib/route.js
var EventEmitter = require('events').EventEmitter, path = require('path'), _ = require('underscore'), store = {}, Route = new EventEmitter(); var format = Route.format = function(str){ str = str.replace(/\\/g, '/'); if (str.substr(0, 1) === '/') str = str.substring(1); var last = str.substr(str.length - 1, 1); if (!last || last === '/') str += 'index.html'; return str; }; Route.get = function(source){ return store[format(source)]; }; Route.set = function(source, callback){ source = format(source); if (_.isFunction(callback)){ store[source] = function(func){ callback(function(err, content){ value = content; func(err, content, source); Route.emit('change', source, content); }); }; } else { store[source] = function(func){ func(null, callback, source); }; Route.emit('change', source, callback); } }; Route.destroy = function(source){ source = format(source); delete store[source]; Route.emit('change', source, null) Route.emit('destroy', source); }; Route.list = function(){ return store; }; module.exports = Route;
JavaScript
0.999999
@@ -141,16 +141,66 @@ mitter() +,%0A sep = path.sep,%0A sepre = new RegExp(sep, 'g') ;%0A%0Avar f @@ -261,13 +261,11 @@ ace( -/%5C%5C/g +sep , '/
c5dc94db90e9135e7b70096e6f93dd2bbae9b171
refactor unit tests
browser_client/__test__/components/greeting_controls-test.js
browser_client/__test__/components/greeting_controls-test.js
import React from 'react'; import { renderIntoDocument, scryRenderedDOMComponentsWithTag, Simulate, } from 'react-addons-test-utils'; import GreetingControls from '../../components/greeting_controls'; function setup (requestsPending = false) { const props = { requestsPending, fetchAndAddName: sinon.spy( x => x ), subtractLastName: sinon.spy( x => x ), }; const greetingControls = renderIntoDocument(<GreetingControls {...props} />); const divs = scryRenderedDOMComponentsWithTag(greetingControls, 'div'); const buttons = scryRenderedDOMComponentsWithTag(greetingControls, 'button'); const [ addButton, subtractButton ] = buttons; const waitingIndicator = divs[1]; return { props, addButton, subtractButton, waitingIndicator }; } describe('adding a greeting', () => { it('calls the `fetchAndAddName` action creator', () => { const { props, addButton } = setup(); Simulate.click(addButton); expect( props.fetchAndAddName ).to.have.been.calledOnce; }); }); describe('subtracting a greeting', () => { it('calls the `subtractLastName` action creator', () => { const { props, subtractButton } = setup(); Simulate.click(subtractButton); expect( props.subtractLastName ).to.have.been.calledOnce; }); }); describe('awaiting a greeting', () => { context('when there is not a pending greeting request', () => { it('does not show a waiting indicator', () => { const { waitingIndicator } = setup(); expect( waitingIndicator.style.visibility ).to.equal( 'hidden' ); }); }); context('when there is a pending greeting request', () => { it('does show a waiting indicator', () => { const { waitingIndicator } = setup(true); expect( waitingIndicator.style.visibility ).to.equal( 'visible' ); }); }); });
JavaScript
0.001162
@@ -61,82 +61,85 @@ -scryRenderedDOMComponentsWithTag,%0A Simulate,%0A%7D from 'react-addons-test- +Simulate,%0A%7D from 'react-addons-test-utils';%0Aimport %7B createFinder %7D from '../ util @@ -496,126 +496,27 @@ nst -divs +find = -s cr -yRenderedDOMComponentsWithTag(greetingControls, 'div');%0A const buttons = scryRenderedDOMComponentsWithTag +eateFinder (gre @@ -532,22 +532,11 @@ rols -, 'button' );%0A -%0A @@ -577,15 +577,22 @@ %5D = +find(' button -s +') ;%0A @@ -622,12 +622,19 @@ r = +find(' div -s +') %5B1%5D;
7c4986ad0231fbd2cc1b3f367c8cf385440ef017
Update flairs for Elite
modules/flair.js
modules/flair.js
module.exports = { ark: { list: [ 'arkstone', 'dodo-blue', 'dodo-cyan', 'dodo-default', 'dodo-lime', 'dodo-red', 'dodo-yellow', 'mushroom', 'woodsign', ], type: 'author_flair_css_class', }, battlefield1: { list: [ 'origin', 'pc', 'psn', 'xbox', ], type: 'author_flair_css_class', }, conan: { list: [], type: 'author_flair_text' }, csgo: { list: [ '/r/globaloffensive janitor', '/r/globaloffensive moderator', '/r/globaloffensive monsorator', '3dmax fan', '400k hype', '5 year subreddit veteran', 'astana dragons fan', 'astralis fan', 'baggage veteran', 'banner competition #1 winner', 'banner competition #2 first place winner', 'banner competition #2 second place winner', 'banner competition #2 third place winner', 'bloodhound', 'bravado gaming fan', 'bravo', 'cache veteran', 'cheeky moderator', 'chroma', 'clan-mystik fan', 'cloud9 fan', 'cloud9 g2a fan', 'cobblestone veteran', 'complexity fan', 'copenhagen wolves fan', 'counter logic gaming fan', 'dat team fan', 'dust 2 veteran', 'envyus fan', 'epsilon esports fan', 'esc gaming fan', 'extra life tournament caster', 'extra life tournament finalist', 'faze clan fan', 'flipsid3 tactics fan', 'flipside tactics fan', 'fnatic fan', 'fnatic fanatic', 'g2 esports fan', 'gambit gaming fan', 'gamers2 fan', 'godsent fan', 'guardian 2', 'guardian elite', 'guardian', 'hellraisers fan', 'https://youtu.be/hX21XHcdlM4?t=15s', 'ibuypower fan', 'inferno veteran', 'italy veteran', 'keyd stars fan', 'kinguin fan', 'ldlc fan', 'legendary chicken master', 'legendary lobster master', 'lgb esports fan', 'london consipracy fan', 'london conspiracy fan', 'luminosity gaming fan', 'militia veteran', 'mirage veteran', 'moderator', 'mousesports fan', 'myxmg fan', 'n!faculty fan', 'natus vincere fan', 'ninjas in pyjamas fan', 'north fan', 'nuke vetera', 'nuke veteran', 'office veteran', 'official dunkmaster', 'one bot to rule them all', 'optic gaming fan', 'overpass veteran', 'penta esports fan', 'penta sports fan', 'phoenix', 'planetkey dynamics fan', 'r/GlobalOffensive Zookeeper', 'reason gaming fan', 'recursive fan', 'renegades fan', 'sk gaming fan', 'splyce fan', 'tactics', 'team astralis fan', 'team dignitas fan', 'team ebettle fan', 'team envyus fan', 'team immunity fan', 'team kinguin fan', 'team liquid fan', 'team solomid fan', 'team wolf fan', 'titan fan', 'train veteran', 'trial moderator', 'tsm kinguin fan', 'universal soldiers fan', 'valeria', 'verygames fan', 'vexed gaming fan', 'victory', 'virtus pro fan', 'virtus.pro fan', 'vox eminor fan', 'xapso fan', ], type: 'author_flair_text', }, elite: { list: [ 'bot img', 'cmdr img alliance', 'cmdr img cobra', 'cmdr img empire', 'cmdr img federation', 'cmdr img sidey', 'cmdr img skull', 'cmdr img viper', 'cmdr', 'dangerous cmdr', 'harmless cmdr', 'img viper cmdr', 'mostlyharmless cmdr', 'novice cmdr', 'star', ], type: 'author_flair_css_class', }, rainbow6: { list: [ 'ash', 'ashnew', 'bandit', 'banditnew', 'blackbeard', 'blackbeardnew', 'blitz', 'blitznew', 'buck', 'bucknew', 'capitao', 'capitaonew', 'castle', 'castlenew', 'caveira', 'caveiranew', 'doc', 'docnew', 'frost', 'frostnew', 'fuze', 'fuzenew', 'glaz', 'glaznew', 'hibana', 'hibananew', 'iq', 'iqnew', 'jager', 'jagernew', 'kapkan', 'kapkannew', 'mod', 'montagne', 'montagnenew', 'mute', 'mutenew', 'pulse', 'pulsenew', 'recruit', 'rook', 'rooknew', 'sledge', 'sledgenew', 'smoke', 'smokenew', 'tachanka', 'tachankanew', 'thatcher', 'thatchernew', 'thermite', 'thermitenew', 'twitch', 'twitchnew', 'valkyrie', 'valkyrienew', ], type: 'author_flair_css_class', }, rimworld: { list: [ 'fun', 'gold', 'granite', 'jade', 'limestone', 'marble', 'mod', 'mod2', 'plasteel', 'pmfaf', 'sandstone', 'silver', 'slate', 'steel', 'uranium', 'war', 'wood', ], type: 'author_flair_css_class', }, };
JavaScript
0
@@ -4392,24 +4392,49 @@ img viper',%0A + 'cmdr star',%0A
a84e6cafd20ffe74cf271dc336b54b04e8c5a0d8
Change description of 'notify' function
lib/snarl.js
lib/snarl.js
'use strict'; var request = require('request') , extend = require('node.extend') , clean ; /** * Constructor. * @author Tomás Hernández <[email protected]> * @since 2015-02-21 * @param {Object} options You can see the options to set in "defaultOptions" */ function Snarl(options){ var self = this , options = extend(true, {}, self.defaultOptions, options) , server = options.server , port = options.port ; self.options = options; self.stack = []; if(port === 443){ self.root = 'https://' + server + ':' + port + '/'; }else{ self.root = 'http://' + server + ':' + port + '/'; } return self; } /** * Extending the prototype. * @author Tomás Hernández <[email protected]> * @since 2015-02-21 */ extend(Snarl.prototype, { /** * Referencing to constructor. * @type {function} */ constructor: Snarl /** * Function to destroy an instance of Snarl (TODO). * @author Tomás Hernández <[email protected]> * @since 2015-02-21 * @return {undefined} */ , destroy: function(){ } /** * Default parameters. * @type {Object} */ , defaultOptions: { server: 'localhost' , port: '8080' , name: 'Snarl4' , path: { icon: __dirname+'\\..\\icon' } } /** * Function to register messages on an app name. * @author Tomás Hernández <[email protected]> * @since 2015-02-21 * @param {String} name Name of the app * @return {undefined} */ , register: function(name){ var self = this , root = self.root , appName = name || self.options.name , url = root + 'register?app-sig='+appName+'&app-title='+appName ; request(url); } /** * Function to unregister messages of an app name. * @author Tomás Hernández <[email protected]> * @since 2015-02-21 * @param {String} name Name of a registered app * @return {undefined} */ , unregister: function(name){ var self = this , root = self.root , appName = name || self.options.name , url = root + 'unregister?app-sig='+appName ; request(url); } /** * Function to send an http request to snarl server and create a snarl * notification. * @author Tomás Hernández <[email protected]> * @since 2015-02-21 * @param {String} name Name of the app * @param {Object} options See available options in * {@link https://sites.google.com/site/snarlapp/developers/api-reference|API Reference} * @return {undefined} */ , notify: function(name, options){ var self = this , root = self.root , id = parseInt(new Date().toISOString().replace(/[\W\D]/g, '')) , url = root , params ; options = options || {}; name = name || self.options.name; options.title = options.title || 'title'; options.text = clean(options.text || 'text'); options.timeout = options.timeout || 3; params = Object.keys(options); url += 'notify?id='+id+'&app-sig='+name; for(var x = 0, len = params.length; x < len; ++x){ var param = params[x]; url += '&'+param+'='+options[param]; } request(url, function(e, res){ if (!e && res.statusCode === 200) { self.stack.push(id); setTimeout(function(){ self.stack.shift(0); }, options.timeout * 1000); } }); } /** * Same as notify function but here is setted a default icon "done". * @author Tomás Hernández <[email protected]> * @since 2015-02-22 * @param {String} name Name of the app * @param {Object} options See available options in * {@link https://sites.google.com/site/snarlapp/developers/api-reference|API Reference} * @return {Function} */ , done: function(name, options){ var self = this; options.icon = self.options.path.icon + '\\done.png'; self.notify(name, options); } /** * Same as notify but here is setted a default icon "error". * @author Tomás Hernández <[email protected]> * @since 2015-02-22 * @param {String} name Name of the app * @param {Object} options See available options in * {@link https://sites.google.com/site/snarlapp/developers/api-reference|API Reference} * @return {Function} */ , error: function(name, options){ var self = this; options.icon = self.options.path.icon + '\\error.png'; self.notify(name, options); } /** * Same as notify but here is setted a default icon "log". * @author Tomás Hernández <[email protected]> * @since 2015-02-22 * @param {String} name Name of the app * @param {Object} options See available options in * {@link https://sites.google.com/site/snarlapp/developers/api-reference|API Reference} * @return {Function} */ , log: function(name, options){ var self = this; options.icon = self.options.path.icon + '\\log.png'; self.notify(name, options); } }); /** * Clean text before output * @author Tomás Hernández <[email protected]> * @since 2015-02-21 * @private * @param {String} text Output message. * @return {String} */ clean = function(text){ return text.replace(/\=/g, '\==').replace(/\\/g,'/').replace(/\n/gi,'\\n'); } module.exports = new Snarl();
JavaScript
0.001224
@@ -2158,15 +2158,48 @@ to -send an +create a notification and send it over a htt @@ -2220,34 +2220,21 @@ narl +%0A * server - and create a snarl +. %0A
09c8207064bc81bd960df897fc23183085647364
Fix #5
lib/stats.js
lib/stats.js
var os = require('os') , fs = require('fs') , p = require('path') , exec = require('child_process').exec , helpers = require('./helpers') var stats = { history: {}, cpu: null, //used to store cpu informations proc: function(pid, options, done) { var self = this if(this.cpu !== null) { fs.readFile('/proc/uptime', 'utf8', function(err, uptime) { if(err) { done(err, null) } self.cpu.uptime = uptime.split(' ')[0] self.proc_calc(pid, options, done) }) } else { helpers.cpu(function(err, cpu) { self.cpu = cpu self.proc_calc(pid, options, done) }) } }, proc_calc: function(pid, options, done) { var history = this.history[pid] ? this.history[pid] : {}, cpu = this.cpu , self = this // Arguments to path.join must be strings fs.readFile(p.join('/proc', ''+pid, 'stat'), 'utf8', function(err, infos) { if(err) return done(err, null) //https://github.com/arunoda/node-usage/commit/a6ca74ecb8dd452c3c00ed2bde93294d7bb75aa8 //preventing process space in name by removing values before last ) (pid (name) ...) var index = infos.lastIndexOf(')') infos = infos.substr(index + 2).split(' ') //according to http://man7.org/linux/man-pages/man5/proc.5.html (index 0 based - 2) //In kernels before Linux 2.6, start was expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks var stat = { utime: parseFloat(infos[11]), stime: parseFloat(infos[12]), cutime: parseFloat(infos[13]), cstime: parseFloat(infos[14]), start: parseFloat(infos[19]) / cpu.clock_tick, rss: parseFloat(infos[21]) } //http://stackoverflow.com/questions/16726779/total-cpu-usage-of-an-application-from-proc-pid-stat/16736599#16736599 var childrens = options.childrens ? stat.cutime + stat.cstime : 0, total if(history.utime) { total = (stat.stime - history.stime) + (stat.utime - history.utime) + childrens } else { total = stat.stime + stat.utime + childrens } total = total / cpu.clock_tick //time elapsed between calls var seconds = history.uptime !== undefined ? cpu.uptime - history.uptime : stat.start - cpu.uptime seconds = Math.abs(seconds) seconds = seconds === 0 ? 0.1 : seconds //we sure can't divide through 0 self.history[pid] = stat self.history[pid].seconds = seconds self.history[pid].uptime = cpu.uptime return done(null, { cpu: (total / seconds) * 100, memory: stat.rss * cpu.pagesize }) }) }, /** * Get pid informations through ps command * @param {int} pid * @return {Function} done (err, stat) * on os x skip headers with pcpu=,rss= * on linux it could be --no-header * on solaris 11 can't figure out a way to do this properly so... */ ps: function(pid, options, done) { var cmd = 'ps -o pcpu,rss -p ' if(os.platform() == 'aix') cmd = 'ps -o pcpu,rssize -p ' //this one could work on other platforms exec(cmd + pid, function(error, stdout, stderr) { if(error) { return done(error) } stdout = stdout.split(os.EOL)[1] stdout = stdout.replace(/^\s+/, '').replace(/\s\s+/g, ' ').split(' ') return done(null, { cpu: parseFloat(stdout[0].replace(',', '.')), memory: parseFloat(stdout[1]) * 1024 }) }) }, /** * This is really in a beta stage */ win: function(pid, options, done) { // var history = this.history[pid] ? this.history[pid] : {} // , uptime = os.uptime() // , self = this //http://social.msdn.microsoft.com/Forums/en-US/469ec6b7-4727-4773-9dc7-6e3de40e87b8/cpu-usage-in-for-each-active-process-how-is-this-best-determined-and-implemented-in-an?forum=csharplanguage exec('wmic PROCESS '+pid+' get workingsetsize,usermodetime,kernelmodetime', function(error, stdout, stderr) { if(error) { console.log(error) return done(error) } stdout = stdout.split(os.EOL)[1] stdout = stdout.replace(/\s\s+/g, ' ').split(' ') var stats = { kernelmodetime: parseFloat(stdout[0]), usermodetime: parseFloat(stdout[1]), workingsetsize: parseFloat(stdout[2]) } //according to http://technet.microsoft.com/en-us/library/ee176718.aspx var total = (stats.usermodetime + stats.kernelmodetime) / 10000000 //seconds return done(null, { cpu: total, memory: stats.workingsetsize }) }) } } module.exports = stats;
JavaScript
0.000001
@@ -422,26 +422,185 @@ l)%0A %7D -%0A%0A + else if(uptime === undefined) %7B%0A console.error(%22We couldn't find uptime from /proc/uptime%22)%0A self.cpu.uptime = os.uptime()%0A %7D else %7B%0A self @@ -634,32 +634,50 @@ ' ')%5B0%5D%0A +%7D%0A%0A return self.proc_calc(p @@ -783,24 +783,31 @@ cpu%0A +return self.proc_ca @@ -1001,15 +1001,8 @@ // -%09%09%09%09%09%09%09 Argu
e452f62a12f97741cfd1b379c63b8d65ce215bcb
remove series and parallel
lib/stuff.js
lib/stuff.js
'use strict'; var ConfigurableRecipeRegistry = require('./recipe/registry'); var cwd = process.cwd(); module.exports = function (options) { return { flows: ConfigurableRecipeRegistry.builder('flow') .dir(cwd, 'gulp/flows') .npm(options) .require('gulp-ccr-parallel') .require('gulp-ccr-series') .require('gulp-ccr-watch') .build(), streams: ConfigurableRecipeRegistry.builder('stream') .dir(cwd, 'gulp/streams') .npm(options) .require('gulp-ccr-merge') .require('gulp-ccr-pipe') .require('gulp-ccr-queue') .build(), tasks: ConfigurableRecipeRegistry.builder('task') .dir(cwd, 'gulp') .dir(cwd, 'gulp/tasks') .npm(options) .require('gulp-ccr-clean') .require('gulp-ccr-copy') .build() }; };
JavaScript
0.000001
@@ -246,72 +246,8 @@ ns)%0A -%09%09%09.require('gulp-ccr-parallel')%0A%09%09%09.require('gulp-ccr-series')%0A %09%09%09.
a67bbe622f61bacdb45ba233c8ad67e6f7ce2a9b
Fix a typo
modules/silly.js
modules/silly.js
var figlet = require('figlet'); var quote = function(quotes, log) { if(!(quotes instanceof Array)) { quotes = [quotes]; } return function(data, nick) { if(log) { this.log(log.split("$nick").join(nick)); } this.talk(quotes[(Math.random() * quotes.length) | 0].replace("$nick", nick)); }; }; module.exports = function(get) { return { "canucks": { fn: quote("http://i.imgur.com/Pkqiwcj.jpg", "$nick made fun of the Canucks") }, "murt": { fn: function(data, nick) { figlet("FUCK OFF MURT", { font: 'Small', horizontalLayout: 'fitted' }, function(err, data) { var msgs = [ "FUCK OFF MURT", "http://i.imgur.com/d9pZQS0.jpg", "http://i.imgur.com/nXqgx5X.jpg", "http://i.imgur.com/0rT7INi.jpg", "http://i.imgur.com/eeBDs9L.jpg", "http://i.imgur.com/wWoifA8.jpg", "http://i.imgur.com/DZtTLqf.jpg", "http://i.imgur.com/3UsTnbP.jpg", "http://i.imgur.com/6d6jNGU.jpg", "http://i.imgur.com/Ynd0IVC.jpg", "http://i.imgur.com/5n0ZAcq.jpg", "http://i.imgur.com/OmrlFRZ.jpg", "http://i.imgur.com/awF5j2e.jpg" ]; if(!err) { msgs.push(data); } this.log(nick + " told murt to fuck off"); this.talk(msgs[(Math.random() * msgs.length) | 0]); }.bind(this)); } }, "doc": { fn: quote("http://i.imgur.com/tJaBJjl.gif", "$nick pasted the Doc Rivers face") }, "leafer": { fn: quote("Man, I really could go for some throat lasagnas right now.", "$nick quoted Leafer91") }, "doubleaw": { fn: quote("That's the guy that made me. He must be way better than amaninacan.", "$nick asked me to talk about how awesome DoubleAW is") }, "ruhan": { fn: quote("No, ruhan, you can't have the Chicago fourth line.", "$nick made fun of ruhan") }, "thero": { fn: function(data, nick) { if(nick.toLowerCase() === "thero") { this.log(nick + " tried to tell dan to fuck himself but failed"); this.talk("Go fuck yourself " + nick + "."); } else { this.log(nick + " told dan to fuck himself"); this.talk("Go fuck yourself dan."); } } }, "dan": { fn: quote("Hey $nick wanna suck me off?", "$nick asked for a blowjob") }, "signal": { fn: quote(["Hey $nick do you have a sister?", "Hey $nick what color are your pubes?", "Hey $nick would you drink my bathwater?", "Hey $nick can you recommend a good porno?"], "$nick quoted SiGNAL") }, "fuck": { fn: quote("Woah, watch your language, asshole.", "$nick swore at me") }, "thirty": { fn: quote("The fix will be posted at noon tomorrow on macrumors.com", "$nick quoted thirty") }, "snackle": { fn: quote("#JasminesNips2014", "$nick said something about Jasmine's nips") }, "panthers": { fn: quote("http://i.imgur.com/LXDNmml.jpg", "$nick blessed the channel with the Panthers logo") }, "blues": { fn: quote("http://i.imgur.com/dfRJweG.jpg", "$nick is a Blues fan") }, "leafs": { fn: quote("4-1", "$nick made fun of the Leafs") } "lahey": { fn: quote([ "Birds of a shitfeather flock together, $nick.", "You just opened Pandora's Shitbox, $nick.", "I am the liquor.", "The shit pool's gettin full $nick, time to strain the shit before it overflows. I will not have a Pompeiian shit catastrophe on my hands.", "Did you see that, $nick? Goddamn shitapple driving the shitmobile. No body else in this park gives a fuck why should I?", "The ole shit liner is coming to port, and I'll be there to tie her up.", "How dare you involve my daughter in your hemisphere of shit.", "Captain Shittacular.", "I'm watching you, like a shithawk.", "We're sailing into a shit typhoon $nick, we'd better haul in the jib before it gets covered in shit.", "How dare you involve my daughter in your hemisphere of shit.", "Your shit-goose is cooked, $nick.", "Shit-apples never fall far from the shit-tree, $nick.", "$nick's about to enter the shit tornado to Oz.", "Do you feel that $nick? The way the shit clings to the air? Shit Blizzard.", "Never Cry Shitwolf, $nick", "Yes I used to drink, $nick, but I got the shitmonkey off my back for good.", "You know what you get when two shit-tectonic plates collide? Shitquakes, $nick. Shitquakes.", "The ole shit liner is coming to port, and I'll be there to tie her up.", "We got the key to shitty city, $nick, and Julian's the muscular mayor.", "You boys have loaded up a hair-trigger, double barrelled shitmachinegun, and the barrel's pointing right at your own heads.", "Shit moths, $nick.", "Do you know what a shit rope is, $nick?", "The old shit barometer is rising." ], "$nick asked for a Lahey quote") }, "figlet": { fn: function(data, nick) { if(nick !== "DoubleAW" && nick !== "AWAW") { this.log(nick + " tried to use figlet."); this.talk("You can't do that."); return; } figlet(data.join(" "), { font: 'Small', horizontalLayout: 'fitted' }, function(err, str) { this.log("Displayed a figlet image for the phrase '" + data.join(" ") + "'"); this.talk(str); }.bind(this)); } } }; };
JavaScript
1
@@ -3302,24 +3302,25 @@ eafs%22)%0A %7D +, %0A %22lahey%22
e6aefa4b0730da77ab0d997a07eda700631a7f31
fix tests
test/unit/function-overloading.js
test/unit/function-overloading.js
'use strict'; var JSIGSnippet = require('../lib/jsig-snippet.js'); JSIGSnippet.test('function overloading works', { snippet: function m() {/* foo('').split(''); foo(2).split(''); foo(2) + 4; foo('') + 4; foo({}) + 4; function foo(x) { return x; } */}, header: function h() {/* foo : ((String) => String) & ((Number) => Number) */} }, function t(snippet, assert) { var meta = snippet.compile(); assert.equal(meta.errors.length, 3, 'expected three errors'); var err1 = meta.errors[0]; assert.equal(err1.type, 'jsig.verify.non-existant-field'); assert.equal(err1.fieldName, 'split'); assert.equal(err1.objName, 'foo(2)'); assert.equal(err1.expected, '{ split: T }'); assert.equal(err1.actual, 'Number'); assert.equal(err1.line, 2); var err2 = meta.errors[1]; assert.equal(err2.type, 'jsig.sub-type.intersection-operator-call-mismatch'); assert.equal(err2.expected, '(String, String) => String & (Number, Number) => Number'); assert.equal(err2.actual, '[String, Number]'); assert.equal(err2.operator, '+'); assert.equal(err2.line, 4); var err3 = meta.errors[2]; assert.equal(err3.type, 'jsig.verify.function-overload-call-mismatch'); assert.equal(err3.expected, '(String) => String & (Number) => Number'); assert.equal(err3.actual, '[{}]'); assert.equal(err3.funcName, 'foo'); assert.equal(err3.line, 5); assert.end(); }); JSIGSnippet.test('overloading based on string argument', { snippet: function m() {/* on("str", x); on("num", y); function x(a) { a.split(""); } function y(b) { b + 4; } function on(str, listener) { } */}, header: function h() {/* on: ((str: "str", (String) => void) => void) & ((str: "num", (Number) => void) => void) */} }, function t(snippet, assert) { snippet.compileAndCheck(assert); assert.end(); }); JSIGSnippet.test('string argument disallows mutations', { snippet: function m() {/* var foo = "str"; foo = "bar" on(foo, x); function x(a) { a.split(""); } function on(str, listener) { } */}, header: function h() {/* on: (str: "str", (String) => void) => void */} }, function t(snippet, assert) { var meta = snippet.compile(assert); assert.equal(meta.errors.length, 1, 'expected one error'); var err = meta.errors[0]; assert.equal(err.type, 'jsig.sub-type.type-class-mismatch'); assert.equal(err.expected, '"str"'); assert.equal(err.actual, '"bar"'); assert.equal(err.line, 3); assert.end(); }); JSIGSnippet.test('overloading a getter-style interface', { snippet: function m() {/* config.get("key1").split('a'); config.get("key2") + 5; config.get("key3").a.split('b'); */}, header: function h() {/* type Config : { get: ( ((this: Config, str: "key1") => String) & ((this: Config, str: "key2") => Number) & ((this: Config, str: "key3") => { a: String }) ) } config: Config */} }, function t(snippet, assert) { snippet.compileAndCheck(assert); assert.end(); }); JSIGSnippet.test('overloading a getter-style interface (sugar)', { snippet: function m() {/* config.get("key1").split('a'); config.get("key2") + 5; config.get("key3").a.split('b'); */}, header: function h() {/* interface Config { get(str: "key1") => String, get(str: "key2") => Number, get(str: "key3") => { a: String } } config: Config */} }, function t(snippet, assert) { snippet.compileAndCheck(assert); assert.end(); }); JSIGSnippet.test('overloading an event emitter object', { snippet: function m() {/* events.on("key1", function f(x) { x.split('a'); }); events.on("key2", function f(x) { x + 5; }); events.on("key3", function f(x) { x.a.split('b'); }); */}, header: function h() {/* type MyEvents : { on: ( ((this: MyEvents, str: "key1", cb: (String) => void) => void) & ((this: MyEvents, str: "key2", cb: (Number) => void) => void) & (( this: MyEvents, str: "key3", cb: ({ a: String }) => void ) => void) ) } events: MyEvents */} }, function t(snippet, assert) { snippet.compileAndCheck(assert); assert.end(); }); JSIGSnippet.test('overloading an event emitter object (sugar)', { snippet: function m() {/* events.on("key1", function f(x) { x.split('a'); }); events.on("key2", function f(x) { x + 5; }); events.on("key3", function f(x) { x.a.split('b'); }); */}, header: function h() {/* interface MyEvents { on(str: "key1", cb: (String) => void) => void, on(str: "key2", cb: (Number) => void) => void, on(str: "key3", cb: ({ a: String}) => void) => void } events: MyEvents */} }, function t(snippet, assert) { snippet.compileAndCheck(assert); assert.end(); });
JavaScript
0.010887
@@ -826,17 +826,317 @@ ual, - 'Number' +%0A '%7B%5Cn' +%0A ' toFixed: (this: Number, digits?: Number) =%3E String,%5Cn' +%0A ' toExponential: (this: Number, digits?: Number) =%3E String,%5Cn' +%0A ' toPrecision: (this: Number, precision?: Number) =%3E String,%5Cn' +%0A ' toString: (this: Number) =%3E String%5Cn' +%0A '%7D'%0A );%0A
d05eda15b38a7630d32192cd7b28f3ec671f5283
remove semicolon to match v0.12 error
test/utils/test_files_getMtime.js
test/utils/test_files_getMtime.js
const files = require('../../lib/utils/files'); const path = require('path'); const fs = require("fs"); describe("files.getMtime",function(){ it("throw an error on file not found",function(){ return expect(files.getMtime( "file:///my/imaginary/path")).to.eventually.be.rejectedWith(/Error: ENOENT:/) }); });
JavaScript
0.005715
@@ -296,17 +296,16 @@ : ENOENT -: /)%0A %7D);
8f8df704678d311141793c097c08bfbee8149a53
Fix timer callback issue
lib/timer.js
lib/timer.js
"use strict"; var dataflow = require("dataflow"); module.exports = dataflow.define({ activate: function () { this.intervalObject = setInterval( this.send("tick", true), this.props.delay); }, deactivate: function () { clearInterval(this.intervalObject); }, outputs: ["tick"], props: { delay: 1000 } });
JavaScript
0.000001
@@ -141,17 +141,34 @@ nterval( - +(function () %7B%0A%09%09%09 this.sen @@ -182,16 +182,33 @@ %22, true) +;%0A%09%09%7D).bind(this) , this.p
9686e5c935b096925762745c28b79d1ec9c2d23c
Fix typo
lib/track.js
lib/track.js
var _ = require('lodash'); var PassThrough = require('stream').PassThrough; var ffmpeg = require('fluent-ffmpeg'); exports = module.exports = Track; function Track(track, _wimp){ this._wimp = _wimp; _.merge(this, track); this.soundQuality = 'HIGH'; } Track.prototype.play = function(){ var wimp = this._wimp; var stream = new PassThrough(); var streamUrl = this.requestStreamUrl(); wimp.agent .get(streamUrl) .end(function(err, res){ console.log(res.body.url); if(err) return stream.emit('error', err); if(!res.body.url) return stream.emit('error', new Error('response contained no "url"')); var command = new ffmpeg('rtmp://' + res.body.url) .toFormat('mp3') .on('error', function(err){ console.log('An error occurred: ' + err.message); }) .on('end', function(){ console.log('Processing finished !'); }); var ffstream = comand.pipe(); ffstream.on('data', function(chunk){ stream.write(chunk); console.log('ffmpeg just wrote ' + chunk.length + ' bytes'); }); }); return stream; }; Track.prototype.requestStreamUrl = function(){ var soundQuality = this.soundQuality; var wimp = this._wimp; return wimp._buildUrl('tracks/' + this.id + '/streamUrl', { 'soundQuality': soundQuality }); };
JavaScript
0.999999
@@ -855,16 +855,17 @@ am = com +m and.pipe
0d2a235fd4bd7e82bd6e421eece1af6c8cd2bf0f
make execute and executeSync handle options
lib/utils.js
lib/utils.js
/* * Copyright 2014, Gregg Tavares. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Gregg Tavares. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; var Promise = require('promise'); var fs = require('fs'); var tmp = require('tmp'); tmp.setGracefulCleanup(); var execute = function(cmd, args, callback) { var spawn = require('child_process').spawn; var proc = spawn(cmd, args, {}); var stdout = []; var stderr = []; proc.stdout.setEncoding('utf8'); proc.stdout.on('data', function (data) { var str = data.toString(); var lines = str.split(/(\r?\n)/g); stdout = stdout.concat(lines); }); proc.stderr.setEncoding('utf8'); proc.stderr.on('data', function (data) { var str = data.toString(); var lines = str.split(/(\r?\n)/g); stderr = stderr.concat(lines); }); proc.on('close', function (code) { var result = {stdout: stdout.join("\n"), stderr: stderr.join("\n")}; if (parseInt(code) !== 0) { callback({msg: "exit code " + code, output: result}); } else { callback(null, result); } }); }; var executeSync = function(cmd, args, callback) { var spawn = require('child_process').execFile; var proc = spawn(cmd, args, {}); var stdout = []; var stderr = []; proc.stdout.setEncoding('utf8'); proc.stdout.on('data', function (data) { var str = data.toString(); var lines = str.split(/(\r?\n)/g); stdout = stdout.concat(lines); }); proc.stderr.setEncoding('utf8'); proc.stderr.on('data', function (data) { var str = data.toString(); var lines = str.split(/(\r?\n)/g); stderr = stderr.concat(lines); }); proc.on('close', function (code) { var result = {stdout: stdout.join("\n"), stderr: stderr.join("\n")}; if (parseInt(code) !== 0) { callback("exit code " + code, result); } else { callback(null, result); } }); }; var getTempFilename = function(options) { options = options || {}; return new Promise(function(fulfill, reject) { tmp.tmpName(options, function(err, filePath) { if (err) { reject(err); } else { fulfill(filePath); } }); }); }; var getTempFolder = function(options) { options = options || {}; return new Promise(function(fulfill, reject) { tmp.dir(options, function(err, filePath) { if (err) { reject(err); } else { fulfill(filePath); } }); }); }; var deleteNoFail = function(filePath) { if (filePath && fs.existsSync(filePath)) { if (fs.statSync(filePath).isDirectory()) { fs.rmdirSync(filePath); } else { fs.unlinkSync(filePath); } } }; exports.deleteNoFail = deleteNoFail; exports.getTempFolder = getTempFolder; exports.getTempFilename = getTempFilename; exports.execute = execute; exports.executeSync = executeSync;
JavaScript
0
@@ -1723,32 +1723,41 @@ ction(cmd, args, + options, callback) %7B%0A v @@ -1745,32 +1745,111 @@ ns, callback) %7B%0A + if (callback === undefined) %7B%0A callback = options;%0A options = %7B%7D;%0A %7D%0A var spawn = re @@ -1901,34 +1901,39 @@ pawn(cmd, args, -%7B%7D +options );%0A var stdout @@ -2648,16 +2648,25 @@ d, args, + options, callbac @@ -2670,16 +2670,96 @@ back) %7B%0A + if (callback === undefined) %7B%0A callback = options;%0A options = %7B %7D;%0A %7D%0A var sp @@ -2830,18 +2830,23 @@ , args, -%7B%7D +options );%0A var
b8b195875ad3ebd62ce82c17a7983efd6ee767bb
Set default log level to environment variable, or warn
lib/utils.js
lib/utils.js
var winston = require('winston'), path = require('path'), Q = require('q'); var logLevel = 'warn'; var sharedLogger = function(filename) { return new winston.Logger({ level: logLevel, transports: [ new winston.transports.Console({ prettyPrint: true, timestamp: true, level: logLevel, label: path.basename(filename, '.js') }) ] }); }; sharedLogger.setLevel = function (val) { logLevel = val; } function failedPromiseHandler(logger) { logger = logger || sharedLogger(__filename); return function(err) { if (err instanceof Error) { logger.error(err.stack); } else { logger.warn(err); } return Q.reject(err); }; } function uuid() { return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } function mergeObjects(defaultObj, specificObj) { var obj = JSON.parse(JSON.stringify(defaultObj)), cleanSpecificObj = JSON.parse(JSON.stringify(specificObj)); Object.keys(cleanSpecificObj).forEach(function(key) { obj[key] = cleanSpecificObj[key]; }); return obj; } module.exports = { logger: sharedLogger, promise: Q, failedPromiseHandler: failedPromiseHandler, uuid: uuid, mergeObjects: mergeObjects }
JavaScript
0
@@ -101,16 +101,41 @@ gLevel = + process.env.LOG_LEVEL %7C%7C 'warn';
2d8ed4d1f15c0410967d113ad628e4aa5705c9a9
Add isFunction to utils
lib/utils.js
lib/utils.js
'use strict'; const path = require('path'); /** * Naive filename sanitize function. * * @link https://github.com/parshap/node-sanitize-filename * @param {String} [name=''] Name to be clean up * @return {String} Sanitized name */ function sanitizeName(name='') { function toCamelCase(str) { // Lower cases the string return str.toLowerCase() // Replaces any - or _ characters with a space .replace( /[-_]+/g, ' ') // Removes any non alphanumeric characters .replace( /[^\w\s]/g, '') // Uppercases the first character in each group immediately following a space // (delimited by spaces) .replace( / (.)/g, function($1) { return $1.toUpperCase(); }) // Removes spaces .replace( / /g, '' ); } function removeStartingDigits(name=''){ return name.replace(/^[0-9]+/g, ''); } name = toCamelCase(name); name = removeStartingDigits(name); return name; } /** * Return name of module from it's path. * @param {String} [file=''] Path to module. * @return {String} Module name. */ function getModuleName(file='') { return path.basename(file).replace(path.extname(file), ''); } /** * Get path to main module. * @return {String} */ function getPathToMain() { var sep = path.sep; var main = process.argv[1]; main = main.split(sep); main.pop(); main = main.join(sep); return main; } /** * Get number of listeners an event emitter * has for a given event type. * @param {Object} emitter * @param {String} type * @return {number} */ function getListenerCount(emitter, type) { if(!emitter) return 0; if(typeof emitter.listeners === 'function') return 0; let listeners = emitter.listeners(type).length - 1; return listeners === -1 ? 0 : listeners; } const VError = require('verror'); module.exports.fullStack = VError.fullStack; /** * Utility function to clean up names. * * @type {Function} * @exports sanitizeName */ module.exports.sanitizeName = sanitizeName; /** * Utility function to get name from file * path. * * @type {Function} * @exports getModuleName */ module.exports.getModuleName = getModuleName; /** * Utility function to get path to * directory from which we run. * * @type {Function} * @exports getPathToMain */ module.exports.getPathToMain = getPathToMain; /** * Get number of listener functions an * event has. * * @type {Function} * @exports getListenerCount */ module.exports.getListenerCount = getListenerCount;
JavaScript
0.000008
@@ -1484,24 +1484,130 @@ rn main;%0A%7D%0A%0A +function isFunction(fn)%7B%0A return typeof fn === 'function';%0A%7D%0A%0Amodule.exports.isFunction = isFunction;%0A%0A /**%0A * Get n
b1235d3b10d8600b9ca446d8bbe6d63643de5ff2
Fix bug in Utils.format that ignore falsy values.
lib/utils.js
lib/utils.js
var mysql = require("mysql") , connection = mysql.createConnection({}) , util = require("util") , DataTypes = require("./data-types") var Utils = module.exports = { _: (function() { var _ = require("underscore") , _s = require('underscore.string') _.mixin(_s.exports()) _.mixin({ includes: _s.include, camelizeIf: function(string, condition) { var result = string if(condition) { result = _.camelize(string) } return result }, underscoredIf: function(string, condition) { var result = string if(condition) { result = _.underscored(string) } return result } }) return _ })(), addEventEmitter: function(_class) { util.inherits(_class, require('events').EventEmitter) }, TICK_CHAR: '`', addTicks: function(s) { return Utils.TICK_CHAR + Utils.removeTicks(s) + Utils.TICK_CHAR }, removeTicks: function(s) { return s.replace(new RegExp(Utils.TICK_CHAR, 'g'), "") }, escape: function(s) { return connection.escape(s).replace(/\\"/g, '"') }, format: function(arr) { var query = arr[0] , replacements = Utils._.compact(arr.map(function(obj) { return obj != query ? obj : null})) return connection.format.apply(connection, [query, replacements]) }, isHash: function(obj) { return Utils._.isObject(obj) && !Utils._.isArray(obj); }, toSqlDate: function(date) { return [ [ date.getFullYear(), ((date.getMonth() < 9 ? '0' : '') + (date.getMonth()+1)), ((date.getDate() < 10 ? '0' : '') + date.getDate()) ].join("-"), date.toLocaleTimeString() ].join(" ") }, argsArePrimaryKeys: function(args, primaryKeys) { var result = (args.length == Utils._.keys(primaryKeys).length) if (result) { Utils._.each(args, function(arg) { if(result) { if(['number', 'string'].indexOf(typeof arg) !== -1) result = true else result = (arg instanceof Date) } }) } return result }, combineTableNames: function(tableName1, tableName2) { return (tableName1.toLowerCase() < tableName2.toLowerCase()) ? (tableName1 + tableName2) : (tableName2 + tableName1) }, singularize: function(s) { return Utils.Lingo.en.isSingular(s) ? s : Utils.Lingo.en.singularize(s) }, pluralize: function(s) { return Utils.Lingo.en.isPlural(s) ? s : Utils.Lingo.en.pluralize(s) }, removeCommentsFromFunctionString: function(s) { s = s.replace(/\s*(\/\/.*)/g, '') s = s.replace(/(\/\*[\n\r\s\S]*?\*\/)/mg, '') return s }, toDefaultValue: function(value) { return (value == DataTypes.NOW) ? new Date() : value }, setAttributes: function(hash, identifier, instance, prefix) { prefix = prefix || '' if (this.isHash(identifier)) { this._.each(identifier, function(elem, key) { hash[prefix + key] = Utils._.isString(instance) ? instance : Utils._.isObject(instance) ? instance[elem.key || elem] : null }) } else { hash[prefix + identifier] = Utils._.isString(instance) ? instance : Utils._.isObject(instance) ? instance.id : null } return hash }, removeNullValuesFromHash: function(hash, omitNull) { var result = hash if(omitNull) { var _hash = {} Utils._.each(hash, function(val, key) { if (key.match(/Id$/) || ((val !== null) && (val !== undefined))) { _hash[key] = val; } }) result = _hash } return result }, prependTableNameToHash: function(tableName, hash) { if (tableName) { var _hash = {} for (var key in hash) { if (key.indexOf('.') === -1) { _hash[tableName + '.' + key] = hash[key] } else { _hash[key] = hash[key] } } return _hash } else { return hash } }, inherit: function(subClass, superClass) { if (superClass.constructor == Function) { // Normal Inheritance subClass.prototype = new superClass(); subClass.prototype.constructor = subClass; subClass.prototype.parent = superClass.prototype; } else { // Pure Virtual Inheritance subClass.prototype = superClass; subClass.prototype.constructor = subClass; subClass.prototype.parent = superClass; } return subClass; } } Utils.CustomEventEmitter = require("./emitters/custom-event-emitter") Utils.QueryChainer = require("./query-chainer") Utils.Lingo = require("lingo")
JavaScript
0.999997
@@ -1161,138 +1161,8 @@ ) %7B%0A - var query = arr%5B0%5D%0A , replacements = Utils._.compact(arr.map(function(obj) %7B return obj != query ? obj : null%7D))%0A%0A @@ -1209,27 +1209,24 @@ n, %5B -query, replacements +arr.shift(), arr %5D)%0A
d58b9da1512c457661f898bfa8fbc5c092924d5e
Fix duplicate variable declaration #38 (#39)
lib/utils.js
lib/utils.js
module.exports = (() => { const _ = require('lodash'); const os = require('os'); const fs = require('fs'); const os = require('os'); const path = require('path'); const execSync = require('child_process').execSync; const spawn = require('child_process').spawn; const promptly = require('promptly'); const GIT_SERVERS_PRESET = { github: { getRepositoryUrl: (owner, repository) => { return `[email protected]:${owner}/${repository}.git`; } } }; const REPOSITORY_OPTION_DEFAULTS = { commitMessageSuffixTemplate: '' }; const BUILDABLE_BRANCH_TAG = 'build#'; const GLOBAL_OPTIONS_FILE_PATH = path.resolve(os.homedir(), '.config', 'gut', 'gut-config.json'); const SCRIPTS_PATH = path.resolve(os.homedir(), '.config', 'gut'); const REPOSITORY_OPTIONS_FILE_NAME = '.gut-config.json'; const configureGutIfNeeded = () => { const gutOptionsPath = GLOBAL_OPTIONS_FILE_PATH; try { fs.statSync(gutOptionsPath); return new Promise((resolve) => resolve(JSON.parse(fs.readFileSync(gutOptionsPath, 'utf8')))); } catch (err) { return require('./configure').initializeConfiguration(); } }; const execute = command => { return execSync(command).toString(); }; const executeAndPipe = (command, arguments) => { spawn(command, arguments, { stdio: 'inherit' }); }; const print = (...arguments) => console.log(...arguments); const fail = (message, exitCode) => { print(message.red); process.exit(exitCode); }; const promisifiedPrompt = (message, options) => { return new Promise((resolve, reject) => { promptly.prompt(message, options, (error, value) => { return error ? reject(error) : resolve(value); }); }); }; const yesNoPrompt = (message, callback) => { const options = { default: 'n', validator: choice => choice === 'y' }; promptly.prompt(`${message} (y/n)`, options, (error, value) => { if (error) { throw error; } callback(value); }); }; const mergeArrayCustomizer = (seed, otherSource) => { if (_.isArray(seed)) { return seed.concat(otherSource); } }; const getTopLevel = () => { const unsanitizedTopLevel = execSync('git rev-parse --show-toplevel'); return _.replace(unsanitizedTopLevel, /\n/, ''); }; const moveUpTop = () => { process.chdir(getTopLevel()); }; const isDirty = () => { try { execSync('git diff --no-ext-diff --quiet --exit-code'); return false; } catch (error) { return true; } }; const hasStagedChanges = () => { try { execSync('git diff-index --cached --quiet HEAD --'); return false; } catch (error) { return true; } }; const hasUnstagedChanges = () => { try { execSync('[ -n "$(git ls-files --others --exclude-standard)" ]'); return true; } catch (error) { return false; } }; const searchForLocalBranch = regex => { const allBranches = execute(`git branch 2> /dev/null`); return _(allBranches.split('\n')) .map(branch => _.replace(branch, /^[* ] /, '')) .filter(branch => regex.test(branch)) .value(); }; const getCurrentBranch = () => { const allBranches = execute(`git branch 2> /dev/null`); return _(allBranches.split('\n')) .filter(branch => branch.startsWith('*')) .map(branch => _.replace(branch, '* ', '')) .first(); }; const parseBranchName = branchName => { const branchFragments = (branchName ? branchName : getCurrentBranch()).split('_'); const featureFragment = branchFragments.length > 1 && !/^[0-9]+$/.test(branchFragments[ 1 ]) ? branchFragments[ 1 ] : ''; const isBuildable = featureFragment.startsWith('build#'); const feature = featureFragment ? _.replace(featureFragment, BUILDABLE_BRANCH_TAG, '') : ''; const ticketNumber = _(branchFragments) .filter(branch => /^[0-9]+$/.test(branch)) .first(); return { version: branchFragments[ 0 ], feature: feature, ticketNumber: ticketNumber, description: _.size(branchFragments) > 1 ? _.last(branchFragments) : '', isBuildable: isBuildable } }; const buildBranchName = parsedBranch => { const versionFragment = parsedBranch.version; const featureFragment = `${parsedBranch.isBuildable ? BUILDABLE_BRANCH_TAG : ''}${parsedBranch.feature || ''}`; const ticketNumberFragment = '' + (parsedBranch.ticketNumber || ''); const descriptionFragment = parsedBranch.description || ''; return _([ versionFragment, featureFragment, ticketNumberFragment, descriptionFragment ]) .reject(fragment => _.isEmpty(fragment)) .join('_'); }; const isMasterBranch = parsedBranch => { return parsedBranch.version === 'master' && !parsedBranch.feature && !parsedBranch.ticketNumber && !parsedBranch.description; }; const isVersionBranch = parsedBranch => { return parsedBranch.version // TODO: semver-check dat && !parsedBranch.feature && !parsedBranch.ticketNumber && !parsedBranch.description; }; const isFeatureBranch = parsedBranch => { return parsedBranch.version // TODO: semver-check dat && parsedBranch.feature && !parsedBranch.ticketNumber && !parsedBranch.description; }; const isDevBranch = parsedBranch => { return parsedBranch.version // TODO: semver-check dat && parsedBranch.description; }; const getRepositoryOption = optionName => { const topLevelDirectory = getTopLevel(); let result; try { const repositoryOptionsFileName = path.resolve(topLevelDirectory, REPOSITORY_OPTIONS_FILE_NAME); fs.statSync(repositoryOptionsFileName); const repositoryOptions = JSON.parse(fs.readFileSync(repositoryOptionsFileName, 'utf8')); result = repositoryOptions[ optionName ]; } catch (err) { result = REPOSITORY_OPTION_DEFAULTS[ optionName ]; } if (!result) { throw Error(`Option ${optionName} is not specified in the repository's options.`.red) } return result; }; const getRemotes = () => { const remotesAsString = execute(`git remote show`); return _(remotesAsString.split('\n')) .reject(remote => _.isEmpty(remote)) .value(); }; const getBranchRemote = branch => { const safeBranch = branch || getCurrentBranch(); try { return execute(`git config branch.${safeBranch}.remote`); } catch (error) { return undefined; } }; return { GIT_SERVERS_PRESET: GIT_SERVERS_PRESET, GLOBAL_OPTIONS_FILE_PATH: GLOBAL_OPTIONS_FILE_PATH, SCRIPTS_PATH: SCRIPTS_PATH, OPTIONS_FILE_NAME: REPOSITORY_OPTIONS_FILE_NAME, configureGutIfNeeded: configureGutIfNeeded, execute: execute, executeAndPipe: executeAndPipe, print: print, exit: fail, yesNoPrompt: yesNoPrompt, promisifiedPrompt: promisifiedPrompt, mergeArrayCustomizer: mergeArrayCustomizer, getRepositoryOption: getRepositoryOption, getTopLevel: getTopLevel, moveUpTop: moveUpTop, isDirty: isDirty, hasStagedChanges: hasStagedChanges, hasUnstagedChanges: hasUnstagedChanges, getCurrentBranch: getCurrentBranch, searchForLocalBranch: searchForLocalBranch, parseBranchName: parseBranchName, buildBranchName: buildBranchName, isMasterBranch: isMasterBranch, isVersionBranch: isVersionBranch, isFeatureBranch: isFeatureBranch, isDevBranch: isDevBranch, getRemotes: getRemotes, getBranchRemote: getBranchRemote, getGitServer: serverName => { if (!_.has(GIT_SERVERS_PRESET, serverName)) { throw Error(`Server ${serverName} not configured. Please make sure it is not being implemented and create an issue.`); } return GIT_SERVERS_PRESET[ serverName ]; } }; })();
JavaScript
0.000001
@@ -110,36 +110,8 @@ ');%0A - const os = require('os');%0A co
a4956b50a3a383aa3841ad1886a23f08b23571c0
Convert dates inside formatNodes function
lib/utils.js
lib/utils.js
var request = require( 'request' ); var async = require( 'async' ); var _ = require( 'underscore' ); var moment = require( 'moment' ); var parseString = require('xml2js').parseString; var utils = module.exports; utils.formatDateTimeItem = function ( item ) { var reDateTime = new RegExp("[0-9]{8} [0-9]{2}:[0-9]{2}$"); var reDateTimeSeconds = new RegExp("[0-9]{8} [0-9]{2}:[0-9]{2}:[0-9]{2}$"); if ( reDateTimeSeconds.test( item ) ) { return moment( item, 'YYYYMMDD HH:mm:ss' ).format(); } if ( reDateTime.test( item ) ) { return moment( item, 'YYYYMMDD HH:mm' ).format(); } return "Invalid date string"; }; utils.apiRequest = function ( options, done ) { request( options, function ( err, res, body ) { if ( !err && res.statusCode === 200 ) { return done( null, body ); } return done( err, body ); } ); }; utils.convertXML = function ( xml, done ) { var formatNodes = function ( data ) { var keys = Object.keys( data ); var reDateTime = new RegExp("[0-9]{8} [0-9]{2}:[0-9]{2}$"); var reDateTimeSeconds = new RegExp("[0-9]{8} [0-9]{2}:[0-9]{2}:[0-9]{2}$"); for ( var k = 0; k < keys.length; k++ ) { var key = keys[ k ]; if ( Array.isArray( data[ key ] ) && data[ key ].length === 1 ) { data[ key ] = data[ key ][ 0 ]; } if ( typeof data[ key ] === "object" ) { data[ key ] = formatNodes( data[ key ] ); } } return data; }; parseString( xml, function ( err, result ) { var data = formatNodes( result[ "bustime-response" ] ); if ( err ) { return done( err, data ); } return done( null, data ); } ); };
JavaScript
0.000254
@@ -213,455 +213,8 @@ ;%0A%0A%0A -utils.formatDateTimeItem = function ( item ) %7B%0A%0A var reDateTime = new RegExp(%22%5B0-9%5D%7B8%7D %5B0-9%5D%7B2%7D:%5B0-9%5D%7B2%7D$%22);%0A var reDateTimeSeconds = new RegExp(%22%5B0-9%5D%7B8%7D %5B0-9%5D%7B2%7D:%5B0-9%5D%7B2%7D:%5B0-9%5D%7B2%7D$%22);%0A%0A if ( reDateTimeSeconds.test( item ) ) %7B%0A return moment( item, 'YYYYMMDD HH:mm:ss' ).format();%0A %7D%0A%0A if ( reDateTime.test( item ) ) %7B%0A return moment( item, 'YYYYMMDD HH:mm' ).format();%0A %7D%0A%0A return %22Invalid date string%22;%0A%0A%7D;%0A%0A%0A util @@ -894,24 +894,25 @@ h === 1 ) %7B%0A +%0A @@ -944,24 +944,352 @@ ey %5D%5B 0 %5D;%0A%0A + if ( reDateTimeSeconds.test( data%5B key %5D ) ) %7B%0A data%5B key %5D = moment( data%5B key %5D, 'YYYYMMDD HH:mm:ss' ).format();%0A %7D%0A%0A if ( reDateTime.test( data%5B key %5D ) ) %7B%0A data%5B key %5D = moment( data%5B key %5D, 'YYYYMMDD HH:mm' ).format();%0A %7D%0A%0A
a47d6f43d397f6ac52fabb3881056af9e8c0a86a
Fix HTTP status code error messages
lib/utils.js
lib/utils.js
var STATUS_CODES = require('http'); exports.error = function (statusCode, message) { var err; if (message instanceof Error) { err = message; } else { err = new Error(message || STATUS_CODES[statusCode]); } err.status = statusCode; return err; }; exports.extend = function extend(obj) { Array.prototype.slice.call(arguments, 1).forEach(function (source) { if (!source) { return; } for (var key in source) { obj[key] = source[key]; } }); return obj; };
JavaScript
0.006499
@@ -27,16 +27,29 @@ ('http') +.STATUS_CODES ;%0A%0Aexpor
d0e30249ae5c0b47fad251565640f23fe3cdc26d
add header comment; replace "try-catch" statement with "path.exists()"
lib/watch.js
lib/watch.js
var fs = require('fs') , path = require('path'); /** * Utility functions to synchronously test whether the giving path * is a file or a directory. */ var is = (function(ret) { ['File', 'Directory'].forEach(function(method) { var memo = {} , fileObj; ret[method] = function(fpath) { if (memo[fpath] !== undefined) { return memo[fpath]; } try { fileObj = fs.statSync(fpath); } catch(e) { return memo[fpath] = false; } return memo[fpath] = fileObj['is'+method](fpath); } }); return ret; }({})); /** * Filtering files and sub-directories in a directory. */ var filter = function(dir) { var ret = {}; ['File', 'Directory'].forEach(function(method){ ret[method] = function(cb) { if (is.Directory(dir)) { fs.readdir(dir, function(err, files) { files .filter(function(n) { return is[method](path.join(dir, n)) }) .map(function(n) { cb.call(null, path.join(dir, n)) }); }); } }; }); return ret; }; /** * A Container for storing unique and valid filenames. */ var fileNameCache = (function(cache) { return { push: function(name) { cache[name] = 1; return this; }, each: function() { var temp = []; for (var name in cache) { if (cache.hasOwnProperty(name) && is.File(name)) { temp.push(name); } } Array.prototype.forEach.apply(temp, arguments); return this; }, clear: function(){ cache = {}; return this; } }; }({})); /** * Abstracting the way of avoiding duplicate function call. */ var worker = (function() { var free = true; return { busydoing: function(cb) { if (free) { free = false; cb.call(); } }, free: function() { free = true; } } }()); /** * Delay function call and ignore invalid filenames. */ var normalizeCall = function(cb, fname) { // Store each name of the modifying or temporary files generated by an editor. fileNameCache.push(fname); worker.busydoing(function() { // A heuristic delay of the write-to-file process. setTimeout(function() { // When the write-to-file process is done, send all filtered filenames // to the callback function and call it. fileNameCache .each(function(f) { cb.call(null, f); }) .clear(); worker.free(); }, 100); }); }; /** * Watch a file or a directory recursively. * * @param {String} fpath * @param {Function} cb * * watch('fpath', function(file) { * console.log(file, ' changed'); * }); */ function watch(fpath, cb) { if (is.File(fpath)) { fs.watchFile(fpath, function(err) { normalizeCall(cb, fpath); }); return; } else if (is.Directory(fpath)) { var filtered = filter(fpath); try { fs.watch(fpath, function(err, fname) { normalizeCall(cb, path.join(fpath, fname) ); }); } catch(e) { //In case the system limit of watching a directory using fs.watch method. //https://github.com/joyent/node/issues/2479 filtered.File(function(file) { watch(file, cb); }); } filtered.Directory(function(dir) { watch(dir, cb); }); } else { console.log("Invalid filename or directory."); } }; // Expose. module.exports = watch;
JavaScript
0
@@ -1,12 +1,45 @@ +/**%0A * Module dependencies.%0A */%0A var fs = r @@ -420,106 +420,102 @@ -try %7B%0A fileObj = fs.statSync(fpath);%0A %7D catch(e) %7B%0A return memo%5Bfpath%5D = false; +if (path.existsSync(fpath)) %7B%0A return memo%5Bfpath%5D = fs.statSync(fpath)%5B'is'+method%5D(); %0A @@ -551,36 +551,13 @@ = f -ileObj%5B'is'+method%5D(fpath); +alse; %0A @@ -874,16 +874,25 @@ files + && files %0A @@ -2922,16 +2922,17 @@ try %7B + %0A f
d8140e122f83b78cf93f6bb3d4e921bd8088b40b
make sure date parsing handles microseconds&&offset, microseconds||offset
ckanext/project/public/shared/src/services/utilityService.js
ckanext/project/public/shared/src/services/utilityService.js
var app = angular.module("app") .service("utilityService",function($mdToast) { var service = {}; /** * This function formats a timestamp and returns it into a simple date dd/mm/yyyy * @returns {*} */ service.formatDate = function(dateString){ if(!(dateString)) return; var date = dateString.split("-").join("/") .replace(/\+[0-9]+$/g,'') .replace(/T/, ' '); var date_object = new Date(date); var month = date_object.getMonth() + 1; var day = date_object.getDate(); var year = date_object.getFullYear(); var date_object_formatted = day + "/" + month + "/" + year; return date_object_formatted; }; /** * function parses a ISO 8601 date safetly since * IE and Safari cannot handle microseconds * @returns Date Object */ service.parseDate = function(dateString){ if(!(dateString)) return; var date = dateString.split("-").join("/").replace(/\+[0-9]+$/g,''); return new Date(date); }; service.showToast = function(text) { $mdToast.show( $mdToast.simple() .content(text) .hideDelay(4000) .position('top right') ); } service.showToastBottomRight = function(text) { $mdToast.show( $mdToast.simple() .content(text) .hideDelay(3000) .position('bottom right') ); } return service; });
JavaScript
0.000094
@@ -332,16 +332,206 @@ return;%0A + /**%0A * some dates return with microseconds and an offset%0A * while other dates return with one or the other%0A * handle all cases%0A */ %0A @@ -578,16 +578,19 @@ in(%22/%22)%0A + @@ -629,23 +629,21 @@ e(/%5C -+%5B0-9%5D+$ +..* /g,'')%0A + @@ -685,14 +685,21 @@ ce(/ -T/, ' +%5C+%5B0-9%5D+$/g,' ');%0A @@ -1283,50 +1283,335 @@ -var date = dateString.split(%22-%22).join(%22/%22) +/**%0A * some dates return with microseconds and an offset%0A * while other dates return with one or the other%0A * handle all cases%0A */%0A var date = dateString.split(%22-%22).join(%22/%22)%0A .replace(/%5C..*/g,'')%0A .rep
89157468287be1b0a59d537c4498bf345d4ccdcc
remove cyclic dependency
client/js/modules/entries/containers/EntryDetailContainer.js
client/js/modules/entries/containers/EntryDetailContainer.js
import React, { Component, PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { routerActions as RouterActions } from 'react-router-redux'; import LayoutHeader from '../../../layouts/LayoutHeader'; import LayoutContent from '../../../layouts/LayoutContent'; import FeedEntryContent from '../components/detail/FeedEntryContent'; import EntryContentToolbar from '../components/EntryContentToolbar'; import EntryContentToolbarMobile from '../components/EntryContentToolbarMobile'; import FeedEntryEmbedWebsiteContent from '../components/detail/FeedEntryEmbedWebsiteContent'; import FeedEntryEmbedArticleContent from '../components/detail/FeedEntryEmbedArticleContent'; import user from '../../user'; import entries from '../../entries'; import sidebar from '../../sidebar'; import { getHasPreviousEntry, getHasNextEntry, getPreviousEntryId, getNextEntryId, getEnhancedEntry } from '../../../redux/selectors'; import { entryPath, mapRequestParams, goBackPathname } from '../../../utils/navigator'; class EntryDetailContainer extends Component { static propTypes = { entries: PropTypes.shape({ listedIds: PropTypes.array.isRequired, byId: PropTypes.object.isRequired, hasMoreEntries: PropTypes.bool.isRequired, isLoading: PropTypes.bool.isRequired, error: PropTypes.string, }).isRequired, entry: PropTypes.object, hasPreviousEntry: PropTypes.bool.isRequired, hasNextEntry: PropTypes.bool.isRequired, previousEntryId: PropTypes.number, nextEntryId: PropTypes.number, currentUser: PropTypes.object, children: PropTypes.node, params: PropTypes.object.isRequired, pathname: PropTypes.string.isRequired, userActions: PropTypes.object.isRequired, subscriptionsActions: PropTypes.object.isRequired, categoriesActions: PropTypes.object.isRequired, entriesActions: PropTypes.object.isRequired, routerActions: PropTypes.object.isRequired, } constructor(props) { super(props); this.state = { currentViewMode: 'normal', showSpinner: false, }; this.nextEntry = this.nextEntry.bind(this); this.previousEntry = this.previousEntry.bind(this); this.handleEntryShown = this.handleEntryShown.bind(this); this.onOpenExternalClick = this.onOpenExternalClick.bind(this); this.onGoBackClick = this.onGoBackClick.bind(this); this.onChangeViewModeClick = this.onChangeViewModeClick.bind(this); this.onLoadingStart = this.onLoadingStart.bind(this); this.onLoadingComplete = this.onLoadingComplete.bind(this); } handleEntryShown(entry) { const { entriesActions, subscriptionsActions } = this.props; entriesActions.requestMarkEntryAsRead(entry).then(() => { subscriptionsActions.decrementUnreadCount({ id: entry.subscription_id }); }); } nextEntry() { const { entriesActions, hasNextEntry, nextEntryId } = this.props; if (hasNextEntry) { this.navigateTo(nextEntryId); } else { entriesActions.requestLoadMore(this.requestParams(this.props)).then(() => { this.navigateTo(nextEntryId); }); } } previousEntry() { const { hasPreviousEntry, previousEntryId } = this.props; if (hasPreviousEntry) { this.navigateTo(previousEntryId); } } onOpenExternalClick() { window.open(this.props.entry.url, '_blank'); } requestParams(props) { const { params, pathname } = props; return mapRequestParams(params, pathname); } navigateTo(entryId) { const { routerActions, params, pathname } = this.props; routerActions.push(entryPath(entryId, params, pathname)); } onGoBackClick() { const { routerActions, params, pathname } = this.props; routerActions.push(goBackPathname(params, pathname)); } onChangeViewModeClick(mode) { this.setState({ currentViewMode: mode }); } onLoadingStart() { this.setState({ showSpinner: true }); } onLoadingComplete() { this.setState({ showSpinner: false }); } render() { const { entry, hasPreviousEntry, hasNextEntry, } = this.props; const entryContentToolbar = ( <EntryContentToolbar entry={entry} currentViewMode={this.state.currentViewMode} showSpinner={this.state.showSpinner} hasPreviousEntry={hasPreviousEntry} hasNextEntry={hasNextEntry} onPreviousEntryClick={this.previousEntry} onNextEntryClick={this.nextEntry} onOpenExternalClick={this.onOpenExternalClick} showEntryContentModalButton onGoBackClick={this.onGoBackClick} onChangeViewModeClick={this.onChangeViewModeClick} /> ); const entryContentToolbarMobile = ( <EntryContentToolbarMobile entry={entry} currentViewMode={this.state.currentViewMode} showSpinner={this.state.showSpinner} hasPreviousEntry={hasPreviousEntry} hasNextEntry={hasNextEntry} onPreviousEntryClick={this.previousEntry} onNextEntryClick={this.nextEntry} onOpenExternalClick={this.onOpenExternalClick} showEntryContentModalButton onGoBackClick={this.onGoBackClick} onChangeViewModeClick={this.onChangeViewModeClick} /> ); return ( <div className="main-detail-container"> <div className="detail"> <div className="layout-master-container"> <LayoutHeader>{entryContentToolbar}{entryContentToolbarMobile}</LayoutHeader> <LayoutContent> {entry && this.state.currentViewMode === 'normal' && <FeedEntryContent entry={entry} onLoadingComplete={this.onLoadingComplete} onLoadingStart={this.onLoadingStart} onEntryShown={this.handleEntryShown} /> } {entry && this.state.currentViewMode === 'article' && <FeedEntryEmbedArticleContent entry={entry} onLoadingStart={this.onLoadingStart} onLoadingComplete={this.onLoadingComplete} onEntryShown={this.handleEntryShown} /> } {entry && this.state.currentViewMode === 'website' && <FeedEntryEmbedWebsiteContent entry={entry} onLoadingStart={this.onLoadingStart} onLoadingComplete={this.onLoadingComplete} onEntryShown={this.handleEntryShown} /> } </LayoutContent> </div> </div> {this.props.children} </div> ); } } function mapStateToProps(state, ownProps) { return { currentUser: state.user.current, entries: state.entries, entry: getEnhancedEntry(state, ownProps), hasPreviousEntry: getHasPreviousEntry(state, ownProps), hasNextEntry: getHasNextEntry(state, ownProps), previousEntryId: getPreviousEntryId(state, ownProps), nextEntryId: getNextEntryId(state, ownProps), pathname: ownProps.location.pathname, }; } function mapDispatchToProps(dispatch) { return { userActions: bindActionCreators(user.actions, dispatch), entriesActions: bindActionCreators(entries.actions, dispatch), subscriptionsActions: bindActionCreators(sidebar.actions.subscriptions, dispatch), categoriesActions: bindActionCreators(sidebar.actions.categories, dispatch), routerActions: bindActionCreators(RouterActions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(EntryDetailContainer);
JavaScript
0.000418
@@ -733,20 +733,35 @@ %0Aimport -user +* as entriesActions from '. @@ -766,32 +766,30 @@ '../ -../user +actions ';%0A +%0A import -entries +user fro @@ -797,23 +797,20 @@ '../../ -entries +user ';%0Aimpor @@ -7249,18 +7249,17 @@ (entries -.a +A ctions,
26bc33be05e3c4ec5403f8074bace5aa447dacf4
Enable touch events on old React versions
demo/js/demo.js
demo/js/demo.js
'use strict'; var require = typeof require === 'undefined' ? function() {} : require; var React = window.React || require('react'); var ReactDom = window.ReactDOM || require('react-dom') || React; var ElementPan = React.createFactory(window.reactElementPan || require('react-element-pan')); // Simple image demo ReactDom.render( new ElementPan({ startX: 771, startY: 360 }, React.DOM.img({ src: 'img/beer.jpg' }) ), document.getElementById('image-demo')); // Huge SVG demo ReactDom.render( new ElementPan({ startX: 1771, startY: 1360 }, React.DOM.img({ src: 'img/metro.svg' }) ), document.getElementById('map-demo')); // Slightly more complicated DOM-element demo var i = 20, themDivs = []; while (--i) { themDivs.push(React.DOM.div({ key: i, style: { width: i * 30, lineHeight: (i * 10) + 'px' } }, 'Smaller...')); } ReactDom.render( new ElementPan(null, themDivs), document.getElementById('html-demo') );
JavaScript
0
@@ -283,24 +283,101 @@ nt-pan'));%0A%0A +if (React.initializeTouchEvents) %7B%0A React.initializeTouchEvents(true);%0A%7D%0A%0A // Simple im
74f933b7f79ea797c07564931b0ed81be28fae84
update dammy environment
tests/dummy/config/environment.js
tests/dummy/config/environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/ember-ds-table'; } return ENV; };
JavaScript
0
@@ -1078,16 +1078,74 @@ table';%0A + ENV%5B'ember-cli-mirage'%5D = %7B%0A enabled: true%0A %7D%0A %7D%0A%0A r
3eddf1e1e21601c23d4922f5524af0cf2a023f53
Allow the editor component to be copied itself
public/visifile_drivers/ui_components/formEditorComponent.js
public/visifile_drivers/ui_components/formEditorComponent.js
function component( args ) { /* base_component_id("form_editor_component") load_once_from_file(true) */ //alert(JSON.stringify(args,null,2)) var uid2 = uuidv4() var mm = null var texti = args.text Vue.component("form_editor_component", { data: function () { return { text: texti, uid2: uid2, model: { fields: [ ] } } }, template: `<div>Form editor <div v-bind:id='uid2' > <div v-for='field in model.fields'> <div v-if='field.type=="text"'>{{field.text}}</div> <div v-if='field.type=="input"'>{{field.label}}<input></input></div> </div> </div> <hr /> <slot :text2="text"></slot> </div>` , mounted: function() { mm = this document.getElementById(uid2).style.width="100%" document.getElementById(uid2).style.height="45vh" var json2 = this.getJsonModelFromCode( texti ) mm.model = json2 this.generateCodeFromModel( json2 ) //alert(this.text) //editor.getSession().on('change', function() { //mm.text = editor.getSession().getValue(); //alert("changed text to : " + mm.text) // }); }, methods: { getText: function() { return this.text }, setText: function(textValue) { this.text = textValue var json2 = this.getJsonModelFromCode( textValue ) mm.model = json2 this.generateCodeFromModel( json2 ) } , getJsonModelFromCode: function( codeV ) { var json2 = saveHelper.getValueOfCodeString(codeV,"formEditor",")//formEditor") return json2 } , generateCodeFromModel: function( jsonModel ) { var startIndex = this.text.indexOf("//** gen_start **//") var endIndex = this.text.indexOf("//** gen_end **//") this.text = this.text.substring(0,startIndex) + "//** gen_start **//\n" + `Vue.component('form_subscribe_to_appshare', { template: \`<div>new form <div v-for='field in model.fields'> <div v-if='field.type=="text"'>{{field.text}}</div> <div v-if='field.type=="input"'>{{field.label}}<input></input></div> </div> </div>\` , data: function() { return { model: { fields: [ {type: "text", text: "Subscribe to the Appshare newsletter" }, {type: "input", label: "name" }, {type: "input", label: "address" } ] } } } } )\n` + this.text.substring(endIndex) console.log(this.text) } } }) }
JavaScript
0.000001
@@ -203,24 +203,77 @@ = args.text%0A + var designMode = true%0A //*** COPY_START ***//%0A Vue.comp @@ -348,16 +348,53 @@ eturn %7B%0A + design_mode: designMode,%0A @@ -2344,16 +2344,62 @@ //%5Cn%22 +%0A + %22var designMode = false%5Cn%22 +%0A%0A @@ -3461,12 +3461,37 @@ %0A%0A %7D) +%0A //*** COPY_END ***// %0A%0A%7D%0A
b048ae93f0e862e323f307e382a2061675db6403
add optionsSchema
jsreport.config.js
jsreport.config.js
module.exports = { 'name': 'studio', 'main': 'lib/studio.js', 'dependencies': ['express'] }
JavaScript
0.000001
@@ -1,8 +1,9 @@ +%0A module.e @@ -60,16 +60,252 @@ io.js',%0A + 'optionsSchema': %7B%0A extensions: %7B%0A studio: %7B%0A type: 'object',%0A properties: %7B%0A entityTreeOrder: %7B%0A type: 'array',%0A items: %7B type: 'string' %7D%0A %7D%0A %7D%0A %7D%0A %7D%0A %7D,%0A 'depen
a66e9e1737b18fbaebf3664afbf712e340de9511
Update deconfigure.js
canvas/utils/deconfigure.js
canvas/utils/deconfigure.js
if (!Canvas.deconfigure) { Canvas.deconfigure = function(canvasElement) { if (!this.configured) { console.warn("KAPhy warning - Attempted to reconfigure canvas."); return; } Canvas.element = null; Canvas.configured = false; Canvas.relWidth = null; Canvas.relHeight = null; Canvas.context = null; }; }
JavaScript
0.000001
@@ -16,16 +16,51 @@ onfigure + %7C%7C KAPhy.version !== KAPhy.current ) %7B%0A Ca
66d229360a98f53a88c41c1c8da5aaade18cc6af
enable test for #154
test/common.test.js
test/common.test.js
'use strict'; const assert = require('assert'); const common = require('../lib/common'); const blank = { title: '', rows: [], description: undefined }; const schema0 = {}; const schema1 = { properties: { firstName: { type: 'string', description: 'your name' } } }; const schema2 = { type: 'object', description: '', properties: { id: { type: 'string', description: 'an id string' }, data: { type: 'object', properties: { name: { type: 'object', properties: { first: { type: 'string' }, last: { type: 'string' } } } } }, _links: { type: 'array', items: { type: 'string' } } } }; const data = { 'translations': { 'indent': '»' } }; describe('common tests', () => { describe('schemaToArray tests', () => { it('should return a blank container if all inputs are blank', () => { const schema = {}; const offset = 0; const options = {}; const result = common.schemaToArray(schema0, offset, options, data); assert.equal(result[0].title, ''); assert.equal(result[0].rows[0], undefined); assert.equal(result[0].description, undefined); }); it('should create a row for each property and subproperty', () => { const offset = 0; const options = {}; assert.equal(common.schemaToArray(schema1, offset, options, data)[0].rows.length, 1); assert.equal(common.schemaToArray(schema2, offset, options, data)[0].rows.length, 6); }); it('should calculate depth properly', () => { const offset = 0; const options = {}; assert.equal(common.schemaToArray(schema1, offset, options, data)[0].rows[0].depth, 1); const result = common.schemaToArray(schema2, offset, options, data); assert.equal(result[0].rows[0].depth, 1); assert.equal(result[0].rows[1].depth, 1); assert.equal(result[0].rows[2].depth, 2); assert.equal(result[0].rows[3].depth, 3); assert.equal(result[0].rows[4].depth, 3); // this is the actual depth calculation test which is failing //assert.equal(result[0].rows[5].depth, 1); }); it('should create a name for each row', () => { const offset = 0; const options = {}; assert.equal(common.schemaToArray(schema1, offset, options, data)[0].rows[0].name, 'firstName'); const result = common.schemaToArray(schema2, offset, options, data); assert.equal(result[0].rows[0].name, 'id'); assert.equal(result[0].rows[1].name, 'data'); assert.equal(result[0].rows[2].name, 'name'); assert.equal(result[0].rows[3].name, 'first'); assert.equal(result[0].rows[4].name, 'last'); assert.equal(result[0].rows[5].name, '_links'); }); }); });
JavaScript
0.000003
@@ -2539,84 +2539,8 @@ -// this is the actual depth calculation test which is failing%0A // asse
f20c04f0ea85f96a23c4f5ab54ddf8ddd2e66787
test if es6 env is disabled
test/config-test.js
test/config-test.js
'use strict'; var assert = require('assert'); var config = require('../'); var reactConfig = require('../react'); var babelConfig = require('../babel'); assert.equal(config.env.node, true); assert((reactConfig.plugins || []).indexOf('react') > -1); assert(reactConfig.ecmaFeatures.jsx); assert(reactConfig.rules['react/jsx-no-undef'], 2); assert(babelConfig.parser === 'babel-eslint'); assert(babelConfig.env.es6); assert(babelConfig.ecmaFeatures.modules);
JavaScript
0.000001
@@ -184,16 +184,53 @@ , true); +%0Aassert.equal(config.env.es6, false); %0A%0Aassert
77caa2b4d57241ad5dda5bd0354c491438b1efa0
Correct /test-data mount point
test/default/pre.js
test/default/pre.js
try { this['Module'] = Module; Module.test; } catch(e) { this['Module'] = Module = {}; } Module['preRun'] = Module['preRun'] || []; Module['preRun'].push(function(){ var randombyte = null; try { function randombyte_standard() { var buf = new Int8Array(1); window.crypto.getRandomValues(buf); return buf[0]; } randombyte_standard(); randombyte = randombyte_standard; } catch (e) { try { var crypto = require('crypto'); function randombyte_node() { return crypto.randomBytes(1)[0]; } randombyte_node(); randombyte = randombyte_node; } catch(e) { throw 'No secure random number generator found'; } } FS.init(); FS.mkdir('/test-data'); FS.mount(NODEFS, { root: '.' }, '/test'); FS.analyzePath('/dev/random').exists && FS.unlink('/dev/random'); FS.analyzePath('/dev/urandom') && FS.unlink('/dev/urandom'); var devFolder = FS.findObject('/dev') || Module['FS_createFolder']('/', 'dev', true, true); Module['FS_createDevice'](devFolder, 'random', randombyte); Module['FS_createDevice'](devFolder, 'urandom', randombyte); });
JavaScript
0.000006
@@ -896,16 +896,21 @@ , '/test +-data ');%0A
e7a8db2bb331aeb55d243e6f7498f22f10e100f0
switch from tape to ava
test/docker.spec.js
test/docker.spec.js
'use strict' const sinon = require('sinon') const test = require('tape') const {execSync} = require('child_process') const log = require('../src/npmlog-env') const docker = !!process.env.WECHATY_DOCKER !docker && test('Docker test skipped', function(t) { t.pass('not in docker, skip docker tests') t.end() }) docker && test('Docker smoking test', function(t) { const n = execSync('ps | grep Xvfb | wc -l') t.equal(n, 1, 'should has Xvfb started') t.end() })
JavaScript
0.000001
@@ -1,95 +1,49 @@ -'use strict'%0A%0Aconst sinon = require('sinon')%0Aconst test = require('tape')%0A%0Acons +import %7B test %7D from 'ava'%0A%0Aimpor t %7B + execSync %7D = @@ -42,20 +42,16 @@ Sync -%7D = require( + %7D from 'chi @@ -65,53 +65,61 @@ ess' -)%0A%0Aconst log = require('../src/npmlog-env') +%0Aimport sinon from 'sinon'%0A%0Aimport %7B log %7D from '../' %0A%0Aco @@ -265,20 +265,8 @@ s')%0A - t.end()%0A %7D)%0A%0A @@ -372,13 +372,10 @@ t. -equal +is (n, @@ -407,19 +407,8 @@ ed') -%0A%0A t.end() %0A%7D)%0A
94535715187e0a30b4448f03627e7c5c61d1cc8b
change idempotence tests structure otherwise errors might happen on beforeEach, which is hard to track
test/format.spec.js
test/format.spec.js
/*jshint node:true*/ /*global describe:false, it:false, beforeEach:false*/ "use strict"; var esprima = require('esprima'); var expect = require('chai').expect; var _glob = require('glob'); var _path = require('path'); var esformatter = require('../lib/esformatter'); var _helpers = require('./helpers'); var readOut = _helpers.readOut; var readIn = _helpers.readIn; var readConfig = _helpers.readConfig; // --- describe('esformatter.format()', function () { // we generate the specs dynamically based on files inside the compare // folder since it will be easier to write the tests and do the comparison describe('default options', function () { var pattern = _path.join(_helpers.COMPARE_FOLDER, 'default/*-in.js'); _glob.sync( pattern ).forEach(function(fileName){ // we read files before the test to avoid affecting the test // benchmark, I/O operations are expensive. var id = fileName.replace(/.+(default\/.+)-in\.js/, '$1'); var input, compare, result; beforeEach(function(){ input = readIn(id); compare = readOut(id); result = result? result : esformatter.format(input); }); it(id, function () { expect( result ).to.equal( compare ); // result should be valid JS expect(function(){ try { esprima.parse(result); } catch (e) { throw new Error('esformatter.format() result produced a non-valid output.\n'+ e); } }).to.not.Throw(); }); it(id +'(idempotent)', function () { // make sure formatting can be applied multiple times // (idempotent) expect( esformatter.format(result) ).to.equal( compare ); }); }); }); describe('custom options', function () { var pattern = _path.join(_helpers.COMPARE_FOLDER, 'custom/*-in.js'); _glob.sync( pattern ).forEach(function(fileName){ // we read files before the test to avoid affecting the test // benchmark, I/O operations are expensive. var id = fileName.replace(/.+(custom\/.+)-in\.js/, '$1'); var input, options, compare, result; beforeEach(function(){ input = readIn(id); options = readConfig(id); compare = readOut(id); result = result? result : esformatter.format(input, options); }); it(id, function () { expect( result ).to.equal( compare ); // result should be valid JS expect(function(){ try { esprima.parse(result); } catch (e) { throw new Error('esformatter.format() result produced a non-valid output.\n'+ e); } }).to.not.Throw(); }); it(id +' (idempotent)', function(){ // make sure formatting can be applied multiple times // (idempotent) expect( esformatter.format(result, options) ).to.equal( compare ); }); }); }); });
JavaScript
0
@@ -51,26 +51,8 @@ alse -, beforeEach:false */%0A%22 @@ -979,32 +979,70 @@ in%5C.js/, '$1');%0A +%0A it(id, function () %7B%0A var @@ -1068,44 +1068,8 @@ ult; -%0A%0A beforeEach(function()%7B %0A @@ -1213,57 +1213,8 @@ t);%0A - %7D);%0A%0A it(id, function () %7B %0A @@ -1256,32 +1256,33 @@ ual( compare );%0A +%0A @@ -1619,73 +1619,8 @@ ();%0A - %7D);%0A%0A it(id +'(idempotent)', function () %7B %0A @@ -2209,24 +2209,62 @@ js/, '$1');%0A +%0A it(id, function () %7B%0A @@ -2303,44 +2303,8 @@ ult; -%0A%0A beforeEach(function()%7B %0A @@ -2499,57 +2499,8 @@ s);%0A - %7D);%0A%0A it(id, function () %7B %0A @@ -2542,32 +2542,33 @@ ual( compare );%0A +%0A @@ -2905,72 +2905,8 @@ ();%0A - %7D);%0A%0A it(id +' (idempotent)', function()%7B %0A
8d19905ff0408d5f8e9fe2b0beb8da625fd21651
Test configuration variations for pending requests
test/max_pending.js
test/max_pending.js
// Copyright (c) 2015 Uber Technologies, Inc. // // 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. 'use strict'; var parallel = require('run-parallel'); var Result = require('bufrw/result'); var MockTimers = require('time-mock'); var allocCluster = require('./lib/alloc-cluster'); testWithOptions({ numPeers: 2, channelOptions: { maxPending: 1, timers: MockTimers(Date.now()), random: lucky, requestDefaults: { trackPending: true } } }, [ 'tchannel.timeout', 'tchannel.max-pending' ]); testWithOptions({ numPeers: 2, channelOptions: { maxPendingForService: 1, timers: MockTimers(1.5e12), // approximately soon random: lucky, requestDefaults: { trackPending: true } } }, [ 'tchannel.timeout', 'tchannel.max-pending-for-service' ]); function testWithOptions(options, expectedErrorTypes) { allocCluster.test('exercise maximum pending requests', options, function t(cluster, assert) { var tweedleDee = cluster.channels[0]; var tweedleDum = cluster.channels[1]; var timers = tweedleDee.timers; var deeChannel = tweedleDee.makeSubChannel({ serviceName: 'battle' }); var dumChannel = tweedleDum.makeSubChannel({ serviceName: 'battle' }); dumChannel.peers.add(tweedleDee.hostPort); deeChannel.register('start', function start() { // Let's just say we did }); parallel([challengeSender(), challengeSender()], function verifyIt(err, results) { if (err) return assert.end(err); assert.equals(results[0].err.type, expectedErrorTypes[0], 'first should fail due to a timeout'); assert.equals(results[1].err.type, expectedErrorTypes[1], 'second should fail because max pending exceeded'); assert.end(); }); // TODO ascertain why this test stalls non-deterministically, and with // increasing probability, for values from 2000ms down to 1000ms. timers.advance(2000); function challengeSender() { return function sendChallenge(cb) { dumChannel.request({ serviceName: 'battle', timeout: 1000 }).send('start', '', '', regardless(cb)); }; } function regardless(cb) { return function resultRegardless(err, value) { return cb(null, new Result(err, value)); }; } }); } function lucky() { return 1.0; }
JavaScript
0
@@ -1299,36 +1299,63 @@ ter');%0A%0Atest -WithOptions( +Battle('cap maximum pending requests', %7B%0A numPee @@ -1608,28 +1608,67 @@ );%0A%0Atest -WithOptions( +Battle('cap maximum pending requests per service', %7B%0A nu @@ -1965,33 +1965,657 @@ );%0A%0A -function testWithOptions( +testBattle('channel-scoped max pending supercedes per-service', %7B%0A numPeers: 2,%0A channelOptions: %7B%0A maxPending: 1,%0A maxPendingForService: 1,%0A timers: MockTimers(1.5e12), // approximately soon%0A random: lucky,%0A requestDefaults: %7B%0A trackPending: true%0A %7D%0A %7D%0A%7D, %5B%0A 'tchannel.timeout',%0A 'tchannel.max-pending'%0A%5D);%0A%0AtestBattle('do not opt-in for pending request tracking', %7B%0A numPeers: 2,%0A channelOptions: %7B%0A maxPending: 1,%0A timers: MockTimers(Date.now()),%0A random: lucky%0A %7D%0A%7D, %5B%0A 'tchannel.timeout',%0A 'tchannel.timeout'%0A%5D);%0A%0Afunction testBattle(name, opti @@ -2667,43 +2667,12 @@ est( -'exercise maximum pending requests' +name , op
ec74e2c1960b364a919484d54e79575ec9eaec90
add two parameter function spec
test/plugin.spec.js
test/plugin.spec.js
const expect = require('chai').expect; let Validator = require('jsonschema').Validator; const isPlugin = require('..'); const v = new Validator(); v.attributes.is = isPlugin(); describe('jsonschema is.js tests', function() { it('should have schema function error', function(done) { const schema = { type: 'object', properties: { emails: { type: 'array', is: 'all.emali' } // <- typo } }; let result = v.validate({ emails: [ '[email protected]', '[email protected]' ] }, schema); expect(result.errors).to.have.length(1); expect(result.errors[0].message).to.equal('function not found: isjs.all.emali'); done(); }); it('should pass', function(done) { const schema = { type: 'object', properties: { emails: { type: 'array', is: 'all.email' } } }; let result = v.validate({ emails: [ '[email protected]', '[email protected]' ] }, schema); expect(result.errors).to.have.length(0); done(); }); it('should have 1 error', function(done) { const schema = { type: 'object', properties: { emails: { type: 'array', is: 'all.email' } } }; let result = v.validate({ emails: [ '[email protected]', '[email protected]', 123, 'test' ] }, schema); expect(result.errors).to.have.length(1); done(); }); });
JavaScript
0.000002
@@ -1286,12 +1286,666 @@ );%0A %7D); +%0A%0A it('should pass two parameter function', function(done) %7B%0A const schema = %7B%0A type: 'object',%0A properties: %7B%0A text: %7B type: 'string', is: 'include:some text' %7D%0A %7D%0A %7D;%0A let result = v.validate(%7B text: 'some text...' %7D, schema);%0A expect(result.errors).to.have.length(0);%0A done();%0A %7D);%0A%0A it('should not pass two parameter function', function(done) %7B%0A const schema = %7B%0A type: 'object',%0A properties: %7B%0A text: %7B type: 'string', is: 'include: some text' %7D%0A %7D%0A %7D;%0A let result = v.validate(%7B text: 'some text...' %7D, schema);%0A expect(result.errors).to.have.length(1);%0A done();%0A %7D); %0A%7D);
6f259a703ca6a7d53e529707f8c5d97f45d30e9f
Fix css for dataset picker dialog [fix #34954383]
app/assets/javascripts/dialogs/tabular_data/import_datasets_picker_dialog.js
app/assets/javascripts/dialogs/tabular_data/import_datasets_picker_dialog.js
chorus.dialogs.ImportDatasetsPicker = chorus.dialogs.PickItems.extend({ title: t("dataset.pick"), constructorName: "DatasetsPickerDialog", submitButtonTranslationKey: "actions.dataset_select", emptyListTranslationKey: "dataset.none", searchPlaceholderKey: "dataset.dialog.search_table", selectedEvent: 'datasets:selected', modelClass: "Table", pagination: true, multiSelection: false, serverSideSearch: true, events: _.extend({ "click a.preview_columns": "clickPreviewColumns" }, this.events), setup: function() { this._super("setup"); this.pickItemsList.templateName = "import_datasets_picker_list"; }, makeModel: function() { this._super("makeModel", arguments); this.collection = new chorus.collections.DatasetSet([], { workspaceId: this.options.workspaceId, type: "SANDBOX_TABLE", objectType: "BASE_TABLE" }); this.collection.sortAsc("objectName"); this.collection.fetch(); }, collectionModelContext: function (model) { return { id: model.get("id"), name: model.get("objectName"), imageUrl: model.iconUrl({size: 'medium'}) } }, clickPreviewColumns: function(e) { e && e.preventDefault(); var clickedId = $(e.target).closest("li").data("id"); var databaseObject = this.collection.get(clickedId); var previewColumnsDialog = new chorus.dialogs.PreviewColumns({model: databaseObject}); previewColumnsDialog.title = this.title; this.launchSubModal(previewColumnsDialog); } });
JavaScript
0
@@ -672,16 +672,86 @@ _list%22;%0A + this.pickItemsList.className = %22import_datasets_picker_list%22;%0A %7D,%0A%0A
cecb778b4b44cf76b17c36781cec5e7f37616a5e
fix querystring tests
test/querystring.js
test/querystring.js
var common = require('../lib/common') var test = require('tape') // https://github.com/webtorrent/webtorrent/issues/196 test('encode special chars +* in http tracker urls', function (t) { var q = { info_hash: Buffer.from('a2a15537542b22925ad10486bf7a8b2a9c42f0d1', 'hex').toString('binary') } var encoded = 'info_hash=%A2%A1U7T%2B%22%92Z%D1%04%86%BFz%8B%2A%9CB%F0%D1' t.equal(common.querystringStringify(q), encoded) // sanity check that encode-decode matches up t.deepEqual(common.querystringParse(common.querystringStringify(q)), q) t.end() })
JavaScript
0.000001
@@ -196,14 +196,32 @@ q = -%7B%0A +Object.create(null)%0A q. info @@ -225,17 +225,18 @@ nfo_hash -: + = Buffer. @@ -314,11 +314,8 @@ y')%0A - %7D %0A v
7a45d261a7720133c7004487f273915c48cfef7b
Fix inviting others to private messages.
app/assets/javascripts/discourse/components/private_message_map_component.js
app/assets/javascripts/discourse/components/private_message_map_component.js
/** The controls at the top of a private message in the map area. @class PrivateMessageMapComponent @extends Ember.Component @namespace Discourse @module Discourse **/ Discourse.PrivateMessageMapComponent = Ember.View.extend({ templateName: 'components/private-message-map', tagName: 'section', classNames: ['information'], details: Em.computed.alias('topic.details'), init: function() { this._super(); this.set('context', this); this.set('controller', this); }, actions: { removeAllowedUser: function(user) { var self = this; bootbox.dialog(I18n.t("private_message_info.remove_allowed_user", {name: user.get('username')}), [ {label: I18n.t("no_value"), 'class': 'btn-danger rightg'}, {label: I18n.t("yes_value"), 'class': 'btn-primary', callback: function() { self.get('topic.details').removeAllowedUser(user); } } ]); }, showPrivateInvite: function() { this.sendAction('showPrivateInviteAction'); } } });
JavaScript
0
@@ -457,42 +457,8 @@ s);%0A - this.set('controller', this);%0A %7D, @@ -973,18 +973,30 @@ his. -sendAction +get('controller').send ('sh
9ca9ac07cbbf12a2fd8d7ff6e890fbcc45e54307
Add more tests.
test/request.get.js
test/request.get.js
var request = require('request'), should = require('should'), muxamp = require('../lib/server').getApplication(), testutils = require('../lib/testutils'); describe('GET', function() { var baseUrl = 'http://localhost:' + 3000 + '/'; testutils.server.testWithServer(3000, function() { describe('search endpoint', function() { it('should return search results as JSON', function(done) { request({url: baseUrl + 'search/ytv/0/deadmau5'}, function(err, response, body) { response.statusCode.should.eql(200); should.not.exist(err); JSON.parse(body).should.have.length(25); done(); }); }); }); }); });
JavaScript
0
@@ -340,266 +340,1064 @@ %0A%09%09%09 -it('should return search results as JSON', function(done) %7B%0A%09%09%09%09request(%7Burl: baseUrl + 'search/ytv/0/deadmau5'%7D, function(err, response, body) %7B%0A%09%09%09%09%09response.statusCode.should.eql(200);%0A%09%09%09%09%09should.not.exist(err);%0A%09%09%09%09%09JSON.parse(body).should.have.length(2 +describe('error handling', function() %7B%0A%09%09%09%09it('should return an error for no query', function(done) %7B%0A%09%09%09%09%09request(%7Burl: baseUrl + 'search/ytv/0/'%7D, function(err, response, body) %7B%0A%09%09%09%09%09%09response.statusCode.should.eql(200);%0A%09%09%09%09%09%09JSON.parse(body).should.have.property('error');%0A%09%09%09%09%09%09done();%0A%09%09%09%09%09%7D);%0A%09%09%09%09%7D);%0A%09%09%09%7D);%0A%09%09%09it('should return search results as JSON', function(done) %7B%0A%09%09%09%09request(%7Burl: baseUrl + 'search/ytv/0/deadmau5'%7D, function(err, response, body) %7B%0A%09%09%09%09%09response.statusCode.should.eql(200);%0A%09%09%09%09%09should.not.exist(err);%0A%09%09%09%09%09JSON.parse(body).should.have.length(25);%0A%09%09%09%09%09done();%0A%09%09%09%09%7D);%0A%09%09%09%7D);%0A%09%09%7D);%0A%09%09describe('playlist endpoint', function() %7B%0A%09%09%09it('should return search results as JSON', function(done) %7B%0A%09%09%09%09request(%7Burl: baseUrl + 'playlists/57'%7D, function(err, response, body) %7B%0A%09%09%09%09%09response.statusCode.should.eql(200);%0A%09%09%09%09%09should.not.exist(err);%0A%09%09%09%09%09var data = JSON.parse(body);%0A%09%09%09%09%09data.should.have.property('id');%0A%09%09%09%09%09data%5B'id'%5D.should.eql(57);%0A%09%09%09%09%09data.should.have.property('tracks');%0A%09%09%09%09%09data%5B'tracks'%5D.should.have.length( 5);%0A
2d9feaa714088dafc473434b8a57e559b3416a5d
Update learn getters to create page link references
kolibri/plugins/learn/assets/src/modules/pluginModule.js
kolibri/plugins/learn/assets/src/modules/pluginModule.js
import mutations from './coreLearn/mutations'; import * as getters from './coreLearn/getters'; import * as actions from './coreLearn/actions'; import classAssignments from './classAssignments'; import classes from './classes'; import examReportViewer from './examReportViewer'; import examViewer from './examViewer'; import lessonPlaylist from './lessonPlaylist'; import topicsTree from './topicsTree'; import plugin_data from 'plugin_data'; export default { state() { return { pageName: '', rootNodes: [], canAccessUnassignedContentSetting: plugin_data.allowLearnerUnassignedResourceAccess, allowGuestAccess: plugin_data.allowGuestAccess, }; }, actions, getters, mutations, modules: { classAssignments, classes, examReportViewer, examViewer, lessonPlaylist, topicsTree, }, };
JavaScript
0
@@ -1,12 +1,74 @@ +import %7B PageNames, ClassesPageNames %7D from './../constants';%0A import mutat @@ -759,16 +759,1275 @@ getters +: %7B%0A ...getters,%0A learnPageLinks() %7B%0A const params = %7B%7D;%0A return %7B%0A HomePage: %7B%0A name: PageNames.HOME,%0A params,%0A %7D,%0A LibraryPage: %7B%0A name: PageNames.LIBRARY,%0A params,%0A %7D,%0A TopicsPage: %7B%0A name: PageNames.TOPICS_TOPIC,%0A params,%0A %7D,%0A TopicsSearchPage: %7B%0A name: PageNames.TOPICS_TOPIC_SEARCH,%0A params,%0A %7D,%0A ContentUnavailablePage: %7B%0A name: PageNames.CONTENT_UNAVAILABLE,%0A params,%0A %7D,%0A BookmarksPage: %7B%0A name: PageNames.BOOKMARKS,%0A params,%0A %7D,%0A ExamPage: id =%3E %7B%0A return %7B%0A name: ClassesPageNames.EXAM_VIWER,%0A params: %7B params, quizId: id %7D,%0A %7D;%0A %7D,%0A ExamReportViewer: %7B%0A name: ClassesPageNames.EXAM_REPORT_VIEWER,%0A params,%0A %7D,%0A AllClassesPage: %7B%0A name: ClassesPageNames.ALL_CLASSES,%0A params,%0A %7D,%0A ClassAssignmentsPage: %7B%0A name: ClassesPageNames.CLASS_ASSIGNMENTS,%0A params,%0A %7D,%0A LessonPlaylistPage: %7B%0A name: ClassesPageNames.LESSON_PLAYLIST,%0A params,%0A %7D,%0A %7D;%0A %7D,%0A %7D ,%0A muta
23d82be04e8189667084a3f168eb593f62216325
add n to desc
test/statistical.js
test/statistical.js
var LFSR = require('../index.js'), expect = require('chai').expect, utils = require('./utils.js'), bin = utils.bin, str = utils.str; context('statistical', function() { utils.everyLength(28, function(n) { (function(n) { it('max length for n = ' + n + ' is ' + (Math.pow(2, n) - 1), function() { this.timeout(20000); var lfsr = new LFSR(n), count = 0, initial = lfsr.register; do { lfsr.shift(); count++; } while (lfsr.register != initial); expect(count).to.equal(Math.pow(2, n) - 1); }); })(n); }); describe('distribution', function() { utils.everyLength(function(n) { (function(n) { it('evenly distributes bits', function() { var lfsr = new LFSR(), occur = {'0': 0, '1': 0}, bit; for (var i = 0; i < 100000; i++) { bit = lfsr.shift(); occur[bit]++; } var ratio = occur['0'] / occur['1']; expect(ratio).to.be.closeTo(1, 0.1); }); })(n); }); }); });
JavaScript
0
@@ -871,17 +871,30 @@ tes bits -' + for n = ' + n , functi
b223c3f57215b8e42ee1792d507c146afad1129d
Test to add a subscriber to new list and remove it.
test/subscribers.js
test/subscribers.js
JavaScript
0
@@ -0,0 +1,927 @@ +/* global describe, it */%0A%0A'use strict'%0A%0Avar expect = require('expect.js')%0A%0Avar MailerLite = require('..')%0Avar ML = new MailerLite()%0A%0Aconst LIST_NAME = 'Mocha Test'%0A%0Aconst TEST_SUBSCRIBERS = %5B%0A %7B%0A email: '[email protected]',%0A name: 'Foo Bar'%0A %7D,%0A %7B%0A email: '[email protected]',%0A name: 'John Doe'%0A %7D%0A%5D%0A%0Adescribe('Subscribers', () =%3E %7B%0A it('should add a subscriber to a new list and remove it immediately', (done) =%3E %7B%0A let list_id = 0%0A let user = TEST_SUBSCRIBERS%5B0%5D%0A%0A ML.Lists.addList(LIST_NAME)%0A .then((data) =%3E %7B%0A list_id = data.id%0A return ML.Subscribers.addSubscriber(list_id, user.email, user.name)%0A %7D)%0A .then((data) =%3E %7B%0A expect(data.email).to.be.equal(user.email)%0A return ML.Subscribers.deleteSubscriber(list_id, user.email)%0A %7D)%0A .then((data) =%3E %7B%0A return ML.Lists.removeList(list_id)%0A %7D)%0A .then(() =%3E %7B%0A done()%0A %7D)%0A %7D)%0A%7D)%0A
039500e9fda16a2ef8dadc6f67f0722a1e13ad5a
add a failing test for #319 (#328)
test/switch_test.js
test/switch_test.js
import check from './support/check.js'; describe('switch', () => { it('works with a single case', () => { check(` switch a when b c `, ` switch (a) { case b: c; break; } `); }); it('works when there is a comment after the expression', () => { check(` switch a # yolo when b c `, ` switch (a) { // yolo case b: c; break; } `); }); it('works when the expression is already surrounded by parens', () => { check(` switch (a?) when b c `, ` switch (typeof a !== 'undefined' && a !== null) { case b: c; break; } `); }); it('only inserts break statements when needed', () => { check(` switch a when b c break when d e break `, ` switch (a) { case b: c; break; case d: e; break; } `); }); it('works with multiple cases', () => { check(` switch a when b c when d e `, ` switch (a) { case b: c; break; case d: e; break; } `); }); it('works with multiple conditions per case', () => { check(` switch a when b, c d `, ` switch (a) { case b: case c: d; break; } `); }); it('works with cases and consequents on the same line', () => { check(` switch a when b then c `, ` switch (a) { case b: c; break; } `); }); it('works with a default case', () => { check(` switch a when b c else d `, ` switch (a) { case b: c; break; default: d; } `); }); it('works with a single-line default case', () => { check(` switch a when b then c else d `, ` switch (a) { case b: c; break; default: d; } `); }); it('works with an indented switch', () => { check(` if true switch a when b c `, ` if (true) { switch (a) { case b: c; break; } } `); }); it('works with implicit returns', () => { check(` -> switch a when b then c when d e f else g `, ` (function() { switch (a) { case b: return c; case d: e; return f; default: return g; } }); `); }); it('works with implicit returns with the default case on another line', () => { check(` -> switch a when b then c else d `, ` (function() { switch (a) { case b: return c; default: return d; } }); `); }); it('writes the closing curly brace inside a function closing brace', () => { check(` a = -> switch b when c d e `, ` let a = function() { switch (b) { case c: return d; } }; e; `); }); it('converts a switch without an expression properly', () => { check(` switch when score < 60 then 'F' when score < 70 then 'D' when score < 80 then 'C' when score < 90 then 'B' else 'A' `, ` switch (false) { case score >= 60: 'F'; break; case score >= 70: 'D'; break; case score >= 80: 'C'; break; case score >= 90: 'B'; break; default: 'A'; } `); }); it('works with `switch` used as an expression', () => { check(` a = switch b when c then d when f return g else e `, ` let a = (() => { switch (b) { case c: return d; case f: return g; default: return e; } })(); `); }); it('works with the switch from the CoffeeScript demo page', () => { check(` switch day when "Mon" then go work when "Tue" then go relax when "Thu" then go iceFishing when "Fri", "Sat" if day is bingoDay go bingo go dancing when "Sun" then go church else go work `, ` switch (day) { case "Mon": go(work); break; case "Tue": go(relax); break; case "Thu": go(iceFishing); break; case "Fri": case "Sat": if (day === bingoDay) { go(bingo); go(dancing); } break; case "Sun": go(church); break; default: go(work); } `); }); });
JavaScript
0.000001
@@ -4233,32 +4233,257 @@ %0A %60);%0A %7D);%0A%0A + it.skip('works with %60switch%60 used as an expression surrounded by parens', () =%3E %7B%0A check(%60%0A a(switch b%0A when c then d)%0A %60, %60%0A a((() =%3E %7B switch (b) %7B%0A case c: return d; %7D %7D)());%0A %60);%0A %7D);%0A%0A it('works with
b32a902c2347b62ed27bcb38f4164903a64261de
Update test-filter.js
test/test-filter.js
test/test-filter.js
var TweetFilter = require('../lib/filter.js') var filter = new TweetFilter('filters', ['excludeme']) var matches = [ 'help me go vegan', 'help me become vegan', 'help me be vegan', 'i want to go vegan', 'i want to become vegan', 'i want to be vegan', 'i wanna go vegan', 'i wanna be vegan', "I would like to go vegan", "I want to be a vegan", "I wanna become vegan", "I wanna be a vegan", "I really wanna be vegan", "I should go vegan", "I probably should go vegan", "I need help going vegan", "I want help going vegan", "I really need help staying vegan", "I think that i want to go vegan", "I think i should go vegan", "i will need help going vegan", "i do need help going vegan", "i definitely want to go vegan", "i definately want to go vegan", "i honestly would like to go vegan", "i truly want to try going vegan", "i wanna try becoming a vegan", "i'm thinking about going vegan", "i'm thinking of going vegan", "im thinking about becoming vegan", "i am considering being a vegan", "i'm mulling over becoming vegan", "i want to go #vegan", "i. want. to. go. vegan.", "i.. want to go ... vegan", "i wish i was vegan", "i wish i were vegan", ]; var falsePositives = [ "I do not want to go vegan", "I should be a vegan", // this phrasing more than likely isn't about going vegan long-term (e.g. I should be a vegan for Halloween) ]; exports.matches = function(test) { matches.forEach(function(match) { test.ok(filter.matches(match), "'" + match + "' should match"); }) test.done(); }; exports.falsePositives = function(test) { falsePositives.forEach(function(falsePositive) { test.ok(!filter.matches(falsePositive), "'" + falsePositive + "' should not match"); }) // matching phrases with the word 'vegetarian' subbed for 'vegan' should not match matches.forEach(function(match) { var falsePositive = match.replace(/vegan/g, 'vegetarian'); test.ok(!filter.matches(falsePositive), "'" + falsePositive + "' should not match"); }) test.done(); }; exports.retweeted = function(test) { var retweetedTweet = {retweeted: true, text: "", user: {description: "", name: "", screen_name: ""}}; test.ok(!filter.matches(retweetedTweet), "Filter should not match retweeted tweets"); test.done(); } exports.reply = function(test) { var replyTweet = {retweeted: false, text: "@someone I want to go vegan", user: {description: "", name: "", screen_name: ""}}; test.ok(!filter.matches(replyTweet), "Filter should not match @reply tweets"); test.done(); } exports.excludedTerms = function(test) { var excludedBioTweet = {retweeted: false, text: "I want to go vegan", user: {description: "Something and excludeme", name: "", screen_name: ""}}; var excludedNameTweet = {retweeted: false, text: "I want to go vegan", user: {description: "", name: "EXCLUDEME", screen_name: ""}}; var excludedScreenNameTweet = {retweeted: false, text: "I want to go vegan", user: {description: "", name: "", screen_name: "excludeme"}}; test.ok(!filter.matches(excludedBioTweet), "Filter should not match tweets from users with excluded terms in their bio"); test.ok(!filter.matches(excludedNameTweet), "Filter should not match tweets from users with excluded terms in their name"); test.ok(!filter.matches(excludedScreenNameTweet), "Filter should not match tweets from users with excluded terms in their screen name"); test.done(); }
JavaScript
0.000001
@@ -1289,16 +1289,117 @@ vegan%22,%0A + %22i can see myself becoming a vegan someday%22,%0A %22i could definitely picture myself going vegan%22%0A %5D;%0A%0Avar @@ -3655,28 +3655,29 @@ n name%22);%0A test.done();%0A%7D +%0A
8de92e7e3acee87e6bf9b2932a56783d0d3ebacf
Add test for PR page, check if author is redacted
test/test-github.js
test/test-github.js
"use strict"; const {expect} = require("chai"); before(() => { browser.url("/login"); browser.setCookie({ name: "user_session", value: process.env.USER_SESSION, }); }); describe("Pull Requests (listings)", () => { it("should redact the author", () => { browser.url("/pulls/mentioned"); const prInfo = $(".opened-by").getText(); expect(prInfo).to.match(/^#1 opened \d+ days ago by$/); }); });
JavaScript
0
@@ -412,16 +412,524 @@ y$/);%0A %7D);%0A%7D);%0A +%0Adescribe(%22(single) Pull Request Page%22, () =%3E %7B%0A it(%22should redact the author%22, () =%3E %7B%0A browser.url(%22/zombie/testing-reviews/pull/3%22);%0A%0A const topFlash = $(%22div.flash %3E div%22).getText();%0A expect(topFlash).to.equal(%22requested your review on this pull request.%22);%0A%0A const commentInfo = $(%22h3.timeline-comment-header-text%22).getText();%0A expect(commentInfo).to.match(/%5Ecommented %5Cd+ days ago$/);%0A%0A const avatar = $(%22a.participant-avatar%22).isVisible();%0A expect(avatar).to.be.false;%0A %7D);%0A%7D);%0A
655a586c7837594222042dcf6d8d2e6b26eb0d87
Add test case in case fetch is overriden
lib/assets/test/spec/cartodb/models/organization.spec.js
lib/assets/test/spec/cartodb/models/organization.spec.js
describe('cdb.admin.Organization', function() { beforeEach(function() { this.organization = new cdb.admin.Organization({ id: "68a57d79-d454-4b28-8af8-968e97b1349c", seats: 5, quota_in_bytes: 1234567890, created_at: "2014-06-05T16:34:51+02:00", updated_at: "2014-06-05T16:34:51+02:00", name: "orgtest3", owner: { id: "4ab67a64-7cbf-4890-88b8-9d3c398249d5", username: "dev", avatar_url: null }, users:[] }); }); it("should have owner", function() { expect(this.organization.owner.get('username')).toEqual('dev'); }); it("should have a users collection attribute", function() { expect(this.organization.users).not.toBeUndefined(); }); it("all collections should have reference to the organization", function() { var newOrg = new cdb.admin.Organization({ id: "68a57d79-d454-4b28-8af8-968e97b1349c", seats: 5, quota_in_bytes: 1234567890, created_at: "2014-06-05T16:34:51+02:00", updated_at: "2014-06-05T16:34:51+02:00", name: "orgtest3", owner: { id: "4ab67a64-7cbf-4890-88b8-9d3c398249d5", username: "dev", avatar_url: null }, users: [ {id: "b6551618-9544-4f22-b8ba-2242d6b20733", "username":"t2", "avatar_url":null}, {id: "5b514d61-fb7a-4b9b-8a0a-3fdb82cf79ca", "username":"t1", "avatar_url":null} ], groups: [ {id: 'g1'}, {id: 'g2'}, ] }) expect(newOrg.users.organization).toEqual(newOrg); expect(newOrg.groups.organization).toEqual(newOrg); expect(newOrg.grantables.organization).toEqual(newOrg); }); }); describe('cdb.admin.Organization.Users', function() { beforeEach(function() { this.org = new cdb.admin.Organization({ id: 'hello-org-id' }); this.orgUsers = new cdb.admin.Organization.Users( null, { organization: this.org, currentUserId: 'current-user-id' } ); this.orgUsers.sync = function(a, b, opts) {} }); it("should include sync abort", function() { expect(this.orgUsers.sync).not.toBeUndefined(); }); it("should parse results properly", function() { this.orgUsers.sync = function(a,b,opts) { opts.success && opts.success({ users: [ generateUser() ], total_user_entries: 1, total_entries: 1 }); }; this.orgUsers.fetch(); expect(this.orgUsers.length).toBe(1); expect(this.orgUsers.total_user_entries).toBe(1); expect(this.orgUsers.total_entries).toBe(1); }); it("should exclude current user from results", function() { this.orgUsers.sync = function(a,b,opts) { opts.success && opts.success({ users: [ generateUser('current-user-id'), generateUser() ], total_user_entries: 2, total_entries: 2 }); }; this.orgUsers.fetch(); expect(this.orgUsers.length).toBe(1); expect(this.orgUsers.total_user_entries).toBe(1); expect(this.orgUsers.total_entries).toBe(1); }); function generateUser(id) { return { id: id || "hello-id", username: "user" + id, avatar_url: "hi", base_url: "base-url" + id } } });
JavaScript
0
@@ -1922,16 +1922,60 @@ %0A );%0A + this.originalSync = this.orgUsers.sync;%0A this @@ -3060,16 +3060,657 @@ %0A %7D);%0A%0A + describe('when fetch is given data options', function() %7B%0A beforeEach(function() %7B%0A spyOn(Backbone, 'sync').and.returnValue($.Deferred());%0A this.orgUsers.sync = this.originalSync;%0A this.orgUsers.fetch(%7B%0A data: %7B%0A page: 1,%0A per_page: 77,%0A %7D%0A %7D);%0A %7D);%0A%0A it('should set them on the fetch URL', function() %7B%0A expect(Backbone.sync).toHaveBeenCalled();%0A var opts = Backbone.sync.calls.argsFor(0)%5B2%5D;%0A expect(opts).toEqual(%0A jasmine.objectContaining(%7B%0A data: %7B%0A page: 1,%0A per_page: 77%0A %7D%0A %7D)%0A );%0A %7D);%0A %7D);%0A%0A functi
5c4d2f2a42655a87aec7d2323faf642ff8cbcc32
Add EDITING_MANAGEMENT_KEY constant.
assets/js/components/dashboard-sharing/DashboardSharingSettings/constants.js
assets/js/components/dashboard-sharing/DashboardSharingSettings/constants.js
/** * DashboardSharingSettings constants. * * Site Kit by Google, Copyright 2021 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. */ export const EDITING_USER_ROLES_KEY = 'editing-user-roles-key'; export const SHARING_SETTINGS_SLUG_KEY = 'sharing-settings-slug-key'; export const SHARING_SETINGS_SAVING_KEY = 'sharing-setings-saving-key';
JavaScript
0
@@ -712,24 +712,88 @@ roles-key';%0A +export const EDITING_MANAGEMENT_KEY = 'editing-management-key';%0A export const
9fcccb71a5d9ff84f3415f64a72658bf19f1fe17
Iterator is workflow_template not workflow_job_template
awx/ui/client/src/access/rbac-multiselect/rbac-multiselect-list.directive.js
awx/ui/client/src/access/rbac-multiselect/rbac-multiselect-list.directive.js
/************************************************* * Copyright (c) 2015 Ansible, Inc. * * All Rights Reserved *************************************************/ /* jshint unused: vars */ export default ['addPermissionsTeamsList', 'addPermissionsUsersList', 'TemplateList', 'ProjectList', 'InventoryList', 'CredentialList', '$compile', 'generateList', 'OrganizationList', '$window', function(addPermissionsTeamsList, addPermissionsUsersList, TemplateList, ProjectList, InventoryList, CredentialList, $compile, generateList, OrganizationList, $window) { return { restrict: 'E', scope: { allSelected: '=', view: '@', dataset: '=' }, template: "<div class='addPermissionsList-inner'></div>", link: function(scope, element, attrs, ctrl) { let listMap, list, list_html; listMap = { Teams: addPermissionsTeamsList, Users: addPermissionsUsersList, Projects: ProjectList, JobTemplates: TemplateList, WorkflowTemplates: TemplateList, Inventories: InventoryList, Credentials: CredentialList, Organizations: OrganizationList }; list = _.cloneDeep(listMap[scope.view]); list.multiSelect = true; list.multiSelectExtended = true; list.listTitleBadge = false; delete list.actions; delete list.fieldActions; switch(scope.view){ case 'Projects': list.fields = { name: list.fields.name, scm_type: list.fields.scm_type }; list.fields.name.ngClick = 'linkoutResource("project", project)'; list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11'; list.fields.scm_type.columnClass = 'col-md-5 col-sm-5 hidden-xs'; break; case 'Inventories': list.fields = { name: list.fields.name, organization: list.fields.organization }; list.fields.name.ngClick = 'linkoutResource("inventory", inventory)'; list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11'; list.fields.organization.columnClass = 'col-md-5 col-sm-5 hidden-xs'; break; case 'JobTemplates': list.name = 'job_templates'; list.iterator = 'job_template'; list.basePath = 'job_templates'; list.fields = { name: list.fields.name }; list.fields.name.ngClick = 'linkoutResource("job_template", job_template)'; list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11'; list.fields.name.ngHref = '#/templates/job_template/{{job_template.id}}'; break; case 'WorkflowTemplates': list.name = 'workflow_templates'; list.iterator = 'workflow_template'; list.basePath = 'workflow_job_templates'; list.fields = { name: list.fields.name }; list.fields.name.ngClick = 'linkoutResource("workflow_job_template", workflow_job_template)'; list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11'; list.fields.name.ngHref = '#/templates/workflow_job_template/{{workflow_template.id}}'; break; case 'Users': list.fields = { username: list.fields.username, first_name: list.fields.first_name, last_name: list.fields.last_name }; list.fields.username.ngClick = 'linkoutResource("user", user)'; list.fields.username.columnClass = 'col-md-5 col-sm-5 col-xs-11'; list.fields.first_name.columnClass = 'col-md-3 col-sm-3 hidden-xs'; list.fields.last_name.columnClass = 'col-md-3 col-sm-3 hidden-xs'; break; case 'Teams': list.fields = { name: list.fields.name, organization: list.fields.organization, }; list.fields.name.ngClick = 'linkoutResource("team", team)'; list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11'; list.fields.organization.columnClass = 'col-md-5 col-sm-5 hidden-xs'; break; case 'Organizations': list.fields = { name: list.fields.name }; list.fields.name.ngClick = 'linkoutResource("organization", organization)'; list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11'; break; case 'Credentials': list.fields = { name: list.fields.name }; list.fields.name.ngClick = 'linkoutResource("credential", credential)'; list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11'; break; default: list.fields = { name: list.fields.name, description: list.fields.description }; list.fields.name.columnClass = 'col-md-6 col-sm-6 col-xs-11'; list.fields.description.columnClass = 'col-md-5 col-sm-5 hidden-xs'; } list_html = generateList.build({ mode: 'edit', list: list, related: false, title: false, hideViewPerPage: true }); scope.list = list; scope[`${list.iterator}_dataset`] = scope.dataset.data; scope[`${list.name}`] = scope[`${list.iterator}_dataset`].results; scope.$watch(list.name, function(){ _.forEach(scope[`${list.name}`], isSelected); optionsRequestDataProcessing(); }); scope.$on(`${list.iterator}_options`, function(event, data){ scope.options = data.data.actions.GET; optionsRequestDataProcessing(); }); // iterate over the list and add fields like type label, after the // OPTIONS request returns, or the list is sorted/paginated/searched function optionsRequestDataProcessing(){ if(scope.list.name === 'projects'){ if (scope[list.name] !== undefined) { scope[list.name].forEach(function(item, item_idx) { var itm = scope[list.name][item_idx]; // Set the item type label if (list.fields.scm_type && scope.options && scope.options.hasOwnProperty('scm_type')) { scope.options.scm_type.choices.forEach(function(choice) { if (choice[0] === item.scm_type) { itm.type_label = choice[1]; } }); } }); } } } function isSelected(item){ if(_.find(scope.allSelected, {id: item.id, type: item.type})){ item.isSelected = true; } return item; } element.append(list_html); $compile(element.contents())(scope); scope.linkoutResource = function(type, resource) { let url; switch(type){ case 'project': url = "/#/projects/" + resource.id; break; case 'inventory': url = resource.kind && resource.kind === "smart" ? "/#/inventories/smart/" + resource.id : "/#/inventories/inventory/" + resource.id; break; case 'job_template': url = "/#/templates/job_template/" + resource.id; break; case 'workflow_job_template': url = "/#/templates/workflow_job_template/" + resource.id; break; case 'user': url = "/#/users/" + resource.id; break; case 'team': url = "/#/teams/" + resource.id; break; case 'organization': url = "/#/organizations/" + resource.id; break; case 'credential': url = "/#/credentials/" + resource.id; break; } $window.open(url,'_blank'); }; } }; }];
JavaScript
0.999857
@@ -3541,36 +3541,32 @@ late%22, workflow_ -job_ template)';%0A
20476caed9ff374a9b201b057d2dcff3522c6ca4
Convert typeof tests to mocha
test/typeOf-test.js
test/typeOf-test.js
"use strict"; var buster = require("buster"); var sinon = require("../lib/sinon"); var assert = buster.assert; buster.testCase("sinon.typeOf", { "returns boolean": function () { assert.equals(sinon.typeOf(false), "boolean"); }, "returns string": function () { assert.equals(sinon.typeOf("Sinon.JS"), "string"); }, "returns number": function () { assert.equals(sinon.typeOf(123), "number"); }, "returns object": function () { assert.equals(sinon.typeOf({}), "object"); }, "returns function": function () { assert.equals(sinon.typeOf(function () {}), "function"); }, "returns undefined": function () { assert.equals(sinon.typeOf(undefined), "undefined"); }, "returns null": function () { assert.equals(sinon.typeOf(null), "null"); }, "returns array": function () { assert.equals(sinon.typeOf([]), "array"); }, "returns regexp": function () { assert.equals(sinon.typeOf(/.*/), "regexp"); }, "returns date": function () { assert.equals(sinon.typeOf(new Date()), "date"); } });
JavaScript
0.999999
@@ -1,8 +1,64 @@ +/*eslint-env mocha*/%0A/*eslint max-nested-callbacks: 0*/%0A %22use str @@ -68,22 +68,23 @@ %22;%0A%0Avar -buster +referee = requi @@ -87,22 +87,23 @@ equire(%22 -buster +referee %22);%0Avar @@ -148,22 +148,23 @@ ssert = -buster +referee .assert; @@ -169,22 +169,15 @@ t;%0A%0A -buster.testCas +describ e(%22s @@ -189,23 +189,38 @@ typeOf%22, + function () %7B%0A +it( %22returns @@ -228,17 +228,17 @@ boolean%22 -: +, functio @@ -296,39 +296,43 @@ boolean%22);%0A %7D -, +); %0A%0A +it( %22returns string%22 @@ -331,17 +331,17 @@ string%22 -: +, functio @@ -403,39 +403,43 @@ %22string%22);%0A %7D -, +); %0A%0A +it( %22returns number%22 @@ -438,17 +438,17 @@ number%22 -: +, functio @@ -503,39 +503,43 @@ %22number%22);%0A %7D -, +); %0A%0A +it( %22returns object%22 @@ -538,17 +538,17 @@ object%22 -: +, functio @@ -602,39 +602,43 @@ %22object%22);%0A %7D -, +); %0A%0A +it( %22returns functio @@ -639,17 +639,17 @@ unction%22 -: +, functio @@ -717,39 +717,43 @@ unction%22);%0A %7D -, +); %0A%0A +it( %22returns undefin @@ -755,17 +755,17 @@ defined%22 -: +, functio @@ -829,39 +829,43 @@ defined%22);%0A %7D -, +); %0A%0A +it( %22returns null%22: @@ -862,17 +862,17 @@ ns null%22 -: +, functio @@ -926,39 +926,43 @@ , %22null%22);%0A %7D -, +); %0A%0A +it( %22returns array%22: @@ -960,17 +960,17 @@ s array%22 -: +, functio @@ -1023,39 +1023,43 @@ %22array%22);%0A %7D -, +); %0A%0A +it( %22returns regexp%22 @@ -1058,17 +1058,17 @@ regexp%22 -: +, functio @@ -1136,15 +1136,19 @@ %7D -, +); %0A%0A +it( %22ret @@ -1157,17 +1157,17 @@ ns date%22 -: +, functio @@ -1235,13 +1235,15 @@ );%0A %7D +); %0A%7D);%0A
1dd437eb6b29a2d9e88ed1542cba5a3bd4e66c99
fix conflict between mocks and skip (#863)
test/utils/utils.js
test/utils/utils.js
const child = require('child_process'); const path = require('path'); const chalk = require('chalk'); const common = require('../../src/common'); function numLines(str) { return typeof str === 'string' ? (str.match(/\n/g) || []).length + 1 : 0; } exports.numLines = numLines; function getTempDir() { // a very random directory return ('tmp' + Math.random() + Math.random()).replace(/\./g, ''); } exports.getTempDir = getTempDir; // On Windows, symlinks for files need admin permissions. This helper // skips certain tests if we are on Windows and got an EPERM error function skipOnWinForEPERM(action, testCase) { const ret = action(); const error = ret.code; const isWindows = process.platform === 'win32'; if (isWindows && error && /EPERM:/.test(error)) { console.warn('Got EPERM when testing symlinks on Windows. Assuming non-admin environment and skipping test.'); } else { testCase(); } } exports.skipOnWinForEPERM = skipOnWinForEPERM; function runScript(script, cb) { child.execFile(common.config.execPath, ['-e', script], cb); } exports.runScript = runScript; function sleep(time) { const testDirectoryPath = path.dirname(__dirname); child.execFileSync(common.config.execPath, [ path.join(testDirectoryPath, 'resources', 'exec', 'slow.js'), time.toString(), ]); } exports.sleep = sleep; function mkfifo(dir) { if (process.platform !== 'win32') { const fifo = dir + 'fifo'; child.execFileSync('mkfifo', [fifo]); return fifo; } return null; } exports.mkfifo = mkfifo; function skipIfTrue(booleanValue, t, closure) { if (booleanValue) { console.warn( chalk.yellow('Warning: skipping platform-dependent test ') + chalk.bold.white(`'${t._test.title}'`) ); t.truthy(true); // dummy assertion to satisfy ava v0.19+ } else { closure(); } } exports.skipOnUnix = skipIfTrue.bind(module.exports, process.platform !== 'win32'); exports.skipOnWin = skipIfTrue.bind(module.exports, process.platform === 'win32');
JavaScript
0.000006
@@ -142,16 +142,164 @@ mon');%0A%0A +// Capture process.stderr.write, otherwise we have a conflict with mocks.js%0Aconst _processStderrWrite = process.stderr.write.bind(process.stderr);%0A%0A function @@ -921,28 +921,35 @@ ) %7B%0A -console.warn +_processStderrWrite ('Got EP @@ -1035,16 +1035,18 @@ ng test. +%5Cn ');%0A %7D @@ -1769,20 +1769,27 @@ -console.warn +_processStderrWrite (%0A @@ -1853,16 +1853,16 @@ st ') +%0A - ch @@ -1897,16 +1897,29 @@ itle%7D'%60) + +%0A '%5Cn' %0A );%0A
f640e18e54943a419d28ebee83cc7b227acbc7e4
apply all screen updates in a single animationFrame
browser/src/render/Renderer.js
browser/src/render/Renderer.js
'use strict' import ViewState from './ViewState' import BrowserRtcBufferFactory from '../BrowserRtcBufferFactory' import YUVASurfaceShader from './YUVASurfaceShader' import YUVSurfaceShader from './YUVSurfaceShader' import Size from '../Size' export default class Renderer { /** * * @param {BrowserSession} browserSession * @returns {Renderer} */ static create (browserSession) { // create offscreen gl context const canvas = document.createElement('canvas') let gl = canvas.getContext('webgl2') if (!gl) { throw new Error('This browser doesn\'t support WebGL2!') } gl.clearColor(0, 0, 0, 0) const yuvaShader = YUVASurfaceShader.create(gl) const yuvShader = YUVSurfaceShader.create(gl) return new Renderer(browserSession, gl, yuvaShader, yuvShader, canvas) } /** * Use Renderer.create(..) instead. * @private * @param browserSession * @param gl * @param yuvaShader * @param yuvShader * @param canvas */ constructor (browserSession, gl, yuvaShader, yuvShader, canvas) { this.browserSession = browserSession this.gl = gl this.yuvaShader = yuvaShader this.yuvShader = yuvShader this.canvas = canvas } /** * @param {BrowserSurface}browserSurface * @return Size */ surfaceSize (browserSurface) { const grBuffer = browserSurface.grBuffer const bufferSize = this.bufferSize(grBuffer) if (browserSurface.bufferScale === 1) { return bufferSize } const surfaceWidth = bufferSize.w / browserSurface.bufferScale const surfaceHeight = bufferSize.h / browserSurface.bufferScale return Size.create(surfaceWidth, surfaceHeight) } /** * @param {GrBuffer}grBuffer * @return Size */ bufferSize (grBuffer) { if (grBuffer === null) { return Size.create(0, 0) } // TODO we could check for null here in case we are dealing with a different kind of buffer const browserRtcDcBuffer = BrowserRtcBufferFactory.get(grBuffer) return browserRtcDcBuffer.geo } async requestRender (browserSurface) { const renderStart = Date.now() const grBuffer = browserSurface.grBuffer if (grBuffer === null) { browserSurface.renderState = null return } let viewState = browserSurface.renderState if (!viewState) { viewState = ViewState.create(this.gl) browserSurface.renderState = viewState } const browserRtcDcBuffer = BrowserRtcBufferFactory.get(grBuffer) const frameCallback = browserSurface.frameCallback browserSurface.frameCallback = null const views = browserSurface.browserSurfaceViews const syncSerial = await browserRtcDcBuffer.whenComplete() browserSurface.size = this.surfaceSize(browserSurface) browserSurface.bufferSize = browserRtcDcBuffer.geo // copy state into a separate object so we don't read a different state when our animation frame fires const state = { buffer: { type: browserRtcDcBuffer.type, pngContent: browserRtcDcBuffer.pngContent, yuvContent: browserRtcDcBuffer.yuvContent, yuvWidth: browserRtcDcBuffer.yuvWidth, yuvHeight: browserRtcDcBuffer.yuvHeight, alphaYuvContent: browserRtcDcBuffer.alphaYuvContent, alphaYuvWidth: browserRtcDcBuffer.alphaYuvWidth, alphaYuvHeight: browserRtcDcBuffer.alphaYuvHeight, geo: browserRtcDcBuffer.geo, resource: browserRtcDcBuffer.resource }, syncSerial: syncSerial, renderStart: renderStart, frameCallback: frameCallback, views: views } window.requestAnimationFrame((frameTimeStamp) => { this._render(viewState, frameTimeStamp, state) this.browserSession.flush() }) } _render (viewState, frameTimeStamp, state) { // update textures viewState.update(state) this._draw(frameTimeStamp, state, viewState) const renderDuration = Date.now() - state.renderStart state.buffer.resource.latency(state.syncSerial, renderDuration) if (state.frameCallback) { state.frameCallback.done(frameTimeStamp << 0) } } _draw (frameTimeStamp, state, renderState) { // paint the textures if (state.buffer.type === 'h264') { this._drawH264(state, renderState) } else { // if (browserRtcDcBuffer.type === 'png') this._drawPNG(state, renderState) } } _drawH264 (state, renderState) { const bufferSize = state.buffer.geo const viewPortUpdate = this.canvas.width !== bufferSize.w || this.canvas.height !== bufferSize.h this.canvas.width = bufferSize.w this.canvas.height = bufferSize.h if (state.buffer.alphaYuvContent != null) { this.yuvaShader.use() this.yuvaShader.draw(renderState.yTexture, renderState.uTexture, renderState.vTexture, renderState.alphaYTexture, bufferSize, viewPortUpdate) } else { this.yuvShader.use() this.yuvShader.draw(renderState.yTexture, renderState.uTexture, renderState.vTexture, bufferSize, viewPortUpdate) } // blit rendered texture from render canvas into view canvasses state.views.forEach((view) => { view.drawCanvas(this.canvas) }) } _drawPNG (state, renderState) { state.views.forEach((view) => { view.drawPNG(renderState.pngImage) }) } }
JavaScript
0
@@ -1201,16 +1201,299 @@ = canvas +%0A%0A this._animationScheduled = false%0A this._sceneUpdates = %5B%5D%0A this._updateScene = (timestamp) =%3E %7B%0A this._sceneUpdates.forEach(frameUpdate =%3E %7B frameUpdate() %7D)%0A this.browserSession.flush()%0A this._sceneUpdates = %5B%5D%0A this._animationScheduled = false%0A %7D %0A %7D%0A%0A @@ -2499,24 +2499,175 @@ tate = null%0A + if (browserSurface.frameCallback) %7B%0A browserSurface.frameCallback.done(Date.now() & 0x7fffffff)%0A %7D%0A this.browserSession.flush()%0A return @@ -4019,152 +4019,243 @@ -window.requestAnimationFrame((frameTimeStamp) =%3E %7B%0A this._render(viewState, frameTimeStamp, state)%0A this.browserSession.flush( +this._sceneUpdates.push(() =%3E %7B%0A this._render(viewState, Date.now() & 0x7fffffff, state)%0A %7D)%0A if (!this._animationScheduled) %7B%0A this._animationScheduled = true%0A window.requestAnimationFrame(this._updateScene )%0A %7D -) %0A %7D
0186cefa3255905033403ec5432c7ead0b987c77
Fix #292
resources/assets/js/stores/queue.js
resources/assets/js/stores/queue.js
import { head, last, includes, union, difference, indexOf, map, shuffle } from 'lodash'; export default { state: { songs: [], current: null, }, init() { // We don't have anything to do here yet. // How about another song then? // // LITTLE WING // -- by Jimi Fucking Hendrix // // Well she's walking // Through the clouds // With a circus mind // That's running wild // Butterflies and zebras and moonbeams and fairytales // That's all she ever thinks about // Riding with the wind // // When I'm sad // She comes to me // With a thousand smiles // She gives to me free // It's alright she said // It's alright // Take anything you want from me // Anything... }, /** * All queued songs. * * @return {Array.<Object>} */ get all() { return this.state.songs; }, /** * The first song in the queue. * * @return {?Object} */ get first() { return head(this.state.songs); }, /** * The last song in the queue. * * @return {?Object} */ get last() { return last(this.state.songs); }, /** * Determine if the queue contains a song. * * @param {Object} song * * @return {Boolean} */ contains(song) { return includes(this.all, song); }, /** * Add a list of songs to the end of the current queue, * or replace the current queue as a whole if `replace` is true. * * @param {Object|Array.<Object>} songs The song, or an array of songs * @param {Boolean} replace Whether to replace the current queue * @param {Boolean} toTop Whether to prepend or append to the queue */ queue(songs, replace = false, toTop = false) { songs = [].concat(songs); if (replace) { this.state.songs = songs; } else { if (toTop) { this.state.songs = union(songs, this.state.songs); } else { this.state.songs = union(this.state.songs, songs); } } }, /** * Queue song(s) to after the current song. * * @param {Array.<Object>|Object} songs */ queueAfterCurrent(songs) { songs = [].concat(songs); if (!this.state.current || !this.state.songs.length) { return this.queue(songs); } const head = this.state.songs.splice(0, this.indexOf(this.state.current) + 1); this.state.songs = head.concat(songs, this.state.songs); }, /** * Unqueue a song, or several songs at once. * * @param {Object|String|Array.<Object>} songs The song(s) to unqueue */ unqueue(songs) { this.state.songs = difference(this.state.songs, [].concat(songs)); }, /** * Move some songs to after a target. * * @param {Array.<Object>} songs Songs to move * @param {Object} target The target song object */ move(songs, target) { const $targetIndex = this.indexOf(target); songs.forEach(song => { this.state.songs.splice(this.indexOf(song), 1); this.state.songs.splice($targetIndex, 0, song); }); }, /** * Clear the current queue. * * @param {?Function} cb The function to execute after clearing */ clear(cb = null) { this.state.songs = []; this.state.current = null; if (cb) { cb(); } }, /** * Get index of a song in the queue. * * @param {Object} song * * @return {?Integer} */ indexOf(song) { return indexOf(this.state.songs, song); }, /** * The next song in queue. * * @return {?Object} */ get next() { if (!this.current) { return first(this.state.songs); } const idx = map(this.state.songs, 'id').indexOf(this.current.id) + 1; return idx >= this.state.songs.length ? null : this.state.songs[idx]; }, /** * The previous song in queue. * * @return {?Object} */ get previous() { if (!this.current) { return last(this.state.songs); } const idx = map(this.state.songs, 'id').indexOf(this.current.id) - 1; return idx < 0 ? null : this.state.songs[idx]; }, /** * The current song. * * @return {Object} */ get current() { return this.state.current; }, /** * Set a song as the current queued song. * * @param {Object} song * * @return {Object} The queued song. */ set current(song) { this.state.current = song; return this.current; }, /** * Shuffle the queue. * * @return {Array.<Object>} The shuffled array of song objects */ shuffle() { return (this.state.songs = shuffle(this.state.songs)); }, };
JavaScript
0.000001
@@ -67,21 +67,8 @@ ce,%0A - indexOf,%0A @@ -3865,24 +3865,16 @@ return -indexOf( this.sta @@ -3877,26 +3877,33 @@ .state.songs -, +.indexOf( song);%0A %7D
85a3519496664cf08cd3d622b54ee85fa4811345
fix typo
www/js/controllers.js
www/js/controllers.js
angular.module('starter.controllers', []) .controller('LoginCtrl', function($scope, auth, $state, store) { auth.signin({ closable: false, // This asks for the refresh token // So that the user never has to log in again authParams: { scope: 'openid offline_access' } }, function(profile, idToken, accessToken, state, refreshToken) { store.set('profile', profile); store.set('token', idToken); store.set('refreshToken', refreshToken); //temporarily just go to tab.polls $state.go('tab.polls'); ///////////////////// auth.getToken({ api: 'firebase' }).then(function(delegation) { store.set('firebaseToken', delegation.id_token); $state.go('tab.polls'); }, function(error) { console.log("There was an error logging in", error); }) }, function(error) { console.log("There was an error logging in", error); }); }) .controller('PollsCtrl', function($scope, Polls, $ionicModal) { $ionicModal.fromTemplateUrl('templates/poll-add-modal.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal; }); $scope.newFriend = { name: '', description: '' }; $scope.aggregateResults = function(poll){ results = {'yes': 0, 'no': 0} if(poll.pollResponses){ for(var key in poll.pollResponses){ if(poll.pollResponses[key]){ poll.pollResponses[key].thisUsersAnswer.toLowerCase()==='Yes' ? results.yes++ : results.no++; } } } return results; }; $scope.polls = Polls.asArray; $scope.showAddFriend = function() { $scope.modal.show(); }; $scope.addFriend = function() { if(!$scope.newFriend.$id) { Polls.add($scope.newFriend); } else { Polls.save($scope.newFriend); } $scope.newFriend = {}; $scope.modal.hide(); }; $scope.deleteFriend = function(friend) { Polls.delete(friend); }; $scope.editFriend = function(friend) { $scope.newFriend = friend; $scope.modal.show(); }; $scope.close = function() { $scope.modal.hide(); }; $scope.$on('$destroy', function() { $scope.modal.remove(); }); }) .controller('singlePollCtrl', function($scope, $stateParams, Polls) { $scope.poll = Poll.get($stateParams.pollId); }) .controller('AccountCtrl', function($scope, auth, $state, store) { $scope.logout = function() { auth.signout(); store.remove('token'); store.remove('profile'); store.remove('refreshToken'); $state.go('login'); } });
JavaScript
0.999991
@@ -1462,9 +1462,9 @@ ===' -Y +y es'
c46557d6f73943a959b67bb25fcad484ad9941a0
correct label for activity/processinstance dropdown in timing tab
src/main/resources/plugin-webapp/statistics-plugin/app/directives/startEndControlElement.js
src/main/resources/plugin-webapp/statistics-plugin/app/directives/startEndControlElement.js
ngDefine('cockpit.plugin.statistics-plugin.directives', function(module) { module.directive('startEndControlElement', function(){ return { restrict: 'E', template: '<form class="form-horizontal">'+ '<h5>Show:<h5>'+ '<h5>starting time or ending time</h5>'+ '<div class="control-group">'+ '<select ng-model="currentXValue" ng-options="currentXValue.xValue for currentXValue in xValueSpecifiers" ng-change="getDataAndDrawGraph()">'+ '</select>'+ '</div>'+ '<h5>{{currentXValue.xValue}} on a weekly or dayly basis</h5>'+ '<div class="control-group">'+ '<select ng-model="currentFrame" ng-options="currentFrame.frame for currentFrame in timeFrames" ng-change="getDataAndDrawGraph()">'+ '</select>'+ '</div>'+ '<h5>of process instances or user tasks<h5>'+ '<div class="control-group">'+ '<select ng-model="currentLevel" ng-options="currentLevel.level for currentLevel in levelSpecifiers" ng-change="getDataAndDrawGraph()">'+ '</select>'+ '</div>'+ '<h5>of a specific process or all<h5>'+ '<div class="control-group">'+ '<select ng-disabled="!currentLevel.moreOptions" ng-model="processInstance" ng-options="processInstance.processDefKey for processInstance in processInstances" ng-change="getDataAndDrawGraph()">'+ '</select>'+ '</div>'+ '<h5>adjust width<h5>'+ '<input type="number" name="points" min="0" step="10" value="1000" ng-model = "width" ng-change="getDataAndDrawGraph()">'+ // '<h5>adjust cluster threshold<h5>'+ // '<input type="number" name="cluster" min="0" step="10" value="10" ng-model = "clusterThreshold" ng-change="getDataAndDrawGraph()">'+ '<div style="visibility:hidden;">'+ '<h5>kmeans<h5>'+ '<input type="number" name="kmeans" min="1" step="1" value="5" ng-model = "kMeans" ng-change="getDataAndDrawGraph()">'+ '</div>'+ '</form>' }; }); });
JavaScript
0
@@ -888,17 +888,17 @@ or -user task +activitie s%3Ch5
0503cca3e7d94a4cff23984653f59b6fbca3ec4c
Remove one DOM element in the Card actions (#9952)
docs/src/pages/demos/cards/RecipeReviewCard.js
docs/src/pages/demos/cards/RecipeReviewCard.js
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import classnames from 'classnames'; import Card, { CardHeader, CardMedia, CardContent, CardActions } from 'material-ui/Card'; import Collapse from 'material-ui/transitions/Collapse'; import Avatar from 'material-ui/Avatar'; import IconButton from 'material-ui/IconButton'; import Typography from 'material-ui/Typography'; import red from 'material-ui/colors/red'; import FavoriteIcon from 'material-ui-icons/Favorite'; import ShareIcon from 'material-ui-icons/Share'; import ExpandMoreIcon from 'material-ui-icons/ExpandMore'; import MoreVertIcon from 'material-ui-icons/MoreVert'; const styles = theme => ({ card: { maxWidth: 400, }, media: { height: 194, }, expand: { transform: 'rotate(0deg)', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shortest, }), }, expandOpen: { transform: 'rotate(180deg)', }, avatar: { backgroundColor: red[500], }, flexGrow: { flex: '1 1 auto', }, }); class RecipeReviewCard extends React.Component { state = { expanded: false }; handleExpandClick = () => { this.setState({ expanded: !this.state.expanded }); }; render() { const { classes } = this.props; return ( <div> <Card className={classes.card}> <CardHeader avatar={ <Avatar aria-label="Recipe" className={classes.avatar}> R </Avatar> } action={ <IconButton> <MoreVertIcon /> </IconButton> } title="Shrimp and Chorizo Paella" subheader="September 14, 2016" /> <CardMedia className={classes.media} image="/static/images/cards/paella.jpg" title="Contemplative Reptile" /> <CardContent> <Typography component="p"> This impressive paella is a perfect party dish and a fun meal to cook together with your guests. Add 1 cup of frozen peas along with the mussels, if you like. </Typography> </CardContent> <CardActions disableActionSpacing> <IconButton aria-label="Add to favorites"> <FavoriteIcon /> </IconButton> <IconButton aria-label="Share"> <ShareIcon /> </IconButton> <div className={classes.flexGrow} /> <IconButton className={classnames(classes.expand, { [classes.expandOpen]: this.state.expanded, })} onClick={this.handleExpandClick} aria-expanded={this.state.expanded} aria-label="Show more" > <ExpandMoreIcon /> </IconButton> </CardActions> <Collapse in={this.state.expanded} timeout="auto" unmountOnExit> <CardContent> <Typography paragraph type="body2"> Method: </Typography> <Typography paragraph> Heat 1/2 cup of the broth in a pot until simmering, add saffron and set aside for 10 minutes. </Typography> <Typography paragraph> Heat oil in a (14- to 16-inch) paella pan or a large, deep skillet over medium-high heat. Add chicken, shrimp and chorizo, and cook, stirring occasionally until lightly browned, 6 to 8 minutes. Transfer shrimp to a large plate and set aside, leaving chicken and chorizo in the pan. Add pimentón, bay leaves, garlic, tomatoes, onion, salt and pepper, and cook, stirring often until thickened and fragrant, about 10 minutes. Add saffron broth and remaining 4 1/2 cups chicken broth; bring to a boil. </Typography> <Typography paragraph> Add rice and stir very gently to distribute. Top with artichokes and peppers, and cook without stirring, until most of the liquid is absorbed, 15 to 18 minutes. Reduce heat to medium-low, add reserved shrimp and mussels, tucking them down into the rice, and cook again without stirring, until mussels have opened and rice is just tender, 5 to 7 minutes more. (Discard any mussels that don’t open.) </Typography> <Typography> Set aside off of the heat to let rest for 10 minutes, and then serve. </Typography> </CardContent> </Collapse> </Card> </div> ); } } RecipeReviewCard.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(RecipeReviewCard);
JavaScript
0
@@ -779,24 +779,63 @@ : 194,%0A %7D,%0A + actions: %7B%0A display: 'flex',%0A %7D,%0A expand: %7B%0A @@ -830,24 +830,24 @@ expand: %7B%0A - transfor @@ -982,16 +982,40 @@ %7D),%0A + marginLeft: 'auto',%0A %7D,%0A e @@ -1073,24 +1073,24 @@ avatar: %7B%0A + backgrou @@ -1117,49 +1117,8 @@ %7D,%0A - flexGrow: %7B%0A flex: '1 1 auto',%0A %7D,%0A %7D);%0A @@ -2288,16 +2288,44 @@ dActions + className=%7Bclasses.actions%7D disable @@ -2553,57 +2553,8 @@ on%3E%0A - %3Cdiv className=%7Bclasses.flexGrow%7D /%3E%0A